clang  19.0.0git
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/AST/Type.h"
25 #include "clang/Basic/CharInfo.h"
26 #include "clang/Basic/Cuda.h"
34 #include "clang/Basic/TargetInfo.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/DeclSpec.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedAttr.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaCUDA.h"
44 #include "clang/Sema/SemaHLSL.h"
46 #include "clang/Sema/SemaSYCL.h"
47 #include "clang/Sema/SemaObjC.h"
48 #include "llvm/ADT/STLExtras.h"
49 #include "llvm/ADT/STLForwardCompat.h"
50 #include "llvm/ADT/StringExtras.h"
51 #include "llvm/Demangle/Demangle.h"
52 #include "llvm/IR/Assumptions.h"
53 #include "llvm/MC/MCSectionMachO.h"
54 #include "llvm/Support/Error.h"
55 #include "llvm/Support/MathExtras.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include "llvm/TargetParser/Triple.h"
58 #include <optional>
59 
60 using namespace clang;
61 using namespace sema;
62 
64  enum LANG {
65  C,
66  Cpp,
67  ObjC
68  };
69 } // end namespace AttributeLangSupport
70 
71 //===----------------------------------------------------------------------===//
72 // Helper functions
73 //===----------------------------------------------------------------------===//
74 
75 /// isFunctionOrMethod - Return true if the given decl has function
76 /// type (function or function-typed variable) or an Objective-C
77 /// method.
78 static bool isFunctionOrMethod(const Decl *D) {
79  return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
80 }
81 
82 /// Return true if the given decl has function type (function or
83 /// function-typed variable) or an Objective-C method or a block.
84 static bool isFunctionOrMethodOrBlock(const Decl *D) {
85  return isFunctionOrMethod(D) || isa<BlockDecl>(D);
86 }
87 
88 /// Return true if the given decl has a declarator that should have
89 /// been processed by Sema::GetTypeForDeclarator.
90 static bool hasDeclarator(const Decl *D) {
91  // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
92  return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
93  isa<ObjCPropertyDecl>(D);
94 }
95 
96 /// hasFunctionProto - Return true if the given decl has a argument
97 /// information. This decl should have already passed
98 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
99 static bool hasFunctionProto(const Decl *D) {
100  if (const FunctionType *FnTy = D->getFunctionType())
101  return isa<FunctionProtoType>(FnTy);
102  return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
103 }
104 
105 /// getFunctionOrMethodNumParams - Return number of function or method
106 /// parameters. It is an error to call this on a K&R function (use
107 /// hasFunctionProto first).
108 static unsigned getFunctionOrMethodNumParams(const Decl *D) {
109  if (const FunctionType *FnTy = D->getFunctionType())
110  return cast<FunctionProtoType>(FnTy)->getNumParams();
111  if (const auto *BD = dyn_cast<BlockDecl>(D))
112  return BD->getNumParams();
113  return cast<ObjCMethodDecl>(D)->param_size();
114 }
115 
117  unsigned Idx) {
118  if (const auto *FD = dyn_cast<FunctionDecl>(D))
119  return FD->getParamDecl(Idx);
120  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
121  return MD->getParamDecl(Idx);
122  if (const auto *BD = dyn_cast<BlockDecl>(D))
123  return BD->getParamDecl(Idx);
124  return nullptr;
125 }
126 
127 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
128  if (const FunctionType *FnTy = D->getFunctionType())
129  return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
130  if (const auto *BD = dyn_cast<BlockDecl>(D))
131  return BD->getParamDecl(Idx)->getType();
132 
133  return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
134 }
135 
136 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
137  if (auto *PVD = getFunctionOrMethodParam(D, Idx))
138  return PVD->getSourceRange();
139  return SourceRange();
140 }
141 
143  if (const FunctionType *FnTy = D->getFunctionType())
144  return FnTy->getReturnType();
145  return cast<ObjCMethodDecl>(D)->getReturnType();
146 }
147 
149  if (const auto *FD = dyn_cast<FunctionDecl>(D))
150  return FD->getReturnTypeSourceRange();
151  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
152  return MD->getReturnTypeSourceRange();
153  return SourceRange();
154 }
155 
156 static bool isFunctionOrMethodVariadic(const Decl *D) {
157  if (const FunctionType *FnTy = D->getFunctionType())
158  return cast<FunctionProtoType>(FnTy)->isVariadic();
159  if (const auto *BD = dyn_cast<BlockDecl>(D))
160  return BD->isVariadic();
161  return cast<ObjCMethodDecl>(D)->isVariadic();
162 }
163 
164 static bool isInstanceMethod(const Decl *D) {
165  if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(D))
166  return MethodDecl->isInstance();
167  return false;
168 }
169 
170 static inline bool isNSStringType(QualType T, ASTContext &Ctx,
171  bool AllowNSAttributedString = false) {
172  const auto *PT = T->getAs<ObjCObjectPointerType>();
173  if (!PT)
174  return false;
175 
176  ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
177  if (!Cls)
178  return false;
179 
180  IdentifierInfo* ClsName = Cls->getIdentifier();
181 
182  if (AllowNSAttributedString &&
183  ClsName == &Ctx.Idents.get("NSAttributedString"))
184  return true;
185  // FIXME: Should we walk the chain of classes?
186  return ClsName == &Ctx.Idents.get("NSString") ||
187  ClsName == &Ctx.Idents.get("NSMutableString");
188 }
189 
190 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
191  const auto *PT = T->getAs<PointerType>();
192  if (!PT)
193  return false;
194 
195  const auto *RT = PT->getPointeeType()->getAs<RecordType>();
196  if (!RT)
197  return false;
198 
199  const RecordDecl *RD = RT->getDecl();
200  if (RD->getTagKind() != TagTypeKind::Struct)
201  return false;
202 
203  return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
204 }
205 
206 static unsigned getNumAttributeArgs(const ParsedAttr &AL) {
207  // FIXME: Include the type in the argument list.
208  return AL.getNumArgs() + AL.hasParsedType();
209 }
210 
211 /// A helper function to provide Attribute Location for the Attr types
212 /// AND the ParsedAttr.
213 template <typename AttrInfo>
214 static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
215 getAttrLoc(const AttrInfo &AL) {
216  return AL.getLocation();
217 }
218 static SourceLocation getAttrLoc(const ParsedAttr &AL) { return AL.getLoc(); }
219 
220 /// If Expr is a valid integer constant, get the value of the integer
221 /// expression and return success or failure. May output an error.
222 ///
223 /// Negative argument is implicitly converted to unsigned, unless
224 /// \p StrictlyUnsigned is true.
225 template <typename AttrInfo>
226 static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr,
227  uint32_t &Val, unsigned Idx = UINT_MAX,
228  bool StrictlyUnsigned = false) {
229  std::optional<llvm::APSInt> I = llvm::APSInt(32);
230  if (Expr->isTypeDependent() ||
231  !(I = Expr->getIntegerConstantExpr(S.Context))) {
232  if (Idx != UINT_MAX)
233  S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
234  << &AI << Idx << AANT_ArgumentIntegerConstant
235  << Expr->getSourceRange();
236  else
237  S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
239  return false;
240  }
241 
242  if (!I->isIntN(32)) {
243  S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
244  << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
245  return false;
246  }
247 
248  if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
249  S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
250  << &AI << /*non-negative*/ 1;
251  return false;
252  }
253 
254  Val = (uint32_t)I->getZExtValue();
255  return true;
256 }
257 
258 /// Wrapper around checkUInt32Argument, with an extra check to be sure
259 /// that the result will fit into a regular (signed) int. All args have the same
260 /// purpose as they do in checkUInt32Argument.
261 template <typename AttrInfo>
262 static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr,
263  int &Val, unsigned Idx = UINT_MAX) {
264  uint32_t UVal;
265  if (!checkUInt32Argument(S, AI, Expr, UVal, Idx))
266  return false;
267 
268  if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
269  llvm::APSInt I(32); // for toString
270  I = UVal;
271  S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
272  << toString(I, 10, false) << 32 << /* Unsigned */ 0;
273  return false;
274  }
275 
276  Val = UVal;
277  return true;
278 }
279 
280 /// Diagnose mutually exclusive attributes when present on a given
281 /// declaration. Returns true if diagnosed.
282 template <typename AttrTy>
283 static bool checkAttrMutualExclusion(Sema &S, Decl *D,
284  const AttributeCommonInfo &AL) {
285  if (const auto *A = D->getAttr<AttrTy>()) {
286  S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
287  << AL << A
288  << (AL.isRegularKeywordAttribute() || A->isRegularKeywordAttribute());
289  S.Diag(A->getLocation(), diag::note_conflicting_attribute);
290  return true;
291  }
292  return false;
293 }
294 
295 template <typename AttrTy>
296 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const Attr &AL) {
297  if (const auto *A = D->getAttr<AttrTy>()) {
298  S.Diag(AL.getLocation(), diag::err_attributes_are_not_compatible)
299  << &AL << A
300  << (AL.isRegularKeywordAttribute() || A->isRegularKeywordAttribute());
301  S.Diag(A->getLocation(), diag::note_conflicting_attribute);
302  return true;
303  }
304  return false;
305 }
306 
307 void Sema::DiagnoseDeprecatedAttribute(const ParsedAttr &A, StringRef NewScope,
308  StringRef NewName) {
309  assert((!NewName.empty() || !NewScope.empty()) &&
310  "Deprecated attribute with no new scope or name?");
311  Diag(A.getLoc(), diag::warn_attribute_spelling_deprecated)
312  << "'" + A.getNormalizedFullName() + "'";
313 
314  FixItHint Fix;
315  std::string NewFullName;
316  if (NewScope.empty() && !NewName.empty()) {
317  // Only have a new name.
318  Fix = FixItHint::CreateReplacement(A.getLoc(), NewName);
319  NewFullName =
320  ((A.hasScope() ? A.getScopeName()->getName() : StringRef("")) +
321  "::" + NewName)
322  .str();
323  } else if (NewName.empty() && !NewScope.empty()) {
324  // Only have a new scope.
325  Fix = FixItHint::CreateReplacement(A.getScopeLoc(), NewScope);
326  NewFullName = (NewScope + "::" + A.getAttrName()->getName()).str();
327  } else {
328  // Have both a new name and a new scope.
329  NewFullName = (NewScope + "::" + NewName).str();
330  Fix = FixItHint::CreateReplacement(A.getRange(), NewFullName);
331  }
332 
333  Diag(A.getLoc(), diag::note_spelling_suggestion)
334  << "'" + NewFullName + "'" << Fix;
335 }
336 
338  StringRef NewName) {
339  // Additionally, diagnose the old [[intel::ii]] spelling.
340  if (A.getKind() == ParsedAttr::AT_SYCLIntelInitiationInterval &&
341  A.getAttrName()->isStr("ii")) {
342  DiagnoseDeprecatedAttribute(A, "intel", "initiation_interval");
343  return;
344  }
345 
346  // Diagnose SYCL 2017 spellings in later SYCL modes.
347  if (LangOpts.getSYCLVersion() > LangOptions::SYCL_2017) {
348  // All attributes in the cl vendor namespace are deprecated in favor of a
349  // name in the sycl namespace as of SYCL 2020.
350  if (A.hasScope() && A.getScopeName()->isStr("cl")) {
351  DiagnoseDeprecatedAttribute(A, "sycl", NewName);
352  return;
353  }
354 
355  // All GNU-style spellings are deprecated in favor of a C++-style spelling.
356  if (A.getSyntax() == ParsedAttr::AS_GNU) {
357  // Note: we cannot suggest an automatic fix-it because GNU-style
358  // spellings can appear in locations that are not valid for a C++-style
359  // spelling, and the attribute could be part of an attribute list within
360  // a single __attribute__ specifier. Just tell the user it's deprecated
361  // manually.
362  //
363  // This currently assumes that the GNU-style spelling is the same as the
364  // SYCL 2020 spelling (sans the vendor namespace).
365  Diag(A.getLoc(), diag::warn_attribute_spelling_deprecated)
366  << "'" + A.getNormalizedFullName() + "'";
367  Diag(A.getLoc(), diag::note_spelling_suggestion)
368  << "'[[sycl::" + A.getNormalizedFullName() + "]]'";
369  return;
370  }
371  }
372 
373  // Diagnose SYCL 2020 spellings used in earlier SYCL modes as being an
374  // extension.
375  if (LangOpts.getSYCLVersion() == LangOptions::SYCL_2017 && A.hasScope() &&
376  A.getScopeName()->isStr("sycl")) {
377  Diag(A.getLoc(), diag::ext_sycl_2020_attr_spelling) << A;
378  return;
379  }
380 }
381 
382 /// Check if IdxExpr is a valid parameter index for a function or
383 /// instance method D. May output an error.
384 ///
385 /// \returns true if IdxExpr is a valid index.
386 template <typename AttrInfo>
387 static bool checkFunctionOrMethodParameterIndex(
388  Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
389  const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) {
390  assert(isFunctionOrMethodOrBlock(D));
391 
392  // In C++ the implicit 'this' function parameter also counts.
393  // Parameters are counted from one.
394  bool HP = hasFunctionProto(D);
395  bool HasImplicitThisParam = isInstanceMethod(D);
396  bool IV = HP && isFunctionOrMethodVariadic(D);
397  unsigned NumParams =
398  (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
399 
400  std::optional<llvm::APSInt> IdxInt;
401  if (IdxExpr->isTypeDependent() ||
402  !(IdxInt = IdxExpr->getIntegerConstantExpr(S.Context))) {
403  S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
404  << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
405  << IdxExpr->getSourceRange();
406  return false;
407  }
408 
409  unsigned IdxSource = IdxInt->getLimitedValue(UINT_MAX);
410  if (IdxSource < 1 || (!IV && IdxSource > NumParams)) {
411  S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
412  << &AI << AttrArgNum << IdxExpr->getSourceRange();
413  return false;
414  }
415  if (HasImplicitThisParam && !CanIndexImplicitThis) {
416  if (IdxSource == 1) {
417  S.Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
418  << &AI << IdxExpr->getSourceRange();
419  return false;
420  }
421  }
422 
423  Idx = ParamIdx(IdxSource, D);
424  return true;
425 }
426 
427 /// Check if the argument \p E is a ASCII string literal. If not emit an error
428 /// and return false, otherwise set \p Str to the value of the string literal
429 /// and return true.
431  const Expr *E, StringRef &Str,
432  SourceLocation *ArgLocation) {
433  const auto *Literal = dyn_cast<StringLiteral>(E->IgnoreParenCasts());
434  if (ArgLocation)
435  *ArgLocation = E->getBeginLoc();
436 
437  if (!Literal || (!Literal->isUnevaluated() && !Literal->isOrdinary())) {
438  Diag(E->getBeginLoc(), diag::err_attribute_argument_type)
439  << CI << AANT_ArgumentString;
440  return false;
441  }
442 
443  Str = Literal->getString();
444  return true;
445 }
446 
447 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
448 /// If not emit an error and return false. If the argument is an identifier it
449 /// will emit an error with a fixit hint and treat it as if it was a string
450 /// literal.
451 bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum,
452  StringRef &Str,
453  SourceLocation *ArgLocation) {
454  // Look for identifiers. If we have one emit a hint to fix it to a literal.
455  if (AL.isArgIdent(ArgNum)) {
456  IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum);
457  Diag(Loc->Loc, diag::err_attribute_argument_type)
458  << AL << AANT_ArgumentString
459  << FixItHint::CreateInsertion(Loc->Loc, "\"")
460  << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
461  Str = Loc->Ident->getName();
462  if (ArgLocation)
463  *ArgLocation = Loc->Loc;
464  return true;
465  }
466 
467  // Now check for an actual string literal.
468  Expr *ArgExpr = AL.getArgAsExpr(ArgNum);
469  const auto *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
470  if (ArgLocation)
471  *ArgLocation = ArgExpr->getBeginLoc();
472 
473  if (!Literal || (!Literal->isUnevaluated() && !Literal->isOrdinary())) {
474  Diag(ArgExpr->getBeginLoc(), diag::err_attribute_argument_type)
475  << AL << AANT_ArgumentString;
476  return false;
477  }
478  Str = Literal->getString();
479  return checkStringLiteralArgumentAttr(AL, ArgExpr, Str, ArgLocation);
480 }
481 
482 /// Applies the given attribute to the Decl without performing any
483 /// additional semantic checking.
484 template <typename AttrType>
485 static void handleSimpleAttribute(Sema &S, Decl *D,
486  const AttributeCommonInfo &CI) {
487  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
488 }
489 
490 template <typename... DiagnosticArgs>
491 static const Sema::SemaDiagnosticBuilder&
492 appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr) {
493  return Bldr;
494 }
495 
496 template <typename T, typename... DiagnosticArgs>
497 static const Sema::SemaDiagnosticBuilder&
498 appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr, T &&ExtraArg,
499  DiagnosticArgs &&... ExtraArgs) {
500  return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
501  std::forward<DiagnosticArgs>(ExtraArgs)...);
502 }
503 
504 /// Add an attribute @c AttrType to declaration @c D, provided that
505 /// @c PassesCheck is true.
506 /// Otherwise, emit diagnostic @c DiagID, passing in all parameters
507 /// specified in @c ExtraArgs.
508 template <typename AttrType, typename... DiagnosticArgs>
509 static void handleSimpleAttributeOrDiagnose(Sema &S, Decl *D,
510  const AttributeCommonInfo &CI,
511  bool PassesCheck, unsigned DiagID,
512  DiagnosticArgs &&... ExtraArgs) {
513  if (!PassesCheck) {
514  Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID);
515  appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
516  return;
517  }
518  handleSimpleAttribute<AttrType>(S, D, CI);
519 }
520 
521 /// Check if the passed-in expression is of type int or bool.
522 static bool isIntOrBool(Expr *Exp) {
523  QualType QT = Exp->getType();
524  return QT->isBooleanType() || QT->isIntegerType();
525 }
526 
527 
528 // Check to see if the type is a smart pointer of some kind. We assume
529 // it's a smart pointer if it defines both operator-> and operator*.
530 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
531  auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record,
533  DeclContextLookupResult Result =
535  return !Result.empty();
536  };
537 
538  const RecordDecl *Record = RT->getDecl();
539  bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star);
540  bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow);
541  if (foundStarOperator && foundArrowOperator)
542  return true;
543 
544  const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record);
545  if (!CXXRecord)
546  return false;
547 
548  for (const auto &BaseSpecifier : CXXRecord->bases()) {
549  if (!foundStarOperator)
550  foundStarOperator = IsOverloadedOperatorPresent(
551  BaseSpecifier.getType()->getAsRecordDecl(), OO_Star);
552  if (!foundArrowOperator)
553  foundArrowOperator = IsOverloadedOperatorPresent(
554  BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow);
555  }
556 
557  if (foundStarOperator && foundArrowOperator)
558  return true;
559 
560  return false;
561 }
562 
563 /// Check if passed in Decl is a pointer type.
564 /// Note that this function may produce an error message.
565 /// \return true if the Decl is a pointer type; false otherwise
566 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
567  const ParsedAttr &AL) {
568  const auto *VD = cast<ValueDecl>(D);
569  QualType QT = VD->getType();
570  if (QT->isAnyPointerType())
571  return true;
572 
573  if (const auto *RT = QT->getAs<RecordType>()) {
574  // If it's an incomplete type, it could be a smart pointer; skip it.
575  // (We don't want to force template instantiation if we can avoid it,
576  // since that would alter the order in which templates are instantiated.)
577  if (RT->isIncompleteType())
578  return true;
579 
580  if (threadSafetyCheckIsSmartPointer(S, RT))
581  return true;
582  }
583 
584  S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << AL << QT;
585  return false;
586 }
587 
588 /// Checks that the passed in QualType either is of RecordType or points
589 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
590 static const RecordType *getRecordType(QualType QT) {
591  if (const auto *RT = QT->getAs<RecordType>())
592  return RT;
593 
594  // Now check if we point to record type.
595  if (const auto *PT = QT->getAs<PointerType>())
596  return PT->getPointeeType()->getAs<RecordType>();
597 
598  return nullptr;
599 }
600 
601 template <typename AttrType>
602 static bool checkRecordDeclForAttr(const RecordDecl *RD) {
603  // Check if the record itself has the attribute.
604  if (RD->hasAttr<AttrType>())
605  return true;
606 
607  // Else check if any base classes have the attribute.
608  if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
609  if (!CRD->forallBases([](const CXXRecordDecl *Base) {
610  return !Base->hasAttr<AttrType>();
611  }))
612  return true;
613  }
614  return false;
615 }
616 
617 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
618  const RecordType *RT = getRecordType(Ty);
619 
620  if (!RT)
621  return false;
622 
623  // Don't check for the capability if the class hasn't been defined yet.
624  if (RT->isIncompleteType())
625  return true;
626 
627  // Allow smart pointers to be used as capability objects.
628  // FIXME -- Check the type that the smart pointer points to.
629  if (threadSafetyCheckIsSmartPointer(S, RT))
630  return true;
631 
632  return checkRecordDeclForAttr<CapabilityAttr>(RT->getDecl());
633 }
634 
635 static bool checkTypedefTypeForCapability(QualType Ty) {
636  const auto *TD = Ty->getAs<TypedefType>();
637  if (!TD)
638  return false;
639 
640  TypedefNameDecl *TN = TD->getDecl();
641  if (!TN)
642  return false;
643 
644  return TN->hasAttr<CapabilityAttr>();
645 }
646 
647 static bool typeHasCapability(Sema &S, QualType Ty) {
648  if (checkTypedefTypeForCapability(Ty))
649  return true;
650 
651  if (checkRecordTypeForCapability(S, Ty))
652  return true;
653 
654  return false;
655 }
656 
657 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
658  // Capability expressions are simple expressions involving the boolean logic
659  // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
660  // a DeclRefExpr is found, its type should be checked to determine whether it
661  // is a capability or not.
662 
663  if (const auto *E = dyn_cast<CastExpr>(Ex))
664  return isCapabilityExpr(S, E->getSubExpr());
665  else if (const auto *E = dyn_cast<ParenExpr>(Ex))
666  return isCapabilityExpr(S, E->getSubExpr());
667  else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
668  if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
669  E->getOpcode() == UO_Deref)
670  return isCapabilityExpr(S, E->getSubExpr());
671  return false;
672  } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
673  if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
674  return isCapabilityExpr(S, E->getLHS()) &&
675  isCapabilityExpr(S, E->getRHS());
676  return false;
677  }
678 
679  return typeHasCapability(S, Ex->getType());
680 }
681 
682 /// Checks that all attribute arguments, starting from Sidx, resolve to
683 /// a capability object.
684 /// \param Sidx The attribute argument index to start checking with.
685 /// \param ParamIdxOk Whether an argument can be indexing into a function
686 /// parameter list.
687 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
688  const ParsedAttr &AL,
690  unsigned Sidx = 0,
691  bool ParamIdxOk = false) {
692  if (Sidx == AL.getNumArgs()) {
693  // If we don't have any capability arguments, the attribute implicitly
694  // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're
695  // a non-static method, and that the class is a (scoped) capability.
696  const auto *MD = dyn_cast<const CXXMethodDecl>(D);
697  if (MD && !MD->isStatic()) {
698  const CXXRecordDecl *RD = MD->getParent();
699  // FIXME -- need to check this again on template instantiation
700  if (!checkRecordDeclForAttr<CapabilityAttr>(RD) &&
701  !checkRecordDeclForAttr<ScopedLockableAttr>(RD))
702  S.Diag(AL.getLoc(),
703  diag::warn_thread_attribute_not_on_capability_member)
704  << AL << MD->getParent();
705  } else {
706  S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member)
707  << AL;
708  }
709  }
710 
711  for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) {
712  Expr *ArgExp = AL.getArgAsExpr(Idx);
713 
714  if (ArgExp->isTypeDependent()) {
715  // FIXME -- need to check this again on template instantiation
716  Args.push_back(ArgExp);
717  continue;
718  }
719 
720  if (const auto *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
721  if (StrLit->getLength() == 0 ||
722  (StrLit->isOrdinary() && StrLit->getString() == "*")) {
723  // Pass empty strings to the analyzer without warnings.
724  // Treat "*" as the universal lock.
725  Args.push_back(ArgExp);
726  continue;
727  }
728 
729  // We allow constant strings to be used as a placeholder for expressions
730  // that are not valid C++ syntax, but warn that they are ignored.
731  S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL;
732  Args.push_back(ArgExp);
733  continue;
734  }
735 
736  QualType ArgTy = ArgExp->getType();
737 
738  // A pointer to member expression of the form &MyClass::mu is treated
739  // specially -- we need to look at the type of the member.
740  if (const auto *UOp = dyn_cast<UnaryOperator>(ArgExp))
741  if (UOp->getOpcode() == UO_AddrOf)
742  if (const auto *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
743  if (DRE->getDecl()->isCXXInstanceMember())
744  ArgTy = DRE->getDecl()->getType();
745 
746  // First see if we can just cast to record type, or pointer to record type.
747  const RecordType *RT = getRecordType(ArgTy);
748 
749  // Now check if we index into a record type function param.
750  if(!RT && ParamIdxOk) {
751  const auto *FD = dyn_cast<FunctionDecl>(D);
752  const auto *IL = dyn_cast<IntegerLiteral>(ArgExp);
753  if(FD && IL) {
754  unsigned int NumParams = FD->getNumParams();
755  llvm::APInt ArgValue = IL->getValue();
756  uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
757  uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
758  if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
759  S.Diag(AL.getLoc(),
760  diag::err_attribute_argument_out_of_bounds_extra_info)
761  << AL << Idx + 1 << NumParams;
762  continue;
763  }
764  ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
765  }
766  }
767 
768  // If the type does not have a capability, see if the components of the
769  // expression have capabilities. This allows for writing C code where the
770  // capability may be on the type, and the expression is a capability
771  // boolean logic expression. Eg) requires_capability(A || B && !C)
772  if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
773  S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
774  << AL << ArgTy;
775 
776  Args.push_back(ArgExp);
777  }
778 }
779 
780 //===----------------------------------------------------------------------===//
781 // Attribute Implementations
782 //===----------------------------------------------------------------------===//
783 
784 static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
785  if (!threadSafetyCheckIsPointer(S, D, AL))
786  return;
787 
788  D->addAttr(::new (S.Context) PtGuardedVarAttr(S.Context, AL));
789 }
790 
791 static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
792  Expr *&Arg) {
794  // check that all arguments are lockable objects
795  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
796  unsigned Size = Args.size();
797  if (Size != 1)
798  return false;
799 
800  Arg = Args[0];
801 
802  return true;
803 }
804 
805 static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
806  Expr *Arg = nullptr;
807  if (!checkGuardedByAttrCommon(S, D, AL, Arg))
808  return;
809 
810  D->addAttr(::new (S.Context) GuardedByAttr(S.Context, AL, Arg));
811 }
812 
813 static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
814  Expr *Arg = nullptr;
815  if (!checkGuardedByAttrCommon(S, D, AL, Arg))
816  return;
817 
818  if (!threadSafetyCheckIsPointer(S, D, AL))
819  return;
820 
821  D->addAttr(::new (S.Context) PtGuardedByAttr(S.Context, AL, Arg));
822 }
823 
824 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
825  SmallVectorImpl<Expr *> &Args) {
826  if (!AL.checkAtLeastNumArgs(S, 1))
827  return false;
828 
829  // Check that this attribute only applies to lockable types.
830  QualType QT = cast<ValueDecl>(D)->getType();
831  if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
832  S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable) << AL;
833  return false;
834  }
835 
836  // Check that all arguments are lockable objects.
837  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
838  if (Args.empty())
839  return false;
840 
841  return true;
842 }
843 
844 static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
846  if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
847  return;
848 
849  Expr **StartArg = &Args[0];
850  D->addAttr(::new (S.Context)
851  AcquiredAfterAttr(S.Context, AL, StartArg, Args.size()));
852 }
853 
854 static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
856  if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
857  return;
858 
859  Expr **StartArg = &Args[0];
860  D->addAttr(::new (S.Context)
861  AcquiredBeforeAttr(S.Context, AL, StartArg, Args.size()));
862 }
863 
864 static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
865  SmallVectorImpl<Expr *> &Args) {
866  // zero or more arguments ok
867  // check that all arguments are lockable objects
868  checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, /*ParamIdxOk=*/true);
869 
870  return true;
871 }
872 
873 static void handleAssertSharedLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
875  if (!checkLockFunAttrCommon(S, D, AL, Args))
876  return;
877 
878  unsigned Size = Args.size();
879  Expr **StartArg = Size == 0 ? nullptr : &Args[0];
880  D->addAttr(::new (S.Context)
881  AssertSharedLockAttr(S.Context, AL, StartArg, Size));
882 }
883 
884 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
885  const ParsedAttr &AL) {
887  if (!checkLockFunAttrCommon(S, D, AL, Args))
888  return;
889 
890  unsigned Size = Args.size();
891  Expr **StartArg = Size == 0 ? nullptr : &Args[0];
892  D->addAttr(::new (S.Context)
893  AssertExclusiveLockAttr(S.Context, AL, StartArg, Size));
894 }
895 
896 /// Checks to be sure that the given parameter number is in bounds, and
897 /// is an integral type. Will emit appropriate diagnostics if this returns
898 /// false.
899 ///
900 /// AttrArgNo is used to actually retrieve the argument, so it's base-0.
901 template <typename AttrInfo>
902 static bool checkParamIsIntegerType(Sema &S, const Decl *D, const AttrInfo &AI,
903  unsigned AttrArgNo) {
904  assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument");
905  Expr *AttrArg = AI.getArgAsExpr(AttrArgNo);
906  ParamIdx Idx;
907  if (!checkFunctionOrMethodParameterIndex(S, D, AI, AttrArgNo + 1, AttrArg,
908  Idx))
909  return false;
910 
912  if (!ParamTy->isIntegerType() && !ParamTy->isCharType()) {
913  SourceLocation SrcLoc = AttrArg->getBeginLoc();
914  S.Diag(SrcLoc, diag::err_attribute_integers_only)
915  << AI << getFunctionOrMethodParamRange(D, Idx.getASTIndex());
916  return false;
917  }
918  return true;
919 }
920 
921 static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
922  if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2))
923  return;
924 
925  assert(isFunctionOrMethod(D) && hasFunctionProto(D));
926 
928  if (!RetTy->isPointerType()) {
929  S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL;
930  return;
931  }
932 
933  const Expr *SizeExpr = AL.getArgAsExpr(0);
934  int SizeArgNoVal;
935  // Parameter indices are 1-indexed, hence Index=1
936  if (!checkPositiveIntArgument(S, AL, SizeExpr, SizeArgNoVal, /*Idx=*/1))
937  return;
938  if (!checkParamIsIntegerType(S, D, AL, /*AttrArgNo=*/0))
939  return;
940  ParamIdx SizeArgNo(SizeArgNoVal, D);
941 
942  ParamIdx NumberArgNo;
943  if (AL.getNumArgs() == 2) {
944  const Expr *NumberExpr = AL.getArgAsExpr(1);
945  int Val;
946  // Parameter indices are 1-based, hence Index=2
947  if (!checkPositiveIntArgument(S, AL, NumberExpr, Val, /*Idx=*/2))
948  return;
949  if (!checkParamIsIntegerType(S, D, AL, /*AttrArgNo=*/1))
950  return;
951  NumberArgNo = ParamIdx(Val, D);
952  }
953 
954  D->addAttr(::new (S.Context)
955  AllocSizeAttr(S.Context, AL, SizeArgNo, NumberArgNo));
956 }
957 
958 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
959  SmallVectorImpl<Expr *> &Args) {
960  if (!AL.checkAtLeastNumArgs(S, 1))
961  return false;
962 
963  if (!isIntOrBool(AL.getArgAsExpr(0))) {
964  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
965  << AL << 1 << AANT_ArgumentIntOrBool;
966  return false;
967  }
968 
969  // check that all arguments are lockable objects
970  checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 1);
971 
972  return true;
973 }
974 
975 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
976  const ParsedAttr &AL) {
978  if (!checkTryLockFunAttrCommon(S, D, AL, Args))
979  return;
980 
981  D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(
982  S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
983 }
984 
985 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
986  const ParsedAttr &AL) {
988  if (!checkTryLockFunAttrCommon(S, D, AL, Args))
989  return;
990 
991  D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
992  S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
993 }
994 
995 static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
996  // check that the argument is lockable object
998  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
999  unsigned Size = Args.size();
1000  if (Size == 0)
1001  return;
1002 
1003  D->addAttr(::new (S.Context) LockReturnedAttr(S.Context, AL, Args[0]));
1004 }
1005 
1006 static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1007  if (!AL.checkAtLeastNumArgs(S, 1))
1008  return;
1009 
1010  // check that all arguments are lockable objects
1011  SmallVector<Expr*, 1> Args;
1012  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
1013  unsigned Size = Args.size();
1014  if (Size == 0)
1015  return;
1016  Expr **StartArg = &Args[0];
1017 
1018  D->addAttr(::new (S.Context)
1019  LocksExcludedAttr(S.Context, AL, StartArg, Size));
1020 }
1021 
1022 static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL,
1023  Expr *&Cond, StringRef &Msg) {
1024  Cond = AL.getArgAsExpr(0);
1025  if (!Cond->isTypeDependent()) {
1026  ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
1027  if (Converted.isInvalid())
1028  return false;
1029  Cond = Converted.get();
1030  }
1031 
1032  if (!S.checkStringLiteralArgumentAttr(AL, 1, Msg))
1033  return false;
1034 
1035  if (Msg.empty())
1036  Msg = "<no message provided>";
1037 
1039  if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
1040  !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
1041  Diags)) {
1042  S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr) << AL;
1043  for (const PartialDiagnosticAt &PDiag : Diags)
1044  S.Diag(PDiag.first, PDiag.second);
1045  return false;
1046  }
1047  return true;
1048 }
1049 
1050 static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1051  S.Diag(AL.getLoc(), diag::ext_clang_enable_if);
1052 
1053  Expr *Cond;
1054  StringRef Msg;
1055  if (checkFunctionConditionAttr(S, D, AL, Cond, Msg))
1056  D->addAttr(::new (S.Context) EnableIfAttr(S.Context, AL, Cond, Msg));
1057 }
1058 
1059 static void handleErrorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1060  StringRef NewUserDiagnostic;
1061  if (!S.checkStringLiteralArgumentAttr(AL, 0, NewUserDiagnostic))
1062  return;
1063  if (ErrorAttr *EA = S.mergeErrorAttr(D, AL, NewUserDiagnostic))
1064  D->addAttr(EA);
1065 }
1066 
1067 static void handleExcludeFromExplicitInstantiationAttr(Sema &S, Decl *D,
1068  const ParsedAttr &AL) {
1069  const auto *PD = isa<CXXRecordDecl>(D)
1070  ? cast<DeclContext>(D)
1071  : D->getDeclContext()->getRedeclContext();
1072  if (const auto *RD = dyn_cast<CXXRecordDecl>(PD); RD && RD->isLocalClass()) {
1073  S.Diag(AL.getLoc(),
1074  diag::warn_attribute_exclude_from_explicit_instantiation_local_class)
1075  << AL << /*IsMember=*/!isa<CXXRecordDecl>(D);
1076  return;
1077  }
1078  D->addAttr(::new (S.Context)
1079  ExcludeFromExplicitInstantiationAttr(S.Context, AL));
1080 }
1081 
1082 namespace {
1083 /// Determines if a given Expr references any of the given function's
1084 /// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
1085 class ArgumentDependenceChecker
1086  : public RecursiveASTVisitor<ArgumentDependenceChecker> {
1087 #ifndef NDEBUG
1088  const CXXRecordDecl *ClassType;
1089 #endif
1091  bool Result;
1092 
1093 public:
1094  ArgumentDependenceChecker(const FunctionDecl *FD) {
1095 #ifndef NDEBUG
1096  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1097  ClassType = MD->getParent();
1098  else
1099  ClassType = nullptr;
1100 #endif
1101  Parms.insert(FD->param_begin(), FD->param_end());
1102  }
1103 
1104  bool referencesArgs(Expr *E) {
1105  Result = false;
1106  TraverseStmt(E);
1107  return Result;
1108  }
1109 
1110  bool VisitCXXThisExpr(CXXThisExpr *E) {
1111  assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
1112  "`this` doesn't refer to the enclosing class?");
1113  Result = true;
1114  return false;
1115  }
1116 
1117  bool VisitDeclRefExpr(DeclRefExpr *DRE) {
1118  if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
1119  if (Parms.count(PVD)) {
1120  Result = true;
1121  return false;
1122  }
1123  return true;
1124  }
1125 };
1126 }
1127 
1128 static void handleDiagnoseAsBuiltinAttr(Sema &S, Decl *D,
1129  const ParsedAttr &AL) {
1130  const auto *DeclFD = cast<FunctionDecl>(D);
1131 
1132  if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(DeclFD))
1133  if (!MethodDecl->isStatic()) {
1134  S.Diag(AL.getLoc(), diag::err_attribute_no_member_function) << AL;
1135  return;
1136  }
1137 
1138  auto DiagnoseType = [&](unsigned Index, AttributeArgumentNType T) {
1139  SourceLocation Loc = [&]() {
1140  auto Union = AL.getArg(Index - 1);
1141  if (Union.is<Expr *>())
1142  return Union.get<Expr *>()->getBeginLoc();
1143  return Union.get<IdentifierLoc *>()->Loc;
1144  }();
1145 
1146  S.Diag(Loc, diag::err_attribute_argument_n_type) << AL << Index << T;
1147  };
1148 
1149  FunctionDecl *AttrFD = [&]() -> FunctionDecl * {
1150  if (!AL.isArgExpr(0))
1151  return nullptr;
1152  auto *F = dyn_cast_if_present<DeclRefExpr>(AL.getArgAsExpr(0));
1153  if (!F)
1154  return nullptr;
1155  return dyn_cast_if_present<FunctionDecl>(F->getFoundDecl());
1156  }();
1157 
1158  if (!AttrFD || !AttrFD->getBuiltinID(true)) {
1159  DiagnoseType(1, AANT_ArgumentBuiltinFunction);
1160  return;
1161  }
1162 
1163  if (AttrFD->getNumParams() != AL.getNumArgs() - 1) {
1164  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments_for)
1165  << AL << AttrFD << AttrFD->getNumParams();
1166  return;
1167  }
1168 
1169  SmallVector<unsigned, 8> Indices;
1170 
1171  for (unsigned I = 1; I < AL.getNumArgs(); ++I) {
1172  if (!AL.isArgExpr(I)) {
1173  DiagnoseType(I + 1, AANT_ArgumentIntegerConstant);
1174  return;
1175  }
1176 
1177  const Expr *IndexExpr = AL.getArgAsExpr(I);
1178  uint32_t Index;
1179 
1180  if (!checkUInt32Argument(S, AL, IndexExpr, Index, I + 1, false))
1181  return;
1182 
1183  if (Index > DeclFD->getNumParams()) {
1184  S.Diag(AL.getLoc(), diag::err_attribute_bounds_for_function)
1185  << AL << Index << DeclFD << DeclFD->getNumParams();
1186  return;
1187  }
1188 
1189  QualType T1 = AttrFD->getParamDecl(I - 1)->getType();
1190  QualType T2 = DeclFD->getParamDecl(Index - 1)->getType();
1191 
1192  if (T1.getCanonicalType().getUnqualifiedType() !=
1194  S.Diag(IndexExpr->getBeginLoc(), diag::err_attribute_parameter_types)
1195  << AL << Index << DeclFD << T2 << I << AttrFD << T1;
1196  return;
1197  }
1198 
1199  Indices.push_back(Index - 1);
1200  }
1201 
1202  D->addAttr(::new (S.Context) DiagnoseAsBuiltinAttr(
1203  S.Context, AL, AttrFD, Indices.data(), Indices.size()));
1204 }
1205 
1206 static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1207  S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if);
1208 
1209  Expr *Cond;
1210  StringRef Msg;
1211  if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg))
1212  return;
1213 
1214  StringRef DiagTypeStr;
1215  if (!S.checkStringLiteralArgumentAttr(AL, 2, DiagTypeStr))
1216  return;
1217 
1218  DiagnoseIfAttr::DiagnosticType DiagType;
1219  if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
1220  S.Diag(AL.getArgAsExpr(2)->getBeginLoc(),
1221  diag::err_diagnose_if_invalid_diagnostic_type);
1222  return;
1223  }
1224 
1225  bool ArgDependent = false;
1226  if (const auto *FD = dyn_cast<FunctionDecl>(D))
1227  ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
1228  D->addAttr(::new (S.Context) DiagnoseIfAttr(
1229  S.Context, AL, Cond, Msg, DiagType, ArgDependent, cast<NamedDecl>(D)));
1230 }
1231 
1232 static void handleNoBuiltinAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1233  static constexpr const StringRef kWildcard = "*";
1234 
1236  bool HasWildcard = false;
1237 
1238  const auto AddBuiltinName = [&Names, &HasWildcard](StringRef Name) {
1239  if (Name == kWildcard)
1240  HasWildcard = true;
1241  Names.push_back(Name);
1242  };
1243 
1244  // Add previously defined attributes.
1245  if (const auto *NBA = D->getAttr<NoBuiltinAttr>())
1246  for (StringRef BuiltinName : NBA->builtinNames())
1247  AddBuiltinName(BuiltinName);
1248 
1249  // Add current attributes.
1250  if (AL.getNumArgs() == 0)
1251  AddBuiltinName(kWildcard);
1252  else
1253  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
1254  StringRef BuiltinName;
1255  SourceLocation LiteralLoc;
1256  if (!S.checkStringLiteralArgumentAttr(AL, I, BuiltinName, &LiteralLoc))
1257  return;
1258 
1259  if (Builtin::Context::isBuiltinFunc(BuiltinName))
1260  AddBuiltinName(BuiltinName);
1261  else
1262  S.Diag(LiteralLoc, diag::warn_attribute_no_builtin_invalid_builtin_name)
1263  << BuiltinName << AL;
1264  }
1265 
1266  // Repeating the same attribute is fine.
1267  llvm::sort(Names);
1268  Names.erase(std::unique(Names.begin(), Names.end()), Names.end());
1269 
1270  // Empty no_builtin must be on its own.
1271  if (HasWildcard && Names.size() > 1)
1272  S.Diag(D->getLocation(),
1273  diag::err_attribute_no_builtin_wildcard_or_builtin_name)
1274  << AL;
1275 
1276  if (D->hasAttr<NoBuiltinAttr>())
1277  D->dropAttr<NoBuiltinAttr>();
1278  D->addAttr(::new (S.Context)
1279  NoBuiltinAttr(S.Context, AL, Names.data(), Names.size()));
1280 }
1281 
1282 static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1283  if (D->hasAttr<PassObjectSizeAttr>()) {
1284  S.Diag(D->getBeginLoc(), diag::err_attribute_only_once_per_parameter) << AL;
1285  return;
1286  }
1287 
1288  Expr *E = AL.getArgAsExpr(0);
1289  uint32_t Type;
1290  if (!checkUInt32Argument(S, AL, E, Type, /*Idx=*/1))
1291  return;
1292 
1293  // pass_object_size's argument is passed in as the second argument of
1294  // __builtin_object_size. So, it has the same constraints as that second
1295  // argument; namely, it must be in the range [0, 3].
1296  if (Type > 3) {
1297  S.Diag(E->getBeginLoc(), diag::err_attribute_argument_out_of_range)
1298  << AL << 0 << 3 << E->getSourceRange();
1299  return;
1300  }
1301 
1302  // pass_object_size is only supported on constant pointer parameters; as a
1303  // kindness to users, we allow the parameter to be non-const for declarations.
1304  // At this point, we have no clue if `D` belongs to a function declaration or
1305  // definition, so we defer the constness check until later.
1306  if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1307  S.Diag(D->getBeginLoc(), diag::err_attribute_pointers_only) << AL << 1;
1308  return;
1309  }
1310 
1311  D->addAttr(::new (S.Context) PassObjectSizeAttr(S.Context, AL, (int)Type));
1312 }
1313 
1314 static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1315  ConsumableAttr::ConsumedState DefaultState;
1316 
1317  if (AL.isArgIdent(0)) {
1318  IdentifierLoc *IL = AL.getArgAsIdent(0);
1319  if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1320  DefaultState)) {
1321  S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1322  << IL->Ident;
1323  return;
1324  }
1325  } else {
1326  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1327  << AL << AANT_ArgumentIdentifier;
1328  return;
1329  }
1330 
1331  D->addAttr(::new (S.Context) ConsumableAttr(S.Context, AL, DefaultState));
1332 }
1333 
1334 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1335  const ParsedAttr &AL) {
1336  QualType ThisType = MD->getFunctionObjectParameterType();
1337 
1338  if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1339  if (!RD->hasAttr<ConsumableAttr>()) {
1340  S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) << RD;
1341 
1342  return false;
1343  }
1344  }
1345 
1346  return true;
1347 }
1348 
1349 static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1350  if (!AL.checkAtLeastNumArgs(S, 1))
1351  return;
1352 
1353  if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1354  return;
1355 
1357  for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
1358  CallableWhenAttr::ConsumedState CallableState;
1359 
1360  StringRef StateString;
1362  if (AL.isArgIdent(ArgIndex)) {
1363  IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
1364  StateString = Ident->Ident->getName();
1365  Loc = Ident->Loc;
1366  } else {
1367  if (!S.checkStringLiteralArgumentAttr(AL, ArgIndex, StateString, &Loc))
1368  return;
1369  }
1370 
1371  if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1372  CallableState)) {
1373  S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << StateString;
1374  return;
1375  }
1376 
1377  States.push_back(CallableState);
1378  }
1379 
1380  D->addAttr(::new (S.Context)
1381  CallableWhenAttr(S.Context, AL, States.data(), States.size()));
1382 }
1383 
1384 static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1386 
1387  if (AL.isArgIdent(0)) {
1388  IdentifierLoc *Ident = AL.getArgAsIdent(0);
1389  StringRef StateString = Ident->Ident->getName();
1390 
1391  if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1392  ParamState)) {
1393  S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1394  << AL << StateString;
1395  return;
1396  }
1397  } else {
1398  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1399  << AL << AANT_ArgumentIdentifier;
1400  return;
1401  }
1402 
1403  // FIXME: This check is currently being done in the analysis. It can be
1404  // enabled here only after the parser propagates attributes at
1405  // template specialization definition, not declaration.
1406  //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1407  //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1408  //
1409  //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1410  // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1411  // ReturnType.getAsString();
1412  // return;
1413  //}
1414 
1415  D->addAttr(::new (S.Context) ParamTypestateAttr(S.Context, AL, ParamState));
1416 }
1417 
1418 static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1420 
1421  if (AL.isArgIdent(0)) {
1422  IdentifierLoc *IL = AL.getArgAsIdent(0);
1423  if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1424  ReturnState)) {
1425  S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1426  << IL->Ident;
1427  return;
1428  }
1429  } else {
1430  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1431  << AL << AANT_ArgumentIdentifier;
1432  return;
1433  }
1434 
1435  // FIXME: This check is currently being done in the analysis. It can be
1436  // enabled here only after the parser propagates attributes at
1437  // template specialization definition, not declaration.
1438  // QualType ReturnType;
1439  //
1440  // if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1441  // ReturnType = Param->getType();
1442  //
1443  //} else if (const CXXConstructorDecl *Constructor =
1444  // dyn_cast<CXXConstructorDecl>(D)) {
1445  // ReturnType = Constructor->getFunctionObjectParameterType();
1446  //
1447  //} else {
1448  //
1449  // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1450  //}
1451  //
1452  // const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1453  //
1454  // if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1455  // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1456  // ReturnType.getAsString();
1457  // return;
1458  //}
1459 
1460  D->addAttr(::new (S.Context) ReturnTypestateAttr(S.Context, AL, ReturnState));
1461 }
1462 
1463 static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1464  if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1465  return;
1466 
1468  if (AL.isArgIdent(0)) {
1469  IdentifierLoc *Ident = AL.getArgAsIdent(0);
1470  StringRef Param = Ident->Ident->getName();
1471  if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1472  S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1473  << Param;
1474  return;
1475  }
1476  } else {
1477  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1478  << AL << AANT_ArgumentIdentifier;
1479  return;
1480  }
1481 
1482  D->addAttr(::new (S.Context) SetTypestateAttr(S.Context, AL, NewState));
1483 }
1484 
1485 static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1486  if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1487  return;
1488 
1490  if (AL.isArgIdent(0)) {
1491  IdentifierLoc *Ident = AL.getArgAsIdent(0);
1492  StringRef Param = Ident->Ident->getName();
1493  if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1494  S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1495  << Param;
1496  return;
1497  }
1498  } else {
1499  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1500  << AL << AANT_ArgumentIdentifier;
1501  return;
1502  }
1503 
1504  D->addAttr(::new (S.Context) TestTypestateAttr(S.Context, AL, TestState));
1505 }
1506 
1507 static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1508  // Remember this typedef decl, we will need it later for diagnostics.
1509  S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1510 }
1511 
1512 static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1513  if (auto *TD = dyn_cast<TagDecl>(D))
1514  TD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1515  else if (auto *FD = dyn_cast<FieldDecl>(D)) {
1516  bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
1517  !FD->getType()->isIncompleteType() &&
1518  FD->isBitField() &&
1519  S.Context.getTypeAlign(FD->getType()) <= 8);
1520 
1521  if (S.getASTContext().getTargetInfo().getTriple().isPS()) {
1522  if (BitfieldByteAligned)
1523  // The PS4/PS5 targets need to maintain ABI backwards compatibility.
1524  S.Diag(AL.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1525  << AL << FD->getType();
1526  else
1527  FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1528  } else {
1529  // Report warning about changed offset in the newer compiler versions.
1530  if (BitfieldByteAligned)
1531  S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield);
1532 
1533  FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1534  }
1535 
1536  } else
1537  S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
1538 }
1539 
1540 static void handlePreferredName(Sema &S, Decl *D, const ParsedAttr &AL) {
1541  auto *RD = cast<CXXRecordDecl>(D);
1543  assert(CTD && "attribute does not appertain to this declaration");
1544 
1545  ParsedType PT = AL.getTypeArg();
1546  TypeSourceInfo *TSI = nullptr;
1547  QualType T = S.GetTypeFromParser(PT, &TSI);
1548  if (!TSI)
1549  TSI = S.Context.getTrivialTypeSourceInfo(T, AL.getLoc());
1550 
1551  if (!T.hasQualifiers() && T->isTypedefNameType()) {
1552  // Find the template name, if this type names a template specialization.
1553  const TemplateDecl *Template = nullptr;
1554  if (const auto *CTSD = dyn_cast_if_present<ClassTemplateSpecializationDecl>(
1555  T->getAsCXXRecordDecl())) {
1556  Template = CTSD->getSpecializedTemplate();
1557  } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
1558  while (TST && TST->isTypeAlias())
1559  TST = TST->getAliasedType()->getAs<TemplateSpecializationType>();
1560  if (TST)
1561  Template = TST->getTemplateName().getAsTemplateDecl();
1562  }
1563 
1564  if (Template && declaresSameEntity(Template, CTD)) {
1565  D->addAttr(::new (S.Context) PreferredNameAttr(S.Context, AL, TSI));
1566  return;
1567  }
1568  }
1569 
1570  S.Diag(AL.getLoc(), diag::err_attribute_preferred_name_arg_invalid)
1571  << T << CTD;
1572  if (const auto *TT = T->getAs<TypedefType>())
1573  S.Diag(TT->getDecl()->getLocation(), diag::note_entity_declared_at)
1574  << TT->getDecl();
1575 }
1576 
1577 static bool checkIBOutletCommon(Sema &S, Decl *D, const ParsedAttr &AL) {
1578  // The IBOutlet/IBOutletCollection attributes only apply to instance
1579  // variables or properties of Objective-C classes. The outlet must also
1580  // have an object reference type.
1581  if (const auto *VD = dyn_cast<ObjCIvarDecl>(D)) {
1582  if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1583  S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1584  << AL << VD->getType() << 0;
1585  return false;
1586  }
1587  }
1588  else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1589  if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1590  S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1591  << AL << PD->getType() << 1;
1592  return false;
1593  }
1594  }
1595  else {
1596  S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL;
1597  return false;
1598  }
1599 
1600  return true;
1601 }
1602 
1603 static void handleIBOutlet(Sema &S, Decl *D, const ParsedAttr &AL) {
1604  if (!checkIBOutletCommon(S, D, AL))
1605  return;
1606 
1607  D->addAttr(::new (S.Context) IBOutletAttr(S.Context, AL));
1608 }
1609 
1610 static void handleIBOutletCollection(Sema &S, Decl *D, const ParsedAttr &AL) {
1611 
1612  // The iboutletcollection attribute can have zero or one arguments.
1613  if (AL.getNumArgs() > 1) {
1614  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1615  return;
1616  }
1617 
1618  if (!checkIBOutletCommon(S, D, AL))
1619  return;
1620 
1621  ParsedType PT;
1622 
1623  if (AL.hasParsedType())
1624  PT = AL.getTypeArg();
1625  else {
1626  PT = S.getTypeName(S.Context.Idents.get("NSObject"), AL.getLoc(),
1628  if (!PT) {
1629  S.Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1630  return;
1631  }
1632  }
1633 
1634  TypeSourceInfo *QTLoc = nullptr;
1635  QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1636  if (!QTLoc)
1637  QTLoc = S.Context.getTrivialTypeSourceInfo(QT, AL.getLoc());
1638 
1639  // Diagnose use of non-object type in iboutletcollection attribute.
1640  // FIXME. Gnu attribute extension ignores use of builtin types in
1641  // attributes. So, __attribute__((iboutletcollection(char))) will be
1642  // treated as __attribute__((iboutletcollection())).
1643  if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1644  S.Diag(AL.getLoc(),
1645  QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1646  : diag::err_iboutletcollection_type) << QT;
1647  return;
1648  }
1649 
1650  D->addAttr(::new (S.Context) IBOutletCollectionAttr(S.Context, AL, QTLoc));
1651 }
1652 
1653 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1654  if (RefOkay) {
1655  if (T->isReferenceType())
1656  return true;
1657  } else {
1658  T = T.getNonReferenceType();
1659  }
1660 
1661  // The nonnull attribute, and other similar attributes, can be applied to a
1662  // transparent union that contains a pointer type.
1663  if (const RecordType *UT = T->getAsUnionType()) {
1664  if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1665  RecordDecl *UD = UT->getDecl();
1666  for (const auto *I : UD->fields()) {
1667  QualType QT = I->getType();
1668  if (QT->isAnyPointerType() || QT->isBlockPointerType())
1669  return true;
1670  }
1671  }
1672  }
1673 
1674  return T->isAnyPointerType() || T->isBlockPointerType();
1675 }
1676 
1677 static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL,
1678  SourceRange AttrParmRange,
1679  SourceRange TypeRange,
1680  bool isReturnValue = false) {
1681  if (!S.isValidPointerAttrType(T)) {
1682  if (isReturnValue)
1683  S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1684  << AL << AttrParmRange << TypeRange;
1685  else
1686  S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1687  << AL << AttrParmRange << TypeRange << 0;
1688  return false;
1689  }
1690  return true;
1691 }
1692 
1693 static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1694  SmallVector<ParamIdx, 8> NonNullArgs;
1695  for (unsigned I = 0; I < AL.getNumArgs(); ++I) {
1696  Expr *Ex = AL.getArgAsExpr(I);
1697  ParamIdx Idx;
1698  if (!checkFunctionOrMethodParameterIndex(S, D, AL, I + 1, Ex, Idx))
1699  return;
1700 
1701  // Is the function argument a pointer type?
1702  if (Idx.getASTIndex() < getFunctionOrMethodNumParams(D) &&
1703  !attrNonNullArgCheck(
1704  S, getFunctionOrMethodParamType(D, Idx.getASTIndex()), AL,
1705  Ex->getSourceRange(),
1707  continue;
1708 
1709  NonNullArgs.push_back(Idx);
1710  }
1711 
1712  // If no arguments were specified to __attribute__((nonnull)) then all pointer
1713  // arguments have a nonnull attribute; warn if there aren't any. Skip this
1714  // check if the attribute came from a macro expansion or a template
1715  // instantiation.
1716  if (NonNullArgs.empty() && AL.getLoc().isFileID() &&
1717  !S.inTemplateInstantiation()) {
1718  bool AnyPointers = isFunctionOrMethodVariadic(D);
1719  for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1720  I != E && !AnyPointers; ++I) {
1723  AnyPointers = true;
1724  }
1725 
1726  if (!AnyPointers)
1727  S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1728  }
1729 
1730  ParamIdx *Start = NonNullArgs.data();
1731  unsigned Size = NonNullArgs.size();
1732  llvm::array_pod_sort(Start, Start + Size);
1733  D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, Start, Size));
1734 }
1735 
1736 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1737  const ParsedAttr &AL) {
1738  if (AL.getNumArgs() > 0) {
1739  if (D->getFunctionType()) {
1740  handleNonNullAttr(S, D, AL);
1741  } else {
1742  S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1743  << D->getSourceRange();
1744  }
1745  return;
1746  }
1747 
1748  // Is the argument a pointer type?
1749  if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(),
1750  D->getSourceRange()))
1751  return;
1752 
1753  D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, nullptr, 0));
1754 }
1755 
1756 static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1757  QualType ResultType = getFunctionOrMethodResultType(D);
1759  if (!attrNonNullArgCheck(S, ResultType, AL, SourceRange(), SR,
1760  /* isReturnValue */ true))
1761  return;
1762 
1763  D->addAttr(::new (S.Context) ReturnsNonNullAttr(S.Context, AL));
1764 }
1765 
1766 static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1767  if (D->isInvalidDecl())
1768  return;
1769 
1770  // noescape only applies to pointer types.
1771  QualType T = cast<ParmVarDecl>(D)->getType();
1772  if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
1773  S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1774  << AL << AL.getRange() << 0;
1775  return;
1776  }
1777 
1778  D->addAttr(::new (S.Context) NoEscapeAttr(S.Context, AL));
1779 }
1780 
1781 static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1782  Expr *E = AL.getArgAsExpr(0),
1783  *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr;
1784  S.AddAssumeAlignedAttr(D, AL, E, OE);
1785 }
1786 
1787 static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1788  S.AddAllocAlignAttr(D, AL, AL.getArgAsExpr(0));
1789 }
1790 
1792  Expr *OE) {
1793  QualType ResultType = getFunctionOrMethodResultType(D);
1795 
1796  AssumeAlignedAttr TmpAttr(Context, CI, E, OE);
1797  SourceLocation AttrLoc = TmpAttr.getLocation();
1798 
1799  if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1800  Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1801  << &TmpAttr << TmpAttr.getRange() << SR;
1802  return;
1803  }
1804 
1805  if (!E->isValueDependent()) {
1806  std::optional<llvm::APSInt> I = llvm::APSInt(64);
1807  if (!(I = E->getIntegerConstantExpr(Context))) {
1808  if (OE)
1809  Diag(AttrLoc, diag::err_attribute_argument_n_type)
1810  << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1811  << E->getSourceRange();
1812  else
1813  Diag(AttrLoc, diag::err_attribute_argument_type)
1814  << &TmpAttr << AANT_ArgumentIntegerConstant
1815  << E->getSourceRange();
1816  return;
1817  }
1818 
1819  if (!I->isPowerOf2()) {
1820  Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1821  << E->getSourceRange();
1822  return;
1823  }
1824 
1825  if (*I > Sema::MaximumAlignment)
1826  Diag(CI.getLoc(), diag::warn_assume_aligned_too_great)
1827  << CI.getRange() << Sema::MaximumAlignment;
1828  }
1829 
1830  if (OE && !OE->isValueDependent() && !OE->isIntegerConstantExpr(Context)) {
1831  Diag(AttrLoc, diag::err_attribute_argument_n_type)
1832  << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1833  << OE->getSourceRange();
1834  return;
1835  }
1836 
1837  D->addAttr(::new (Context) AssumeAlignedAttr(Context, CI, E, OE));
1838 }
1839 
1841  Expr *ParamExpr) {
1842  QualType ResultType = getFunctionOrMethodResultType(D);
1843 
1844  AllocAlignAttr TmpAttr(Context, CI, ParamIdx());
1845  SourceLocation AttrLoc = CI.getLoc();
1846 
1847  if (!ResultType->isDependentType() &&
1848  !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1849  Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1850  << &TmpAttr << CI.getRange() << getFunctionOrMethodResultSourceRange(D);
1851  return;
1852  }
1853 
1854  ParamIdx Idx;
1855  const auto *FuncDecl = cast<FunctionDecl>(D);
1856  if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
1857  /*AttrArgNum=*/1, ParamExpr, Idx))
1858  return;
1859 
1861  if (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
1862  !Ty->isAlignValT()) {
1863  Diag(ParamExpr->getBeginLoc(), diag::err_attribute_integers_only)
1864  << &TmpAttr
1865  << FuncDecl->getParamDecl(Idx.getASTIndex())->getSourceRange();
1866  return;
1867  }
1868 
1869  D->addAttr(::new (Context) AllocAlignAttr(Context, CI, Idx));
1870 }
1871 
1872 /// Check if \p AssumptionStr is a known assumption and warn if not.
1873 static void checkOMPAssumeAttr(Sema &S, SourceLocation Loc,
1874  StringRef AssumptionStr) {
1875  if (llvm::KnownAssumptionStrings.count(AssumptionStr))
1876  return;
1877 
1878  unsigned BestEditDistance = 3;
1879  StringRef Suggestion;
1880  for (const auto &KnownAssumptionIt : llvm::KnownAssumptionStrings) {
1881  unsigned EditDistance =
1882  AssumptionStr.edit_distance(KnownAssumptionIt.getKey());
1883  if (EditDistance < BestEditDistance) {
1884  Suggestion = KnownAssumptionIt.getKey();
1885  BestEditDistance = EditDistance;
1886  }
1887  }
1888 
1889  if (!Suggestion.empty())
1890  S.Diag(Loc, diag::warn_omp_assume_attribute_string_unknown_suggested)
1891  << AssumptionStr << Suggestion;
1892  else
1893  S.Diag(Loc, diag::warn_omp_assume_attribute_string_unknown)
1894  << AssumptionStr;
1895 }
1896 
1897 static void handleOMPAssumeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1898  // Handle the case where the attribute has a text message.
1899  StringRef Str;
1900  SourceLocation AttrStrLoc;
1901  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &AttrStrLoc))
1902  return;
1903 
1904  checkOMPAssumeAttr(S, AttrStrLoc, Str);
1905 
1906  D->addAttr(::new (S.Context) OMPAssumeAttr(S.Context, AL, Str));
1907 }
1908 
1909 /// Normalize the attribute, __foo__ becomes foo.
1910 /// Returns true if normalization was applied.
1911 static bool normalizeName(StringRef &AttrName) {
1912  if (AttrName.size() > 4 && AttrName.starts_with("__") &&
1913  AttrName.ends_with("__")) {
1914  AttrName = AttrName.drop_front(2).drop_back(2);
1915  return true;
1916  }
1917  return false;
1918 }
1919 
1920 static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1921  // This attribute must be applied to a function declaration. The first
1922  // argument to the attribute must be an identifier, the name of the resource,
1923  // for example: malloc. The following arguments must be argument indexes, the
1924  // arguments must be of integer type for Returns, otherwise of pointer type.
1925  // The difference between Holds and Takes is that a pointer may still be used
1926  // after being held. free() should be __attribute((ownership_takes)), whereas
1927  // a list append function may well be __attribute((ownership_holds)).
1928 
1929  if (!AL.isArgIdent(0)) {
1930  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1931  << AL << 1 << AANT_ArgumentIdentifier;
1932  return;
1933  }
1934 
1935  // Figure out our Kind.
1936  OwnershipAttr::OwnershipKind K =
1937  OwnershipAttr(S.Context, AL, nullptr, nullptr, 0).getOwnKind();
1938 
1939  // Check arguments.
1940  switch (K) {
1941  case OwnershipAttr::Takes:
1942  case OwnershipAttr::Holds:
1943  if (AL.getNumArgs() < 2) {
1944  S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << AL << 2;
1945  return;
1946  }
1947  break;
1948  case OwnershipAttr::Returns:
1949  if (AL.getNumArgs() > 2) {
1950  S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
1951  return;
1952  }
1953  break;
1954  }
1955 
1957 
1958  StringRef ModuleName = Module->getName();
1959  if (normalizeName(ModuleName)) {
1960  Module = &S.PP.getIdentifierTable().get(ModuleName);
1961  }
1962 
1963  SmallVector<ParamIdx, 8> OwnershipArgs;
1964  for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1965  Expr *Ex = AL.getArgAsExpr(i);
1966  ParamIdx Idx;
1967  if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1968  return;
1969 
1970  // Is the function argument a pointer type?
1972  int Err = -1; // No error
1973  switch (K) {
1974  case OwnershipAttr::Takes:
1975  case OwnershipAttr::Holds:
1976  if (!T->isAnyPointerType() && !T->isBlockPointerType())
1977  Err = 0;
1978  break;
1979  case OwnershipAttr::Returns:
1980  if (!T->isIntegerType())
1981  Err = 1;
1982  break;
1983  }
1984  if (-1 != Err) {
1985  S.Diag(AL.getLoc(), diag::err_ownership_type) << AL << Err
1986  << Ex->getSourceRange();
1987  return;
1988  }
1989 
1990  // Check we don't have a conflict with another ownership attribute.
1991  for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1992  // Cannot have two ownership attributes of different kinds for the same
1993  // index.
1994  if (I->getOwnKind() != K && llvm::is_contained(I->args(), Idx)) {
1995  S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1996  << AL << I
1997  << (AL.isRegularKeywordAttribute() ||
1998  I->isRegularKeywordAttribute());
1999  return;
2000  } else if (K == OwnershipAttr::Returns &&
2001  I->getOwnKind() == OwnershipAttr::Returns) {
2002  // A returns attribute conflicts with any other returns attribute using
2003  // a different index.
2004  if (!llvm::is_contained(I->args(), Idx)) {
2005  S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
2006  << I->args_begin()->getSourceIndex();
2007  if (I->args_size())
2008  S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
2009  << Idx.getSourceIndex() << Ex->getSourceRange();
2010  return;
2011  }
2012  }
2013  }
2014  OwnershipArgs.push_back(Idx);
2015  }
2016 
2017  ParamIdx *Start = OwnershipArgs.data();
2018  unsigned Size = OwnershipArgs.size();
2019  llvm::array_pod_sort(Start, Start + Size);
2020  D->addAttr(::new (S.Context)
2021  OwnershipAttr(S.Context, AL, Module, Start, Size));
2022 }
2023 
2024 static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2025  // Check the attribute arguments.
2026  if (AL.getNumArgs() > 1) {
2027  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
2028  return;
2029  }
2030 
2031  // gcc rejects
2032  // class c {
2033  // static int a __attribute__((weakref ("v2")));
2034  // static int b() __attribute__((weakref ("f3")));
2035  // };
2036  // and ignores the attributes of
2037  // void f(void) {
2038  // static int a __attribute__((weakref ("v2")));
2039  // }
2040  // we reject them
2041  const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
2042  if (!Ctx->isFileContext()) {
2043  S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context)
2044  << cast<NamedDecl>(D);
2045  return;
2046  }
2047 
2048  // The GCC manual says
2049  //
2050  // At present, a declaration to which `weakref' is attached can only
2051  // be `static'.
2052  //
2053  // It also says
2054  //
2055  // Without a TARGET,
2056  // given as an argument to `weakref' or to `alias', `weakref' is
2057  // equivalent to `weak'.
2058  //
2059  // gcc 4.4.1 will accept
2060  // int a7 __attribute__((weakref));
2061  // as
2062  // int a7 __attribute__((weak));
2063  // This looks like a bug in gcc. We reject that for now. We should revisit
2064  // it if this behaviour is actually used.
2065 
2066  // GCC rejects
2067  // static ((alias ("y"), weakref)).
2068  // Should we? How to check that weakref is before or after alias?
2069 
2070  // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
2071  // of transforming it into an AliasAttr. The WeakRefAttr never uses the
2072  // StringRef parameter it was given anyway.
2073  StringRef Str;
2074  if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, 0, Str))
2075  // GCC will accept anything as the argument of weakref. Should we
2076  // check for an existing decl?
2077  D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
2078 
2079  D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
2080 }
2081 
2082 // Mark alias/ifunc target as used. Due to name mangling, we look up the
2083 // demangled name ignoring parameters (not supported by microsoftDemangle
2084 // https://github.com/llvm/llvm-project/issues/88825). This should handle the
2085 // majority of use cases while leaving namespace scope names unmarked.
2086 static void markUsedForAliasOrIfunc(Sema &S, Decl *D, const ParsedAttr &AL,
2087  StringRef Str) {
2088  std::unique_ptr<char, llvm::FreeDeleter> Demangled;
2089  if (S.getASTContext().getCXXABIKind() != TargetCXXABI::Microsoft)
2090  Demangled.reset(llvm::itaniumDemangle(Str, /*ParseParams=*/false));
2091  std::unique_ptr<MangleContext> MC(S.Context.createMangleContext());
2092  SmallString<256> Name;
2093 
2095  &S.Context.Idents.get(Demangled ? Demangled.get() : Str), AL.getLoc());
2097  if (S.LookupName(LR, S.TUScope)) {
2098  for (NamedDecl *ND : LR) {
2099  if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND))
2100  continue;
2101  if (MC->shouldMangleDeclName(ND)) {
2102  llvm::raw_svector_ostream Out(Name);
2103  Name.clear();
2104  MC->mangleName(GlobalDecl(ND), Out);
2105  } else {
2106  Name = ND->getIdentifier()->getName();
2107  }
2108  if (Name == Str)
2109  ND->markUsed(S.Context);
2110  }
2111  }
2112 }
2113 
2114 static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2115  StringRef Str;
2116  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
2117  return;
2118 
2119  // Aliases should be on declarations, not definitions.
2120  const auto *FD = cast<FunctionDecl>(D);
2121  if (FD->isThisDeclarationADefinition()) {
2122  S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1;
2123  return;
2124  }
2125 
2126  markUsedForAliasOrIfunc(S, D, AL, Str);
2127  D->addAttr(::new (S.Context) IFuncAttr(S.Context, AL, Str));
2128 }
2129 
2130 static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2131  StringRef Str;
2132  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
2133  return;
2134 
2135  if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
2136  S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin);
2137  return;
2138  }
2139 
2140  if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
2141  CudaVersion Version =
2143  if (Version != CudaVersion::UNKNOWN && Version < CudaVersion::CUDA_100)
2144  S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx);
2145  }
2146 
2147  // Aliases should be on declarations, not definitions.
2148  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2149  if (FD->isThisDeclarationADefinition()) {
2150  S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0;
2151  return;
2152  }
2153  } else {
2154  const auto *VD = cast<VarDecl>(D);
2155  if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
2156  S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0;
2157  return;
2158  }
2159  }
2160 
2161  markUsedForAliasOrIfunc(S, D, AL, Str);
2162  D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
2163 }
2164 
2165 static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2166  StringRef Model;
2167  SourceLocation LiteralLoc;
2168  // Check that it is a string.
2169  if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc))
2170  return;
2171 
2172  // Check that the value.
2173  if (Model != "global-dynamic" && Model != "local-dynamic"
2174  && Model != "initial-exec" && Model != "local-exec") {
2175  S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
2176  return;
2177  }
2178 
2179  D->addAttr(::new (S.Context) TLSModelAttr(S.Context, AL, Model));
2180 }
2181 
2182 static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2183  QualType ResultType = getFunctionOrMethodResultType(D);
2184  if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
2185  D->addAttr(::new (S.Context) RestrictAttr(S.Context, AL));
2186  return;
2187  }
2188 
2189  S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
2191 }
2192 
2193 static void handleCPUSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2194  // Ensure we don't combine these with themselves, since that causes some
2195  // confusing behavior.
2196  if (AL.getParsedKind() == ParsedAttr::AT_CPUDispatch) {
2197  if (checkAttrMutualExclusion<CPUSpecificAttr>(S, D, AL))
2198  return;
2199 
2200  if (const auto *Other = D->getAttr<CPUDispatchAttr>()) {
2201  S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
2202  S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
2203  return;
2204  }
2205  } else if (AL.getParsedKind() == ParsedAttr::AT_CPUSpecific) {
2206  if (checkAttrMutualExclusion<CPUDispatchAttr>(S, D, AL))
2207  return;
2208 
2209  if (const auto *Other = D->getAttr<CPUSpecificAttr>()) {
2210  S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
2211  S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
2212  return;
2213  }
2214  }
2215 
2216  FunctionDecl *FD = cast<FunctionDecl>(D);
2217 
2218  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
2219  if (MD->getParent()->isLambda()) {
2220  S.Diag(AL.getLoc(), diag::err_attribute_dll_lambda) << AL;
2221  return;
2222  }
2223  }
2224 
2225  if (!AL.checkAtLeastNumArgs(S, 1))
2226  return;
2227 
2229  for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); ++ArgNo) {
2230  if (!AL.isArgIdent(ArgNo)) {
2231  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
2232  << AL << AANT_ArgumentIdentifier;
2233  return;
2234  }
2235 
2236  IdentifierLoc *CPUArg = AL.getArgAsIdent(ArgNo);
2237  StringRef CPUName = CPUArg->Ident->getName().trim();
2238 
2240  S.Diag(CPUArg->Loc, diag::err_invalid_cpu_specific_dispatch_value)
2241  << CPUName << (AL.getKind() == ParsedAttr::AT_CPUDispatch);
2242  return;
2243  }
2244 
2245  const TargetInfo &Target = S.Context.getTargetInfo();
2246  if (llvm::any_of(CPUs, [CPUName, &Target](const IdentifierInfo *Cur) {
2247  return Target.CPUSpecificManglingCharacter(CPUName) ==
2248  Target.CPUSpecificManglingCharacter(Cur->getName());
2249  })) {
2250  S.Diag(AL.getLoc(), diag::warn_multiversion_duplicate_entries);
2251  return;
2252  }
2253  CPUs.push_back(CPUArg->Ident);
2254  }
2255 
2256  FD->setIsMultiVersion(true);
2257  if (AL.getKind() == ParsedAttr::AT_CPUSpecific)
2258  D->addAttr(::new (S.Context)
2259  CPUSpecificAttr(S.Context, AL, CPUs.data(), CPUs.size()));
2260  else
2261  D->addAttr(::new (S.Context)
2262  CPUDispatchAttr(S.Context, AL, CPUs.data(), CPUs.size()));
2263 }
2264 
2265 static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2266  if (S.LangOpts.CPlusPlus) {
2267  S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
2268  << AL << AttributeLangSupport::Cpp;
2269  return;
2270  }
2271 
2272  D->addAttr(::new (S.Context) CommonAttr(S.Context, AL));
2273 }
2274 
2275 static void handleCmseNSEntryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2276  if (S.LangOpts.CPlusPlus && !D->getDeclContext()->isExternCContext()) {
2277  S.Diag(AL.getLoc(), diag::err_attribute_not_clinkage) << AL;
2278  return;
2279  }
2280 
2281  const auto *FD = cast<FunctionDecl>(D);
2282  if (!FD->isExternallyVisible()) {
2283  S.Diag(AL.getLoc(), diag::warn_attribute_cmse_entry_static);
2284  return;
2285  }
2286 
2287  D->addAttr(::new (S.Context) CmseNSEntryAttr(S.Context, AL));
2288 }
2289 
2290 static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2291  if (AL.isDeclspecAttribute()) {
2292  const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
2293  const auto &Arch = Triple.getArch();
2294  if (Arch != llvm::Triple::x86 &&
2295  (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
2296  S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch)
2297  << AL << Triple.getArchName();
2298  return;
2299  }
2300 
2301  // This form is not allowed to be written on a member function (static or
2302  // nonstatic) when in Microsoft compatibility mode.
2303  if (S.getLangOpts().MSVCCompat && isa<CXXMethodDecl>(D)) {
2304  S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type_str)
2305  << AL << AL.isRegularKeywordAttribute() << "non-member functions";
2306  return;
2307  }
2308  }
2309 
2310  D->addAttr(::new (S.Context) NakedAttr(S.Context, AL));
2311 }
2312 
2313 static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2314  if (hasDeclarator(D)) return;
2315 
2316  if (!isa<ObjCMethodDecl>(D)) {
2317  S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
2318  << Attrs << Attrs.isRegularKeywordAttribute()
2320  return;
2321  }
2322 
2323  D->addAttr(::new (S.Context) NoReturnAttr(S.Context, Attrs));
2324 }
2325 
2326 static void handleStandardNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &A) {
2327  // The [[_Noreturn]] spelling is deprecated in C23, so if that was used,
2328  // issue an appropriate diagnostic. However, don't issue a diagnostic if the
2329  // attribute name comes from a macro expansion. We don't want to punish users
2330  // who write [[noreturn]] after including <stdnoreturn.h> (where 'noreturn'
2331  // is defined as a macro which expands to '_Noreturn').
2332  if (!S.getLangOpts().CPlusPlus &&
2333  A.getSemanticSpelling() == CXX11NoReturnAttr::C23_Noreturn &&
2334  !(A.getLoc().isMacroID() &&
2336  S.Diag(A.getLoc(), diag::warn_deprecated_noreturn_spelling) << A.getRange();
2337 
2338  D->addAttr(::new (S.Context) CXX11NoReturnAttr(S.Context, A));
2339 }
2340 
2341 static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2342  if (!S.getLangOpts().CFProtectionBranch)
2343  S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored);
2344  else
2345  handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs);
2346 }
2347 
2348 bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) {
2349  if (!Attrs.checkExactlyNumArgs(*this, 0)) {
2350  Attrs.setInvalid();
2351  return true;
2352  }
2353 
2354  return false;
2355 }
2356 
2357 bool Sema::CheckAttrTarget(const ParsedAttr &AL) {
2358  // Check whether the attribute is valid on the current target.
2359  const TargetInfo *Aux = Context.getAuxTargetInfo();
2360  if (!(AL.existsInTarget(Context.getTargetInfo()) ||
2361  (Context.getLangOpts().SYCLIsDevice &&
2362  Aux && AL.existsInTarget(*Aux)))) {
2364  ? diag::err_keyword_not_supported_on_target
2365  : diag::warn_unknown_attribute_ignored)
2366  << AL << AL.getRange();
2367  AL.setInvalid();
2368  return true;
2369  }
2370 
2371  return false;
2372 }
2373 
2374 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2375 
2376  // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2377  // because 'analyzer_noreturn' does not impact the type.
2378  if (!isFunctionOrMethodOrBlock(D)) {
2379  ValueDecl *VD = dyn_cast<ValueDecl>(D);
2380  if (!VD || (!VD->getType()->isBlockPointerType() &&
2381  !VD->getType()->isFunctionPointerType())) {
2383  ? diag::err_attribute_wrong_decl_type
2384  : diag::warn_attribute_wrong_decl_type)
2385  << AL << AL.isRegularKeywordAttribute()
2387  return;
2388  }
2389  }
2390 
2391  D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(S.Context, AL));
2392 }
2393 
2394 // PS3 PPU-specific.
2395 static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2396  /*
2397  Returning a Vector Class in Registers
2398 
2399  According to the PPU ABI specifications, a class with a single member of
2400  vector type is returned in memory when used as the return value of a
2401  function.
2402  This results in inefficient code when implementing vector classes. To return
2403  the value in a single vector register, add the vecreturn attribute to the
2404  class definition. This attribute is also applicable to struct types.
2405 
2406  Example:
2407 
2408  struct Vector
2409  {
2410  __vector float xyzw;
2411  } __attribute__((vecreturn));
2412 
2413  Vector Add(Vector lhs, Vector rhs)
2414  {
2415  Vector result;
2416  result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2417  return result; // This will be returned in a register
2418  }
2419  */
2420  if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2421  S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A;
2422  return;
2423  }
2424 
2425  const auto *R = cast<RecordDecl>(D);
2426  int count = 0;
2427 
2428  if (!isa<CXXRecordDecl>(R)) {
2429  S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2430  return;
2431  }
2432 
2433  if (!cast<CXXRecordDecl>(R)->isPOD()) {
2434  S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2435  return;
2436  }
2437 
2438  for (const auto *I : R->fields()) {
2439  if ((count == 1) || !I->getType()->isVectorType()) {
2440  S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2441  return;
2442  }
2443  count++;
2444  }
2445 
2446  D->addAttr(::new (S.Context) VecReturnAttr(S.Context, AL));
2447 }
2448 
2449 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
2450  const ParsedAttr &AL) {
2451  if (isa<ParmVarDecl>(D)) {
2452  // [[carries_dependency]] can only be applied to a parameter if it is a
2453  // parameter of a function declaration or lambda.
2455  S.Diag(AL.getLoc(),
2456  diag::err_carries_dependency_param_not_function_decl);
2457  return;
2458  }
2459  }
2460 
2461  D->addAttr(::new (S.Context) CarriesDependencyAttr(S.Context, AL));
2462 }
2463 
2464 static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2465  bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName();
2466 
2467  // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2468  // about using it as an extension.
2469  if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
2470  S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2471 
2472  D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL));
2473 }
2474 
2475 static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2476  uint32_t priority = ConstructorAttr::DefaultPriority;
2477  if (S.getLangOpts().HLSL && AL.getNumArgs()) {
2478  S.Diag(AL.getLoc(), diag::err_hlsl_init_priority_unsupported);
2479  return;
2480  }
2481  if (AL.getNumArgs() &&
2482  !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2483  return;
2484 
2485  D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority));
2486 }
2487 
2488 static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2489  uint32_t priority = DestructorAttr::DefaultPriority;
2490  if (AL.getNumArgs() &&
2491  !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2492  return;
2493 
2494  D->addAttr(::new (S.Context) DestructorAttr(S.Context, AL, priority));
2495 }
2496 
2497 template <typename AttrTy>
2498 static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) {
2499  // Handle the case where the attribute has a text message.
2500  StringRef Str;
2501  if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str))
2502  return;
2503 
2504  D->addAttr(::new (S.Context) AttrTy(S.Context, AL, Str));
2505 }
2506 
2507 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
2508  const ParsedAttr &AL) {
2509  if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
2510  S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2511  << AL << AL.getRange();
2512  return;
2513  }
2514 
2515  D->addAttr(::new (S.Context) ObjCExplicitProtocolImplAttr(S.Context, AL));
2516 }
2517 
2518 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2519  IdentifierInfo *Platform,
2520  VersionTuple Introduced,
2521  VersionTuple Deprecated,
2522  VersionTuple Obsoleted) {
2523  StringRef PlatformName
2524  = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2525  if (PlatformName.empty())
2526  PlatformName = Platform->getName();
2527 
2528  // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2529  // of these steps are needed).
2530  if (!Introduced.empty() && !Deprecated.empty() &&
2531  !(Introduced <= Deprecated)) {
2532  S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2533  << 1 << PlatformName << Deprecated.getAsString()
2534  << 0 << Introduced.getAsString();
2535  return true;
2536  }
2537 
2538  if (!Introduced.empty() && !Obsoleted.empty() &&
2539  !(Introduced <= Obsoleted)) {
2540  S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2541  << 2 << PlatformName << Obsoleted.getAsString()
2542  << 0 << Introduced.getAsString();
2543  return true;
2544  }
2545 
2546  if (!Deprecated.empty() && !Obsoleted.empty() &&
2547  !(Deprecated <= Obsoleted)) {
2548  S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2549  << 2 << PlatformName << Obsoleted.getAsString()
2550  << 1 << Deprecated.getAsString();
2551  return true;
2552  }
2553 
2554  return false;
2555 }
2556 
2557 /// Check whether the two versions match.
2558 ///
2559 /// If either version tuple is empty, then they are assumed to match. If
2560 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2561 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2562  bool BeforeIsOkay) {
2563  if (X.empty() || Y.empty())
2564  return true;
2565 
2566  if (X == Y)
2567  return true;
2568 
2569  if (BeforeIsOkay && X < Y)
2570  return true;
2571 
2572  return false;
2573 }
2574 
2575 AvailabilityAttr *Sema::mergeAvailabilityAttr(
2576  NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform,
2577  bool Implicit, VersionTuple Introduced, VersionTuple Deprecated,
2578  VersionTuple Obsoleted, bool IsUnavailable, StringRef Message,
2579  bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK,
2580  int Priority, IdentifierInfo *Environment) {
2581  VersionTuple MergedIntroduced = Introduced;
2582  VersionTuple MergedDeprecated = Deprecated;
2583  VersionTuple MergedObsoleted = Obsoleted;
2584  bool FoundAny = false;
2585  bool OverrideOrImpl = false;
2586  switch (AMK) {
2587  case AMK_None:
2588  case AMK_Redeclaration:
2589  OverrideOrImpl = false;
2590  break;
2591 
2592  case AMK_Override:
2593  case AMK_ProtocolImplementation:
2594  case AMK_OptionalProtocolImplementation:
2595  OverrideOrImpl = true;
2596  break;
2597  }
2598 
2599  if (D->hasAttrs()) {
2600  AttrVec &Attrs = D->getAttrs();
2601  for (unsigned i = 0, e = Attrs.size(); i != e;) {
2602  const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2603  if (!OldAA) {
2604  ++i;
2605  continue;
2606  }
2607 
2608  IdentifierInfo *OldPlatform = OldAA->getPlatform();
2609  if (OldPlatform != Platform) {
2610  ++i;
2611  continue;
2612  }
2613 
2614  IdentifierInfo *OldEnvironment = OldAA->getEnvironment();
2615  if (OldEnvironment != Environment) {
2616  ++i;
2617  continue;
2618  }
2619 
2620  // If there is an existing availability attribute for this platform that
2621  // has a lower priority use the existing one and discard the new
2622  // attribute.
2623  if (OldAA->getPriority() < Priority)
2624  return nullptr;
2625 
2626  // If there is an existing attribute for this platform that has a higher
2627  // priority than the new attribute then erase the old one and continue
2628  // processing the attributes.
2629  if (OldAA->getPriority() > Priority) {
2630  Attrs.erase(Attrs.begin() + i);
2631  --e;
2632  continue;
2633  }
2634 
2635  FoundAny = true;
2636  VersionTuple OldIntroduced = OldAA->getIntroduced();
2637  VersionTuple OldDeprecated = OldAA->getDeprecated();
2638  VersionTuple OldObsoleted = OldAA->getObsoleted();
2639  bool OldIsUnavailable = OldAA->getUnavailable();
2640 
2641  if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2642  !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2643  !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2644  !(OldIsUnavailable == IsUnavailable ||
2645  (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2646  if (OverrideOrImpl) {
2647  int Which = -1;
2648  VersionTuple FirstVersion;
2649  VersionTuple SecondVersion;
2650  if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2651  Which = 0;
2652  FirstVersion = OldIntroduced;
2653  SecondVersion = Introduced;
2654  } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2655  Which = 1;
2656  FirstVersion = Deprecated;
2657  SecondVersion = OldDeprecated;
2658  } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2659  Which = 2;
2660  FirstVersion = Obsoleted;
2661  SecondVersion = OldObsoleted;
2662  }
2663 
2664  if (Which == -1) {
2665  Diag(OldAA->getLocation(),
2666  diag::warn_mismatched_availability_override_unavail)
2667  << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2668  << (AMK == AMK_Override);
2669  } else if (Which != 1 && AMK == AMK_OptionalProtocolImplementation) {
2670  // Allow different 'introduced' / 'obsoleted' availability versions
2671  // on a method that implements an optional protocol requirement. It
2672  // makes less sense to allow this for 'deprecated' as the user can't
2673  // see if the method is 'deprecated' as 'respondsToSelector' will
2674  // still return true when the method is deprecated.
2675  ++i;
2676  continue;
2677  } else {
2678  Diag(OldAA->getLocation(),
2679  diag::warn_mismatched_availability_override)
2680  << Which
2681  << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2682  << FirstVersion.getAsString() << SecondVersion.getAsString()
2683  << (AMK == AMK_Override);
2684  }
2685  if (AMK == AMK_Override)
2686  Diag(CI.getLoc(), diag::note_overridden_method);
2687  else
2688  Diag(CI.getLoc(), diag::note_protocol_method);
2689  } else {
2690  Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2691  Diag(CI.getLoc(), diag::note_previous_attribute);
2692  }
2693 
2694  Attrs.erase(Attrs.begin() + i);
2695  --e;
2696  continue;
2697  }
2698 
2699  VersionTuple MergedIntroduced2 = MergedIntroduced;
2700  VersionTuple MergedDeprecated2 = MergedDeprecated;
2701  VersionTuple MergedObsoleted2 = MergedObsoleted;
2702 
2703  if (MergedIntroduced2.empty())
2704  MergedIntroduced2 = OldIntroduced;
2705  if (MergedDeprecated2.empty())
2706  MergedDeprecated2 = OldDeprecated;
2707  if (MergedObsoleted2.empty())
2708  MergedObsoleted2 = OldObsoleted;
2709 
2710  if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2711  MergedIntroduced2, MergedDeprecated2,
2712  MergedObsoleted2)) {
2713  Attrs.erase(Attrs.begin() + i);
2714  --e;
2715  continue;
2716  }
2717 
2718  MergedIntroduced = MergedIntroduced2;
2719  MergedDeprecated = MergedDeprecated2;
2720  MergedObsoleted = MergedObsoleted2;
2721  ++i;
2722  }
2723  }
2724 
2725  if (FoundAny &&
2726  MergedIntroduced == Introduced &&
2727  MergedDeprecated == Deprecated &&
2728  MergedObsoleted == Obsoleted)
2729  return nullptr;
2730 
2731  // Only create a new attribute if !OverrideOrImpl, but we want to do
2732  // the checking.
2733  if (!checkAvailabilityAttr(*this, CI.getRange(), Platform, MergedIntroduced,
2734  MergedDeprecated, MergedObsoleted) &&
2735  !OverrideOrImpl) {
2736  auto *Avail = ::new (Context) AvailabilityAttr(
2737  Context, CI, Platform, Introduced, Deprecated, Obsoleted, IsUnavailable,
2738  Message, IsStrict, Replacement, Priority, Environment);
2739  Avail->setImplicit(Implicit);
2740  return Avail;
2741  }
2742  return nullptr;
2743 }
2744 
2745 static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2746  if (isa<UsingDecl, UnresolvedUsingTypenameDecl, UnresolvedUsingValueDecl>(
2747  D)) {
2748  S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using)
2749  << AL;
2750  return;
2751  }
2752 
2753  if (!AL.checkExactlyNumArgs(S, 1))
2754  return;
2755  IdentifierLoc *Platform = AL.getArgAsIdent(0);
2756 
2757  IdentifierInfo *II = Platform->Ident;
2758  if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2759  S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2760  << Platform->Ident;
2761 
2762  auto *ND = dyn_cast<NamedDecl>(D);
2763  if (!ND) // We warned about this already, so just return.
2764  return;
2765 
2769  bool IsUnavailable = AL.getUnavailableLoc().isValid();
2770  bool IsStrict = AL.getStrictLoc().isValid();
2771  StringRef Str;
2772  if (const auto *SE = dyn_cast_if_present<StringLiteral>(AL.getMessageExpr()))
2773  Str = SE->getString();
2774  StringRef Replacement;
2775  if (const auto *SE =
2776  dyn_cast_if_present<StringLiteral>(AL.getReplacementExpr()))
2777  Replacement = SE->getString();
2778 
2779  if (II->isStr("swift")) {
2780  if (Introduced.isValid() || Obsoleted.isValid() ||
2781  (!IsUnavailable && !Deprecated.isValid())) {
2782  S.Diag(AL.getLoc(),
2783  diag::warn_availability_swift_unavailable_deprecated_only);
2784  return;
2785  }
2786  }
2787 
2788  if (II->isStr("fuchsia")) {
2789  std::optional<unsigned> Min, Sub;
2790  if ((Min = Introduced.Version.getMinor()) ||
2791  (Sub = Introduced.Version.getSubminor())) {
2792  S.Diag(AL.getLoc(), diag::warn_availability_fuchsia_unavailable_minor);
2793  return;
2794  }
2795  }
2796 
2797  if (S.getLangOpts().HLSL && IsStrict)
2798  S.Diag(AL.getStrictLoc(), diag::err_availability_unexpected_parameter)
2799  << "strict" << /* HLSL */ 0;
2800 
2801  int PriorityModifier = AL.isPragmaClangAttribute()
2804 
2805  const IdentifierLoc *EnvironmentLoc = AL.getEnvironment();
2806  IdentifierInfo *IIEnvironment = nullptr;
2807  if (EnvironmentLoc) {
2808  if (S.getLangOpts().HLSL) {
2809  IIEnvironment = EnvironmentLoc->Ident;
2810  if (AvailabilityAttr::getEnvironmentType(
2811  EnvironmentLoc->Ident->getName()) ==
2812  llvm::Triple::EnvironmentType::UnknownEnvironment)
2813  S.Diag(EnvironmentLoc->Loc, diag::warn_availability_unknown_environment)
2814  << EnvironmentLoc->Ident;
2815  } else {
2816  S.Diag(EnvironmentLoc->Loc, diag::err_availability_unexpected_parameter)
2817  << "environment" << /* C/C++ */ 1;
2818  }
2819  }
2820 
2821  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2822  ND, AL, II, false /*Implicit*/, Introduced.Version, Deprecated.Version,
2823  Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement,
2824  Sema::AMK_None, PriorityModifier, IIEnvironment);
2825  if (NewAttr)
2826  D->addAttr(NewAttr);
2827 
2828  // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2829  // matches before the start of the watchOS platform.
2830  if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2831  IdentifierInfo *NewII = nullptr;
2832  if (II->getName() == "ios")
2833  NewII = &S.Context.Idents.get("watchos");
2834  else if (II->getName() == "ios_app_extension")
2835  NewII = &S.Context.Idents.get("watchos_app_extension");
2836 
2837  if (NewII) {
2838  const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking();
2839  const auto *IOSToWatchOSMapping =
2840  SDKInfo ? SDKInfo->getVersionMapping(
2842  : nullptr;
2843 
2844  auto adjustWatchOSVersion =
2845  [IOSToWatchOSMapping](VersionTuple Version) -> VersionTuple {
2846  if (Version.empty())
2847  return Version;
2848  auto MinimumWatchOSVersion = VersionTuple(2, 0);
2849 
2850  if (IOSToWatchOSMapping) {
2851  if (auto MappedVersion = IOSToWatchOSMapping->map(
2852  Version, MinimumWatchOSVersion, std::nullopt)) {
2853  return *MappedVersion;
2854  }
2855  }
2856 
2857  auto Major = Version.getMajor();
2858  auto NewMajor = Major >= 9 ? Major - 7 : 0;
2859  if (NewMajor >= 2) {
2860  if (Version.getMinor()) {
2861  if (Version.getSubminor())
2862  return VersionTuple(NewMajor, *Version.getMinor(),
2863  *Version.getSubminor());
2864  else
2865  return VersionTuple(NewMajor, *Version.getMinor());
2866  }
2867  return VersionTuple(NewMajor);
2868  }
2869 
2870  return MinimumWatchOSVersion;
2871  };
2872 
2873  auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2874  auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2875  auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2876 
2877  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2878  ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
2879  NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
2881  IIEnvironment);
2882  if (NewAttr)
2883  D->addAttr(NewAttr);
2884  }
2885  } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2886  // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2887  // matches before the start of the tvOS platform.
2888  IdentifierInfo *NewII = nullptr;
2889  if (II->getName() == "ios")
2890  NewII = &S.Context.Idents.get("tvos");
2891  else if (II->getName() == "ios_app_extension")
2892  NewII = &S.Context.Idents.get("tvos_app_extension");
2893 
2894  if (NewII) {
2895  const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking();
2896  const auto *IOSToTvOSMapping =
2897  SDKInfo ? SDKInfo->getVersionMapping(
2899  : nullptr;
2900 
2901  auto AdjustTvOSVersion =
2902  [IOSToTvOSMapping](VersionTuple Version) -> VersionTuple {
2903  if (Version.empty())
2904  return Version;
2905 
2906  if (IOSToTvOSMapping) {
2907  if (auto MappedVersion = IOSToTvOSMapping->map(
2908  Version, VersionTuple(0, 0), std::nullopt)) {
2909  return *MappedVersion;
2910  }
2911  }
2912  return Version;
2913  };
2914 
2915  auto NewIntroduced = AdjustTvOSVersion(Introduced.Version);
2916  auto NewDeprecated = AdjustTvOSVersion(Deprecated.Version);
2917  auto NewObsoleted = AdjustTvOSVersion(Obsoleted.Version);
2918 
2919  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2920  ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
2921  NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
2923  IIEnvironment);
2924  if (NewAttr)
2925  D->addAttr(NewAttr);
2926  }
2927  } else if (S.Context.getTargetInfo().getTriple().getOS() ==
2928  llvm::Triple::IOS &&
2929  S.Context.getTargetInfo().getTriple().isMacCatalystEnvironment()) {
2930  auto GetSDKInfo = [&]() {
2932  "macOS");
2933  };
2934 
2935  // Transcribe "ios" to "maccatalyst" (and add a new attribute).
2936  IdentifierInfo *NewII = nullptr;
2937  if (II->getName() == "ios")
2938  NewII = &S.Context.Idents.get("maccatalyst");
2939  else if (II->getName() == "ios_app_extension")
2940  NewII = &S.Context.Idents.get("maccatalyst_app_extension");
2941  if (NewII) {
2942  auto MinMacCatalystVersion = [](const VersionTuple &V) {
2943  if (V.empty())
2944  return V;
2945  if (V.getMajor() < 13 ||
2946  (V.getMajor() == 13 && V.getMinor() && *V.getMinor() < 1))
2947  return VersionTuple(13, 1); // The min Mac Catalyst version is 13.1.
2948  return V;
2949  };
2950  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2951  ND, AL, NewII, true /*Implicit*/,
2952  MinMacCatalystVersion(Introduced.Version),
2953  MinMacCatalystVersion(Deprecated.Version),
2954  MinMacCatalystVersion(Obsoleted.Version), IsUnavailable, Str,
2955  IsStrict, Replacement, Sema::AMK_None,
2956  PriorityModifier + Sema::AP_InferredFromOtherPlatform, IIEnvironment);
2957  if (NewAttr)
2958  D->addAttr(NewAttr);
2959  } else if (II->getName() == "macos" && GetSDKInfo() &&
2960  (!Introduced.Version.empty() || !Deprecated.Version.empty() ||
2961  !Obsoleted.Version.empty())) {
2962  if (const auto *MacOStoMacCatalystMapping =
2963  GetSDKInfo()->getVersionMapping(
2965  // Infer Mac Catalyst availability from the macOS availability attribute
2966  // if it has versioned availability. Don't infer 'unavailable'. This
2967  // inferred availability has lower priority than the other availability
2968  // attributes that are inferred from 'ios'.
2969  NewII = &S.Context.Idents.get("maccatalyst");
2970  auto RemapMacOSVersion =
2971  [&](const VersionTuple &V) -> std::optional<VersionTuple> {
2972  if (V.empty())
2973  return std::nullopt;
2974  // API_TO_BE_DEPRECATED is 100000.
2975  if (V.getMajor() == 100000)
2976  return VersionTuple(100000);
2977  // The minimum iosmac version is 13.1
2978  return MacOStoMacCatalystMapping->map(V, VersionTuple(13, 1),
2979  std::nullopt);
2980  };
2981  std::optional<VersionTuple> NewIntroduced =
2982  RemapMacOSVersion(Introduced.Version),
2983  NewDeprecated =
2984  RemapMacOSVersion(Deprecated.Version),
2985  NewObsoleted =
2986  RemapMacOSVersion(Obsoleted.Version);
2987  if (NewIntroduced || NewDeprecated || NewObsoleted) {
2988  auto VersionOrEmptyVersion =
2989  [](const std::optional<VersionTuple> &V) -> VersionTuple {
2990  return V ? *V : VersionTuple();
2991  };
2992  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2993  ND, AL, NewII, true /*Implicit*/,
2994  VersionOrEmptyVersion(NewIntroduced),
2995  VersionOrEmptyVersion(NewDeprecated),
2996  VersionOrEmptyVersion(NewObsoleted), /*IsUnavailable=*/false, Str,
2997  IsStrict, Replacement, Sema::AMK_None,
2998  PriorityModifier + Sema::AP_InferredFromOtherPlatform +
3000  IIEnvironment);
3001  if (NewAttr)
3002  D->addAttr(NewAttr);
3003  }
3004  }
3005  }
3006  }
3007 }
3008 
3009 static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
3010  const ParsedAttr &AL) {
3011  if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 4))
3012  return;
3013 
3014  StringRef Language;
3015  if (const auto *SE = dyn_cast_if_present<StringLiteral>(AL.getArgAsExpr(0)))
3016  Language = SE->getString();
3017  StringRef DefinedIn;
3018  if (const auto *SE = dyn_cast_if_present<StringLiteral>(AL.getArgAsExpr(1)))
3019  DefinedIn = SE->getString();
3020  bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
3021  StringRef USR;
3022  if (const auto *SE = dyn_cast_if_present<StringLiteral>(AL.getArgAsExpr(3)))
3023  USR = SE->getString();
3024 
3025  D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
3026  S.Context, AL, Language, DefinedIn, IsGeneratedDeclaration, USR));
3027 }
3028 
3029 template <class T>
3030 static T *mergeVisibilityAttr(Sema &S, Decl *D, const AttributeCommonInfo &CI,
3031  typename T::VisibilityType value) {
3032  T *existingAttr = D->getAttr<T>();
3033  if (existingAttr) {
3034  typename T::VisibilityType existingValue = existingAttr->getVisibility();
3035  if (existingValue == value)
3036  return nullptr;
3037  S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
3038  S.Diag(CI.getLoc(), diag::note_previous_attribute);
3039  D->dropAttr<T>();
3040  }
3041  return ::new (S.Context) T(S.Context, CI, value);
3042 }
3043 
3044 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D,
3045  const AttributeCommonInfo &CI,
3046  VisibilityAttr::VisibilityType Vis) {
3047  return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, CI, Vis);
3048 }
3049 
3050 TypeVisibilityAttr *
3052  TypeVisibilityAttr::VisibilityType Vis) {
3053  return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, CI, Vis);
3054 }
3055 
3056 static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
3057  bool isTypeVisibility) {
3058  // Visibility attributes don't mean anything on a typedef.
3059  if (isa<TypedefNameDecl>(D)) {
3060  S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
3061  return;
3062  }
3063 
3064  // 'type_visibility' can only go on a type or namespace.
3065  if (isTypeVisibility && !(isa<TagDecl>(D) || isa<ObjCInterfaceDecl>(D) ||
3066  isa<NamespaceDecl>(D))) {
3067  S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
3069  return;
3070  }
3071 
3072  // Check that the argument is a string literal.
3073  StringRef TypeStr;
3074  SourceLocation LiteralLoc;
3075  if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc))
3076  return;
3077 
3078  VisibilityAttr::VisibilityType type;
3079  if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
3080  S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL
3081  << TypeStr;
3082  return;
3083  }
3084 
3085  // Complain about attempts to use protected visibility on targets
3086  // (like Darwin) that don't support it.
3087  if (type == VisibilityAttr::Protected &&
3089  S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
3090  type = VisibilityAttr::Default;
3091  }
3092 
3093  Attr *newAttr;
3094  if (isTypeVisibility) {
3095  newAttr = S.mergeTypeVisibilityAttr(
3096  D, AL, (TypeVisibilityAttr::VisibilityType)type);
3097  } else {
3098  newAttr = S.mergeVisibilityAttr(D, AL, type);
3099  }
3100  if (newAttr)
3101  D->addAttr(newAttr);
3102 }
3103 
3104 static void handleObjCDirectAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3105  // objc_direct cannot be set on methods declared in the context of a protocol
3106  if (isa<ObjCProtocolDecl>(D->getDeclContext())) {
3107  S.Diag(AL.getLoc(), diag::err_objc_direct_on_protocol) << false;
3108  return;
3109  }
3110 
3112  handleSimpleAttribute<ObjCDirectAttr>(S, D, AL);
3113  } else {
3114  S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
3115  }
3116 }
3117 
3118 static void handleObjCDirectMembersAttr(Sema &S, Decl *D,
3119  const ParsedAttr &AL) {
3121  handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL);
3122  } else {
3123  S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
3124  }
3125 }
3126 
3127 static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3128  const auto *M = cast<ObjCMethodDecl>(D);
3129  if (!AL.isArgIdent(0)) {
3130  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3131  << AL << 1 << AANT_ArgumentIdentifier;
3132  return;
3133  }
3134 
3135  IdentifierLoc *IL = AL.getArgAsIdent(0);
3136  ObjCMethodFamilyAttr::FamilyKind F;
3137  if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
3138  S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident;
3139  return;
3140  }
3141 
3142  if (F == ObjCMethodFamilyAttr::OMF_init &&
3143  !M->getReturnType()->isObjCObjectPointerType()) {
3144  S.Diag(M->getLocation(), diag::err_init_method_bad_return_type)
3145  << M->getReturnType();
3146  // Ignore the attribute.
3147  return;
3148  }
3149 
3150  D->addAttr(new (S.Context) ObjCMethodFamilyAttr(S.Context, AL, F));
3151 }
3152 
3153 static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) {
3154  if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
3155  QualType T = TD->getUnderlyingType();
3156  if (!T->isCARCBridgableType()) {
3157  S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
3158  return;
3159  }
3160  }
3161  else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
3162  QualType T = PD->getType();
3163  if (!T->isCARCBridgableType()) {
3164  S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
3165  return;
3166  }
3167  }
3168  else {
3169  // It is okay to include this attribute on properties, e.g.:
3170  //
3171  // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
3172  //
3173  // In this case it follows tradition and suppresses an error in the above
3174  // case.
3175  S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
3176  }
3177  D->addAttr(::new (S.Context) ObjCNSObjectAttr(S.Context, AL));
3178 }
3179 
3180 static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) {
3181  if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
3182  QualType T = TD->getUnderlyingType();
3183  if (!T->isObjCObjectPointerType()) {
3184  S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
3185  return;
3186  }
3187  } else {
3188  S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
3189  return;
3190  }
3191  D->addAttr(::new (S.Context) ObjCIndependentClassAttr(S.Context, AL));
3192 }
3193 
3194 static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3195  if (!AL.isArgIdent(0)) {
3196  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3197  << AL << 1 << AANT_ArgumentIdentifier;
3198  return;
3199  }
3200 
3201  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3202  BlocksAttr::BlockType type;
3203  if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
3204  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3205  return;
3206  }
3207 
3208  D->addAttr(::new (S.Context) BlocksAttr(S.Context, AL, type));
3209 }
3210 
3211 static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3212  unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
3213  if (AL.getNumArgs() > 0) {
3214  Expr *E = AL.getArgAsExpr(0);
3215  std::optional<llvm::APSInt> Idx = llvm::APSInt(32);
3216  if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) {
3217  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3218  << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
3219  return;
3220  }
3221 
3222  if (Idx->isSigned() && Idx->isNegative()) {
3223  S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
3224  << E->getSourceRange();
3225  return;
3226  }
3227 
3228  sentinel = Idx->getZExtValue();
3229  }
3230 
3231  unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
3232  if (AL.getNumArgs() > 1) {
3233  Expr *E = AL.getArgAsExpr(1);
3234  std::optional<llvm::APSInt> Idx = llvm::APSInt(32);
3235  if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) {
3236  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3237  << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
3238  return;
3239  }
3240  nullPos = Idx->getZExtValue();
3241 
3242  if ((Idx->isSigned() && Idx->isNegative()) || nullPos > 1) {
3243  // FIXME: This error message could be improved, it would be nice
3244  // to say what the bounds actually are.
3245  S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
3246  << E->getSourceRange();
3247  return;
3248  }
3249  }
3250 
3251  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3252  const FunctionType *FT = FD->getType()->castAs<FunctionType>();
3253  if (isa<FunctionNoProtoType>(FT)) {
3254  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
3255  return;
3256  }
3257 
3258  if (!cast<FunctionProtoType>(FT)->isVariadic()) {
3259  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
3260  return;
3261  }
3262  } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
3263  if (!MD->isVariadic()) {
3264  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
3265  return;
3266  }
3267  } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
3268  if (!BD->isVariadic()) {
3269  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
3270  return;
3271  }
3272  } else if (const auto *V = dyn_cast<VarDecl>(D)) {
3273  QualType Ty = V->getType();
3274  if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
3275  const FunctionType *FT = Ty->isFunctionPointerType()
3276  ? D->getFunctionType()
3277  : Ty->castAs<BlockPointerType>()
3278  ->getPointeeType()
3279  ->castAs<FunctionType>();
3280  if (!cast<FunctionProtoType>(FT)->isVariadic()) {
3281  int m = Ty->isFunctionPointerType() ? 0 : 1;
3282  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
3283  return;
3284  }
3285  } else {
3286  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
3287  << AL << AL.isRegularKeywordAttribute()
3289  return;
3290  }
3291  } else {
3292  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
3293  << AL << AL.isRegularKeywordAttribute()
3295  return;
3296  }
3297  D->addAttr(::new (S.Context) SentinelAttr(S.Context, AL, sentinel, nullPos));
3298 }
3299 
3300 static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
3301  if (D->getFunctionType() &&
3303  !isa<CXXConstructorDecl>(D)) {
3304  S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0;
3305  return;
3306  }
3307  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
3308  if (MD->getReturnType()->isVoidType()) {
3309  S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1;
3310  return;
3311  }
3312 
3313  StringRef Str;
3314  if (AL.isStandardAttributeSyntax() && !AL.getScopeName()) {
3315  // The standard attribute cannot be applied to variable declarations such
3316  // as a function pointer.
3317  if (isa<VarDecl>(D))
3318  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str)
3319  << AL << AL.isRegularKeywordAttribute()
3320  << "functions, classes, or enumerations";
3321 
3322  // If this is spelled as the standard C++17 attribute, but not in C++17,
3323  // warn about using it as an extension. If there are attribute arguments,
3324  // then claim it's a C++20 extension instead.
3325  // FIXME: If WG14 does not seem likely to adopt the same feature, add an
3326  // extension warning for C23 mode.
3327  const LangOptions &LO = S.getLangOpts();
3328  if (AL.getNumArgs() == 1) {
3329  if (LO.CPlusPlus && !LO.CPlusPlus20)
3330  S.Diag(AL.getLoc(), diag::ext_cxx20_attr) << AL;
3331 
3332  // Since this is spelled [[nodiscard]], get the optional string
3333  // literal. If in C++ mode, but not in C++20 mode, diagnose as an
3334  // extension.
3335  // FIXME: C23 should support this feature as well, even as an extension.
3336  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, nullptr))
3337  return;
3338  } else if (LO.CPlusPlus && !LO.CPlusPlus17)
3339  S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
3340  }
3341 
3342  if ((!AL.isGNUAttribute() &&
3343  !(AL.isStandardAttributeSyntax() && AL.isClangScope())) &&
3344  isa<TypedefNameDecl>(D)) {
3345  S.Diag(AL.getLoc(), diag::warn_unused_result_typedef_unsupported_spelling)
3346  << AL.isGNUScope();
3347  return;
3348  }
3349 
3350  D->addAttr(::new (S.Context) WarnUnusedResultAttr(S.Context, AL, Str));
3351 }
3352 
3353 static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3354  // weak_import only applies to variable & function declarations.
3355  bool isDef = false;
3356  if (!D->canBeWeakImported(isDef)) {
3357  if (isDef)
3358  S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
3359  << "weak_import";
3360  else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
3361  (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
3362  (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
3363  // Nothing to warn about here.
3364  } else
3365  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
3367 
3368  return;
3369  }
3370 
3371  D->addAttr(::new (S.Context) WeakImportAttr(S.Context, AL));
3372 }
3373 
3374 // Handles reqd_work_group_size and work_group_size_hint.
3375 template <typename WorkGroupAttr>
3376 static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
3377  if (!AL.checkExactlyNumArgs(S, 3))
3378  return;
3379 
3380  uint32_t WGSize[3];
3381  for (unsigned i = 0; i < 3; ++i) {
3382  const Expr *E = AL.getArgAsExpr(i);
3383  if (!checkUInt32Argument(S, AL, E, WGSize[i], i,
3384  /*StrictlyUnsigned=*/true))
3385  return;
3386  if (WGSize[i] == 0) {
3387  S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
3388  << AL << E->getSourceRange();
3389  return;
3390  }
3391  }
3392 
3393  WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
3394  if (Existing && !(Existing->getXDim() == WGSize[0] &&
3395  Existing->getYDim() == WGSize[1] &&
3396  Existing->getZDim() == WGSize[2]))
3397  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3398 
3399  D->addAttr(::new (S.Context)
3400  WorkGroupAttr(S.Context, AL, WGSize[0], WGSize[1], WGSize[2]));
3401 }
3402 
3403 // Returns a DupArgResult value; Same means the args have the same value,
3404 // Different means the args do not have the same value, and Unknown means that
3405 // the args cannot (yet) be compared.
3406 enum class DupArgResult { Unknown, Same, Different };
3407 static DupArgResult AreArgValuesIdentical(const Expr *LHS, const Expr *RHS) {
3408  // If both operands are nullptr they are unspecified and are considered the
3409  // same.
3410  if (!LHS && !RHS)
3411  return DupArgResult::Same;
3412 
3413  // Otherwise, if either operand is nullptr they are considered different.
3414  if (!LHS || !RHS)
3415  return DupArgResult::Different;
3416 
3417  // Otherwise, if either operand is still value dependent, we can't test
3418  // anything.
3419  const auto *LHSCE = dyn_cast<ConstantExpr>(LHS);
3420  const auto *RHSCE = dyn_cast<ConstantExpr>(RHS);
3421  if (!LHSCE || !RHSCE)
3422  return DupArgResult::Unknown;
3423 
3424  // Otherwise, test that the values.
3425  return LHSCE->getResultAsAPSInt() == RHSCE->getResultAsAPSInt()
3426  ? DupArgResult::Same
3427  : DupArgResult::Different;
3428 }
3429 
3430 // Returns true if any of the specified dimensions (X,Y,Z) differ between the
3431 // arguments.
3432 bool Sema::AnyWorkGroupSizesDiffer(const Expr *LHSXDim, const Expr *LHSYDim,
3433  const Expr *LHSZDim, const Expr *RHSXDim,
3434  const Expr *RHSYDim, const Expr *RHSZDim) {
3435  DupArgResult Results[] = {AreArgValuesIdentical(LHSXDim, RHSXDim),
3436  AreArgValuesIdentical(LHSYDim, RHSYDim),
3437  AreArgValuesIdentical(LHSZDim, RHSZDim)};
3438  return llvm::is_contained(Results, DupArgResult::Different);
3439 }
3440 
3441 // Returns true if all of the specified dimensions (X,Y,Z) are the same between
3442 // the arguments.
3443 bool Sema::AllWorkGroupSizesSame(const Expr *LHSXDim, const Expr *LHSYDim,
3444  const Expr *LHSZDim, const Expr *RHSXDim,
3445  const Expr *RHSYDim, const Expr *RHSZDim) {
3446  DupArgResult Results[] = {AreArgValuesIdentical(LHSXDim, RHSXDim),
3447  AreArgValuesIdentical(LHSYDim, RHSYDim),
3448  AreArgValuesIdentical(LHSZDim, RHSZDim)};
3449  return llvm::all_of(Results,
3450  [](DupArgResult V) { return V == DupArgResult::Same; });
3451 }
3452 
3454  Expr *XDim, Expr *YDim, Expr *ZDim) {
3455  // Returns nullptr if diagnosing, otherwise returns the original expression
3456  // or the original expression converted to a constant expression.
3457  auto CheckAndConvertArg = [&](Expr *E) -> std::optional<Expr *> {
3458  // We can only check if the expression is not value dependent.
3459  if (E && !E->isValueDependent()) {
3460  llvm::APSInt ArgVal;
3461  ExprResult Res = VerifyIntegerConstantExpression(E, &ArgVal);
3462  if (Res.isInvalid())
3463  return std::nullopt;
3464  E = Res.get();
3465 
3466  // This attribute requires a strictly positive value.
3467  if (ArgVal <= 0) {
3468  Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer)
3469  << CI << /*positive*/ 0;
3470  return std::nullopt;
3471  }
3472  }
3473 
3474  return E;
3475  };
3476 
3477  // Check all three argument values, and if any are bad, bail out. This will
3478  // convert the given expressions into constant expressions when possible.
3479  std::optional<Expr *> XDimConvert = CheckAndConvertArg(XDim);
3480  std::optional<Expr *> YDimConvert = CheckAndConvertArg(YDim);
3481  std::optional<Expr *> ZDimConvert = CheckAndConvertArg(ZDim);
3482  if (!XDimConvert || !YDimConvert || !ZDimConvert)
3483  return;
3484  XDim = XDimConvert.value();
3485  YDim = YDimConvert.value();
3486  ZDim = ZDimConvert.value();
3487 
3488  // If the attribute was already applied with different arguments, then
3489  // diagnose the second attribute as a duplicate and don't add it.
3490  if (const auto *Existing = D->getAttr<SYCLWorkGroupSizeHintAttr>()) {
3491  // If any of the results are known to be different, we can diagnose at this
3492  // point and drop the attribute.
3493  if (AnyWorkGroupSizesDiffer(XDim, YDim, ZDim, Existing->getXDim(),
3494  Existing->getYDim(), Existing->getZDim())) {
3495  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << CI;
3496  Diag(Existing->getLoc(), diag::note_previous_attribute);
3497  return;
3498  }
3499  // If all of the results are known to be the same, we can silently drop the
3500  // attribute. Otherwise, we have to add the attribute and resolve its
3501  // differences later.
3502  if (AllWorkGroupSizesSame(XDim, YDim, ZDim, Existing->getXDim(),
3503  Existing->getYDim(), Existing->getZDim()))
3504  return;
3505  }
3506 
3507  D->addAttr(::new (Context)
3508  SYCLWorkGroupSizeHintAttr(Context, CI, XDim, YDim, ZDim));
3509 }
3510 
3511 SYCLWorkGroupSizeHintAttr *
3513  const SYCLWorkGroupSizeHintAttr &A) {
3514  // Check to see if there's a duplicate attribute already applied.
3515  if (const auto *DeclAttr = D->getAttr<SYCLWorkGroupSizeHintAttr>()) {
3516  // If any of the results are known to be different, we can diagnose at this
3517  // point and drop the attribute.
3518  if (AnyWorkGroupSizesDiffer(DeclAttr->getXDim(), DeclAttr->getYDim(),
3519  DeclAttr->getZDim(), A.getXDim(), A.getYDim(),
3520  A.getZDim())) {
3521  Diag(DeclAttr->getLoc(), diag::warn_duplicate_attribute) << &A;
3522  Diag(A.getLoc(), diag::note_previous_attribute);
3523  return nullptr;
3524  }
3525  // If all of the results are known to be the same, we can silently drop the
3526  // attribute. Otherwise, we have to add the attribute and resolve its
3527  // differences later.
3528  if (AllWorkGroupSizesSame(DeclAttr->getXDim(), DeclAttr->getYDim(),
3529  DeclAttr->getZDim(), A.getXDim(), A.getYDim(),
3530  A.getZDim()))
3531  return nullptr;
3532  }
3533  return ::new (Context) SYCLWorkGroupSizeHintAttr(Context, A, A.getXDim(),
3534  A.getYDim(), A.getZDim());
3535 }
3536 
3537 // Handles SYCL work_group_size_hint.
3538 static void handleSYCLWorkGroupSizeHint(Sema &S, Decl *D,
3539  const ParsedAttr &AL) {
3541 
3542  // __attribute__((work_group_size_hint) requires exactly three arguments.
3543  if (AL.getSyntax() == ParsedAttr::AS_GNU || !AL.hasScope() ||
3544  (AL.hasScope() && !AL.getScopeName()->isStr("sycl"))) {
3545  if (!AL.checkExactlyNumArgs(S, 3))
3546  return;
3547  } else if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 3))
3548  return;
3549 
3550  size_t NumArgs = AL.getNumArgs();
3551  Expr *XDimExpr = NumArgs > 0 ? AL.getArgAsExpr(0) : nullptr;
3552  Expr *YDimExpr = NumArgs > 1 ? AL.getArgAsExpr(1) : nullptr;
3553  Expr *ZDimExpr = NumArgs > 2 ? AL.getArgAsExpr(2) : nullptr;
3554  S.AddSYCLWorkGroupSizeHintAttr(D, AL, XDimExpr, YDimExpr, ZDimExpr);
3555 }
3556 
3557 static void handleWorkGroupSizeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
3558  // Handle the attribute based on whether we are targeting SYCL or not.
3559  if (S.getLangOpts().SYCLIsDevice || S.getLangOpts().SYCLIsHost)
3560  handleSYCLWorkGroupSizeHint(S, D, AL);
3561  else
3562  handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL);
3563 }
3564 
3565 // Checks correctness of mutual usage of different work_group_size attributes:
3566 // reqd_work_group_size, max_work_group_size, and max_global_work_dim.
3567 //
3568 // If [[intel::max_work_group_size(X, Y, Z)]] or
3569 // [[sycl::reqd_work_group_size(X, Y, Z)]] or
3570 // [[cl::reqd_work_group_size(X, Y, Z)]]
3571 // or __attribute__((reqd_work_group_size)) attribute is specified on a
3572 // declaration along with [[intel::max_global_work_dim()]] attribute, check to
3573 // see if all arguments of 'max_work_group_size' or different spellings of
3574 // 'reqd_work_group_size' attribute hold value 1 in case the argument of
3575 // [[intel::max_global_work_dim()]] attribute value equals to 0.
3576 static bool InvalidWorkGroupSizeAttrs(Sema &S, const Expr *MGValue,
3577  const Expr *XDim, const Expr *YDim,
3578  const Expr *ZDim) {
3579  // If any of the operand is still value dependent, we can't test anything.
3580  const auto *MGValueExpr = dyn_cast<ConstantExpr>(MGValue);
3581  const auto *XDimExpr = dyn_cast<ConstantExpr>(XDim);
3582 
3583  if (!MGValueExpr || !XDimExpr)
3584  return false;
3585 
3586  // Y and Z may be optional so we allow them to be null and consider them
3587  // dependent if the original epxression was not null while the result of the
3588  // cast is.
3589  const auto *YDimExpr = dyn_cast_or_null<ConstantExpr>(YDim);
3590  const auto *ZDimExpr = dyn_cast_or_null<ConstantExpr>(ZDim);
3591 
3592  if ((!YDimExpr && YDim) || (!ZDimExpr && ZDim))
3593  return false;
3594 
3595  // Otherwise, check if the attribute values are equal to one.
3596  // Y and Z dimensions are optional and are considered trivially 1 if
3597  // unspecified.
3598  return (MGValueExpr->getResultAsAPSInt() == 0 &&
3599  (XDimExpr->getResultAsAPSInt() != 1 ||
3600  (YDimExpr && YDimExpr->getResultAsAPSInt() != 1) ||
3601  (ZDimExpr && ZDimExpr->getResultAsAPSInt() != 1)));
3602 }
3603 
3604 // Checks correctness of mutual usage of different work_group_size attributes:
3605 // reqd_work_group_size and max_work_group_size.
3606 //
3607 // If the 'reqd_work_group_size' attribute is specified on a declaration along
3608 // with 'max_work_group_size' attribute, check to see if values of
3609 // 'reqd_work_group_size' attribute arguments are equal to or less than values
3610 // of 'max_work_group_size' attribute arguments.
3611 //
3612 // The arguments to reqd_work_group_size are ordered based on which index
3613 // increments the fastest. In OpenCL, the first argument is the index that
3614 // increments the fastest, and in SYCL, the last argument is the index that
3615 // increments the fastest.
3616 //
3617 // __attribute__((reqd_work_group_size)) follows the OpenCL rules in OpenCL
3618 // mode. All spellings of reqd_work_group_size attribute (regardless of
3619 // syntax used) follow the SYCL rules when in SYCL mode.
3621  const Expr *RWGSXDim, const Expr *RWGSYDim, const Expr *RWGSZDim,
3622  const Expr *MWGSXDim, const Expr *MWGSYDim, const Expr *MWGSZDim) {
3623  // If any of the operand is still value dependent, we can't test anything.
3624  const auto *RWGSXDimExpr = dyn_cast<ConstantExpr>(RWGSXDim);
3625  const auto *MWGSXDimExpr = dyn_cast<ConstantExpr>(MWGSXDim);
3626  const auto *MWGSYDimExpr = dyn_cast<ConstantExpr>(MWGSYDim);
3627  const auto *MWGSZDimExpr = dyn_cast<ConstantExpr>(MWGSZDim);
3628 
3629  if (!RWGSXDimExpr || !MWGSXDimExpr || !MWGSYDimExpr || !MWGSZDimExpr)
3630  return false;
3631 
3632  // Y and Z may be optional so we allow them to be null and consider them
3633  // dependent if the original epxression was not null while the result of the
3634  // cast is.
3635  const auto *RWGSYDimExpr = dyn_cast_or_null<ConstantExpr>(RWGSYDim);
3636  const auto *RWGSZDimExpr = dyn_cast_or_null<ConstantExpr>(RWGSZDim);
3637 
3638  if ((!RWGSYDimExpr && RWGSYDim) || (!RWGSZDimExpr && RWGSZDim))
3639  return false;
3640 
3641  // SYCL reorders arguments based on the dimensionality.
3642  // If we only have the X-dimension, there is no change to the expressions,
3643  // otherwise the last specified dimension acts as the first dimension in the
3644  // work-group size.
3645  const ConstantExpr *FirstRWGDimExpr = RWGSXDimExpr;
3646  const ConstantExpr *SecondRWGDimExpr = RWGSYDimExpr;
3647  const ConstantExpr *ThirdRWGDimExpr = RWGSZDimExpr;
3648  if (getLangOpts().SYCLIsDevice && RWGSYDim)
3649  std::swap(FirstRWGDimExpr, RWGSZDim ? ThirdRWGDimExpr : SecondRWGDimExpr);
3650 
3651  // Check if values of 'reqd_work_group_size' attribute arguments are greater
3652  // than values of 'max_work_group_size' attribute arguments.
3653  bool CheckFirstArgument =
3654  FirstRWGDimExpr->getResultAsAPSInt().getZExtValue() >
3655  MWGSZDimExpr->getResultAsAPSInt().getZExtValue();
3656 
3657  bool CheckSecondArgument =
3658  SecondRWGDimExpr && SecondRWGDimExpr->getResultAsAPSInt().getZExtValue() >
3659  MWGSYDimExpr->getResultAsAPSInt().getZExtValue();
3660 
3661  bool CheckThirdArgument =
3662  ThirdRWGDimExpr && ThirdRWGDimExpr->getResultAsAPSInt().getZExtValue() >
3663  MWGSXDimExpr->getResultAsAPSInt().getZExtValue();
3664 
3665  return CheckFirstArgument || CheckSecondArgument || CheckThirdArgument;
3666 }
3667 
3669  const AttributeCommonInfo &CI,
3670  Expr *XDim, Expr *YDim,
3671  Expr *ZDim) {
3672  // Returns nullptr if diagnosing, otherwise returns the original expression
3673  // or the original expression converted to a constant expression.
3674  auto CheckAndConvertArg = [&](Expr *E) -> Expr * {
3675  // Check if the expression is not value dependent.
3676  if (!E->isValueDependent()) {
3677  llvm::APSInt ArgVal;
3678  ExprResult Res = VerifyIntegerConstantExpression(E, &ArgVal);
3679  if (Res.isInvalid())
3680  return nullptr;
3681  E = Res.get();
3682 
3683  // This attribute requires a strictly positive value.
3684  if (ArgVal <= 0) {
3685  Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer)
3686  << CI << /*positive*/ 0;
3687  return nullptr;
3688  }
3689  }
3690  return E;
3691  };
3692 
3693  // Check all three argument values, and if any are bad, bail out. This will
3694  // convert the given expressions into constant expressions when possible.
3695  XDim = CheckAndConvertArg(XDim);
3696  YDim = CheckAndConvertArg(YDim);
3697  ZDim = CheckAndConvertArg(ZDim);
3698  if (!XDim || !YDim || !ZDim)
3699  return;
3700 
3701  // If the 'max_work_group_size' attribute is specified on a declaration along
3702  // with 'reqd_work_group_size' attribute, check to see if values of
3703  // 'reqd_work_group_size' attribute arguments are equal to or less than values
3704  // of 'max_work_group_size' attribute arguments.
3705  //
3706  // We emit diagnostic if values of 'reqd_work_group_size' attribute arguments
3707  // are greater than values of 'max_work_group_size' attribute arguments.
3708  if (const auto *DeclAttr = D->getAttr<SYCLReqdWorkGroupSizeAttr>()) {
3709  if (CheckMaxAllowedWorkGroupSize(DeclAttr->getXDim(), DeclAttr->getYDim(),
3710  DeclAttr->getZDim(), XDim, YDim, ZDim)) {
3711  Diag(CI.getLoc(), diag::err_conflicting_sycl_function_attributes)
3712  << CI << DeclAttr;
3713  Diag(DeclAttr->getLoc(), diag::note_conflicting_attribute);
3714  return;
3715  }
3716  }
3717 
3718  // If the declaration has a SYCLIntelMaxWorkGroupSizeAttr, check to see if
3719  // the attribute holds values equal to (1, 1, 1) in case the value of
3720  // SYCLIntelMaxGlobalWorkDimAttr equals to 0.
3721  if (const auto *DeclAttr = D->getAttr<SYCLIntelMaxGlobalWorkDimAttr>()) {
3722  if (InvalidWorkGroupSizeAttrs(*this, DeclAttr->getValue(), XDim, YDim,
3723  ZDim)) {
3724  Diag(CI.getLoc(), diag::err_sycl_x_y_z_arguments_must_be_one)
3725  << CI << DeclAttr;
3726  return;
3727  }
3728  }
3729 
3730  // If the attribute was already applied with different arguments, then
3731  // diagnose the second attribute as a duplicate and don't add it.
3732  if (const auto *Existing = D->getAttr<SYCLIntelMaxWorkGroupSizeAttr>()) {
3733  // If any of the results are known to be different, we can diagnose at this
3734  // point and drop the attribute.
3735  if (AnyWorkGroupSizesDiffer(XDim, YDim, ZDim, Existing->getXDim(),
3736  Existing->getYDim(), Existing->getZDim())) {
3737  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << CI;
3738  Diag(Existing->getLoc(), diag::note_previous_attribute);
3739  return;
3740  }
3741  // If all of the results are known to be the same, we can silently drop the
3742  // attribute. Otherwise, we have to add the attribute and resolve its
3743  // differences later.
3744  if (AllWorkGroupSizesSame(XDim, YDim, ZDim, Existing->getXDim(),
3745  Existing->getYDim(), Existing->getZDim()))
3746  return;
3747  }
3748 
3749  D->addAttr(::new (Context)
3750  SYCLIntelMaxWorkGroupSizeAttr(Context, CI, XDim, YDim, ZDim));
3751 }
3752 
3753 SYCLIntelMaxWorkGroupSizeAttr *Sema::MergeSYCLIntelMaxWorkGroupSizeAttr(
3754  Decl *D, const SYCLIntelMaxWorkGroupSizeAttr &A) {
3755  // Check to see if there's a duplicate attribute already applied.
3756  if (const auto *DeclAttr = D->getAttr<SYCLIntelMaxWorkGroupSizeAttr>()) {
3757  // If any of the results are known to be different, we can diagnose at this
3758  // point and drop the attribute.
3759  if (AnyWorkGroupSizesDiffer(DeclAttr->getXDim(), DeclAttr->getYDim(),
3760  DeclAttr->getZDim(), A.getXDim(), A.getYDim(),
3761  A.getZDim())) {
3762  Diag(DeclAttr->getLoc(), diag::warn_duplicate_attribute) << &A;
3763  Diag(A.getLoc(), diag::note_previous_attribute);
3764  return nullptr;
3765  }
3766  // If all of the results are known to be the same, we can silently drop the
3767  // attribute. Otherwise, we have to add the attribute and resolve its
3768  // differences later.
3769  if (AllWorkGroupSizesSame(DeclAttr->getXDim(), DeclAttr->getYDim(),
3770  DeclAttr->getZDim(), A.getXDim(), A.getYDim(),
3771  A.getZDim()))
3772  return nullptr;
3773  }
3774 
3775  // If the 'max_work_group_size' attribute is specified on a declaration along
3776  // with 'reqd_work_group_size' attribute, check to see if values of
3777  // 'reqd_work_group_size' attribute arguments are equal to or less than values
3778  // of 'max_work_group_size' attribute arguments.
3779  //
3780  // We emit diagnostic if values of 'reqd_work_group_size' attribute arguments
3781  // are greater than values of 'max_work_group_size' attribute arguments.
3782  if (const auto *DeclAttr = D->getAttr<SYCLReqdWorkGroupSizeAttr>()) {
3783  if (CheckMaxAllowedWorkGroupSize(DeclAttr->getXDim(), DeclAttr->getYDim(),
3784  DeclAttr->getZDim(), A.getXDim(),
3785  A.getYDim(), A.getZDim())) {
3786  Diag(DeclAttr->getLoc(), diag::err_conflicting_sycl_function_attributes)
3787  << DeclAttr << &A;
3788  Diag(A.getLoc(), diag::note_conflicting_attribute);
3789  return nullptr;
3790  }
3791  }
3792 
3793  // If the declaration has a SYCLIntelMaxWorkGroupSizeAttr, check to see if
3794  // the attribute holds values equal to (1, 1, 1) in case the value of
3795  // SYCLIntelMaxGlobalWorkDimAttr equals to 0.
3796  if (const auto *DeclAttr = D->getAttr<SYCLIntelMaxGlobalWorkDimAttr>()) {
3797  if (InvalidWorkGroupSizeAttrs(*this, DeclAttr->getValue(), A.getXDim(),
3798  A.getYDim(), A.getZDim())) {
3799  Diag(A.getLoc(), diag::err_sycl_x_y_z_arguments_must_be_one)
3800  << &A << DeclAttr;
3801  return nullptr;
3802  }
3803  }
3804 
3805  return ::new (Context) SYCLIntelMaxWorkGroupSizeAttr(
3806  Context, A, A.getXDim(), A.getYDim(), A.getZDim());
3807 }
3808 
3809 // Handles max_work_group_size attribute.
3810 static void handleSYCLIntelMaxWorkGroupSize(Sema &S, Decl *D,
3811  const ParsedAttr &AL) {
3813  AL.getArgAsExpr(1), AL.getArgAsExpr(2));
3814 }
3815 
3816 // Handles min_work_groups_per_cu attribute.
3817 static void handleSYCLIntelMinWorkGroupsPerComputeUnit(Sema &S, Decl *D,
3818  const ParsedAttr &AL) {
3820 }
3821 
3822 // Handles max_work_groups_per_mp attribute.
3823 static void
3824 handleSYCLIntelMaxWorkGroupsPerMultiprocessor(Sema &S, Decl *D,
3825  const ParsedAttr &AL) {
3827 }
3828 
3829 // Handles reqd_work_group_size.
3830 // If the 'reqd_work_group_size' attribute is specified on a declaration along
3831 // with 'num_simd_work_items' attribute, the required work group size specified
3832 // by 'num_simd_work_items' attribute must evenly divide the index that
3833 // increments fastest in the 'reqd_work_group_size' attribute.
3834 //
3835 // The arguments to reqd_work_group_size are ordered based on which index
3836 // increments the fastest. In OpenCL, the first argument is the index that
3837 // increments the fastest, and in SYCL, the last argument is the index that
3838 // increments the fastest.
3839 //
3840 // __attribute__((reqd_work_group_size)) follows the OpenCL rules in OpenCL
3841 // mode. All spellings of reqd_work_group_size attribute (regardless of
3842 // syntax used) follow the SYCL rules when in SYCL mode.
3843 static bool CheckWorkGroupSize(Sema &S, const Expr *NSWIValue,
3844  const Expr *RWGSXDim, const Expr *RWGSYDim,
3845  const Expr *RWGSZDim) {
3846  // If any of the operand is still value dependent, we can't test anything.
3847  const auto *NSWIValueExpr = dyn_cast<ConstantExpr>(NSWIValue);
3848  const auto *RWGSXDimExpr = dyn_cast<ConstantExpr>(RWGSXDim);
3849 
3850  if (!NSWIValueExpr || !RWGSXDimExpr)
3851  return false;
3852 
3853  // Y and Z may be optional so we allow them to be null and consider them
3854  // dependent if the original epxression was not null while the result of the
3855  // cast is.
3856  const auto *RWGSYDimExpr = dyn_cast_or_null<ConstantExpr>(RWGSYDim);
3857  const auto *RWGSZDimExpr = dyn_cast_or_null<ConstantExpr>(RWGSZDim);
3858 
3859  if ((!RWGSYDimExpr && RWGSYDim) || (!RWGSZDimExpr && RWGSZDim))
3860  return false;
3861 
3862  // Otherwise, check which argument increments the fastest.
3863  const ConstantExpr *LastRWGSDimExpr =
3864  RWGSZDim ? RWGSZDimExpr : (RWGSYDim ? RWGSYDimExpr : RWGSXDimExpr);
3865  unsigned WorkGroupSize = LastRWGSDimExpr->getResultAsAPSInt().getZExtValue();
3866 
3867  // Check if the required work group size specified by 'num_simd_work_items'
3868  // attribute evenly divides the index that increments fastest in the
3869  // 'reqd_work_group_size' attribute.
3870  return WorkGroupSize % NSWIValueExpr->getResultAsAPSInt().getZExtValue() != 0;
3871 }
3872 
3874  Expr *XDim, Expr *YDim, Expr *ZDim) {
3875  // Returns nullptr if diagnosing, otherwise returns the original expression
3876  // or the original expression converted to a constant expression.
3877  auto CheckAndConvertArg = [&](Expr *E) -> std::optional<Expr *> {
3878  // Check if the expression is not value dependent.
3879  if (E && !E->isValueDependent()) {
3880  llvm::APSInt ArgVal;
3881  ExprResult Res = VerifyIntegerConstantExpression(E, &ArgVal);
3882  if (Res.isInvalid())
3883  return std::nullopt;
3884  E = Res.get();
3885 
3886  // This attribute requires a strictly positive value.
3887  if (ArgVal <= 0) {
3888  Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer)
3889  << CI << /*positive*/ 0;
3890  return std::nullopt;
3891  }
3892  }
3893  return E;
3894  };
3895 
3896  // Check all three argument values, and if any are bad, bail out. This will
3897  // convert the given expressions into constant expressions when possible.
3898  std::optional<Expr *> XDimConvert = CheckAndConvertArg(XDim);
3899  std::optional<Expr *> YDimConvert = CheckAndConvertArg(YDim);
3900  std::optional<Expr *> ZDimConvert = CheckAndConvertArg(ZDim);
3901  if (!XDimConvert || !YDimConvert || !ZDimConvert)
3902  return;
3903  XDim = XDimConvert.value();
3904  YDim = YDimConvert.value();
3905  ZDim = ZDimConvert.value();
3906 
3907  // If the declaration has a ReqdWorkGroupSizeAttr, check to see if
3908  // the attribute holds values equal to (1, 1, 1) in case the value of
3909  // SYCLIntelMaxGlobalWorkDimAttr equals to 0.
3910  if (const auto *DeclAttr = D->getAttr<SYCLIntelMaxGlobalWorkDimAttr>()) {
3911  if (InvalidWorkGroupSizeAttrs(*this, DeclAttr->getValue(), XDim, YDim,
3912  ZDim)) {
3913  Diag(CI.getLoc(), diag::err_sycl_x_y_z_arguments_must_be_one)
3914  << CI << DeclAttr;
3915  }
3916  }
3917 
3918  // If the 'max_work_group_size' attribute is specified on a declaration along
3919  // with 'reqd_work_group_size' attribute, check to see if values of
3920  // 'reqd_work_group_size' attribute arguments are equal to or less than values
3921  // of 'max_work_group_size' attribute arguments.
3922  //
3923  // We emit diagnostic if values of 'reqd_work_group_size' attribute arguments
3924  // are greater than values of 'max_work_group_size' attribute arguments.
3925  if (const auto *DeclAttr = D->getAttr<SYCLIntelMaxWorkGroupSizeAttr>()) {
3926  if (CheckMaxAllowedWorkGroupSize(XDim, YDim, ZDim, DeclAttr->getXDim(),
3927  DeclAttr->getYDim(),
3928  DeclAttr->getZDim())) {
3929  Diag(CI.getLoc(), diag::err_conflicting_sycl_function_attributes)
3930  << CI << DeclAttr;
3931  Diag(DeclAttr->getLoc(), diag::note_conflicting_attribute);
3932  return;
3933  }
3934  }
3935 
3936  // If the 'reqd_work_group_size' attribute is specified on a declaration
3937  // along with 'num_simd_work_items' attribute, the required work group size
3938  // specified by 'num_simd_work_items' attribute must evenly divide the index
3939  // that increments fastest in the 'reqd_work_group_size' attribute.
3940  if (const auto *DeclAttr = D->getAttr<SYCLIntelNumSimdWorkItemsAttr>()) {
3941  if (CheckWorkGroupSize(*this, DeclAttr->getValue(), XDim, YDim, ZDim)) {
3942  Diag(DeclAttr->getLoc(), diag::err_sycl_num_kernel_wrong_reqd_wg_size)
3943  << DeclAttr << CI;
3944  Diag(CI.getLoc(), diag::note_conflicting_attribute);
3945  return;
3946  }
3947  }
3948 
3949  // If the attribute was already applied with different arguments, then
3950  // diagnose the second attribute as a duplicate and don't add it.
3951  if (const auto *Existing = D->getAttr<SYCLReqdWorkGroupSizeAttr>()) {
3952  // If any of the results are known to be different, we can diagnose at this
3953  // point and drop the attribute.
3954  if (AnyWorkGroupSizesDiffer(XDim, YDim, ZDim, Existing->getXDim(),
3955  Existing->getYDim(), Existing->getZDim())) {
3956  Diag(CI.getLoc(), diag::err_duplicate_attribute) << CI;
3957  Diag(Existing->getLoc(), diag::note_previous_attribute);
3958  return;
3959  }
3960 
3961  // If all of the results are known to be the same, we can silently drop the
3962  // attribute. Otherwise, we have to add the attribute and resolve its
3963  // differences later.
3964  if (AllWorkGroupSizesSame(XDim, YDim, ZDim, Existing->getXDim(),
3965  Existing->getYDim(), Existing->getZDim()))
3966  return;
3967  }
3968 
3969  D->addAttr(::new (Context)
3970  SYCLReqdWorkGroupSizeAttr(Context, CI, XDim, YDim, ZDim));
3971 }
3972 
3973 SYCLReqdWorkGroupSizeAttr *
3975  const SYCLReqdWorkGroupSizeAttr &A) {
3976  // If the declaration has a SYCLReqdWorkGroupSizeAttr, check to see if the
3977  // attribute holds values equal to (1, 1, 1) in case the value of
3978  // SYCLIntelMaxGlobalWorkDimAttr equals to 0.
3979  if (const auto *DeclAttr = D->getAttr<SYCLIntelMaxGlobalWorkDimAttr>()) {
3980  if (InvalidWorkGroupSizeAttrs(*this, DeclAttr->getValue(), A.getXDim(),
3981  A.getYDim(), A.getZDim())) {
3982  Diag(A.getLoc(), diag::err_sycl_x_y_z_arguments_must_be_one)
3983  << &A << DeclAttr;
3984  return nullptr;
3985  }
3986  }
3987 
3988  // If the 'max_work_group_size' attribute is specified on a declaration along
3989  // with 'reqd_work_group_size' attribute, check to see if values of
3990  // 'reqd_work_group_size' attribute arguments are equal or less than values
3991  // of 'max_work_group_size' attribute arguments.
3992  //
3993  // We emit diagnostic if values of 'reqd_work_group_size' attribute arguments
3994  // are greater than values of 'max_work_group_size' attribute arguments.
3995  if (const auto *DeclAttr = D->getAttr<SYCLIntelMaxWorkGroupSizeAttr>()) {
3996  if (CheckMaxAllowedWorkGroupSize(A.getXDim(), A.getYDim(), A.getZDim(),
3997  DeclAttr->getXDim(), DeclAttr->getYDim(),
3998  DeclAttr->getZDim())) {
3999  Diag(DeclAttr->getLoc(), diag::err_conflicting_sycl_function_attributes)
4000  << DeclAttr << &A;
4001  Diag(A.getLoc(), diag::note_conflicting_attribute);
4002  return nullptr;
4003  }
4004  }
4005 
4006  // If the 'reqd_work_group_size' attribute is specified on a declaration
4007  // along with 'num_simd_work_items' attribute, the required work group size
4008  // specified by 'num_simd_work_items' attribute must evenly divide the index
4009  // that increments fastest in the 'reqd_work_group_size' attribute.
4010  if (const auto *DeclAttr = D->getAttr<SYCLIntelNumSimdWorkItemsAttr>()) {
4011  if (CheckWorkGroupSize(*this, DeclAttr->getValue(), A.getXDim(),
4012  A.getYDim(), A.getZDim())) {
4013  Diag(DeclAttr->getLoc(), diag::err_sycl_num_kernel_wrong_reqd_wg_size)
4014  << DeclAttr << &A;
4015  Diag(A.getLoc(), diag::note_conflicting_attribute);
4016  return nullptr;
4017  }
4018  }
4019 
4020  // Check to see if there's a duplicate attribute already applied.
4021  if (const auto *DeclAttr = D->getAttr<SYCLReqdWorkGroupSizeAttr>()) {
4022  // If any of the results are known to be different, we can diagnose at this
4023  // point and drop the attribute.
4024  if (AnyWorkGroupSizesDiffer(DeclAttr->getXDim(), DeclAttr->getYDim(),
4025  DeclAttr->getZDim(), A.getXDim(), A.getYDim(),
4026  A.getZDim())) {
4027  Diag(DeclAttr->getLoc(), diag::err_duplicate_attribute) << &A;
4028  Diag(A.getLoc(), diag::note_previous_attribute);
4029  return nullptr;
4030  }
4031 
4032  // If all of the results are known to be the same, we can silently drop the
4033  // attribute. Otherwise, we have to add the attribute and resolve its
4034  // differences later.
4035  if (AllWorkGroupSizesSame(DeclAttr->getXDim(), DeclAttr->getYDim(),
4036  DeclAttr->getZDim(), A.getXDim(), A.getYDim(),
4037  A.getZDim()))
4038  return nullptr;
4039  }
4040 
4041  return ::new (Context) SYCLReqdWorkGroupSizeAttr(Context, A, A.getXDim(),
4042  A.getYDim(), A.getZDim());
4043 }
4044 
4045 static void handleSYCLReqdWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL){
4047 
4048  // __attribute__((reqd_work_group_size)) and [[cl::reqd_work_group_size]]
4049  // all require exactly three arguments.
4050  if ((AL.getKind() == ParsedAttr::AT_ReqdWorkGroupSize &&
4052  SYCLReqdWorkGroupSizeAttr::CXX11_cl_reqd_work_group_size) ||
4053  AL.getSyntax() == ParsedAttr::AS_GNU) {
4054  if (!AL.checkExactlyNumArgs(S, 3))
4055  return;
4056  } else if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 3))
4057  return;
4058 
4059  size_t NumArgs = AL.getNumArgs();
4060  Expr *XDimExpr = NumArgs > 0 ? AL.getArgAsExpr(0) : nullptr;
4061  Expr *YDimExpr = NumArgs > 1 ? AL.getArgAsExpr(1) : nullptr;
4062  Expr *ZDimExpr = NumArgs > 2 ? AL.getArgAsExpr(2) : nullptr;
4063  S.AddSYCLReqdWorkGroupSizeAttr(D, AL, XDimExpr, YDimExpr, ZDimExpr);
4064 }
4065 
4066 static void handleReqdWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
4067  // Handle the attribute based on whether we are targeting SYCL or not.
4068  if (S.getLangOpts().SYCLIsDevice || S.getLangOpts().SYCLIsHost)
4069  handleSYCLReqdWorkGroupSize(S, D, AL);
4070  else
4071  handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL);
4072 }
4073 
4075  Expr *E) {
4076  if (!E->isValueDependent()) {
4077  // Validate that we have an integer constant expression and then store the
4078  // converted constant expression into the semantic attribute so that we
4079  // don't have to evaluate it again later.
4080  llvm::APSInt ArgVal;
4081  ExprResult Res = VerifyIntegerConstantExpression(E, &ArgVal);
4082  if (Res.isInvalid())
4083  return;
4084  E = Res.get();
4085 
4086  // This attribute requires a strictly positive value.
4087  if (ArgVal <= 0) {
4088  Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer)
4089  << CI << /*positive*/ 0;
4090  return;
4091  }
4092  auto &TI = Context.getTargetInfo();
4093  if (TI.getTriple().isNVPTX() && ArgVal != 32)
4094  Diag(E->getExprLoc(), diag::warn_reqd_sub_group_attribute_n)
4095  << ArgVal.getSExtValue() << TI.getTriple().getArchName() << 32;
4096  if (TI.getTriple().isAMDGPU()) {
4097  const auto HasWaveFrontSize64 =
4098  TI.getTargetOpts().FeatureMap["wavefrontsize64"];
4099  const auto HasWaveFrontSize32 =
4100  TI.getTargetOpts().FeatureMap["wavefrontsize32"];
4101 
4102  // CDNA supports only 64 wave front size, for those GPUs allow subgroup
4103  // size of 64. Some GPUs support both 32 and 64, for those (and the rest)
4104  // only allow 32. Warn on incompatible sizes.
4105  const auto SupportedWaveFrontSize =
4106  HasWaveFrontSize64 && !HasWaveFrontSize32 ? 64 : 32;
4107  if (ArgVal != SupportedWaveFrontSize)
4108  Diag(E->getExprLoc(), diag::warn_reqd_sub_group_attribute_n)
4109  << ArgVal.getSExtValue() << TI.getTriple().getArchName()
4110  << SupportedWaveFrontSize;
4111  }
4112 
4113  // Check to see if there's a duplicate attribute with different values
4114  // already applied to the declaration.
4115  if (const auto *DeclAttr = D->getAttr<IntelReqdSubGroupSizeAttr>()) {
4116  // If the other attribute argument is instantiation dependent, we won't
4117  // have converted it to a constant expression yet and thus we test
4118  // whether this is a null pointer.
4119  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
4120  if (ArgVal != DeclExpr->getResultAsAPSInt()) {
4121  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << CI;
4122  Diag(DeclAttr->getLoc(), diag::note_previous_attribute);
4123  }
4124  // Drop the duplicate attribute.
4125  return;
4126  }
4127  }
4128  }
4129 
4130  D->addAttr(::new (Context) IntelReqdSubGroupSizeAttr(Context, CI, E));
4131 }
4132 
4133 IntelReqdSubGroupSizeAttr *
4135  const IntelReqdSubGroupSizeAttr &A) {
4136  // Check to see if there's a duplicate attribute with different values
4137  // already applied to the declaration.
4138  if (const auto *DeclAttr = D->getAttr<IntelReqdSubGroupSizeAttr>()) {
4139  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
4140  if (const auto *MergeExpr = dyn_cast<ConstantExpr>(A.getValue())) {
4141  if (DeclExpr->getResultAsAPSInt() != MergeExpr->getResultAsAPSInt()) {
4142  Diag(DeclAttr->getLoc(), diag::warn_duplicate_attribute) << &A;
4143  Diag(A.getLoc(), diag::note_previous_attribute);
4144  return nullptr;
4145  }
4146  // Do not add a duplicate attribute.
4147  return nullptr;
4148  }
4149  }
4150  }
4151  return ::new (Context) IntelReqdSubGroupSizeAttr(Context, A, A.getValue());
4152 }
4153 
4154 static void handleIntelReqdSubGroupSize(Sema &S, Decl *D,
4155  const ParsedAttr &AL) {
4157 
4158  Expr *E = AL.getArgAsExpr(0);
4159  S.AddIntelReqdSubGroupSize(D, AL, E);
4160 }
4161 
4162 IntelNamedSubGroupSizeAttr *
4164  const IntelNamedSubGroupSizeAttr &A) {
4165  // Check to see if there's a duplicate attribute with different values
4166  // already applied to the declaration.
4167  if (const auto *DeclAttr = D->getAttr<IntelNamedSubGroupSizeAttr>()) {
4168  if (DeclAttr->getType() != A.getType()) {
4169  Diag(DeclAttr->getLoc(), diag::warn_duplicate_attribute) << &A;
4170  Diag(A.getLoc(), diag::note_previous_attribute);
4171  }
4172  return nullptr;
4173  }
4174 
4175  return IntelNamedSubGroupSizeAttr::Create(Context, A.getType(), A);
4176 }
4177 
4178 static void handleIntelNamedSubGroupSize(Sema &S, Decl *D,
4179  const ParsedAttr &AL) {
4180  StringRef SizeStr;
4182  if (AL.isArgIdent(0)) {
4183  IdentifierLoc *IL = AL.getArgAsIdent(0);
4184  SizeStr = IL->Ident->getName();
4185  Loc = IL->Loc;
4186  } else if (!S.checkStringLiteralArgumentAttr(AL, 0, SizeStr, &Loc)) {
4187  return;
4188  }
4189 
4190  IntelNamedSubGroupSizeAttr::SubGroupSizeType SizeType;
4191  if (!IntelNamedSubGroupSizeAttr::ConvertStrToSubGroupSizeType(SizeStr,
4192  SizeType)) {
4193  S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << SizeStr;
4194  return;
4195  }
4196  D->addAttr(IntelNamedSubGroupSizeAttr::Create(S.Context, SizeType, AL));
4197 }
4198 
4200  const AttributeCommonInfo &CI,
4201  Expr *E) {
4202  if (!E->isValueDependent()) {
4203  // Validate that we have an integer constant expression and then store the
4204  // converted constant expression into the semantic attribute so that we
4205  // don't have to evaluate it again later.
4206  llvm::APSInt ArgVal;
4207  ExprResult Res = VerifyIntegerConstantExpression(E, &ArgVal);
4208  if (Res.isInvalid())
4209  return;
4210  E = Res.get();
4211 
4212  // This attribute requires a strictly positive value.
4213  if (ArgVal <= 0) {
4214  Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer)
4215  << CI << /*positive*/ 0;
4216  return;
4217  }
4218 
4219  // Check to see if there's a duplicate attribute with different values
4220  // already applied to the declaration.
4221  if (const auto *DeclAttr = D->getAttr<SYCLIntelNumSimdWorkItemsAttr>()) {
4222  // If the other attribute argument is instantiation dependent, we won't
4223  // have converted it to a constant expression yet and thus we test
4224  // whether this is a null pointer.
4225  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
4226  if (ArgVal != DeclExpr->getResultAsAPSInt()) {
4227  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << CI;
4228  Diag(DeclAttr->getLoc(), diag::note_previous_attribute);
4229  }
4230  // Drop the duplicate attribute.
4231  return;
4232  }
4233  }
4234 
4235  // If the 'reqd_work_group_size' attribute is specified on a declaration
4236  // along with 'num_simd_work_items' attribute, the required work group size
4237  // specified by 'num_simd_work_items' attribute must evenly divide the index
4238  // that increments fastest in the 'reqd_work_group_size' attribute.
4239  if (const auto *DeclAttr = D->getAttr<SYCLReqdWorkGroupSizeAttr>()) {
4240  if (CheckWorkGroupSize(*this, E, DeclAttr->getXDim(), DeclAttr->getYDim(),
4241  DeclAttr->getZDim())) {
4242  Diag(CI.getLoc(), diag::err_sycl_num_kernel_wrong_reqd_wg_size)
4243  << CI << DeclAttr;
4244  Diag(DeclAttr->getLoc(), diag::note_conflicting_attribute);
4245  return;
4246  }
4247  }
4248  }
4249 
4250  D->addAttr(::new (Context) SYCLIntelNumSimdWorkItemsAttr(Context, CI, E));
4251 }
4252 
4253 SYCLIntelNumSimdWorkItemsAttr *Sema::MergeSYCLIntelNumSimdWorkItemsAttr(
4254  Decl *D, const SYCLIntelNumSimdWorkItemsAttr &A) {
4255  // Check to see if there's a duplicate attribute with different values
4256  // already applied to the declaration.
4257  if (const auto *DeclAttr = D->getAttr<SYCLIntelNumSimdWorkItemsAttr>()) {
4258  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
4259  if (const auto *MergeExpr = dyn_cast<ConstantExpr>(A.getValue())) {
4260  if (DeclExpr->getResultAsAPSInt() != MergeExpr->getResultAsAPSInt()) {
4261  Diag(DeclAttr->getLoc(), diag::warn_duplicate_attribute) << &A;
4262  Diag(A.getLoc(), diag::note_previous_attribute);
4263  }
4264  // Do not add a duplicate attribute.
4265  return nullptr;
4266  }
4267  }
4268  }
4269 
4270  // If the 'reqd_work_group_size' attribute is specified on a declaration
4271  // along with 'num_simd_work_items' attribute, the required work group size
4272  // specified by 'num_simd_work_items' attribute must evenly divide the index
4273  // that increments fastest in the 'reqd_work_group_size' attribute.
4274  if (const auto *DeclAttr = D->getAttr<SYCLReqdWorkGroupSizeAttr>()) {
4275  if (CheckWorkGroupSize(*this, A.getValue(), DeclAttr->getXDim(),
4276  DeclAttr->getYDim(), DeclAttr->getZDim())) {
4277  Diag(A.getLoc(), diag::err_sycl_num_kernel_wrong_reqd_wg_size)
4278  << &A << DeclAttr;
4279  Diag(DeclAttr->getLoc(), diag::note_conflicting_attribute);
4280  return nullptr;
4281  }
4282  }
4283 
4284  return ::new (Context)
4285  SYCLIntelNumSimdWorkItemsAttr(Context, A, A.getValue());
4286 }
4287 
4288 static void handleSYCLIntelNumSimdWorkItemsAttr(Sema &S, Decl *D,
4289  const ParsedAttr &A) {
4290  Expr *E = A.getArgAsExpr(0);
4292 }
4293 
4294 // Handles use_stall_enable_clusters
4295 static void handleSYCLIntelUseStallEnableClustersAttr(Sema &S, Decl *D,
4296  const ParsedAttr &A) {
4297  D->addAttr(::new (S.Context)
4298  SYCLIntelUseStallEnableClustersAttr(S.Context, A));
4299 }
4300 
4301 // Handles initiation_interval attribute.
4303  const AttributeCommonInfo &CI,
4304  Expr *E) {
4305  if (!E->isValueDependent()) {
4306  // Validate that we have an integer constant expression and then store the
4307  // converted constant expression into the semantic attribute so that we
4308  // don't have to evaluate it again later.
4309  llvm::APSInt ArgVal;
4310  ExprResult Res = VerifyIntegerConstantExpression(E, &ArgVal);
4311  if (Res.isInvalid())
4312  return;
4313  E = Res.get();
4314  // This attribute requires a strictly positive value.
4315  if (ArgVal <= 0) {
4316  Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer)
4317  << CI << /*positive*/ 0;
4318  return;
4319  }
4320  // Check to see if there's a duplicate attribute with different values
4321  // already applied to the declaration.
4322  if (const auto *DeclAttr =
4323  D->getAttr<SYCLIntelInitiationIntervalAttr>()) {
4324  // If the other attribute argument is instantiation dependent, we won't
4325  // have converted it to a constant expression yet and thus we test
4326  // whether this is a null pointer.
4327  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getNExpr())) {
4328  if (ArgVal != DeclExpr->getResultAsAPSInt()) {
4329  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << CI;
4330  Diag(DeclAttr->getLoc(), diag::note_previous_attribute);
4331  }
4332  // Drop the duplicate attribute.
4333  return;
4334  }
4335  }
4336  }
4337 
4338  D->addAttr(::new (Context)
4339  SYCLIntelInitiationIntervalAttr(Context, CI, E));
4340 }
4341 
4342 SYCLIntelInitiationIntervalAttr *
4344  Decl *D, const SYCLIntelInitiationIntervalAttr &A) {
4345  // Check to see if there's a duplicate attribute with different values
4346  // already applied to the declaration.
4347  if (const auto *DeclAttr =
4348  D->getAttr<SYCLIntelInitiationIntervalAttr>()) {
4349  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getNExpr())) {
4350  if (const auto *MergeExpr = dyn_cast<ConstantExpr>(A.getNExpr())) {
4351  if (DeclExpr->getResultAsAPSInt() != MergeExpr->getResultAsAPSInt()) {
4352  Diag(DeclAttr->getLoc(), diag::warn_duplicate_attribute) << &A;
4353  Diag(A.getLoc(), diag::note_previous_attribute);
4354  }
4355  // Do not add a duplicate attribute.
4356  return nullptr;
4357  }
4358  }
4359  }
4360 
4361  return ::new (Context)
4362  SYCLIntelInitiationIntervalAttr(Context, A, A.getNExpr());
4363 }
4364 
4366  const ParsedAttr &A) {
4368 
4370 }
4371 
4372 // Handle scheduler_target_fmax_mhz
4374  const AttributeCommonInfo &CI,
4375  Expr *E) {
4376  if (!E->isValueDependent()) {
4377  // Validate that we have an integer constant expression and then store the
4378  // converted constant expression into the semantic attribute so that we
4379  // don't have to evaluate it again later.
4380  llvm::APSInt ArgVal;
4381  ExprResult Res = VerifyIntegerConstantExpression(E, &ArgVal);
4382  if (Res.isInvalid())
4383  return;
4384  E = Res.get();
4385 
4386  // This attribute requires a non-negative value.
4387  if (ArgVal < 0) {
4388  Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer)
4389  << CI << /*non-negative*/ 1;
4390  return;
4391  }
4392  // Check to see if there's a duplicate attribute with different values
4393  // already applied to the declaration.
4394  if (const auto *DeclAttr =
4395  D->getAttr<SYCLIntelSchedulerTargetFmaxMhzAttr>()) {
4396  // If the other attribute argument is instantiation dependent, we won't
4397  // have converted it to a constant expression yet and thus we test
4398  // whether this is a null pointer.
4399  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
4400  if (ArgVal != DeclExpr->getResultAsAPSInt()) {
4401  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << CI;
4402  Diag(DeclAttr->getLoc(), diag::note_previous_attribute);
4403  }
4404  // Drop the duplicate attribute.
4405  return;
4406  }
4407  }
4408  }
4409 
4410  D->addAttr(::new (Context)
4411  SYCLIntelSchedulerTargetFmaxMhzAttr(Context, CI, E));
4412 }
4413 
4414 SYCLIntelSchedulerTargetFmaxMhzAttr *
4416  Decl *D, const SYCLIntelSchedulerTargetFmaxMhzAttr &A) {
4417  // Check to see if there's a duplicate attribute with different values
4418  // already applied to the declaration.
4419  if (const auto *DeclAttr =
4420  D->getAttr<SYCLIntelSchedulerTargetFmaxMhzAttr>()) {
4421  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
4422  if (const auto *MergeExpr = dyn_cast<ConstantExpr>(A.getValue())) {
4423  if (DeclExpr->getResultAsAPSInt() != MergeExpr->getResultAsAPSInt()) {
4424  Diag(DeclAttr->getLoc(), diag::warn_duplicate_attribute) << &A;
4425  Diag(A.getLoc(), diag::note_previous_attribute);
4426  return nullptr;
4427  }
4428  // Do not add a duplicate attribute.
4429  return nullptr;
4430  }
4431  }
4432  }
4433  return ::new (Context)
4434  SYCLIntelSchedulerTargetFmaxMhzAttr(Context, A, A.getValue());
4435 }
4436 
4437 static void handleSYCLIntelSchedulerTargetFmaxMhzAttr(Sema &S, Decl *D,
4438  const ParsedAttr &AL) {
4439  Expr *E = AL.getArgAsExpr(0);
4441 }
4442 
4443 // Handles max_global_work_dim.
4444 // Returns a OneArgResult value; EqualToOne means all argument values are
4445 // equal to one, NotEqualToOne means at least one argument value is not
4446 // equal to one, and Unknown means that at least one of the argument values
4447 // could not be determined.
4448 enum class OneArgResult { Unknown, EqualToOne, NotEqualToOne };
4449 static OneArgResult AreAllArgsOne(const Expr *Args[], size_t Count) {
4450 
4451  for (size_t Idx = 0; Idx < Count; ++Idx) {
4452  const Expr *Arg = Args[Idx];
4453  // Optional arguments are considered trivially one.
4454  if (!Arg)
4455  return OneArgResult::EqualToOne;
4456  const auto *CE = dyn_cast<ConstantExpr>(Args[Idx]);
4457  if (!CE)
4458  return OneArgResult::Unknown;
4459  if (CE->getResultAsAPSInt() != 1)
4460  return OneArgResult::NotEqualToOne;
4461  }
4462  return OneArgResult::EqualToOne;
4463 }
4464 
4465 // If the declaration has a SYCLIntelMaxWorkGroupSizeAttr or
4466 // ReqdWorkGroupSizeAttr, check to see if they hold equal values
4467 // (1, 1, 1). Returns true if diagnosed.
4468 template <typename AttrTy>
4469 static bool checkWorkGroupSizeAttrExpr(Sema &S, Decl *D,
4470  const AttributeCommonInfo &AL) {
4471  if (const auto *A = D->getAttr<AttrTy>()) {
4472  const Expr *Args[3] = {A->getXDim(), A->getYDim(), A->getZDim()};
4473  if (OneArgResult::NotEqualToOne == AreAllArgsOne(Args, 3)) {
4474  S.Diag(A->getLocation(), diag::err_sycl_x_y_z_arguments_must_be_one)
4475  << A << AL;
4476  return true;
4477  }
4478  }
4479  return false;
4480 }
4481 
4483  const AttributeCommonInfo &CI,
4484  Expr *E) {
4485  if (!E->isValueDependent()) {
4486  // Validate that we have an integer constant expression and then store the
4487  // converted constant expression into the semantic attribute so that we
4488  // don't have to evaluate it again later.
4489  llvm::APSInt ArgVal;
4490  ExprResult Res = VerifyIntegerConstantExpression(E, &ArgVal);
4491  if (Res.isInvalid())
4492  return;
4493  E = Res.get();
4494 
4495  // This attribute must be in the range [0, 3].
4496  if (ArgVal < 0 || ArgVal > 3) {
4497  Diag(E->getBeginLoc(), diag::err_attribute_argument_out_of_range)
4498  << CI << 0 << 3 << E->getSourceRange();
4499  return;
4500  }
4501 
4502  // Check to see if there's a duplicate attribute with different values
4503  // already applied to the declaration.
4504  if (const auto *DeclAttr = D->getAttr<SYCLIntelMaxGlobalWorkDimAttr>()) {
4505  // If the other attribute argument is instantiation dependent, we won't
4506  // have converted it to a constant expression yet and thus we test
4507  // whether this is a null pointer.
4508  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
4509  if (ArgVal != DeclExpr->getResultAsAPSInt()) {
4510  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << CI;
4511  Diag(DeclAttr->getLoc(), diag::note_previous_attribute);
4512  }
4513  // Drop the duplicate attribute.
4514  return;
4515  }
4516  }
4517 
4518  // If the declaration has a SYCLIntelMaxWorkGroupSizeAttr or
4519  // SYCLReqdWorkGroupSizeAttr, check to see if the attribute holds values
4520  // equal to (1, 1, 1) in case the value of SYCLIntelMaxGlobalWorkDimAttr
4521  // equals to 0.
4522  if (ArgVal == 0) {
4523  if (checkWorkGroupSizeAttrExpr<SYCLIntelMaxWorkGroupSizeAttr>(*this, D,
4524  CI) ||
4525  checkWorkGroupSizeAttrExpr<SYCLReqdWorkGroupSizeAttr>(*this, D, CI))
4526  return;
4527  }
4528  }
4529 
4530  D->addAttr(::new (Context) SYCLIntelMaxGlobalWorkDimAttr(Context, CI, E));
4531 }
4532 
4533 // Check that the value is a non-negative integer constant that can fit in
4534 // 32-bits. Issue correct error message and return false on failure.
4535 bool static check32BitInt(const Expr *E, Sema &S, llvm::APSInt &I,
4536  const AttributeCommonInfo &CI) {
4537  if (!I.isIntN(32)) {
4538  S.Diag(E->getExprLoc(), diag::err_ice_too_large)
4539  << llvm::toString(I, 10, false) << 32 << /* Unsigned */ 1;
4540  return false;
4541  }
4542 
4543  if (I.isSigned() && I.isNegative()) {
4544  S.Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer)
4545  << CI << /* Non-negative */ 1;
4546  return false;
4547  }
4548 
4549  return true;
4550 }
4551 
4553  Decl *D, const AttributeCommonInfo &CI, Expr *E) {
4554  if (Context.getLangOpts().SYCLIsDevice &&
4555  !Context.getTargetInfo().getTriple().isNVPTX()) {
4556  Diag(E->getBeginLoc(), diag::warn_launch_bounds_is_cuda_specific)
4557  << CI << E->getSourceRange();
4558  return;
4559  }
4560  if (!E->isValueDependent()) {
4561  // Validate that we have an integer constant expression and then store the
4562  // converted constant expression into the semantic attribute so that we
4563  // don't have to evaluate it again later.
4564  llvm::APSInt ArgVal;
4565  ExprResult Res = VerifyIntegerConstantExpression(E, &ArgVal);
4566  if (Res.isInvalid())
4567  return;
4568  if (!check32BitInt(E, *this, ArgVal, CI))
4569  return;
4570  E = Res.get();
4571 
4572  // Check to see if there's a duplicate attribute with different values
4573  // already applied to the declaration.
4574  if (const auto *DeclAttr =
4575  D->getAttr<SYCLIntelMinWorkGroupsPerComputeUnitAttr>()) {
4576  // If the other attribute argument is instantiation dependent, we won't
4577  // have converted it to a constant expression yet and thus we test
4578  // whether this is a null pointer.
4579  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
4580  if (ArgVal != DeclExpr->getResultAsAPSInt()) {
4581  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << CI;
4582  Diag(DeclAttr->getLoc(), diag::note_previous_attribute);
4583  }
4584  // Drop the duplicate attribute.
4585  return;
4586  }
4587  }
4588  }
4589 
4590  D->addAttr(::new (Context)
4591  SYCLIntelMinWorkGroupsPerComputeUnitAttr(Context, CI, E));
4592 }
4593 
4594 // Helper to get CudaArch.
4595 static CudaArch getCudaArch(const TargetInfo &TI) {
4596  if (!TI.getTriple().isNVPTX())
4597  llvm_unreachable("getCudaArch is only valid for NVPTX triple");
4598  auto &TO = TI.getTargetOpts();
4599  return StringToCudaArch(TO.CPU);
4600 }
4601 
4603  Decl *D, const AttributeCommonInfo &CI, Expr *E) {
4604  auto &TI = Context.getTargetInfo();
4605  if (Context.getLangOpts().SYCLIsDevice) {
4606  if (!TI.getTriple().isNVPTX()) {
4607  Diag(E->getBeginLoc(), diag::warn_launch_bounds_is_cuda_specific)
4608  << CI << E->getSourceRange();
4609  return;
4610  }
4611 
4612  // Feature '.maxclusterrank' requires .target sm_90 or higher.
4613  auto SM = getCudaArch(TI);
4614  if (SM == CudaArch::UNKNOWN || SM < CudaArch::SM_90) {
4615  Diag(E->getBeginLoc(), diag::warn_cuda_maxclusterrank_sm_90)
4616  << CudaArchToString(SM) << CI << E->getSourceRange();
4617  return;
4618  }
4619  }
4620  if (!E->isValueDependent()) {
4621  // Validate that we have an integer constant expression and then store the
4622  // converted constant expression into the semantic attribute so that we
4623  // don't have to evaluate it again later.
4624  llvm::APSInt ArgVal;
4625  ExprResult Res = VerifyIntegerConstantExpression(E, &ArgVal);
4626  if (Res.isInvalid())
4627  return;
4628  if (!check32BitInt(E, *this, ArgVal, CI))
4629  return;
4630  E = Res.get();
4631 
4632  // Check to see if there's a duplicate attribute with different values
4633  // already applied to the declaration.
4634  if (const auto *DeclAttr =
4635  D->getAttr<SYCLIntelMaxWorkGroupsPerMultiprocessorAttr>()) {
4636  // If the other attribute argument is instantiation dependent, we won't
4637  // have converted it to a constant expression yet and thus we test
4638  // whether this is a null pointer.
4639  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
4640  if (ArgVal != DeclExpr->getResultAsAPSInt()) {
4641  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << CI;
4642  Diag(DeclAttr->getLoc(), diag::note_previous_attribute);
4643  }
4644  // Drop the duplicate attribute.
4645  return;
4646  }
4647  }
4648  }
4649 
4650  D->addAttr(::new (Context)
4651  SYCLIntelMaxWorkGroupsPerMultiprocessorAttr(Context, CI, E));
4652 }
4653 
4654 SYCLIntelMaxGlobalWorkDimAttr *Sema::MergeSYCLIntelMaxGlobalWorkDimAttr(
4655  Decl *D, const SYCLIntelMaxGlobalWorkDimAttr &A) {
4656  // Check to see if there's a duplicate attribute with different values
4657  // already applied to the declaration.
4658  if (const auto *DeclAttr = D->getAttr<SYCLIntelMaxGlobalWorkDimAttr>()) {
4659  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
4660  if (const auto *MergeExpr = dyn_cast<ConstantExpr>(A.getValue())) {
4661  if (DeclExpr->getResultAsAPSInt() != MergeExpr->getResultAsAPSInt()) {
4662  Diag(DeclAttr->getLoc(), diag::warn_duplicate_attribute) << &A;
4663  Diag(A.getLoc(), diag::note_previous_attribute);
4664  }
4665  // Do not add a duplicate attribute.
4666  return nullptr;
4667  }
4668  }
4669  }
4670 
4671  // If the declaration has a SYCLIntelMaxWorkGroupSizeAttr or
4672  // SYCLReqdWorkGroupSizeAttr, check to see if the attribute holds values equal
4673  // to (1, 1, 1) in case the value of SYCLIntelMaxGlobalWorkDimAttr equals to
4674  // 0.
4675  const auto *MergeExpr = dyn_cast<ConstantExpr>(A.getValue());
4676  if (MergeExpr && MergeExpr->getResultAsAPSInt() == 0) {
4677  if (checkWorkGroupSizeAttrExpr<SYCLIntelMaxWorkGroupSizeAttr>(*this, D,
4678  A) ||
4679  checkWorkGroupSizeAttrExpr<SYCLReqdWorkGroupSizeAttr>(*this, D, A))
4680  return nullptr;
4681  }
4682 
4683  return ::new (Context)
4684  SYCLIntelMaxGlobalWorkDimAttr(Context, A, A.getValue());
4685 }
4686 
4687 static void handleSYCLIntelMaxGlobalWorkDimAttr(Sema &S, Decl *D,
4688  const ParsedAttr &AL) {
4689  Expr *E = AL.getArgAsExpr(0);
4691 }
4692 
4693 SYCLIntelMinWorkGroupsPerComputeUnitAttr *
4695  Decl *D, const SYCLIntelMinWorkGroupsPerComputeUnitAttr &A) {
4696  // Check to see if there's a duplicate attribute with different values
4697  // already applied to the declaration.
4698  if (const auto *DeclAttr =
4699  D->getAttr<SYCLIntelMinWorkGroupsPerComputeUnitAttr>()) {
4700  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
4701  if (const auto *MergeExpr = dyn_cast<ConstantExpr>(A.getValue())) {
4702  if (DeclExpr->getResultAsAPSInt() != MergeExpr->getResultAsAPSInt()) {
4703  Diag(DeclAttr->getLoc(), diag::warn_duplicate_attribute) << &A;
4704  Diag(A.getLoc(), diag::note_previous_attribute);
4705  }
4706  // Do not add a duplicate attribute.
4707  return nullptr;
4708  }
4709  }
4710  }
4711 
4712  return ::new (Context)
4713  SYCLIntelMinWorkGroupsPerComputeUnitAttr(Context, A, A.getValue());
4714 }
4715 
4716 SYCLIntelMaxWorkGroupsPerMultiprocessorAttr *
4718  Decl *D, const SYCLIntelMaxWorkGroupsPerMultiprocessorAttr &A) {
4719  // Check to see if there's a duplicate attribute with different values
4720  // already applied to the declaration.
4721  if (const auto *DeclAttr =
4722  D->getAttr<SYCLIntelMaxWorkGroupsPerMultiprocessorAttr>()) {
4723  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
4724  if (const auto *MergeExpr = dyn_cast<ConstantExpr>(A.getValue())) {
4725  if (DeclExpr->getResultAsAPSInt() != MergeExpr->getResultAsAPSInt()) {
4726  Diag(DeclAttr->getLoc(), diag::warn_duplicate_attribute) << &A;
4727  Diag(A.getLoc(), diag::note_previous_attribute);
4728  }
4729  // Do not add a duplicate attribute.
4730  return nullptr;
4731  }
4732  }
4733  }
4734 
4735  return ::new (Context)
4736  SYCLIntelMaxWorkGroupsPerMultiprocessorAttr(Context, A, A.getValue());
4737 }
4738 
4739 // Handles [[intel::loop_fuse]] and [[intel::loop_fuse_independent]].
4741  Expr *E) {
4742  if (!E->isValueDependent()) {
4743  // Validate that we have an integer constant expression and then store the
4744  // converted constant expression into the semantic attribute so that we
4745  // don't have to evaluate it again later.
4746  llvm::APSInt ArgVal;
4747  ExprResult Res = VerifyIntegerConstantExpression(E, &ArgVal);
4748  if (Res.isInvalid())
4749  return;
4750  E = Res.get();
4751 
4752  // This attribute requires a non-negative value.
4753  if (ArgVal < 0) {
4754  Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer)
4755  << CI << /*non-negative*/ 1;
4756  return;
4757  }
4758  // Check to see if there's a duplicate attribute with different values
4759  // already applied to the declaration.
4760  if (const auto *DeclAttr = D->getAttr<SYCLIntelLoopFuseAttr>()) {
4761  // [[intel::loop_fuse]] and [[intel::loop_fuse_independent]] are
4762  // incompatible.
4763  // FIXME: If additional spellings are provided for this attribute,
4764  // this code will do the wrong thing.
4765  if (DeclAttr->getAttributeSpellingListIndex() !=
4767  Diag(CI.getLoc(), diag::err_attributes_are_not_compatible)
4768  << CI << DeclAttr << CI.isRegularKeywordAttribute();
4769  Diag(DeclAttr->getLocation(), diag::note_conflicting_attribute);
4770  return;
4771  }
4772  // If the other attribute argument is instantiation dependent, we won't
4773  // have converted it to a constant expression yet and thus we test
4774  // whether this is a null pointer.
4775  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
4776  if (ArgVal != DeclExpr->getResultAsAPSInt()) {
4777  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << CI;
4778  Diag(DeclAttr->getLoc(), diag::note_previous_attribute);
4779  }
4780  // Drop the duplicate attribute.
4781  return;
4782  }
4783  }
4784  }
4785 
4786  D->addAttr(::new (Context) SYCLIntelLoopFuseAttr(Context, CI, E));
4787 }
4788 
4789 SYCLIntelLoopFuseAttr *
4790 Sema::MergeSYCLIntelLoopFuseAttr(Decl *D, const SYCLIntelLoopFuseAttr &A) {
4791  // Check to see if there's a duplicate attribute with different values
4792  // already applied to the declaration.
4793  if (const auto *DeclAttr = D->getAttr<SYCLIntelLoopFuseAttr>()) {
4794  // [[intel::loop_fuse]] and [[intel::loop_fuse_independent]] are
4795  // incompatible.
4796  // FIXME: If additional spellings are provided for this attribute,
4797  // this code will do the wrong thing.
4798  if (DeclAttr->getAttributeSpellingListIndex() !=
4799  A.getAttributeSpellingListIndex()) {
4800  Diag(A.getLoc(), diag::err_attributes_are_not_compatible)
4801  << &A << DeclAttr << A.isRegularKeywordAttribute();
4802  Diag(DeclAttr->getLoc(), diag::note_conflicting_attribute);
4803  return nullptr;
4804  }
4805  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
4806  if (const auto *MergeExpr = dyn_cast<ConstantExpr>(A.getValue())) {
4807  if (DeclExpr->getResultAsAPSInt() != MergeExpr->getResultAsAPSInt()) {
4808  Diag(DeclAttr->getLoc(), diag::warn_duplicate_attribute) << &A;
4809  Diag(A.getLoc(), diag::note_previous_attribute);
4810  }
4811  // Do not add a duplicate attribute.
4812  return nullptr;
4813  }
4814  }
4815  }
4816 
4817  return ::new (Context) SYCLIntelLoopFuseAttr(Context, A, A.getValue());
4818 }
4819 
4820 static void handleSYCLIntelLoopFuseAttr(Sema &S, Decl *D, const ParsedAttr &A) {
4821  // If no attribute argument is specified, set to default value '1'.
4822  Expr *E = A.isArgExpr(0)
4823  ? A.getArgAsExpr(0)
4825  S.Context.IntTy, A.getLoc());
4826 
4827  S.AddSYCLIntelLoopFuseAttr(D, A, E);
4828 }
4829 
4830 static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
4831  // This attribute is deprecated without replacement in SYCL 2020 mode.
4832  // Ignore the attribute in SYCL 2020.
4833  if (S.LangOpts.getSYCLVersion() > LangOptions::SYCL_2017) {
4834  S.Diag(AL.getLoc(), diag::warn_attribute_deprecated_ignored) << AL;
4835  return;
4836  }
4837 
4838  // If the attribute is used with the [[sycl::vec_type_hint]] spelling in SYCL
4839  // 2017 mode, we want to warn about using the newer name in the older
4840  // standard as a compatibility extension.
4841  if (S.LangOpts.getSYCLVersion() == LangOptions::SYCL_2017 && AL.hasScope())
4842  S.Diag(AL.getLoc(), diag::ext_sycl_2020_attr_spelling) << AL;
4843 
4844  if (!AL.hasParsedType()) {
4845  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
4846  return;
4847  }
4848 
4849  TypeSourceInfo *ParmTSI = nullptr;
4850  QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
4851  assert(ParmTSI && "no type source info for attribute argument");
4852 
4853  if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
4854  (ParmType->isBooleanType() ||
4855  !ParmType->isIntegralType(S.getASTContext()))) {
4856  S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) << 2 << AL;
4857  return;
4858  }
4859 
4860  if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
4861  if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
4862  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
4863  return;
4864  }
4865  }
4866 
4867  D->addAttr(::new (S.Context) VecTypeHintAttr(S.Context, AL, ParmTSI));
4868 }
4869 
4870 SectionAttr *Sema::mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
4871  StringRef Name) {
4872  // Explicit or partial specializations do not inherit
4873  // the section attribute from the primary template.
4874  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4875  if (CI.getAttributeSpellingListIndex() == SectionAttr::Declspec_allocate &&
4877  return nullptr;
4878  }
4879  if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
4880  if (ExistingAttr->getName() == Name)
4881  return nullptr;
4882  Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
4883  << 1 /*section*/;
4884  Diag(CI.getLoc(), diag::note_previous_attribute);
4885  return nullptr;
4886  }
4887  return ::new (Context) SectionAttr(Context, CI, Name);
4888 }
4889 
4890 /// Used to implement to perform semantic checking on
4891 /// attribute((section("foo"))) specifiers.
4892 ///
4893 /// In this case, "foo" is passed in to be checked. If the section
4894 /// specifier is invalid, return an Error that indicates the problem.
4895 ///
4896 /// This is a simple quality of implementation feature to catch errors
4897 /// and give good diagnostics in cases when the assembler or code generator
4898 /// would otherwise reject the section specifier.
4899 llvm::Error Sema::isValidSectionSpecifier(StringRef SecName) {
4900  if (!Context.getTargetInfo().getTriple().isOSDarwin())
4901  return llvm::Error::success();
4902 
4903  // Let MCSectionMachO validate this.
4904  StringRef Segment, Section;
4905  unsigned TAA, StubSize;
4906  bool HasTAA;
4907  return llvm::MCSectionMachO::ParseSectionSpecifier(SecName, Segment, Section,
4908  TAA, HasTAA, StubSize);
4909 }
4910 
4911 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
4912  if (llvm::Error E = isValidSectionSpecifier(SecName)) {
4913  Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
4914  << toString(std::move(E)) << 1 /*'section'*/;
4915  return false;
4916  }
4917  return true;
4918 }
4919 
4920 static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4921  // Make sure that there is a string literal as the sections's single
4922  // argument.
4923  StringRef Str;
4924  SourceLocation LiteralLoc;
4925  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
4926  return;
4927 
4928  if (!S.checkSectionName(LiteralLoc, Str))
4929  return;
4930 
4931  SectionAttr *NewAttr = S.mergeSectionAttr(D, AL, Str);
4932  if (NewAttr) {
4933  D->addAttr(NewAttr);
4935  ObjCPropertyDecl>(D))
4936  S.UnifySection(NewAttr->getName(),
4938  cast<NamedDecl>(D));
4939  }
4940 }
4941 
4942 static void handleCodeModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4943  StringRef Str;
4944  SourceLocation LiteralLoc;
4945  // Check that it is a string.
4946  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
4947  return;
4948 
4949  llvm::CodeModel::Model CM;
4950  if (!CodeModelAttr::ConvertStrToModel(Str, CM)) {
4951  S.Diag(LiteralLoc, diag::err_attr_codemodel_arg) << Str;
4952  return;
4953  }
4954 
4955  D->addAttr(::new (S.Context) CodeModelAttr(S.Context, AL, CM));
4956 }
4957 
4958 // This is used for `__declspec(code_seg("segname"))` on a decl.
4959 // `#pragma code_seg("segname")` uses checkSectionName() instead.
4960 static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc,
4961  StringRef CodeSegName) {
4962  if (llvm::Error E = S.isValidSectionSpecifier(CodeSegName)) {
4963  S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
4964  << toString(std::move(E)) << 0 /*'code-seg'*/;
4965  return false;
4966  }
4967 
4968  return true;
4969 }
4970 
4971 CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
4972  StringRef Name) {
4973  // Explicit or partial specializations do not inherit
4974  // the code_seg attribute from the primary template.
4975  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4977  return nullptr;
4978  }
4979  if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
4980  if (ExistingAttr->getName() == Name)
4981  return nullptr;
4982  Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
4983  << 0 /*codeseg*/;
4984  Diag(CI.getLoc(), diag::note_previous_attribute);
4985  return nullptr;
4986  }
4987  return ::new (Context) CodeSegAttr(Context, CI, Name);
4988 }
4989 
4990 static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4991  StringRef Str;
4992  SourceLocation LiteralLoc;
4993  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
4994  return;
4995  if (!checkCodeSegName(S, LiteralLoc, Str))
4996  return;
4997  if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
4998  if (!ExistingAttr->isImplicit()) {
4999  S.Diag(AL.getLoc(),
5000  ExistingAttr->getName() == Str
5001  ? diag::warn_duplicate_codeseg_attribute
5002  : diag::err_conflicting_codeseg_attribute);
5003  return;
5004  }
5005  D->dropAttr<CodeSegAttr>();
5006  }
5007  if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL, Str))
5008  D->addAttr(CSA);
5009 }
5010 
5011 // Check for things we'd like to warn about. Multiversioning issues are
5012 // handled later in the process, once we know how many exist.
5013 bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
5014  enum FirstParam { Unsupported, Duplicate, Unknown };
5015  enum SecondParam { None, CPU, Tune };
5016  enum ThirdParam { Target, TargetClones };
5017  if (AttrStr.contains("fpmath="))
5018  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
5019  << Unsupported << None << "fpmath=" << Target;
5020 
5021  // Diagnose use of tune if target doesn't support it.
5022  if (!Context.getTargetInfo().supportsTargetAttributeTune() &&
5023  AttrStr.contains("tune="))
5024  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
5025  << Unsupported << None << "tune=" << Target;
5026 
5027  ParsedTargetAttr ParsedAttrs =
5028  Context.getTargetInfo().parseTargetAttr(AttrStr);
5029 
5030  if (!ParsedAttrs.CPU.empty() &&
5031  !Context.getTargetInfo().isValidCPUName(ParsedAttrs.CPU))
5032  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
5033  << Unknown << CPU << ParsedAttrs.CPU << Target;
5034 
5035  if (!ParsedAttrs.Tune.empty() &&
5036  !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Tune))
5037  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
5038  << Unknown << Tune << ParsedAttrs.Tune << Target;
5039 
5040  if (Context.getTargetInfo().getTriple().isRISCV() &&
5041  ParsedAttrs.Duplicate != "")
5042  return Diag(LiteralLoc, diag::err_duplicate_target_attribute)
5043  << Duplicate << None << ParsedAttrs.Duplicate << Target;
5044 
5045  if (ParsedAttrs.Duplicate != "")
5046  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
5047  << Duplicate << None << ParsedAttrs.Duplicate << Target;
5048 
5049  for (const auto &Feature : ParsedAttrs.Features) {
5050  auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
5051  if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
5052  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
5053  << Unsupported << None << CurFeature << Target;
5054  }
5055 
5057  StringRef DiagMsg;
5058  if (ParsedAttrs.BranchProtection.empty())
5059  return false;
5060  if (!Context.getTargetInfo().validateBranchProtection(
5061  ParsedAttrs.BranchProtection, ParsedAttrs.CPU, BPI, DiagMsg)) {
5062  if (DiagMsg.empty())
5063  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
5064  << Unsupported << None << "branch-protection" << Target;
5065  return Diag(LiteralLoc, diag::err_invalid_branch_protection_spec)
5066  << DiagMsg;
5067  }
5068  if (!DiagMsg.empty())
5069  Diag(LiteralLoc, diag::warn_unsupported_branch_protection_spec) << DiagMsg;
5070 
5071  return false;
5072 }
5073 
5074 // Check Target Version attrs
5076  StringRef &AttrStr, bool &isDefault) {
5077  enum FirstParam { Unsupported };
5078  enum SecondParam { None };
5079  enum ThirdParam { Target, TargetClones, TargetVersion };
5080  if (AttrStr.trim() == "default")
5081  isDefault = true;
5083  AttrStr.split(Features, "+");
5084  for (auto &CurFeature : Features) {
5085  CurFeature = CurFeature.trim();
5086  if (CurFeature == "default")
5087  continue;
5088  if (!Context.getTargetInfo().validateCpuSupports(CurFeature))
5089  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
5090  << Unsupported << None << CurFeature << TargetVersion;
5091  }
5092  if (IsArmStreamingFunction(cast<FunctionDecl>(D),
5093  /*IncludeLocallyStreaming=*/false))
5094  return Diag(LiteralLoc, diag::err_sme_streaming_cannot_be_multiversioned);
5095  return false;
5096 }
5097 
5098 static void handleTargetVersionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5099  StringRef Str;
5100  SourceLocation LiteralLoc;
5101  bool isDefault = false;
5102  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
5103  S.checkTargetVersionAttr(LiteralLoc, D, Str, isDefault))
5104  return;
5105  // Do not create default only target_version attribute
5106  if (!isDefault) {
5107  TargetVersionAttr *NewAttr =
5108  ::new (S.Context) TargetVersionAttr(S.Context, AL, Str);
5109  D->addAttr(NewAttr);
5110  }
5111 }
5112 
5113 static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5114  StringRef Str;
5115  SourceLocation LiteralLoc;
5116  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
5117  S.checkTargetAttr(LiteralLoc, Str))
5118  return;
5119 
5120  TargetAttr *NewAttr = ::new (S.Context) TargetAttr(S.Context, AL, Str);
5121  D->addAttr(NewAttr);
5122 }
5123 
5124 bool Sema::checkTargetClonesAttrString(
5125  SourceLocation LiteralLoc, StringRef Str, const StringLiteral *Literal,
5126  Decl *D, bool &HasDefault, bool &HasCommas, bool &HasNotDefault,
5127  SmallVectorImpl<SmallString<64>> &StringsBuffer) {
5128  enum FirstParam { Unsupported, Duplicate, Unknown };
5129  enum SecondParam { None, CPU, Tune };
5130  enum ThirdParam { Target, TargetClones };
5131  HasCommas = HasCommas || Str.contains(',');
5132  const TargetInfo &TInfo = Context.getTargetInfo();
5133  // Warn on empty at the beginning of a string.
5134  if (Str.size() == 0)
5135  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
5136  << Unsupported << None << "" << TargetClones;
5137 
5138  std::pair<StringRef, StringRef> Parts = {{}, Str};
5139  while (!Parts.second.empty()) {
5140  Parts = Parts.second.split(',');
5141  StringRef Cur = Parts.first.trim();
5142  SourceLocation CurLoc =
5143  Literal->getLocationOfByte(Cur.data() - Literal->getString().data(),
5144  getSourceManager(), getLangOpts(), TInfo);
5145 
5146  bool DefaultIsDupe = false;
5147  bool HasCodeGenImpact = false;
5148  if (Cur.empty())
5149  return Diag(CurLoc, diag::warn_unsupported_target_attribute)
5150  << Unsupported << None << "" << TargetClones;
5151 
5152  if (TInfo.getTriple().isAArch64()) {
5153  // AArch64 target clones specific
5154  if (Cur == "default") {
5155  DefaultIsDupe = HasDefault;
5156  HasDefault = true;
5157  if (llvm::is_contained(StringsBuffer, Cur) || DefaultIsDupe)
5158  Diag(CurLoc, diag::warn_target_clone_duplicate_options);
5159  else
5160  StringsBuffer.push_back(Cur);
5161  } else {
5162  std::pair<StringRef, StringRef> CurParts = {{}, Cur};
5163  llvm::SmallVector<StringRef, 8> CurFeatures;
5164  while (!CurParts.second.empty()) {
5165  CurParts = CurParts.second.split('+');
5166  StringRef CurFeature = CurParts.first.trim();
5167  if (!TInfo.validateCpuSupports(CurFeature)) {
5168  Diag(CurLoc, diag::warn_unsupported_target_attribute)
5169  << Unsupported << None << CurFeature << TargetClones;
5170  continue;
5171  }
5172  if (TInfo.doesFeatureAffectCodeGen(CurFeature))
5173  HasCodeGenImpact = true;
5174  CurFeatures.push_back(CurFeature);
5175  }
5176  // Canonize TargetClones Attributes
5177  llvm::sort(CurFeatures);
5178  SmallString<64> Res;
5179  for (auto &CurFeat : CurFeatures) {
5180  if (!Res.empty())
5181  Res.append("+");
5182  Res.append(CurFeat);
5183  }
5184  if (llvm::is_contained(StringsBuffer, Res) || DefaultIsDupe)
5185  Diag(CurLoc, diag::warn_target_clone_duplicate_options);
5186  else if (!HasCodeGenImpact)
5187  // Ignore features in target_clone attribute that don't impact
5188  // code generation
5189  Diag(CurLoc, diag::warn_target_clone_no_impact_options);
5190  else if (!Res.empty()) {
5191  StringsBuffer.push_back(Res);
5192  HasNotDefault = true;
5193  }
5194  }
5195  if (IsArmStreamingFunction(cast<FunctionDecl>(D),
5196  /*IncludeLocallyStreaming=*/false))
5197  return Diag(LiteralLoc,
5198  diag::err_sme_streaming_cannot_be_multiversioned);
5199  } else {
5200  // Other targets ( currently X86 )
5201  if (Cur.starts_with("arch=")) {
5202  if (!Context.getTargetInfo().isValidCPUName(
5203  Cur.drop_front(sizeof("arch=") - 1)))
5204  return Diag(CurLoc, diag::warn_unsupported_target_attribute)
5205  << Unsupported << CPU << Cur.drop_front(sizeof("arch=") - 1)
5206  << TargetClones;
5207  } else if (Cur == "default") {
5208  DefaultIsDupe = HasDefault;
5209  HasDefault = true;
5210  } else if (!Context.getTargetInfo().isValidFeatureName(Cur))
5211  return Diag(CurLoc, diag::warn_unsupported_target_attribute)
5212  << Unsupported << None << Cur << TargetClones;
5213  if (llvm::is_contained(StringsBuffer, Cur) || DefaultIsDupe)
5214  Diag(CurLoc, diag::warn_target_clone_duplicate_options);
5215  // Note: Add even if there are duplicates, since it changes name mangling.
5216  StringsBuffer.push_back(Cur);
5217  }
5218  }
5219 
5220  if (Str.rtrim().ends_with(","))
5221  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
5222  << Unsupported << None << "" << TargetClones;
5223  return false;
5224 }
5225 
5226 static void handleTargetClonesAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5227  if (S.Context.getTargetInfo().getTriple().isAArch64() &&
5228  !S.Context.getTargetInfo().hasFeature("fmv"))
5229  return;
5230 
5231  // Ensure we don't combine these with themselves, since that causes some
5232  // confusing behavior.
5233  if (const auto *Other = D->getAttr<TargetClonesAttr>()) {
5234  S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
5235  S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
5236  return;
5237  }
5238  if (checkAttrMutualExclusion<TargetClonesAttr>(S, D, AL))
5239  return;
5240 
5241  SmallVector<StringRef, 2> Strings;
5242  SmallVector<SmallString<64>, 2> StringsBuffer;
5243  bool HasCommas = false, HasDefault = false, HasNotDefault = false;
5244 
5245  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
5246  StringRef CurStr;
5247  SourceLocation LiteralLoc;
5248  if (!S.checkStringLiteralArgumentAttr(AL, I, CurStr, &LiteralLoc) ||
5250  LiteralLoc, CurStr,
5251  cast<StringLiteral>(AL.getArgAsExpr(I)->IgnoreParenCasts()), D,
5252  HasDefault, HasCommas, HasNotDefault, StringsBuffer))
5253  return;
5254  }
5255 
5256  for (auto &SmallStr : StringsBuffer)
5257  Strings.push_back(SmallStr.str());
5258 
5259  if (HasCommas && AL.getNumArgs() > 1)
5260  S.Diag(AL.getLoc(), diag::warn_target_clone_mixed_values);
5261 
5262  if (S.Context.getTargetInfo().getTriple().isAArch64() && !HasDefault) {
5263  // Add default attribute if there is no one
5264  HasDefault = true;
5265  Strings.push_back("default");
5266  }
5267 
5268  if (!HasDefault) {
5269  S.Diag(AL.getLoc(), diag::err_target_clone_must_have_default);
5270  return;
5271  }
5272 
5273  // FIXME: We could probably figure out how to get this to work for lambdas
5274  // someday.
5275  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
5276  if (MD->getParent()->isLambda()) {
5277  S.Diag(D->getLocation(), diag::err_multiversion_doesnt_support)
5278  << static_cast<unsigned>(MultiVersionKind::TargetClones)
5279  << /*Lambda*/ 9;
5280  return;
5281  }
5282  }
5283 
5284  // No multiversion if we have default version only.
5285  if (S.Context.getTargetInfo().getTriple().isAArch64() && !HasNotDefault)
5286  return;
5287 
5288  cast<FunctionDecl>(D)->setIsMultiVersion();
5289  TargetClonesAttr *NewAttr = ::new (S.Context)
5290  TargetClonesAttr(S.Context, AL, Strings.data(), Strings.size());
5291  D->addAttr(NewAttr);
5292 }
5293 
5294 static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5295  Expr *E = AL.getArgAsExpr(0);
5296  uint32_t VecWidth;
5297  if (!checkUInt32Argument(S, AL, E, VecWidth)) {
5298  AL.setInvalid();
5299  return;
5300  }
5301 
5302  MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
5303  if (Existing && Existing->getVectorWidth() != VecWidth) {
5304  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
5305  return;
5306  }
5307 
5308  D->addAttr(::new (S.Context) MinVectorWidthAttr(S.Context, AL, VecWidth));
5309 }
5310 
5311 static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5312  Expr *E = AL.getArgAsExpr(0);
5313  SourceLocation Loc = E->getExprLoc();
5314  FunctionDecl *FD = nullptr;
5316 
5317  // gcc only allows for simple identifiers. Since we support more than gcc, we
5318  // will warn the user.
5319  if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
5320  if (DRE->hasQualifier())
5321  S.Diag(Loc, diag::warn_cleanup_ext);
5322  FD = dyn_cast<FunctionDecl>(DRE->getDecl());
5323  NI = DRE->getNameInfo();
5324  if (!FD) {
5325  S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
5326  << NI.getName();
5327  return;
5328  }
5329  } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
5330  if (ULE->hasExplicitTemplateArgs())
5331  S.Diag(Loc, diag::warn_cleanup_ext);
5333  NI = ULE->getNameInfo();
5334  if (!FD) {
5335  S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
5336  << NI.getName();
5337  if (ULE->getType() == S.Context.OverloadTy)
5339  return;
5340  }
5341  } else {
5342  S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
5343  return;
5344  }
5345 
5346  if (FD->getNumParams() != 1) {
5347  S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
5348  << NI.getName();
5349  return;
5350  }
5351 
5352  // We're currently more strict than GCC about what function types we accept.
5353  // If this ever proves to be a problem it should be easy to fix.
5354  QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
5355  QualType ParamTy = FD->getParamDecl(0)->getType();
5357  ParamTy, Ty) != Sema::Compatible) {
5358  S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
5359  << NI.getName() << ParamTy << Ty;
5360  return;
5361  }
5362  VarDecl *VD = cast<VarDecl>(D);
5363  // Create a reference to the variable declaration. This is a fake/dummy
5364  // reference.
5365  DeclRefExpr *VariableReference = DeclRefExpr::Create(
5366  S.Context, NestedNameSpecifierLoc{}, FD->getLocation(), VD, false,
5367  DeclarationNameInfo{VD->getDeclName(), VD->getLocation()}, VD->getType(),
5368  VK_LValue);
5369 
5370  // Create a unary operator expression that represents taking the address of
5371  // the variable. This is a fake/dummy expression.
5372  Expr *AddressOfVariable = UnaryOperator::Create(
5373  S.Context, VariableReference, UnaryOperatorKind::UO_AddrOf,
5375  +false, FPOptionsOverride{});
5376 
5377  // Create a function call expression. This is a fake/dummy call expression.
5378  CallExpr *FunctionCallExpression =
5379  CallExpr::Create(S.Context, E, ArrayRef{AddressOfVariable},
5381 
5382  if (S.CheckFunctionCall(FD, FunctionCallExpression,
5383  FD->getType()->getAs<FunctionProtoType>())) {
5384  return;
5385  }
5386 
5387  D->addAttr(::new (S.Context) CleanupAttr(S.Context, AL, FD));
5388 }
5389 
5390 static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
5391  const ParsedAttr &AL) {
5392  if (!AL.isArgIdent(0)) {
5393  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5394  << AL << 0 << AANT_ArgumentIdentifier;
5395  return;
5396  }
5397 
5398  EnumExtensibilityAttr::Kind ExtensibilityKind;
5399  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
5400  if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
5401  ExtensibilityKind)) {
5402  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
5403  return;
5404  }
5405 
5406  D->addAttr(::new (S.Context)
5407  EnumExtensibilityAttr(S.Context, AL, ExtensibilityKind));
5408 }
5409 
5410 /// Handle __attribute__((format_arg((idx)))) attribute based on
5411 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
5412 static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5413  const Expr *IdxExpr = AL.getArgAsExpr(0);
5414  ParamIdx Idx;
5415  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx))
5416  return;
5417 
5418  // Make sure the format string is really a string.
5420 
5421  bool NotNSStringTy = !isNSStringType(Ty, S.Context);
5422  if (NotNSStringTy &&
5423  !isCFStringType(Ty, S.Context) &&
5424  (!Ty->isPointerType() ||
5425  !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
5426  S.Diag(AL.getLoc(), diag::err_format_attribute_not)
5427  << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
5428  return;
5429  }
5431  // replace instancetype with the class type
5432  auto Instancetype = S.Context.getObjCInstanceTypeDecl()->getTypeForDecl();
5433  if (Ty->getAs<TypedefType>() == Instancetype)
5434  if (auto *OMD = dyn_cast<ObjCMethodDecl>(D))
5435  if (auto *Interface = OMD->getClassInterface())
5437  QualType(Interface->getTypeForDecl(), 0));
5438  if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true) &&
5439  !isCFStringType(Ty, S.Context) &&
5440  (!Ty->isPointerType() ||
5441  !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
5442  S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
5443  << (NotNSStringTy ? "string type" : "NSString")
5444  << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
5445  return;
5446  }
5447 
5448  D->addAttr(::new (S.Context) FormatArgAttr(S.Context, AL, Idx));
5449 }
5450 
5451 enum FormatAttrKind {
5452  CFStringFormat,
5453  NSStringFormat,
5454  StrftimeFormat,
5455  SupportedFormat,
5456  IgnoredFormat,
5457  InvalidFormat
5458 };
5459 
5460 /// getFormatAttrKind - Map from format attribute names to supported format
5461 /// types.
5462 static FormatAttrKind getFormatAttrKind(StringRef Format) {
5463  return llvm::StringSwitch<FormatAttrKind>(Format)
5464  // Check for formats that get handled specially.
5465  .Case("NSString", NSStringFormat)
5466  .Case("CFString", CFStringFormat)
5467  .Case("strftime", StrftimeFormat)
5468 
5469  // Otherwise, check for supported formats.
5470  .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
5471  .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
5472  .Case("kprintf", SupportedFormat) // OpenBSD.
5473  .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
5474  .Case("os_trace", SupportedFormat)
5475  .Case("os_log", SupportedFormat)
5476 
5477  .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
5478  .Default(InvalidFormat);
5479 }
5480 
5481 /// Handle __attribute__((init_priority(priority))) attributes based on
5482 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
5483 static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5484  if (!S.getLangOpts().CPlusPlus) {
5485  S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
5486  return;
5487  }
5488 
5489  if (S.getLangOpts().HLSL) {
5490  S.Diag(AL.getLoc(), diag::err_hlsl_init_priority_unsupported);
5491  return;
5492  }
5493 
5494  if (S.getCurFunctionOrMethodDecl()) {
5495  S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
5496  AL.setInvalid();
5497  return;
5498  }
5499  QualType T = cast<VarDecl>(D)->getType();
5500  if (S.Context.getAsArrayType(T))
5502  if (!T->getAs<RecordType>()) {
5503  S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
5504  AL.setInvalid();
5505  return;
5506  }
5507 
5508  Expr *E = AL.getArgAsExpr(0);
5509  uint32_t prioritynum;
5510  if (!checkUInt32Argument(S, AL, E, prioritynum)) {
5511  AL.setInvalid();
5512  return;
5513  }
5514 
5515  // Only perform the priority check if the attribute is outside of a system
5516  // header. Values <= 100 are reserved for the implementation, and libc++
5517  // benefits from being able to specify values in that range.
5518  if ((prioritynum < 101 || prioritynum > 65535) &&
5520  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
5521  << E->getSourceRange() << AL << 101 << 65535;
5522  AL.setInvalid();
5523  return;
5524  }
5525  D->addAttr(::new (S.Context) InitPriorityAttr(S.Context, AL, prioritynum));
5526 }
5527 
5528 ErrorAttr *Sema::mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
5529  StringRef NewUserDiagnostic) {
5530  if (const auto *EA = D->getAttr<ErrorAttr>()) {
5531  std::string NewAttr = CI.getNormalizedFullName();
5532  assert((NewAttr == "error" || NewAttr == "warning") &&
5533  "unexpected normalized full name");
5534  bool Match = (EA->isError() && NewAttr == "error") ||
5535  (EA->isWarning() && NewAttr == "warning");
5536  if (!Match) {
5537  Diag(EA->getLocation(), diag::err_attributes_are_not_compatible)
5538  << CI << EA
5539  << (CI.isRegularKeywordAttribute() ||
5540  EA->isRegularKeywordAttribute());
5541  Diag(CI.getLoc(), diag::note_conflicting_attribute);
5542  return nullptr;
5543  }
5544  if (EA->getUserDiagnostic() != NewUserDiagnostic) {
5545  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << EA;
5546  Diag(EA->getLoc(), diag::note_previous_attribute);
5547  }
5548  D->dropAttr<ErrorAttr>();
5549  }
5550  return ::new (Context) ErrorAttr(Context, CI, NewUserDiagnostic);
5551 }
5552 
5553 FormatAttr *Sema::mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
5554  IdentifierInfo *Format, int FormatIdx,
5555  int FirstArg) {
5556  // Check whether we already have an equivalent format attribute.
5557  for (auto *F : D->specific_attrs<FormatAttr>()) {
5558  if (F->getType() == Format &&
5559  F->getFormatIdx() == FormatIdx &&
5560  F->getFirstArg() == FirstArg) {
5561  // If we don't have a valid location for this attribute, adopt the
5562  // location.
5563  if (F->getLocation().isInvalid())
5564  F->setRange(CI.getRange());
5565  return nullptr;
5566  }
5567  }
5568 
5569  return ::new (Context) FormatAttr(Context, CI, Format, FormatIdx, FirstArg);
5570 }
5571 
5572 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
5573 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
5574 static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5575  if (!AL.isArgIdent(0)) {
5576  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
5577  << AL << 1 << AANT_ArgumentIdentifier;
5578  return;
5579  }
5580 
5581  // In C++ the implicit 'this' function parameter also counts, and they are
5582  // counted from one.
5583  bool HasImplicitThisParam = isInstanceMethod(D);
5584  unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
5585 
5586  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
5587  StringRef Format = II->getName();
5588 
5589  if (normalizeName(Format)) {
5590  // If we've modified the string name, we need a new identifier for it.
5591  II = &S.Context.Idents.get(Format);
5592  }
5593 
5594  // Check for supported formats.
5595  FormatAttrKind Kind = getFormatAttrKind(Format);
5596 
5597  if (Kind == IgnoredFormat)
5598  return;
5599 
5600  if (Kind == InvalidFormat) {
5601  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
5602  << AL << II->getName();
5603  return;
5604  }
5605 
5606  // checks for the 2nd argument
5607  Expr *IdxExpr = AL.getArgAsExpr(1);
5608  uint32_t Idx;
5609  if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2))
5610  return;
5611 
5612  if (Idx < 1 || Idx > NumArgs) {
5613  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
5614  << AL << 2 << IdxExpr->getSourceRange();
5615  return;
5616  }
5617 
5618  // FIXME: Do we need to bounds check?
5619  unsigned ArgIdx = Idx - 1;
5620 
5621  if (HasImplicitThisParam) {
5622  if (ArgIdx == 0) {
5623  S.Diag(AL.getLoc(),
5624  diag::err_format_attribute_implicit_this_format_string)
5625  << IdxExpr->getSourceRange();
5626  return;
5627  }
5628  ArgIdx--;
5629  }
5630 
5631  // make sure the format string is really a string
5632  QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
5633 
5634  if (!isNSStringType(Ty, S.Context, true) &&
5635  !isCFStringType(Ty, S.Context) &&
5636  (!Ty->isPointerType() ||
5637  !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
5638  S.Diag(AL.getLoc(), diag::err_format_attribute_not)
5639  << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, ArgIdx);
5640  return;
5641  }
5642 
5643  // check the 3rd argument
5644  Expr *FirstArgExpr = AL.getArgAsExpr(2);
5645  uint32_t FirstArg;
5646  if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3))
5647  return;
5648 
5649  // FirstArg == 0 is is always valid.
5650  if (FirstArg != 0) {
5651  if (Kind == StrftimeFormat) {
5652  // If the kind is strftime, FirstArg must be 0 because strftime does not
5653  // use any variadic arguments.
5654  S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
5655  << FirstArgExpr->getSourceRange()
5656  << FixItHint::CreateReplacement(FirstArgExpr->getSourceRange(), "0");
5657  return;
5658  } else if (isFunctionOrMethodVariadic(D)) {
5659  // Else, if the function is variadic, then FirstArg must be 0 or the
5660  // "position" of the ... parameter. It's unusual to use 0 with variadic
5661  // functions, so the fixit proposes the latter.
5662  if (FirstArg != NumArgs + 1) {
5663  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
5664  << AL << 3 << FirstArgExpr->getSourceRange()
5665  << FixItHint::CreateReplacement(FirstArgExpr->getSourceRange(),
5666  std::to_string(NumArgs + 1));
5667  return;
5668  }
5669  } else {
5670  // Inescapable GCC compatibility diagnostic.
5671  S.Diag(D->getLocation(), diag::warn_gcc_requires_variadic_function) << AL;
5672  if (FirstArg <= Idx) {
5673  // Else, the function is not variadic, and FirstArg must be 0 or any
5674  // parameter after the format parameter. We don't offer a fixit because
5675  // there are too many possible good values.
5676  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
5677  << AL << 3 << FirstArgExpr->getSourceRange();
5678  return;
5679  }
5680  }
5681  }
5682 
5683  FormatAttr *NewAttr = S.mergeFormatAttr(D, AL, II, Idx, FirstArg);
5684  if (NewAttr)
5685  D->addAttr(NewAttr);
5686 }
5687 
5688 /// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
5689 static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5690  // The index that identifies the callback callee is mandatory.
5691  if (AL.getNumArgs() == 0) {
5692  S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee)
5693  << AL.getRange();
5694  return;
5695  }
5696 
5697  bool HasImplicitThisParam = isInstanceMethod(D);
5698  int32_t NumArgs = getFunctionOrMethodNumParams(D);
5699 
5700  FunctionDecl *FD = D->getAsFunction();
5701  assert(FD && "Expected a function declaration!");
5702 
5703  llvm::StringMap<int> NameIdxMapping;
5704  NameIdxMapping["__"] = -1;
5705 
5706  NameIdxMapping["this"] = 0;
5707 
5708  int Idx = 1;
5709  for (const ParmVarDecl *PVD : FD->parameters())
5710  NameIdxMapping[PVD->getName()] = Idx++;
5711 
5712  auto UnknownName = NameIdxMapping.end();
5713 
5714  SmallVector<int, 8> EncodingIndices;
5715  for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) {
5716  SourceRange SR;
5717  int32_t ArgIdx;
5718 
5719  if (AL.isArgIdent(I)) {
5720  IdentifierLoc *IdLoc = AL.getArgAsIdent(I);
5721  auto It = NameIdxMapping.find(IdLoc->Ident->getName());
5722  if (It == UnknownName) {
5723  S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown)
5724  << IdLoc->Ident << IdLoc->Loc;
5725  return;
5726  }
5727 
5728  SR = SourceRange(IdLoc->Loc);
5729  ArgIdx = It->second;
5730  } else if (AL.isArgExpr(I)) {
5731  Expr *IdxExpr = AL.getArgAsExpr(I);
5732 
5733  // If the expression is not parseable as an int32_t we have a problem.
5734  if (!checkUInt32Argument(S, AL, IdxExpr, (uint32_t &)ArgIdx, I + 1,
5735  false)) {
5736  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
5737  << AL << (I + 1) << IdxExpr->getSourceRange();
5738  return;
5739  }
5740 
5741  // Check oob, excluding the special values, 0 and -1.
5742  if (ArgIdx < -1 || ArgIdx > NumArgs) {
5743  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
5744  << AL << (I + 1) << IdxExpr->getSourceRange();
5745  return;
5746  }
5747 
5748  SR = IdxExpr->getSourceRange();
5749  } else {
5750  llvm_unreachable("Unexpected ParsedAttr argument type!");
5751  }
5752 
5753  if (ArgIdx == 0 && !HasImplicitThisParam) {
5754  S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available)
5755  << (I + 1) << SR;
5756  return;
5757  }
5758 
5759  // Adjust for the case we do not have an implicit "this" parameter. In this
5760  // case we decrease all positive values by 1 to get LLVM argument indices.
5761  if (!HasImplicitThisParam && ArgIdx > 0)
5762  ArgIdx -= 1;
5763 
5764  EncodingIndices.push_back(ArgIdx);
5765  }
5766 
5767  int CalleeIdx = EncodingIndices.front();
5768  // Check if the callee index is proper, thus not "this" and not "unknown".
5769  // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam"
5770  // is false and positive if "HasImplicitThisParam" is true.
5771  if (CalleeIdx < (int)HasImplicitThisParam) {
5772  S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee)
5773  << AL.getRange();
5774  return;
5775  }
5776 
5777  // Get the callee type, note the index adjustment as the AST doesn't contain
5778  // the this type (which the callee cannot reference anyway!).
5779  const Type *CalleeType =
5780  getFunctionOrMethodParamType(D, CalleeIdx - HasImplicitThisParam)
5781  .getTypePtr();
5782  if (!CalleeType || !CalleeType->isFunctionPointerType()) {
5783  S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
5784  << AL.getRange();
5785  return;
5786  }
5787 
5788  const Type *CalleeFnType =
5790 
5791  // TODO: Check the type of the callee arguments.
5792 
5793  const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(CalleeFnType);
5794  if (!CalleeFnProtoType) {
5795  S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
5796  << AL.getRange();
5797  return;
5798  }
5799 
5800  if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) {
5801  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
5802  << AL << (unsigned)(EncodingIndices.size() - 1);
5803  return;
5804  }
5805 
5806  if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) {
5807  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
5808  << AL << (unsigned)(EncodingIndices.size() - 1);
5809  return;
5810  }
5811 
5812  if (CalleeFnProtoType->isVariadic()) {
5813  S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange();
5814  return;
5815  }
5816 
5817  // Do not allow multiple callback attributes.
5818  if (D->hasAttr<CallbackAttr>()) {
5819  S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange();
5820  return;
5821  }
5822 
5823  D->addAttr(::new (S.Context) CallbackAttr(
5824  S.Context, AL, EncodingIndices.data(), EncodingIndices.size()));
5825 }
5826 
5827 static bool isFunctionLike(const Type &T) {
5828  // Check for explicit function types.
5829  // 'called_once' is only supported in Objective-C and it has
5830  // function pointers and block pointers.
5832 }
5833 
5834 /// Handle 'called_once' attribute.
5835 static void handleCalledOnceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5836  // 'called_once' only applies to parameters representing functions.
5837  QualType T = cast<ParmVarDecl>(D)->getType();
5838 
5839  if (!isFunctionLike(*T)) {
5840  S.Diag(AL.getLoc(), diag::err_called_once_attribute_wrong_type);
5841  return;
5842  }
5843 
5844  D->addAttr(::new (S.Context) CalledOnceAttr(S.Context, AL));
5845 }
5846 
5847 static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5848  // Try to find the underlying union declaration.
5849  RecordDecl *RD = nullptr;
5850  const auto *TD = dyn_cast<TypedefNameDecl>(D);
5851  if (TD && TD->getUnderlyingType()->isUnionType())
5852  RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
5853  else
5854  RD = dyn_cast<RecordDecl>(D);
5855 
5856  if (!RD || !RD->isUnion()) {
5857  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
5858  << AL << AL.isRegularKeywordAttribute() << ExpectedUnion;
5859  return;
5860  }
5861 
5862  if (!RD->isCompleteDefinition()) {
5863  if (!RD->isBeingDefined())
5864  S.Diag(AL.getLoc(),
5865  diag::warn_transparent_union_attribute_not_definition);
5866  return;
5867  }
5868 
5870  FieldEnd = RD->field_end();
5871  if (Field == FieldEnd) {
5872  S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
5873  return;
5874  }
5875 
5876  FieldDecl *FirstField = *Field;
5877  QualType FirstType = FirstField->getType();
5878  if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
5879  S.Diag(FirstField->getLocation(),
5880  diag::warn_transparent_union_attribute_floating)
5881  << FirstType->isVectorType() << FirstType;
5882  return;
5883  }
5884 
5885  if (FirstType->isIncompleteType())
5886  return;
5887  uint64_t FirstSize = S.Context.getTypeSize(FirstType);
5888  uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
5889  for (; Field != FieldEnd; ++Field) {
5890  QualType FieldType = Field->getType();
5891  if (FieldType->isIncompleteType())
5892  return;
5893  // FIXME: this isn't fully correct; we also need to test whether the
5894  // members of the union would all have the same calling convention as the
5895  // first member of the union. Checking just the size and alignment isn't
5896  // sufficient (consider structs passed on the stack instead of in registers
5897  // as an example).
5898  if (S.Context.getTypeSize(FieldType) != FirstSize ||
5899  S.Context.getTypeAlign(FieldType) > FirstAlign) {
5900  // Warn if we drop the attribute.
5901  bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
5902  unsigned FieldBits = isSize ? S.Context.getTypeSize(FieldType)
5903  : S.Context.getTypeAlign(FieldType);
5904  S.Diag(Field->getLocation(),
5905  diag::warn_transparent_union_attribute_field_size_align)
5906  << isSize << *Field << FieldBits;
5907  unsigned FirstBits = isSize ? FirstSize : FirstAlign;
5908  S.Diag(FirstField->getLocation(),
5909  diag::note_transparent_union_first_field_size_align)
5910  << isSize << FirstBits;
5911  return;
5912  }
5913  }
5914 
5915  RD->addAttr(::new (S.Context) TransparentUnionAttr(S.Context, AL));
5916 }
5917 
5919  StringRef Str, MutableArrayRef<Expr *> Args) {
5920  auto *Attr = AnnotateAttr::Create(Context, Str, Args.data(), Args.size(), CI);
5921  if (ConstantFoldAttrArgs(
5922  CI, MutableArrayRef<Expr *>(Attr->args_begin(), Attr->args_end()))) {
5923  D->addAttr(Attr);
5924  }
5925 }
5926 
5927 static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5928  // Make sure that there is a string literal as the annotation's first
5929  // argument.
5930  StringRef Str;
5931  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
5932  return;
5933 
5935  Args.reserve(AL.getNumArgs() - 1);
5936  for (unsigned Idx = 1; Idx < AL.getNumArgs(); Idx++) {
5937  assert(!AL.isArgIdent(Idx));
5938  Args.push_back(AL.getArgAsExpr(Idx));
5939  }
5940 
5941  S.AddAnnotationAttr(D, AL, Str, Args);
5942 }
5943 
5944 static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5945  S.AddAlignValueAttr(D, AL, AL.getArgAsExpr(0));
5946 }
5947 
5948 void Sema::AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E) {
5949  AlignValueAttr TmpAttr(Context, CI, E);
5950  SourceLocation AttrLoc = CI.getLoc();
5951 
5952  QualType T;
5953  if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
5954  T = TD->getUnderlyingType();
5955  else if (const auto *VD = dyn_cast<ValueDecl>(D))
5956  T = VD->getType();
5957  else
5958  llvm_unreachable("Unknown decl type for align_value");
5959 
5960  if (!T->isDependentType() && !T->isAnyPointerType() &&
5961  !T->isReferenceType() && !T->isMemberPointerType()) {
5962  Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
5963  << &TmpAttr << T << D->getSourceRange();
5964  return;
5965  }
5966 
5967  if (!E->isValueDependent()) {
5968  llvm::APSInt Alignment;
5969  ExprResult ICE = VerifyIntegerConstantExpression(
5970  E, &Alignment, diag::err_align_value_attribute_argument_not_int);
5971  if (ICE.isInvalid())
5972  return;
5973 
5974  if (!Alignment.isPowerOf2()) {
5975  Diag(AttrLoc, diag::err_alignment_not_power_of_two)
5976  << E->getSourceRange();
5977  return;
5978  }
5979 
5980  D->addAttr(::new (Context) AlignValueAttr(Context, CI, ICE.get()));
5981  return;
5982  }
5983 
5984  // Save dependent expressions in the AST to be instantiated.
5985  D->addAttr(::new (Context) AlignValueAttr(Context, CI, E));
5986 }
5987 
5988 static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5989  if (AL.hasParsedType()) {
5990  const ParsedType &TypeArg = AL.getTypeArg();
5991  TypeSourceInfo *TInfo;
5992  (void)S.GetTypeFromParser(
5993  ParsedType::getFromOpaquePtr(TypeArg.getAsOpaquePtr()), &TInfo);
5994  if (AL.isPackExpansion() &&
5996  S.Diag(AL.getEllipsisLoc(),
5997  diag::err_pack_expansion_without_parameter_packs);
5998  return;
5999  }
6000 
6001  if (!AL.isPackExpansion() &&
6003  TInfo, Sema::UPPC_Expression))
6004  return;
6005 
6006  S.AddAlignedAttr(D, AL, TInfo, AL.isPackExpansion());
6007  return;
6008  }
6009 
6010  // check the attribute arguments.
6011  if (AL.getNumArgs() > 1) {
6012  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
6013  return;
6014  }
6015 
6016  if (AL.getNumArgs() == 0) {
6017  D->addAttr(::new (S.Context) AlignedAttr(S.Context, AL, true, nullptr));
6018  return;
6019  }
6020 
6021  Expr *E = AL.getArgAsExpr(0);
6023  S.Diag(AL.getEllipsisLoc(),
6024  diag::err_pack_expansion_without_parameter_packs);
6025  return;
6026  }
6027 
6029  return;
6030 
6031  S.AddAlignedAttr(D, AL, E, AL.isPackExpansion());
6032 }
6033 
6034 /// Perform checking of type validity
6035 ///
6036 /// C++11 [dcl.align]p1:
6037 /// An alignment-specifier may be applied to a variable or to a class
6038 /// data member, but it shall not be applied to a bit-field, a function
6039 /// parameter, the formal parameter of a catch clause, or a variable
6040 /// declared with the register storage class specifier. An
6041 /// alignment-specifier may also be applied to the declaration of a class
6042 /// or enumeration type.
6043 /// CWG 2354:
6044 /// CWG agreed to remove permission for alignas to be applied to
6045 /// enumerations.
6046 /// C11 6.7.5/2:
6047 /// An alignment attribute shall not be specified in a declaration of
6048 /// a typedef, or a bit-field, or a function, or a parameter, or an
6049 /// object declared with the register storage-class specifier.
6050 static bool validateAlignasAppliedType(Sema &S, Decl *D,
6051  const AlignedAttr &Attr,
6052  SourceLocation AttrLoc) {
6053  int DiagKind = -1;
6054  if (isa<ParmVarDecl>(D)) {
6055  DiagKind = 0;
6056  } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
6057  if (VD->getStorageClass() == SC_Register)
6058  DiagKind = 1;
6059  if (VD->isExceptionVariable())
6060  DiagKind = 2;
6061  } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
6062  if (FD->isBitField())
6063  DiagKind = 3;
6064  } else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
6065  if (ED->getLangOpts().CPlusPlus)
6066  DiagKind = 4;
6067  } else if (!isa<TagDecl>(D)) {
6068  return S.Diag(AttrLoc, diag::err_attribute_wrong_decl_type)
6070  << (Attr.isC11() ? ExpectedVariableOrField
6072  }
6073  if (DiagKind != -1) {
6074  return S.Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
6075  << &Attr << DiagKind;
6076  }
6077  return false;
6078 }
6079 
6080 void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
6081  bool IsPackExpansion) {
6082  AlignedAttr TmpAttr(Context, CI, true, E);
6083  SourceLocation AttrLoc = CI.getLoc();
6084 
6085  // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
6086  if (TmpAttr.isAlignas() &&
6087  validateAlignasAppliedType(*this, D, TmpAttr, AttrLoc))
6088  return;
6089 
6090  if (E->isValueDependent()) {
6091  // We can't support a dependent alignment on a non-dependent type,
6092  // because we have no way to model that a type is "alignment-dependent"
6093  // but not dependent in any other way.
6094  if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
6095  if (!TND->getUnderlyingType()->isDependentType()) {
6096  Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
6097  << E->getSourceRange();
6098  return;
6099  }
6100  }
6101 
6102  // Save dependent expressions in the AST to be instantiated.
6103  AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, E);
6104  AA->setPackExpansion(IsPackExpansion);
6105  D->addAttr(AA);
6106  return;
6107  }
6108 
6109  // FIXME: Cache the number on the AL object?
6110  llvm::APSInt Alignment;
6111  ExprResult ICE = VerifyIntegerConstantExpression(
6112  E, &Alignment, diag::err_aligned_attribute_argument_not_int);
6113  if (ICE.isInvalid())
6114  return;
6115 
6116  uint64_t MaximumAlignment = Sema::MaximumAlignment;
6117  if (Context.getTargetInfo().getTriple().isOSBinFormatCOFF())
6118  MaximumAlignment = std::min(MaximumAlignment, uint64_t(8192));
6119  if (Alignment > MaximumAlignment) {
6120  Diag(AttrLoc, diag::err_attribute_aligned_too_great)
6121  << MaximumAlignment << E->getSourceRange();
6122  return;
6123  }
6124 
6125  uint64_t AlignVal = Alignment.getZExtValue();
6126  // C++11 [dcl.align]p2:
6127  // -- if the constant expression evaluates to zero, the alignment
6128  // specifier shall have no effect
6129  // C11 6.7.5p6:
6130  // An alignment specification of zero has no effect.
6131  if (!(TmpAttr.isAlignas() && !Alignment)) {
6132  if (!llvm::isPowerOf2_64(AlignVal)) {
6133  Diag(AttrLoc, diag::err_alignment_not_power_of_two)
6134  << E->getSourceRange();
6135  return;
6136  }
6137  }
6138 
6139  const auto *VD = dyn_cast<VarDecl>(D);
6140  if (VD) {
6141  unsigned MaxTLSAlign =
6142  Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
6143  .getQuantity();
6144  if (MaxTLSAlign && AlignVal > MaxTLSAlign &&
6145  VD->getTLSKind() != VarDecl::TLS_None) {
6146  Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
6147  << (unsigned)AlignVal << VD << MaxTLSAlign;
6148  return;
6149  }
6150  }
6151 
6152  // On AIX, an aligned attribute can not decrease the alignment when applied
6153  // to a variable declaration with vector type.
6154  if (VD && Context.getTargetInfo().getTriple().isOSAIX()) {
6155  const Type *Ty = VD->getType().getTypePtr();
6156  if (Ty->isVectorType() && AlignVal < 16) {
6157  Diag(VD->getLocation(), diag::warn_aligned_attr_underaligned)
6158  << VD->getType() << 16;
6159  return;
6160  }
6161  }
6162 
6163  AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, ICE.get());
6164  AA->setPackExpansion(IsPackExpansion);
6165  AA->setCachedAlignmentValue(
6166  static_cast<unsigned>(AlignVal * Context.getCharWidth()));
6167  D->addAttr(AA);
6168 }
6169 
6170 void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI,
6171  TypeSourceInfo *TS, bool IsPackExpansion) {
6172  AlignedAttr TmpAttr(Context, CI, false, TS);
6173  SourceLocation AttrLoc = CI.getLoc();
6174 
6175  // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
6176  if (TmpAttr.isAlignas() &&
6177  validateAlignasAppliedType(*this, D, TmpAttr, AttrLoc))
6178  return;
6179 
6180  if (TS->getType()->isDependentType()) {
6181  // We can't support a dependent alignment on a non-dependent type,
6182  // because we have no way to model that a type is "type-dependent"
6183  // but not dependent in any other way.
6184  if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
6185  if (!TND->getUnderlyingType()->isDependentType()) {
6186  Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
6187  << TS->getTypeLoc().getSourceRange();
6188  return;
6189  }
6190  }
6191 
6192  AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
6193  AA->setPackExpansion(IsPackExpansion);
6194  D->addAttr(AA);
6195  return;
6196  }
6197 
6198  const auto *VD = dyn_cast<VarDecl>(D);
6199  unsigned AlignVal = TmpAttr.getAlignment(Context);
6200  // On AIX, an aligned attribute can not decrease the alignment when applied
6201  // to a variable declaration with vector type.
6202  if (VD && Context.getTargetInfo().getTriple().isOSAIX()) {
6203  const Type *Ty = VD->getType().getTypePtr();
6204  if (Ty->isVectorType() &&
6205  Context.toCharUnitsFromBits(AlignVal).getQuantity() < 16) {
6206  Diag(VD->getLocation(), diag::warn_aligned_attr_underaligned)
6207  << VD->getType() << 16;
6208  return;
6209  }
6210  }
6211 
6212  AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
6213  AA->setPackExpansion(IsPackExpansion);
6214  AA->setCachedAlignmentValue(AlignVal);
6215  D->addAttr(AA);
6216 }
6217 
6219  assert(D->hasAttrs() && "no attributes on decl");
6220 
6221  QualType UnderlyingTy, DiagTy;
6222  if (const auto *VD = dyn_cast<ValueDecl>(D)) {
6223  UnderlyingTy = DiagTy = VD->getType();
6224  } else {
6225  UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
6226  if (const auto *ED = dyn_cast<EnumDecl>(D))
6227  UnderlyingTy = ED->getIntegerType();
6228  }
6229  if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
6230  return;
6231 
6232  // C++11 [dcl.align]p5, C11 6.7.5/4:
6233  // The combined effect of all alignment attributes in a declaration shall
6234  // not specify an alignment that is less strict than the alignment that
6235  // would otherwise be required for the entity being declared.
6236  AlignedAttr *AlignasAttr = nullptr;
6237  AlignedAttr *LastAlignedAttr = nullptr;
6238  unsigned Align = 0;
6239  for (auto *I : D->specific_attrs<AlignedAttr>()) {
6240  if (I->isAlignmentDependent())
6241  return;
6242  if (I->isAlignas())
6243  AlignasAttr = I;
6244  Align = std::max(Align, I->getAlignment(Context));
6245  LastAlignedAttr = I;
6246  }
6247 
6248  if (Align && DiagTy->isSizelessType()) {
6249  Diag(LastAlignedAttr->getLocation(), diag::err_attribute_sizeless_type)
6250  << LastAlignedAttr << DiagTy;
6251  } else if (AlignasAttr && Align) {
6252  CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
6253  CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
6254  if (NaturalAlign > RequestedAlign)
6255  Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
6256  << DiagTy << (unsigned)NaturalAlign.getQuantity();
6257  }
6258 }
6259 
6261  CXXRecordDecl *RD, SourceRange Range, bool BestCase,
6262  MSInheritanceModel ExplicitModel) {
6263  assert(RD->hasDefinition() && "RD has no definition!");
6264 
6265  // We may not have seen base specifiers or any virtual methods yet. We will
6266  // have to wait until the record is defined to catch any mismatches.
6267  if (!RD->getDefinition()->isCompleteDefinition())
6268  return false;
6269 
6270  // The unspecified model never matches what a definition could need.
6271  if (ExplicitModel == MSInheritanceModel::Unspecified)
6272  return false;
6273 
6274  if (BestCase) {
6275  if (RD->calculateInheritanceModel() == ExplicitModel)
6276  return false;
6277  } else {
6278  if (RD->calculateInheritanceModel() <= ExplicitModel)
6279  return false;
6280  }
6281 
6282  Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
6283  << 0 /*definition*/;
6284  Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) << RD;
6285  return true;
6286 }
6287 
6288 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
6289 /// attribute.
6290 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
6291  bool &IntegerMode, bool &ComplexMode,
6292  FloatModeKind &ExplicitType) {
6293  IntegerMode = true;
6294  ComplexMode = false;
6295  ExplicitType = FloatModeKind::NoFloat;
6296  switch (Str.size()) {
6297  case 2:
6298  switch (Str[0]) {
6299  case 'Q':
6300  DestWidth = 8;
6301  break;
6302  case 'H':
6303  DestWidth = 16;
6304  break;
6305  case 'S':
6306  DestWidth = 32;
6307  break;
6308  case 'D':
6309  DestWidth = 64;
6310  break;
6311  case 'X':
6312  DestWidth = 96;
6313  break;
6314  case 'K': // KFmode - IEEE quad precision (__float128)
6315  ExplicitType = FloatModeKind::Float128;
6316  DestWidth = Str[1] == 'I' ? 0 : 128;
6317  break;
6318  case 'T':
6319  ExplicitType = FloatModeKind::LongDouble;
6320  DestWidth = 128;
6321  break;
6322  case 'I':
6323  ExplicitType = FloatModeKind::Ibm128;
6324  DestWidth = Str[1] == 'I' ? 0 : 128;
6325  break;
6326  }
6327  if (Str[1] == 'F') {
6328  IntegerMode = false;
6329  } else if (Str[1] == 'C') {
6330  IntegerMode = false;
6331  ComplexMode = true;
6332  } else if (Str[1] != 'I') {
6333  DestWidth = 0;
6334  }
6335  break;
6336  case 4:
6337  // FIXME: glibc uses 'word' to define register_t; this is narrower than a
6338  // pointer on PIC16 and other embedded platforms.
6339  if (Str == "word")
6340  DestWidth = S.Context.getTargetInfo().getRegisterWidth();
6341  else if (Str == "byte")
6342  DestWidth = S.Context.getTargetInfo().getCharWidth();
6343  break;
6344  case 7:
6345  if (Str == "pointer")
6347  break;
6348  case 11:
6349  if (Str == "unwind_word")
6350  DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
6351  break;
6352  }
6353 }
6354 
6355 /// handleModeAttr - This attribute modifies the width of a decl with primitive
6356 /// type.
6357 ///
6358 /// Despite what would be logical, the mode attribute is a decl attribute, not a
6359 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
6360 /// HImode, not an intermediate pointer.
6361 static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6362  // This attribute isn't documented, but glibc uses it. It changes
6363  // the width of an int or unsigned int to the specified size.
6364  if (!AL.isArgIdent(0)) {
6365  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
6366  << AL << AANT_ArgumentIdentifier;
6367  return;
6368  }
6369 
6370  IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
6371 
6372  S.AddModeAttr(D, AL, Name);
6373 }
6374 
6375 void Sema::AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
6376  IdentifierInfo *Name, bool InInstantiation) {
6377  StringRef Str = Name->getName();
6378  normalizeName(Str);
6379  SourceLocation AttrLoc = CI.getLoc();
6380 
6381  unsigned DestWidth = 0;
6382  bool IntegerMode = true;
6383  bool ComplexMode = false;
6384  FloatModeKind ExplicitType = FloatModeKind::NoFloat;
6385  llvm::APInt VectorSize(64, 0);
6386  if (Str.size() >= 4 && Str[0] == 'V') {
6387  // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
6388  size_t StrSize = Str.size();
6389  size_t VectorStringLength = 0;
6390  while ((VectorStringLength + 1) < StrSize &&
6391  isdigit(Str[VectorStringLength + 1]))
6392  ++VectorStringLength;
6393  if (VectorStringLength &&
6394  !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
6395  VectorSize.isPowerOf2()) {
6396  parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
6397  IntegerMode, ComplexMode, ExplicitType);
6398  // Avoid duplicate warning from template instantiation.
6399  if (!InInstantiation)
6400  Diag(AttrLoc, diag::warn_vector_mode_deprecated);
6401  } else {
6402  VectorSize = 0;
6403  }
6404  }
6405 
6406  if (!VectorSize)
6407  parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode,
6408  ExplicitType);
6409 
6410  // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
6411  // and friends, at least with glibc.
6412  // FIXME: Make sure floating-point mappings are accurate
6413  // FIXME: Support XF and TF types
6414  if (!DestWidth) {
6415  Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
6416  return;
6417  }
6418 
6419  QualType OldTy;
6420  if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
6421  OldTy = TD->getUnderlyingType();
6422  else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
6423  // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
6424  // Try to get type from enum declaration, default to int.
6425  OldTy = ED->getIntegerType();
6426  if (OldTy.isNull())
6427  OldTy = Context.IntTy;
6428  } else
6429  OldTy = cast<ValueDecl>(D)->getType();
6430 
6431  if (OldTy->isDependentType()) {
6432  D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
6433  return;
6434  }
6435 
6436  // Base type can also be a vector type (see PR17453).
6437  // Distinguish between base type and base element type.
6438  QualType OldElemTy = OldTy;
6439  if (const auto *VT = OldTy->getAs<VectorType>())
6440  OldElemTy = VT->getElementType();
6441 
6442  // GCC allows 'mode' attribute on enumeration types (even incomplete), except
6443  // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
6444  // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
6445  if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
6446  VectorSize.getBoolValue()) {
6447  Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << CI.getRange();
6448  return;
6449  }
6450  bool IntegralOrAnyEnumType = (OldElemTy->isIntegralOrEnumerationType() &&
6451  !OldElemTy->isBitIntType()) ||
6452  OldElemTy->getAs<EnumType>();
6453 
6454  if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
6455  !IntegralOrAnyEnumType)
6456  Diag(AttrLoc, diag::err_mode_not_primitive);
6457  else if (IntegerMode) {
6458  if (!IntegralOrAnyEnumType)
6459  Diag(AttrLoc, diag::err_mode_wrong_type);
6460  } else if (ComplexMode) {
6461  if (!OldElemTy->isComplexType())
6462  Diag(AttrLoc, diag::err_mode_wrong_type);
6463  } else {
6464  if (!OldElemTy->isFloatingType())
6465  Diag(AttrLoc, diag::err_mode_wrong_type);
6466  }
6467 
6468  QualType NewElemTy;
6469 
6470  if (IntegerMode)
6471  NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
6472  OldElemTy->isSignedIntegerType());
6473  else
6474  NewElemTy = Context.getRealTypeForBitwidth(DestWidth, ExplicitType);
6475 
6476  if (NewElemTy.isNull()) {
6477  // Only emit diagnostic on host for 128-bit mode attribute
6478  if (!(DestWidth == 128 && getLangOpts().CUDAIsDevice))
6479  Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
6480  return;
6481  }
6482 
6483  if (ComplexMode) {
6484  NewElemTy = Context.getComplexType(NewElemTy);
6485  }
6486 
6487  QualType NewTy = NewElemTy;
6488  if (VectorSize.getBoolValue()) {
6489  NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
6491  } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
6492  // Complex machine mode does not support base vector types.
6493  if (ComplexMode) {
6494  Diag(AttrLoc, diag::err_complex_mode_vector_type);
6495  return;
6496  }
6497  unsigned NumElements = Context.getTypeSize(OldElemTy) *
6498  OldVT->getNumElements() /
6499  Context.getTypeSize(NewElemTy);
6500  NewTy =
6501  Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
6502  }
6503 
6504  if (NewTy.isNull()) {
6505  Diag(AttrLoc, diag::err_mode_wrong_type);
6506  return;
6507  }
6508 
6509  // Install the new type.
6510  if (auto *TD = dyn_cast<TypedefNameDecl>(D))
6511  TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
6512  else if (auto *ED = dyn_cast<EnumDecl>(D))
6513  ED->setIntegerType(NewTy);
6514  else
6515  cast<ValueDecl>(D)->setType(NewTy);
6516 
6517  D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
6518 }
6519 
6520 static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6521  D->addAttr(::new (S.Context) NoDebugAttr(S.Context, AL));
6522 }
6523 
6524 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D,
6525  const AttributeCommonInfo &CI,
6526  const IdentifierInfo *Ident) {
6527  if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
6528  Diag(CI.getLoc(), diag::warn_attribute_ignored) << Ident;
6529  Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
6530  return nullptr;
6531  }
6532 
6533  if (D->hasAttr<AlwaysInlineAttr>())
6534  return nullptr;
6535 
6536  return ::new (Context) AlwaysInlineAttr(Context, CI);
6537 }
6538 
6539 InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
6540  const ParsedAttr &AL) {
6541  if (const auto *VD = dyn_cast<VarDecl>(D)) {
6542  // Attribute applies to Var but not any subclass of it (like ParmVar,
6543  // ImplicitParm or VarTemplateSpecialization).
6544  if (VD->getKind() != Decl::Var) {
6545  Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
6546  << AL << AL.isRegularKeywordAttribute()
6547  << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
6549  return nullptr;
6550  }
6551  // Attribute does not apply to non-static local variables.
6552  if (VD->hasLocalStorage()) {
6553  Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
6554  return nullptr;
6555  }
6556  }
6557 
6558  return ::new (Context) InternalLinkageAttr(Context, AL);
6559 }
6560 InternalLinkageAttr *
6561 Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
6562  if (const auto *VD = dyn_cast<VarDecl>(D)) {
6563  // Attribute applies to Var but not any subclass of it (like ParmVar,
6564  // ImplicitParm or VarTemplateSpecialization).
6565  if (VD->getKind() != Decl::Var) {
6566  Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
6567  << &AL << AL.isRegularKeywordAttribute()
6568  << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
6570  return nullptr;
6571  }
6572  // Attribute does not apply to non-static local variables.
6573  if (VD->hasLocalStorage()) {
6574  Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
6575  return nullptr;
6576  }
6577  }
6578 
6579  return ::new (Context) InternalLinkageAttr(Context, AL);
6580 }
6581 
6582 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI) {
6583  if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
6584  Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'minsize'";
6585  Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
6586  return nullptr;
6587  }
6588 
6589  if (D->hasAttr<MinSizeAttr>())
6590  return nullptr;
6591 
6592  return ::new (Context) MinSizeAttr(Context, CI);
6593 }
6594 
6595 SwiftNameAttr *Sema::mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
6596  StringRef Name) {
6597  if (const auto *PrevSNA = D->getAttr<SwiftNameAttr>()) {
6598  if (PrevSNA->getName() != Name && !PrevSNA->isImplicit()) {
6599  Diag(PrevSNA->getLocation(), diag::err_attributes_are_not_compatible)
6600  << PrevSNA << &SNA
6601  << (PrevSNA->isRegularKeywordAttribute() ||
6602  SNA.isRegularKeywordAttribute());
6603  Diag(SNA.getLoc(), diag::note_conflicting_attribute);
6604  }
6605 
6606  D->dropAttr<SwiftNameAttr>();
6607  }
6608  return ::new (Context) SwiftNameAttr(Context, SNA, Name);
6609 }
6610 
6611 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D,
6612  const AttributeCommonInfo &CI) {
6613  if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
6614  Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
6615  Diag(CI.getLoc(), diag::note_conflicting_attribute);
6616  D->dropAttr<AlwaysInlineAttr>();
6617  }
6618  if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
6619  Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
6620  Diag(CI.getLoc(), diag::note_conflicting_attribute);
6621  D->dropAttr<MinSizeAttr>();
6622  }
6623 
6624  if (D->hasAttr<OptimizeNoneAttr>())
6625  return nullptr;
6626 
6627  return ::new (Context) OptimizeNoneAttr(Context, CI);
6628 }
6629 
6630 static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6631  if (AlwaysInlineAttr *Inline =
6632  S.mergeAlwaysInlineAttr(D, AL, AL.getAttrName()))
6633  D->addAttr(Inline);
6634 }
6635 
6636 static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6637  if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(D, AL))
6638  D->addAttr(MinSize);
6639 }
6640 
6641 static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6642  if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(D, AL))
6643  D->addAttr(Optnone);
6644 }
6645 
6646 static void handleSYCLDeviceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6647  auto *ND = cast<NamedDecl>(D);
6648  if (!ND->isExternallyVisible()) {
6649  S.Diag(AL.getLoc(), diag::err_sycl_attribute_internal_decl)
6650  << AL << !isa<FunctionDecl>(ND);
6651  return;
6652  }
6653 
6654  if (auto *VD = dyn_cast<VarDecl>(D)) {
6655  QualType VarType = VD->getType();
6656  // Diagnose only for non-dependent types since dependent type don't have
6657  // attributes applied on them ATM.
6658  if (!VarType->isDependentType() &&
6659  !S.SYCL().isTypeDecoratedWithDeclAttribute<SYCLDeviceGlobalAttr>(
6660  VD->getType())) {
6661  S.Diag(AL.getLoc(), diag::err_sycl_attribute_not_device_global) << AL;
6662  return;
6663  }
6664  }
6665 
6666  handleSimpleAttribute<SYCLDeviceAttr>(S, D, AL);
6667 }
6668 
6669 static void handleSYCLDeviceIndirectlyCallableAttr(Sema &S, Decl *D,
6670  const ParsedAttr &AL) {
6671  auto *FD = cast<FunctionDecl>(D);
6672  if (!FD->isExternallyVisible()) {
6673  S.Diag(AL.getLoc(), diag::err_sycl_attribute_internal_decl)
6674  << AL << /*function*/ 0;
6675  return;
6676  }
6677 
6678  D->addAttr(SYCLDeviceAttr::CreateImplicit(S.Context));
6679  handleSimpleAttribute<SYCLDeviceIndirectlyCallableAttr>(S, D, AL);
6680 }
6681 
6682 static void handleSYCLGlobalVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6684  S.Diag(AL.getLoc(), diag::err_attribute_only_system_header) << AL;
6685  return;
6686  }
6687 
6688  handleSimpleAttribute<SYCLGlobalVarAttr>(S, D, AL);
6689 }
6690 
6691 static void handleSYCLRegisterNumAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6692  if (!AL.checkExactlyNumArgs(S, 1))
6693  return;
6694  uint32_t RegNo = 0;
6695  const Expr *E = AL.getArgAsExpr(0);
6696  if (!checkUInt32Argument(S, AL, E, RegNo, 0, /*StrictlyUnsigned=*/true))
6697  return;
6698  D->addAttr(::new (S.Context) SYCLRegisterNumAttr(S.Context, AL, RegNo));
6699 }
6700 
6702  const AttributeCommonInfo &CI,
6703  Expr *E) {
6704  if (!E->isValueDependent()) {
6705  // Validate that we have an integer constant expression and then store the
6706  // converted constant expression into the semantic attribute so that we
6707  // don't have to evaluate it again later.
6708  llvm::APSInt ArgVal;
6709  ExprResult Res = VerifyIntegerConstantExpression(E, &ArgVal);
6710  if (Res.isInvalid())
6711  return;
6712  E = Res.get();
6713 
6714  if (ArgVal != 8 && ArgVal != 16 && ArgVal != 32) {
6715  Diag(E->getExprLoc(), diag::err_sycl_esimd_vectorize_unsupported_value)
6716  << CI;
6717  return;
6718  }
6719 
6720  // Check to see if there's a duplicate attribute with different values
6721  // already applied to the declaration.
6722  if (const auto *DeclAttr = D->getAttr<SYCLIntelESimdVectorizeAttr>()) {
6723  // If the other attribute argument is instantiation dependent, we won't
6724  // have converted it to a constant expression yet and thus we test
6725  // whether this is a null pointer.
6726  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
6727  if (ArgVal != DeclExpr->getResultAsAPSInt()) {
6728  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << CI;
6729  Diag(DeclAttr->getLoc(), diag::note_previous_attribute);
6730  }
6731  // Drop the duplicate attribute.
6732  return;
6733  }
6734  }
6735  }
6736 
6737  D->addAttr(::new (Context) SYCLIntelESimdVectorizeAttr(Context, CI, E));
6738 }
6739 
6740 SYCLIntelESimdVectorizeAttr *
6742  const SYCLIntelESimdVectorizeAttr &A) {
6743  // Check to see if there's a duplicate attribute with different values
6744  // already applied to the declaration.
6745  if (const auto *DeclAttr = D->getAttr<SYCLIntelESimdVectorizeAttr>()) {
6746  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
6747  if (const auto *MergeExpr = dyn_cast<ConstantExpr>(A.getValue())) {
6748  if (DeclExpr->getResultAsAPSInt() != MergeExpr->getResultAsAPSInt()) {
6749  Diag(DeclAttr->getLoc(), diag::warn_duplicate_attribute) << &A;
6750  Diag(A.getLoc(), diag::note_previous_attribute);
6751  }
6752  // Do not add a duplicate attribute.
6753  return nullptr;
6754  }
6755  }
6756  }
6757  return ::new (Context) SYCLIntelESimdVectorizeAttr(Context, A, A.getValue());
6758 }
6759 
6760 static void handleSYCLIntelESimdVectorizeAttr(Sema &S, Decl *D,
6761  const ParsedAttr &A) {
6763 
6764  Expr *E = A.getArgAsExpr(0);
6765  S.AddSYCLIntelESimdVectorizeAttr(D, A, E);
6766 }
6767 
6768 static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6769  const auto *VD = cast<VarDecl>(D);
6770  if (VD->hasLocalStorage()) {
6771  S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
6772  return;
6773  }
6774  // constexpr variable may already get an implicit constant attr, which should
6775  // be replaced by the explicit constant attr.
6776  if (auto *A = D->getAttr<CUDAConstantAttr>()) {
6777  if (!A->isImplicit())
6778  return;
6779  D->dropAttr<CUDAConstantAttr>();
6780  }
6781  D->addAttr(::new (S.Context) CUDAConstantAttr(S.Context, AL));
6782 }
6783 
6784 static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6785  const auto *VD = cast<VarDecl>(D);
6786  // extern __shared__ is only allowed on arrays with no length (e.g.
6787  // "int x[]").
6788  if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
6789  !isa<IncompleteArrayType>(VD->getType())) {
6790  S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
6791  return;
6792  }
6793  if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
6794  S.CUDA().DiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
6795  << llvm::to_underlying(S.CUDA().CurrentTarget()))
6796  return;
6797  D->addAttr(::new (S.Context) CUDASharedAttr(S.Context, AL));
6798 }
6799 
6800 static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6801  const auto *FD = cast<FunctionDecl>(D);
6802  if (!FD->getReturnType()->isVoidType() &&
6803  !FD->getReturnType()->getAs<AutoType>() &&
6805  SourceRange RTRange = FD->getReturnTypeSourceRange();
6806  S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
6807  << FD->getType()
6808  << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
6809  : FixItHint());
6810  return;
6811  }
6812  if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
6813  if (Method->isInstance()) {
6814  S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
6815  << Method;
6816  return;
6817  }
6818  S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
6819  }
6820  // Only warn for "inline" when compiling for host, to cut down on noise.
6821  if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
6822  S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
6823 
6824  if (AL.getKind() == ParsedAttr::AT_NVPTXKernel)
6825  D->addAttr(::new (S.Context) NVPTXKernelAttr(S.Context, AL));
6826  else
6827  D->addAttr(::new (S.Context) CUDAGlobalAttr(S.Context, AL));
6828  // In host compilation the kernel is emitted as a stub function, which is
6829  // a helper function for launching the kernel. The instructions in the helper
6830  // function has nothing to do with the source code of the kernel. Do not emit
6831  // debug info for the stub function to avoid confusing the debugger.
6832  if (S.LangOpts.HIP && !S.LangOpts.CUDAIsDevice)
6833  D->addAttr(NoDebugAttr::CreateImplicit(S.Context));
6834 }
6835 
6836 static void handleDeviceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6837  if (const auto *VD = dyn_cast<VarDecl>(D)) {
6838  if (VD->hasLocalStorage()) {
6839  S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
6840  return;
6841  }
6842  }
6843 
6844  if (auto *A = D->getAttr<CUDADeviceAttr>()) {
6845  if (!A->isImplicit())
6846  return;
6847  D->dropAttr<CUDADeviceAttr>();
6848  }
6849  D->addAttr(::new (S.Context) CUDADeviceAttr(S.Context, AL));
6850 }
6851 
6852 static void handleManagedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6853  if (const auto *VD = dyn_cast<VarDecl>(D)) {
6854  if (VD->hasLocalStorage()) {
6855  S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
6856  return;
6857  }
6858  }
6859  if (!D->hasAttr<HIPManagedAttr>())
6860  D->addAttr(::new (S.Context) HIPManagedAttr(S.Context, AL));
6861  if (!D->hasAttr<CUDADeviceAttr>())
6862  D->addAttr(CUDADeviceAttr::CreateImplicit(S.Context));
6863 }
6864 
6865 static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6866  const auto *Fn = cast<FunctionDecl>(D);
6867  if (!Fn->isInlineSpecified()) {
6868  S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
6869  return;
6870  }
6871 
6872  if (S.LangOpts.CPlusPlus && Fn->getStorageClass() != SC_Extern)
6873  S.Diag(AL.getLoc(), diag::warn_gnu_inline_cplusplus_without_extern);
6874 
6875  D->addAttr(::new (S.Context) GNUInlineAttr(S.Context, AL));
6876 }
6877 
6878 static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6879  if (hasDeclarator(D)) return;
6880 
6881  // Diagnostic is emitted elsewhere: here we store the (valid) AL
6882  // in the Decl node for syntactic reasoning, e.g., pretty-printing.
6883  CallingConv CC;
6884  if (S.CheckCallingConvAttr(
6885  AL, CC, /*FD*/ nullptr,
6886  S.CUDA().IdentifyTarget(dyn_cast<FunctionDecl>(D))))
6887  return;
6888 
6889  if (!isa<ObjCMethodDecl>(D)) {
6890  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
6892  return;
6893  }
6894 
6895  switch (AL.getKind()) {
6896  case ParsedAttr::AT_FastCall:
6897  D->addAttr(::new (S.Context) FastCallAttr(S.Context, AL));
6898  return;
6899  case ParsedAttr::AT_StdCall:
6900  D->addAttr(::new (S.Context) StdCallAttr(S.Context, AL));
6901  return;
6902  case ParsedAttr::AT_ThisCall:
6903  D->addAttr(::new (S.Context) ThisCallAttr(S.Context, AL));
6904  return;
6905  case ParsedAttr::AT_CDecl:
6906  D->addAttr(::new (S.Context) CDeclAttr(S.Context, AL));
6907  return;
6908  case ParsedAttr::AT_Pascal:
6909  D->addAttr(::new (S.Context) PascalAttr(S.Context, AL));
6910  return;
6911  case ParsedAttr::AT_SwiftCall:
6912  D->addAttr(::new (S.Context) SwiftCallAttr(S.Context, AL));
6913  return;
6914  case ParsedAttr::AT_SwiftAsyncCall:
6915  D->addAttr(::new (S.Context) SwiftAsyncCallAttr(S.Context, AL));
6916  return;
6917  case ParsedAttr::AT_VectorCall:
6918  D->addAttr(::new (S.Context) VectorCallAttr(S.Context, AL));
6919  return;
6920  case ParsedAttr::AT_MSABI:
6921  D->addAttr(::new (S.Context) MSABIAttr(S.Context, AL));
6922  return;
6923  case ParsedAttr::AT_SysVABI:
6924  D->addAttr(::new (S.Context) SysVABIAttr(S.Context, AL));
6925  return;
6926  case ParsedAttr::AT_RegCall:
6927  D->addAttr(::new (S.Context) RegCallAttr(S.Context, AL));
6928  return;
6929  case ParsedAttr::AT_Pcs: {
6930  PcsAttr::PCSType PCS;
6931  switch (CC) {
6932  case CC_AAPCS:
6933  PCS = PcsAttr::AAPCS;
6934  break;
6935  case CC_AAPCS_VFP:
6936  PCS = PcsAttr::AAPCS_VFP;
6937  break;
6938  default:
6939  llvm_unreachable("unexpected calling convention in pcs attribute");
6940  }
6941 
6942  D->addAttr(::new (S.Context) PcsAttr(S.Context, AL, PCS));
6943  return;
6944  }
6945  case ParsedAttr::AT_AArch64VectorPcs:
6946  D->addAttr(::new (S.Context) AArch64VectorPcsAttr(S.Context, AL));
6947  return;
6948  case ParsedAttr::AT_AArch64SVEPcs:
6949  D->addAttr(::new (S.Context) AArch64SVEPcsAttr(S.Context, AL));
6950  return;
6951  case ParsedAttr::AT_AMDGPUKernelCall:
6952  D->addAttr(::new (S.Context) AMDGPUKernelCallAttr(S.Context, AL));
6953  return;
6954  case ParsedAttr::AT_IntelOclBicc:
6955  D->addAttr(::new (S.Context) IntelOclBiccAttr(S.Context, AL));
6956  return;
6957  case ParsedAttr::AT_PreserveMost:
6958  D->addAttr(::new (S.Context) PreserveMostAttr(S.Context, AL));
6959  return;
6960  case ParsedAttr::AT_PreserveAll:
6961  D->addAttr(::new (S.Context) PreserveAllAttr(S.Context, AL));
6962  return;
6963  case ParsedAttr::AT_M68kRTD:
6964  D->addAttr(::new (S.Context) M68kRTDAttr(S.Context, AL));
6965  return;
6966  case ParsedAttr::AT_PreserveNone:
6967  D->addAttr(::new (S.Context) PreserveNoneAttr(S.Context, AL));
6968  return;
6969  case ParsedAttr::AT_RISCVVectorCC:
6970  D->addAttr(::new (S.Context) RISCVVectorCCAttr(S.Context, AL));
6971  return;
6972  default:
6973  llvm_unreachable("unexpected attribute kind");
6974  }
6975 }
6976 
6977 static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6978  if (AL.getAttributeSpellingListIndex() == SuppressAttr::CXX11_gsl_suppress) {
6979  // Suppression attribute with GSL spelling requires at least 1 argument.
6980  if (!AL.checkAtLeastNumArgs(S, 1))
6981  return;
6982  }
6983 
6984  std::vector<StringRef> DiagnosticIdentifiers;
6985  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
6986  StringRef RuleName;
6987 
6988  if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr))
6989  return;
6990 
6991  DiagnosticIdentifiers.push_back(RuleName);
6992  }
6993  D->addAttr(::new (S.Context)
6994  SuppressAttr(S.Context, AL, DiagnosticIdentifiers.data(),
6995  DiagnosticIdentifiers.size()));
6996 }
6997 
6998 static void handleLifetimeCategoryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6999  TypeSourceInfo *DerefTypeLoc = nullptr;
7000  QualType ParmType;
7001  if (AL.hasParsedType()) {
7002  ParmType = S.GetTypeFromParser(AL.getTypeArg(), &DerefTypeLoc);
7003 
7004  unsigned SelectIdx = ~0U;
7005  if (ParmType->isReferenceType())
7006  SelectIdx = 0;
7007  else if (ParmType->isArrayType())
7008  SelectIdx = 1;
7009 
7010  if (SelectIdx != ~0U) {
7011  S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument)
7012  << SelectIdx << AL;
7013  return;
7014  }
7015  }
7016 
7017  // To check if earlier decl attributes do not conflict the newly parsed ones
7018  // we always add (and check) the attribute to the canonical decl. We need
7019  // to repeat the check for attribute mutual exclusion because we're attaching
7020  // all of the attributes to the canonical declaration rather than the current
7021  // declaration.
7022  D = D->getCanonicalDecl();
7023  if (AL.getKind() == ParsedAttr::AT_Owner) {
7024  if (checkAttrMutualExclusion<PointerAttr>(S, D, AL))
7025  return;
7026  if (const auto *OAttr = D->getAttr<OwnerAttr>()) {
7027  const Type *ExistingDerefType = OAttr->getDerefTypeLoc()
7028  ? OAttr->getDerefType().getTypePtr()
7029  : nullptr;
7030  if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
7031  S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
7032  << AL << OAttr
7033  << (AL.isRegularKeywordAttribute() ||
7034  OAttr->isRegularKeywordAttribute());
7035  S.Diag(OAttr->getLocation(), diag::note_conflicting_attribute);
7036  }
7037  return;
7038  }
7039  for (Decl *Redecl : D->redecls()) {
7040  Redecl->addAttr(::new (S.Context) OwnerAttr(S.Context, AL, DerefTypeLoc));
7041  }
7042  } else {
7043  if (checkAttrMutualExclusion<OwnerAttr>(S, D, AL))
7044  return;
7045  if (const auto *PAttr = D->getAttr<PointerAttr>()) {
7046  const Type *ExistingDerefType = PAttr->getDerefTypeLoc()
7047  ? PAttr->getDerefType().getTypePtr()
7048  : nullptr;
7049  if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
7050  S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
7051  << AL << PAttr
7052  << (AL.isRegularKeywordAttribute() ||
7053  PAttr->isRegularKeywordAttribute());
7054  S.Diag(PAttr->getLocation(), diag::note_conflicting_attribute);
7055  }
7056  return;
7057  }
7058  for (Decl *Redecl : D->redecls()) {
7059  Redecl->addAttr(::new (S.Context)
7060  PointerAttr(S.Context, AL, DerefTypeLoc));
7061  }
7062  }
7063 }
7064 
7065 static void handleRandomizeLayoutAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7066  if (checkAttrMutualExclusion<NoRandomizeLayoutAttr>(S, D, AL))
7067  return;
7068  if (!D->hasAttr<RandomizeLayoutAttr>())
7069  D->addAttr(::new (S.Context) RandomizeLayoutAttr(S.Context, AL));
7070 }
7071 
7072 static void handleNoRandomizeLayoutAttr(Sema &S, Decl *D,
7073  const ParsedAttr &AL) {
7074  if (checkAttrMutualExclusion<RandomizeLayoutAttr>(S, D, AL))
7075  return;
7076  if (!D->hasAttr<NoRandomizeLayoutAttr>())
7077  D->addAttr(::new (S.Context) NoRandomizeLayoutAttr(S.Context, AL));
7078 }
7079 
7080 bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC,
7081  const FunctionDecl *FD,
7082  CUDAFunctionTarget CFT) {
7083  if (Attrs.isInvalid())
7084  return true;
7085 
7086  if (Attrs.hasProcessingCache()) {
7087  CC = (CallingConv) Attrs.getProcessingCache();
7088  return false;
7089  }
7090 
7091  unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
7092  if (!Attrs.checkExactlyNumArgs(*this, ReqArgs)) {
7093  Attrs.setInvalid();
7094  return true;
7095  }
7096 
7097  const TargetInfo &TI = Context.getTargetInfo();
7098  // TODO: diagnose uses of these conventions on the wrong target.
7099  switch (Attrs.getKind()) {
7100  case ParsedAttr::AT_CDecl:
7101  CC = TI.getDefaultCallingConv();
7102  break;
7103  case ParsedAttr::AT_FastCall:
7104  CC = CC_X86FastCall;
7105  break;
7106  case ParsedAttr::AT_StdCall:
7107  CC = CC_X86StdCall;
7108  break;
7109  case ParsedAttr::AT_ThisCall:
7110  CC = CC_X86ThisCall;
7111  break;
7112  case ParsedAttr::AT_Pascal:
7113  CC = CC_X86Pascal;
7114  break;
7115  case ParsedAttr::AT_SwiftCall:
7116  CC = CC_Swift;
7117  break;
7118  case ParsedAttr::AT_SwiftAsyncCall:
7119  CC = CC_SwiftAsync;
7120  break;
7121  case ParsedAttr::AT_VectorCall:
7122  CC = CC_X86VectorCall;
7123  break;
7124  case ParsedAttr::AT_AArch64VectorPcs:
7125  CC = CC_AArch64VectorCall;
7126  break;
7127  case ParsedAttr::AT_AArch64SVEPcs:
7128  CC = CC_AArch64SVEPCS;
7129  break;
7130  case ParsedAttr::AT_AMDGPUKernelCall:
7131  CC = CC_AMDGPUKernelCall;
7132  break;
7133  case ParsedAttr::AT_RegCall:
7134  CC = CC_X86RegCall;
7135  break;
7136  case ParsedAttr::AT_MSABI:
7137  CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
7138  CC_Win64;
7139  break;
7140  case ParsedAttr::AT_SysVABI:
7141  CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
7142  CC_C;
7143  break;
7144  case ParsedAttr::AT_Pcs: {
7145  StringRef StrRef;
7146  if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
7147  Attrs.setInvalid();
7148  return true;
7149  }
7150  if (StrRef == "aapcs") {
7151  CC = CC_AAPCS;
7152  break;
7153  } else if (StrRef == "aapcs-vfp") {
7154  CC = CC_AAPCS_VFP;
7155  break;
7156  }
7157 
7158  Attrs.setInvalid();
7159  Diag(Attrs.getLoc(), diag::err_invalid_pcs);
7160  return true;
7161  }
7162  case ParsedAttr::AT_IntelOclBicc:
7163  CC = CC_IntelOclBicc;
7164  break;
7165  case ParsedAttr::AT_PreserveMost:
7166  CC = CC_PreserveMost;
7167  break;
7168  case ParsedAttr::AT_PreserveAll:
7169  CC = CC_PreserveAll;
7170  break;
7171  case ParsedAttr::AT_M68kRTD:
7172  CC = CC_M68kRTD;
7173  break;
7174  case ParsedAttr::AT_PreserveNone:
7175  CC = CC_PreserveNone;
7176  break;
7177  case ParsedAttr::AT_RISCVVectorCC:
7178  CC = CC_RISCVVectorCall;
7179  break;
7180  default: llvm_unreachable("unexpected attribute kind");
7181  }
7182 
7184  // CUDA functions may have host and/or device attributes which indicate
7185  // their targeted execution environment, therefore the calling convention
7186  // of functions in CUDA should be checked against the target deduced based
7187  // on their host/device attributes.
7188  if (LangOpts.CUDA) {
7189  auto *Aux = Context.getAuxTargetInfo();
7190  assert(FD || CFT != CUDAFunctionTarget::InvalidTarget);
7191  auto CudaTarget = FD ? CUDA().IdentifyTarget(FD) : CFT;
7192  bool CheckHost = false, CheckDevice = false;
7193  switch (CudaTarget) {
7195  CheckHost = true;
7196  CheckDevice = true;
7197  break;
7199  CheckHost = true;
7200  break;
7203  CheckDevice = true;
7204  break;
7206  llvm_unreachable("unexpected cuda target");
7207  }
7208  auto *HostTI = LangOpts.CUDAIsDevice ? Aux : &TI;
7209  auto *DeviceTI = LangOpts.CUDAIsDevice ? &TI : Aux;
7210  if (CheckHost && HostTI)
7211  A = HostTI->checkCallingConvention(CC);
7212  if (A == TargetInfo::CCCR_OK && CheckDevice && DeviceTI)
7213  A = DeviceTI->checkCallingConvention(CC);
7214  } else {
7215  A = TI.checkCallingConvention(CC);
7216  }
7217 
7218  switch (A) {
7219  case TargetInfo::CCCR_OK:
7220  break;
7221 
7223  // Treat an ignored convention as if it was an explicit C calling convention
7224  // attribute. For example, __stdcall on Win x64 functions as __cdecl, so
7225  // that command line flags that change the default convention to
7226  // __vectorcall don't affect declarations marked __stdcall.
7227  CC = CC_C;
7228  break;
7229 
7231  Diag(Attrs.getLoc(), diag::error_cconv_unsupported)
7232  << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
7233  break;
7234 
7235  case TargetInfo::CCCR_Warning: {
7236  Diag(Attrs.getLoc(), diag::warn_cconv_unsupported)
7237  << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
7238 
7239  // This convention is not valid for the target. Use the default function or
7240  // method calling convention.
7241  bool IsCXXMethod = false, IsVariadic = false;
7242  if (FD) {
7243  IsCXXMethod = FD->isCXXInstanceMember();
7244  IsVariadic = FD->isVariadic();
7245  }
7246  CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
7247  break;
7248  }
7249  }
7250 
7251  Attrs.setProcessingCache((unsigned) CC);
7252  return false;
7253 }
7254 
7255 /// Pointer-like types in the default address space.
7256 static bool isValidSwiftContextType(QualType Ty) {
7257  if (!Ty->hasPointerRepresentation())
7258  return Ty->isDependentType();
7260 }
7261 
7262 /// Pointers and references in the default address space.
7263 static bool isValidSwiftIndirectResultType(QualType Ty) {
7264  if (const auto *PtrType = Ty->getAs<PointerType>()) {
7265  Ty = PtrType->getPointeeType();
7266  } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
7267  Ty = RefType->getPointeeType();
7268  } else {
7269  return Ty->isDependentType();
7270  }
7271  return Ty.getAddressSpace() == LangAS::Default;
7272 }
7273 
7274 /// Pointers and references to pointers in the default address space.
7275 static bool isValidSwiftErrorResultType(QualType Ty) {
7276  if (const auto *PtrType = Ty->getAs<PointerType>()) {
7277  Ty = PtrType->getPointeeType();
7278  } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
7279  Ty = RefType->getPointeeType();
7280  } else {
7281  return Ty->isDependentType();
7282  }
7283  if (!Ty.getQualifiers().empty())
7284  return false;
7285  return isValidSwiftContextType(Ty);
7286 }
7287 
7289  ParameterABI abi) {
7290 
7291  QualType type = cast<ParmVarDecl>(D)->getType();
7292 
7293  if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
7294  if (existingAttr->getABI() != abi) {
7295  Diag(CI.getLoc(), diag::err_attributes_are_not_compatible)
7296  << getParameterABISpelling(abi) << existingAttr
7297  << (CI.isRegularKeywordAttribute() ||
7298  existingAttr->isRegularKeywordAttribute());
7299  Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
7300  return;
7301  }
7302  }
7303 
7304  switch (abi) {
7306  llvm_unreachable("explicit attribute for ordinary parameter ABI?");
7307 
7309  if (!isValidSwiftContextType(type)) {
7310  Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
7311  << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
7312  }
7313  D->addAttr(::new (Context) SwiftContextAttr(Context, CI));
7314  return;
7315 
7317  if (!isValidSwiftContextType(type)) {
7318  Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
7319  << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
7320  }
7321  D->addAttr(::new (Context) SwiftAsyncContextAttr(Context, CI));
7322  return;
7323 
7325  if (!isValidSwiftErrorResultType(type)) {
7326  Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
7327  << getParameterABISpelling(abi) << /*pointer to pointer */ 1 << type;
7328  }
7329  D->addAttr(::new (Context) SwiftErrorResultAttr(Context, CI));
7330  return;
7331 
7333  if (!isValidSwiftIndirectResultType(type)) {
7334  Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
7335  << getParameterABISpelling(abi) << /*pointer*/ 0 << type;
7336  }
7337  D->addAttr(::new (Context) SwiftIndirectResultAttr(Context, CI));
7338  return;
7339  }
7340  llvm_unreachable("bad parameter ABI attribute");
7341 }
7342 
7343 /// Checks a regparm attribute, returning true if it is ill-formed and
7344 /// otherwise setting numParams to the appropriate value.
7345 bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) {
7346  if (AL.isInvalid())
7347  return true;
7348 
7349  if (!AL.checkExactlyNumArgs(*this, 1)) {
7350  AL.setInvalid();
7351  return true;
7352  }
7353 
7354  uint32_t NP;
7355  Expr *NumParamsExpr = AL.getArgAsExpr(0);
7356  if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) {
7357  AL.setInvalid();
7358  return true;
7359  }
7360 
7361  if (Context.getTargetInfo().getRegParmMax() == 0) {
7362  Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform)
7363  << NumParamsExpr->getSourceRange();
7364  AL.setInvalid();
7365  return true;
7366  }
7367 
7368  numParams = NP;
7369  if (numParams > Context.getTargetInfo().getRegParmMax()) {
7370  Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number)
7371  << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
7372  AL.setInvalid();
7373  return true;
7374  }
7375 
7376  return false;
7377 }
7378 
7379 // Checks whether an argument of launch_bounds attribute is
7380 // acceptable, performs implicit conversion to Rvalue, and returns
7381 // non-nullptr Expr result on success. Otherwise, it returns nullptr
7382 // and may output an error.
7383 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
7384  const CUDALaunchBoundsAttr &AL,
7385  const unsigned Idx) {
7387  return nullptr;
7388 
7389  // Accept template arguments for now as they depend on something else.
7390  // We'll get to check them when they eventually get instantiated.
7391  if (E->isValueDependent())
7392  return E;
7393 
7394  std::optional<llvm::APSInt> I = llvm::APSInt(64);
7395  if (!(I = E->getIntegerConstantExpr(S.Context))) {
7396  S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
7397  << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
7398  return nullptr;
7399  }
7400  // Make sure we can fit it in 32 bits.
7401  if (!I->isIntN(32)) {
7402  S.Diag(E->getExprLoc(), diag::err_ice_too_large)
7403  << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
7404  return nullptr;
7405  }
7406  if (*I < 0)
7407  S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
7408  << &AL << Idx << E->getSourceRange();
7409 
7410  // We may need to perform implicit conversion of the argument.
7412  S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
7413  ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
7414  assert(!ValArg.isInvalid() &&
7415  "Unexpected PerformCopyInitialization() failure.");
7416 
7417  return ValArg.getAs<Expr>();
7418 }
7419 
7420 CUDALaunchBoundsAttr *
7422  Expr *MinBlocks, Expr *MaxBlocks) {
7423  CUDALaunchBoundsAttr TmpAttr(Context, CI, MaxThreads, MinBlocks, MaxBlocks);
7424  MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
7425  if (!MaxThreads)
7426  return nullptr;
7427 
7428  if (MinBlocks) {
7429  MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
7430  if (!MinBlocks)
7431  return nullptr;
7432  }
7433 
7434  if (MaxBlocks) {
7435  // '.maxclusterrank' ptx directive requires .target sm_90 or higher.
7436  auto SM = getCudaArch(Context.getTargetInfo());
7437  if (SM == CudaArch::UNKNOWN || SM < CudaArch::SM_90) {
7438  Diag(MaxBlocks->getBeginLoc(), diag::warn_cuda_maxclusterrank_sm_90)
7439  << CudaArchToString(SM) << CI << MaxBlocks->getSourceRange();
7440  // Ignore it by setting MaxBlocks to null;
7441  MaxBlocks = nullptr;
7442  } else {
7443  MaxBlocks = makeLaunchBoundsArgExpr(*this, MaxBlocks, TmpAttr, 2);
7444  if (!MaxBlocks)
7445  return nullptr;
7446  }
7447  }
7448 
7449  return ::new (Context)
7450  CUDALaunchBoundsAttr(Context, CI, MaxThreads, MinBlocks, MaxBlocks);
7451 }
7452 
7454  Expr *MaxThreads, Expr *MinBlocks,
7455  Expr *MaxBlocks) {
7456  if (auto *Attr = CreateLaunchBoundsAttr(CI, MaxThreads, MinBlocks, MaxBlocks))
7457  D->addAttr(Attr);
7458 }
7459 
7460 static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7461  if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 3))
7462  return;
7463 
7464  S.AddLaunchBoundsAttr(D, AL, AL.getArgAsExpr(0),
7465  AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr,
7466  AL.getNumArgs() > 2 ? AL.getArgAsExpr(2) : nullptr);
7467 }
7468 
7469 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
7470  const ParsedAttr &AL) {
7471  if (!AL.isArgIdent(0)) {
7472  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
7473  << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier;
7474  return;
7475  }
7476 
7477  ParamIdx ArgumentIdx;
7478  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1),
7479  ArgumentIdx))
7480  return;
7481 
7482  ParamIdx TypeTagIdx;
7483  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2),
7484  TypeTagIdx))
7485  return;
7486 
7487  bool IsPointer = AL.getAttrName()->getName() == "pointer_with_type_tag";
7488  if (IsPointer) {
7489  // Ensure that buffer has a pointer type.
7490  unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex();
7491  if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) ||
7492  !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType())
7493  S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0;
7494  }
7495 
7496  D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr(
7497  S.Context, AL, AL.getArgAsIdent(0)->Ident, ArgumentIdx, TypeTagIdx,
7498  IsPointer));
7499 }
7500 
7501 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
7502  const ParsedAttr &AL) {
7503  if (!AL.isArgIdent(0)) {
7504  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
7505  << AL << 1 << AANT_ArgumentIdentifier;
7506  return;
7507  }
7508 
7509  if (!AL.checkExactlyNumArgs(S, 1))
7510  return;
7511 
7512  if (!isa<VarDecl>(D)) {
7513  S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type)
7515  return;
7516  }
7517 
7518  IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident;
7519  TypeSourceInfo *MatchingCTypeLoc = nullptr;
7520  S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc);
7521  assert(MatchingCTypeLoc && "no type source info for attribute argument");
7522 
7523  D->addAttr(::new (S.Context) TypeTagForDatatypeAttr(
7524  S.Context, AL, PointerKind, MatchingCTypeLoc, AL.getLayoutCompatible(),
7525  AL.getMustBeNull()));
7526 }
7527 
7528 /// Give a warning for duplicate attributes, return true if duplicate.
7529 template <typename AttrType>
7530 static bool checkForDuplicateAttribute(Sema &S, Decl *D,
7531  const ParsedAttr &Attr) {
7532  // Give a warning for duplicates but not if it's one we've implicitly added.
7533  auto *A = D->getAttr<AttrType>();
7534  if (A && !A->isImplicit()) {
7535  S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact) << A;
7536  return true;
7537  }
7538  return false;
7539 }
7540 
7541 // Checks if FPGA memory attributes apply on valid variables.
7542 // Returns true if an error occured.
7543 static bool CheckValidFPGAMemoryAttributesVar(Sema &S, Decl *D) {
7544  if (const auto *VD = dyn_cast<VarDecl>(D)) {
7545  if (!(isa<FieldDecl>(D) ||
7546  (VD->getKind() != Decl::ImplicitParam &&
7547  VD->getKind() != Decl::NonTypeTemplateParm &&
7548  (S.SYCL().isTypeDecoratedWithDeclAttribute<SYCLDeviceGlobalAttr>(
7549  VD->getType()) ||
7550  VD->getType().isConstQualified() ||
7552  VD->getStorageClass() == SC_Static || VD->hasLocalStorage())))) {
7553  return true;
7554  }
7555  }
7556  return false;
7557 }
7558 
7560  const AttributeCommonInfo &CI,
7561  Expr *E) {
7562  if (!E->isValueDependent()) {
7563  // Validate that we have an integer constant expression and then store the
7564  // converted constant expression into the semantic attribute so that we
7565  // don't have to evaluate it again later.
7566  llvm::APSInt ArgVal;
7567  ExprResult Res = VerifyIntegerConstantExpression(E, &ArgVal);
7568  if (Res.isInvalid())
7569  return;
7570  E = Res.get();
7571 
7572  // Check to see if there's a duplicate attribute with different values
7573  // already applied to the declaration.
7574  if (const auto *DeclAttr = D->getAttr<SYCLIntelNoGlobalWorkOffsetAttr>()) {
7575  // If the other attribute argument is instantiation dependent, we won't
7576  // have converted it to a constant expression yet and thus we test
7577  // whether this is a null pointer.
7578  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
7579  if (ArgVal != DeclExpr->getResultAsAPSInt()) {
7580  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << CI;
7581  Diag(DeclAttr->getLoc(), diag::note_previous_attribute);
7582  }
7583  // Drop the duplicate attribute.
7584  return;
7585  }
7586  }
7587  }
7588 
7589  D->addAttr(::new (Context) SYCLIntelNoGlobalWorkOffsetAttr(Context, CI, E));
7590 }
7591 
7592 SYCLIntelNoGlobalWorkOffsetAttr *Sema::MergeSYCLIntelNoGlobalWorkOffsetAttr(
7593  Decl *D, const SYCLIntelNoGlobalWorkOffsetAttr &A) {
7594  // Check to see if there's a duplicate attribute with different values
7595  // already applied to the declaration.
7596  if (const auto *DeclAttr = D->getAttr<SYCLIntelNoGlobalWorkOffsetAttr>()) {
7597  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
7598  if (const auto *MergeExpr = dyn_cast<ConstantExpr>(A.getValue())) {
7599  if (DeclExpr->getResultAsAPSInt() != MergeExpr->getResultAsAPSInt()) {
7600  Diag(DeclAttr->getLoc(), diag::warn_duplicate_attribute) << &A;
7601  Diag(A.getLoc(), diag::note_previous_attribute);
7602  }
7603  // Do not add a duplicate attribute.
7604  return nullptr;
7605  }
7606  }
7607  }
7608  return ::new (Context)
7609  SYCLIntelNoGlobalWorkOffsetAttr(Context, A, A.getValue());
7610 }
7611 
7612 static void handleSYCLIntelNoGlobalWorkOffsetAttr(Sema &S, Decl *D,
7613  const ParsedAttr &A) {
7614  // If no attribute argument is specified, set to default value '1'.
7615  Expr *E = A.isArgExpr(0)
7616  ? A.getArgAsExpr(0)
7618  S.Context.IntTy, A.getLoc());
7619 
7621 }
7622 
7623 /// Handle the [[intel::singlepump]] attribute.
7624 static void handleSYCLIntelSinglePumpAttr(Sema &S, Decl *D,
7625  const ParsedAttr &AL) {
7626  // 'singlepump' Attribute does not take any argument. Give a warning for
7627  // duplicate attributes but not if it's one we've implicitly added and drop
7628  // any duplicates.
7629  if (const auto *ExistingAttr = D->getAttr<SYCLIntelSinglePumpAttr>()) {
7630  if (ExistingAttr && !ExistingAttr->isImplicit()) {
7631  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute_exact) << &AL;
7632  S.Diag(ExistingAttr->getLoc(), diag::note_previous_attribute);
7633  return;
7634  }
7635  }
7636 
7637  // Check attribute applies to field, constant variables, local variables,
7638  // static variables, non-static data members, and device_global variables
7639  // for the device compilation.
7640  if (S.Context.getLangOpts().SYCLIsDevice &&
7641  ((D->getKind() == Decl::ParmVar) ||
7642  CheckValidFPGAMemoryAttributesVar(S, D))) {
7643  S.Diag(AL.getLoc(), diag::err_fpga_attribute_incorrect_variable)
7644  << AL << /*agent memory arguments*/ 0;
7645  return;
7646  }
7647 
7648  // If the declaration does not have an [[intel::fpga_memory]]
7649  // attribute, this creates one as an implicit attribute.
7650  if (!D->hasAttr<SYCLIntelMemoryAttr>())
7651  D->addAttr(SYCLIntelMemoryAttr::CreateImplicit(
7652  S.Context, SYCLIntelMemoryAttr::Default));
7653 
7654  D->addAttr(::new (S.Context) SYCLIntelSinglePumpAttr(S.Context, AL));
7655 }
7656 
7657 /// Handle the [[intel::doublepump]] attribute.
7658 static void handleSYCLIntelDoublePumpAttr(Sema &S, Decl *D,
7659  const ParsedAttr &AL) {
7660  // 'doublepump' Attribute does not take any argument. Give a warning for
7661  // duplicate attributes but not if it's one we've implicitly added and drop
7662  // any duplicates.
7663  if (const auto *ExistingAttr = D->getAttr<SYCLIntelDoublePumpAttr>()) {
7664  if (ExistingAttr && !ExistingAttr->isImplicit()) {
7665  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute_exact) << &AL;
7666  S.Diag(ExistingAttr->getLoc(), diag::note_previous_attribute);
7667  return;
7668  }
7669  }
7670 
7671  // Check attribute applies to field, constant variables, local variables,
7672  // static variables, non-static data members, and device_global variables
7673  // for the device compilation.
7674  if (S.Context.getLangOpts().SYCLIsDevice &&
7675  ((D->getKind() == Decl::ParmVar) ||
7676  CheckValidFPGAMemoryAttributesVar(S, D))) {
7677  S.Diag(AL.getLoc(), diag::err_fpga_attribute_incorrect_variable)
7678  << AL << /*agent memory arguments*/ 0;
7679  return;
7680  }
7681 
7682  // If the declaration does not have an [[intel::fpga_memory]]
7683  // attribute, this creates one as an implicit attribute.
7684  if (!D->hasAttr<SYCLIntelMemoryAttr>())
7685  D->addAttr(SYCLIntelMemoryAttr::CreateImplicit(
7686  S.Context, SYCLIntelMemoryAttr::Default));
7687 
7688  D->addAttr(::new (S.Context) SYCLIntelDoublePumpAttr(S.Context, AL));
7689 }
7690 
7691 /// Handle the [[intel::fpga_memory]] attribute.
7692 /// This is incompatible with the [[intel::fpga_register]] attribute.
7693 static void handleSYCLIntelMemoryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7694  SYCLIntelMemoryAttr::MemoryKind Kind;
7695  if (AL.getNumArgs() == 0)
7696  Kind = SYCLIntelMemoryAttr::Default;
7697  else {
7698  StringRef Str;
7699  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
7700  return;
7701  if (Str.empty() ||
7702  !SYCLIntelMemoryAttr::ConvertStrToMemoryKind(Str, Kind)) {
7703  SmallString<256> ValidStrings;
7704  SYCLIntelMemoryAttr::generateValidStrings(ValidStrings);
7705  S.Diag(AL.getLoc(), diag::err_intel_fpga_memory_arg_invalid)
7706  << AL << ValidStrings;
7707  return;
7708  }
7709  }
7710 
7711  if (auto *MA = D->getAttr<SYCLIntelMemoryAttr>()) {
7712  // Check to see if there's a duplicate memory attribute with different
7713  // values already applied to the declaration.
7714  if (!MA->isImplicit()) {
7715  if (MA->getKind() != Kind) {
7716  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << &AL;
7717  S.Diag(MA->getLocation(), diag::note_previous_attribute);
7718  }
7719  // Drop the duplicate attribute.
7720  return;
7721  }
7722  // We are adding a user memory attribute, drop any implicit default.
7723  D->dropAttr<SYCLIntelMemoryAttr>();
7724  }
7725 
7726  // Check attribute applies to field, constant variables, local variables,
7727  // static variables, agent memory arguments, non-static data members,
7728  // and device_global variables for the device compilation.
7729  if (S.Context.getLangOpts().SYCLIsDevice &&
7730  CheckValidFPGAMemoryAttributesVar(S, D)) {
7731  S.Diag(AL.getLoc(), diag::err_fpga_attribute_incorrect_variable)
7732  << AL << /*agent memory arguments*/ 1;
7733  return;
7734  }
7735 
7736  D->addAttr(::new (S.Context) SYCLIntelMemoryAttr(S.Context, AL, Kind));
7737 }
7738 
7739 /// Handle the [[intel::fpga_register]] attribute.
7740 /// This is incompatible with most of the other memory attributes.
7741 static void handleSYCLIntelRegisterAttr(Sema &S, Decl *D,
7742  const ParsedAttr &A) {
7743 
7744  // 'fpga_register' Attribute does not take any argument. Give a warning for
7745  // duplicate attributes but not if it's one we've implicitly added and drop
7746  // any duplicates.
7747  if (const auto *ExistingAttr = D->getAttr<SYCLIntelRegisterAttr>()) {
7748  if (ExistingAttr && !ExistingAttr->isImplicit()) {
7749  S.Diag(A.getLoc(), diag::warn_duplicate_attribute_exact) << &A;
7750  S.Diag(ExistingAttr->getLoc(), diag::note_previous_attribute);
7751  return;
7752  }
7753  }
7754 
7755  // Check attribute applies to field, constant variables, local variables,
7756  // static variables, non-static data members, and device_global variables
7757  // for the device compilation.
7758  if (S.Context.getLangOpts().SYCLIsDevice &&
7759  ((D->getKind() == Decl::ParmVar) ||
7760  CheckValidFPGAMemoryAttributesVar(S, D))) {
7761  S.Diag(A.getLoc(), diag::err_fpga_attribute_incorrect_variable)
7762  << A << /*agent memory arguments*/ 0;
7763  return;
7764  }
7765 
7766  D->addAttr(::new (S.Context) SYCLIntelRegisterAttr(S.Context, A));
7767 }
7768 
7769 /// Handle the [[intel::bankwidth]] and [[intel::numbanks]] attributes.
7770 /// These require a single constant power of two greater than zero.
7771 /// These are incompatible with the register attribute.
7772 /// The numbanks and bank_bits attributes are related. If bank_bits exists
7773 /// when handling numbanks they are checked for consistency.
7774 
7776  Expr *E) {
7777  if (!E->isValueDependent()) {
7778  // Validate that we have an integer constant expression and then store the
7779  // converted constant expression into the semantic attribute so that we
7780  // don't have to evaluate it again later.
7781  llvm::APSInt ArgVal;
7782  ExprResult Res = VerifyIntegerConstantExpression(E, &ArgVal);
7783  if (Res.isInvalid())
7784  return;
7785  E = Res.get();
7786 
7787  // This attribute requires a strictly positive value.
7788  if (ArgVal <= 0) {
7789  Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer)
7790  << CI << /*positive*/ 0;
7791  return;
7792  }
7793 
7794  // This attribute requires a single constant power of two greater than zero.
7795  if (!ArgVal.isPowerOf2()) {
7796  Diag(E->getExprLoc(), diag::err_attribute_argument_not_power_of_two)
7797  << CI;
7798  return;
7799  }
7800 
7801  // Check attribute applies to field, constant variables, local variables,
7802  // static variables, agent memory arguments, non-static data members,
7803  // and device_global variables for the device compilation.
7804  if (Context.getLangOpts().SYCLIsDevice &&
7805  CheckValidFPGAMemoryAttributesVar(*this, D)) {
7806  Diag(CI.getLoc(), diag::err_fpga_attribute_incorrect_variable)
7807  << CI << /*agent memory arguments*/ 1;
7808  return;
7809  }
7810 
7811  // Check to see if there's a duplicate attribute with different values
7812  // already applied to the declaration.
7813  if (const auto *DeclAttr = D->getAttr<SYCLIntelBankWidthAttr>()) {
7814  // If the other attribute argument is instantiation dependent, we won't
7815  // have converted it to a constant expression yet and thus we test
7816  // whether this is a null pointer.
7817  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
7818  if (ArgVal != DeclExpr->getResultAsAPSInt()) {
7819  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << CI;
7820  Diag(DeclAttr->getLoc(), diag::note_previous_attribute);
7821  }
7822  // Drop the duplicate attribute.
7823  return;
7824  }
7825  }
7826  }
7827 
7828  // If the declaration does not have an [[intel::fpga_memory]]
7829  // attribute, this creates one as an implicit attribute.
7830  if (!D->hasAttr<SYCLIntelMemoryAttr>())
7831  D->addAttr(SYCLIntelMemoryAttr::CreateImplicit(
7832  Context, SYCLIntelMemoryAttr::Default));
7833 
7834  D->addAttr(::new (Context) SYCLIntelBankWidthAttr(Context, CI, E));
7835 }
7836 
7837 SYCLIntelBankWidthAttr *
7838 Sema::MergeSYCLIntelBankWidthAttr(Decl *D, const SYCLIntelBankWidthAttr &A) {
7839  // Check to see if there's a duplicate attribute with different values
7840  // already applied to the declaration.
7841  if (const auto *DeclAttr = D->getAttr<SYCLIntelBankWidthAttr>()) {
7842  const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue());
7843  const auto *MergeExpr = dyn_cast<ConstantExpr>(A.getValue());
7844  if (DeclExpr && MergeExpr &&
7845  DeclExpr->getResultAsAPSInt() != MergeExpr->getResultAsAPSInt()) {
7846  Diag(DeclAttr->getLoc(), diag::warn_duplicate_attribute) << &A;
7847  Diag(A.getLoc(), diag::note_previous_attribute);
7848  return nullptr;
7849  }
7850  }
7851 
7852  return ::new (Context) SYCLIntelBankWidthAttr(Context, A, A.getValue());
7853 }
7854 
7855 static void handleSYCLIntelBankWidthAttr(Sema &S, Decl *D,
7856  const ParsedAttr &A) {
7858 }
7859 
7861  Expr *E) {
7862  if (!E->isValueDependent()) {
7863  // Validate that we have an integer constant expression and then store the
7864  // converted constant expression into the semantic attribute so that we
7865  // don't have to evaluate it again later.
7866  llvm::APSInt ArgVal;
7867  ExprResult Res = VerifyIntegerConstantExpression(E, &ArgVal);
7868  if (Res.isInvalid())
7869  return;
7870  E = Res.get();
7871 
7872  // This attribute requires a strictly positive value.
7873  if (ArgVal <= 0) {
7874  Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer)
7875  << CI << /*positive*/ 0;
7876  return;
7877  }
7878 
7879  // This attribute requires a single constant power of two greater than zero.
7880  if (!ArgVal.isPowerOf2()) {
7881  Diag(E->getExprLoc(), diag::err_attribute_argument_not_power_of_two)
7882  << CI;
7883  return;
7884  }
7885 
7886  // Check or add the related BankBits attribute.
7887  if (auto *BBA = D->getAttr<SYCLIntelBankBitsAttr>()) {
7888  unsigned NumBankBits = BBA->args_size();
7889  if (NumBankBits != ArgVal.ceilLogBase2()) {
7890  Diag(E->getExprLoc(), diag::err_bankbits_numbanks_conflicting) << CI;
7891  return;
7892  }
7893  }
7894 
7895  // Check attribute applies to constant variables, local variables,
7896  // static variables, agent memory arguments, non-static data members,
7897  // and device_global variables for the device compilation.
7898  if (Context.getLangOpts().SYCLIsDevice &&
7899  CheckValidFPGAMemoryAttributesVar(*this, D)) {
7900  Diag(CI.getLoc(), diag::err_fpga_attribute_incorrect_variable)
7901  << CI << /*agent memory arguments*/ 1;
7902  return;
7903  }
7904 
7905  // Check to see if there's a duplicate attribute with different values
7906  // already applied to the declaration.
7907  if (const auto *DeclAttr = D->getAttr<SYCLIntelNumBanksAttr>()) {
7908  // If the other attribute argument is instantiation dependent, we won't
7909  // have converted it to a constant expression yet and thus we test
7910  // whether this is a null pointer.
7911  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
7912  if (ArgVal != DeclExpr->getResultAsAPSInt()) {
7913  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << CI;
7914  Diag(DeclAttr->getLoc(), diag::note_previous_attribute);
7915  }
7916  // Drop the duplicate attribute.
7917  return;
7918  }
7919  }
7920  }
7921 
7922  // If the declaration does not have an [[intel::fpga_memory]]
7923  // attribute, this creates one as an implicit attribute.
7924  if (!D->hasAttr<SYCLIntelMemoryAttr>())
7925  D->addAttr(SYCLIntelMemoryAttr::CreateImplicit(
7926  Context, SYCLIntelMemoryAttr::Default));
7927 
7928  // We are adding a user NumBanks attribute, drop any implicit default.
7929  if (auto *NBA = D->getAttr<SYCLIntelNumBanksAttr>()) {
7930  if (NBA->isImplicit())
7931  D->dropAttr<SYCLIntelNumBanksAttr>();
7932  }
7933 
7934  D->addAttr(::new (Context) SYCLIntelNumBanksAttr(Context, CI, E));
7935 }
7936 
7937 SYCLIntelNumBanksAttr *
7938 Sema::MergeSYCLIntelNumBanksAttr(Decl *D, const SYCLIntelNumBanksAttr &A) {
7939  // Check to see if there's a duplicate attribute with different values
7940  // already applied to the declaration.
7941  if (const auto *DeclAttr = D->getAttr<SYCLIntelNumBanksAttr>()) {
7942  const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue());
7943  const auto *MergeExpr = dyn_cast<ConstantExpr>(A.getValue());
7944  if (DeclExpr && MergeExpr &&
7945  DeclExpr->getResultAsAPSInt() != MergeExpr->getResultAsAPSInt()) {
7946  Diag(DeclAttr->getLoc(), diag::warn_duplicate_attribute) << &A;
7947  Diag(A.getLoc(), diag::note_previous_attribute);
7948  return nullptr;
7949  }
7950  }
7951 
7952  return ::new (Context) SYCLIntelNumBanksAttr(Context, A, A.getValue());
7953 }
7954 
7955 static void handleSYCLIntelNumBanksAttr(Sema &S, Decl *D, const ParsedAttr &A) {
7956  S.AddSYCLIntelNumBanksAttr(D, A, A.getArgAsExpr(0));
7957 }
7958 
7959 static void handleIntelSimpleDualPortAttr(Sema &S, Decl *D,
7960  const ParsedAttr &AL) {
7961  // 'simple_dual_port' Attribute does not take any argument. Give a warning for
7962  // duplicate attributes but not if it's one we've implicitly added and drop
7963  // any duplicates.
7964  if (const auto *ExistingAttr = D->getAttr<SYCLIntelSimpleDualPortAttr>()) {
7965  if (ExistingAttr && !ExistingAttr->isImplicit()) {
7966  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute_exact) << &AL;
7967  S.Diag(ExistingAttr->getLoc(), diag::note_previous_attribute);
7968  return;
7969  }
7970  }
7971 
7972  // Check attribute applies to field, constant variables, local variables,
7973  // static variables, agent memory arguments, non-static data members,
7974  // and device_global variables for the device compilation.
7975  if (S.Context.getLangOpts().SYCLIsDevice &&
7976  CheckValidFPGAMemoryAttributesVar(S, D)) {
7977  S.Diag(AL.getLoc(), diag::err_fpga_attribute_incorrect_variable)
7978  << AL << /*agent memory arguments*/ 1;
7979  return;
7980  }
7981 
7982  if (!D->hasAttr<SYCLIntelMemoryAttr>())
7983  D->addAttr(SYCLIntelMemoryAttr::CreateImplicit(
7984  S.Context, SYCLIntelMemoryAttr::Default));
7985 
7986  D->addAttr(::new (S.Context)
7987  SYCLIntelSimpleDualPortAttr(S.Context, AL));
7988 }
7989 
7991  Expr *E) {
7992  if (!E->isValueDependent()) {
7993  // Validate that we have an integer constant expression and then store the
7994  // converted constant expression into the semantic attribute so that we
7995  // don't have to evaluate it again later.
7996  llvm::APSInt ArgVal;
7997  ExprResult Res = VerifyIntegerConstantExpression(E, &ArgVal);
7998  if (Res.isInvalid())
7999  return;
8000  E = Res.get();
8001  // This attribute requires a strictly positive value.
8002  if (ArgVal <= 0) {
8003  Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer)
8004  << CI << /*positive*/ 0;
8005  return;
8006  }
8007 
8008  // Check attribute applies to field, constant variables, local variables,
8009  // static variables, agent memory arguments, non-static data members,
8010  // and device_global variables for the device compilation.
8011  if (Context.getLangOpts().SYCLIsDevice &&
8012  CheckValidFPGAMemoryAttributesVar(*this, D)) {
8013  Diag(CI.getLoc(), diag::err_fpga_attribute_incorrect_variable)
8014  << CI << /*agent memory arguments*/ 1;
8015  return;
8016  }
8017 
8018  // Check to see if there's a duplicate attribute with different values
8019  // already applied to the declaration.
8020  if (const auto *DeclAttr = D->getAttr<SYCLIntelMaxReplicatesAttr>()) {
8021  // If the other attribute argument is instantiation dependent, we won't
8022  // have converted it to a constant expression yet and thus we test
8023  // whether this is a null pointer.
8024  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
8025  if (ArgVal != DeclExpr->getResultAsAPSInt()) {
8026  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << CI;
8027  Diag(DeclAttr->getLoc(), diag::note_previous_attribute);
8028  }
8029  // Drop the duplicate attribute.
8030  return;
8031  }
8032  }
8033  }
8034 
8035  // If the declaration does not have an [[intel::fpga_memory]]
8036  // attribute, this creates one as an implicit attribute.
8037  if (!D->hasAttr<SYCLIntelMemoryAttr>())
8038  D->addAttr(SYCLIntelMemoryAttr::CreateImplicit(
8039  Context, SYCLIntelMemoryAttr::Default));
8040 
8041  D->addAttr(::new (Context) SYCLIntelMaxReplicatesAttr(Context, CI, E));
8042 }
8043 
8044 SYCLIntelMaxReplicatesAttr *
8046  const SYCLIntelMaxReplicatesAttr &A) {
8047  // Check to see if there's a duplicate attribute with different values
8048  // already applied to the declaration.
8049  if (const auto *DeclAttr = D->getAttr<SYCLIntelMaxReplicatesAttr>()) {
8050  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
8051  if (const auto *MergeExpr = dyn_cast<ConstantExpr>(A.getValue())) {
8052  if (DeclExpr->getResultAsAPSInt() != MergeExpr->getResultAsAPSInt()) {
8053  Diag(DeclAttr->getLoc(), diag::warn_duplicate_attribute) << &A;
8054  Diag(A.getLoc(), diag::note_previous_attribute);
8055  }
8056  // Do not add a duplicate attribute.
8057  return nullptr;
8058  }
8059  }
8060  }
8061 
8062  return ::new (Context) SYCLIntelMaxReplicatesAttr(Context, A, A.getValue());
8063 }
8064 
8065 static void handleSYCLIntelMaxReplicatesAttr(Sema &S, Decl *D,
8066  const ParsedAttr &A) {
8068 }
8069 
8070 /// Handle the merge attribute.
8071 /// This requires two string arguments. The first argument is a name, the
8072 /// second is a direction. The direction must be "depth" or "width".
8073 /// This is incompatible with the register attribute.
8074 static void handleSYCLIntelMergeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8075  SmallVector<StringRef, 2> Results;
8076  for (int I = 0; I < 2; I++) {
8077  StringRef Str;
8078  if (!S.checkStringLiteralArgumentAttr(AL, I, Str))
8079  return;
8080 
8081  if (I == 1 && Str != "depth" && Str != "width") {
8082  S.Diag(AL.getLoc(), diag::err_intel_fpga_merge_dir_invalid) << AL;
8083  return;
8084  }
8085  Results.push_back(Str);
8086  }
8087 
8088  // Warn about duplicate attributes if they have different arguments, no
8089  // diagnostic is emitted if the arguments match, and drop any duplicate
8090  // attributes.
8091  if (const auto *Existing = D->getAttr<SYCLIntelMergeAttr>()) {
8092  if (Existing && !(Existing->getName() == Results[0] &&
8093  Existing->getDirection() == Results[1])) {
8094  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
8095  S.Diag(Existing->getLoc(), diag::note_previous_attribute);
8096  }
8097  // If there is no mismatch, drop any duplicate attributes.
8098  return;
8099  }
8100 
8101  // Check attribute applies to field, constant variables, local variables,
8102  // static variables, non-static data members, and device_global variables
8103  // for the device compilation.
8104  if (S.Context.getLangOpts().SYCLIsDevice &&
8105  ((D->getKind() == Decl::ParmVar) ||
8106  CheckValidFPGAMemoryAttributesVar(S, D))) {
8107  S.Diag(AL.getLoc(), diag::err_fpga_attribute_incorrect_variable)
8108  << AL << /*agent memory arguments*/ 0;
8109  return;
8110  }
8111 
8112  if (!D->hasAttr<SYCLIntelMemoryAttr>())
8113  D->addAttr(SYCLIntelMemoryAttr::CreateImplicit(
8114  S.Context, SYCLIntelMemoryAttr::Default));
8115 
8116  D->addAttr(::new (S.Context)
8117  SYCLIntelMergeAttr(S.Context, AL, Results[0], Results[1]));
8118 }
8119 
8120 /// Handle the bank_bits attribute.
8121 /// This attribute accepts a list of values greater than zero.
8122 /// This is incompatible with the register attribute.
8123 /// The numbanks and bank_bits attributes are related. If numbanks exists
8124 /// when handling bank_bits they are checked for consistency. If numbanks
8125 /// hasn't been added yet an implicit one is added with the correct value.
8126 /// If the user later adds a numbanks attribute the implicit one is removed.
8127 /// The values must be consecutive values (i.e. 3,4,5 or 2,1).
8128 static void handleSYCLIntelBankBitsAttr(Sema &S, Decl *D, const ParsedAttr &A) {
8129  checkForDuplicateAttribute<SYCLIntelBankBitsAttr>(S, D, A);
8130 
8131  if (!A.checkAtLeastNumArgs(S, 1))
8132  return;
8133 
8135  for (unsigned I = 0; I < A.getNumArgs(); ++I) {
8136  Args.push_back(A.getArgAsExpr(I));
8137  }
8138 
8139  S.AddSYCLIntelBankBitsAttr(D, A, Args.data(), Args.size());
8140 }
8141 
8143  Expr **Exprs, unsigned Size) {
8144  SYCLIntelBankBitsAttr TmpAttr(Context, CI, Exprs, Size);
8146  SmallVector<int64_t, 8> Values;
8147  bool ListIsValueDep = false;
8148  for (auto *E : TmpAttr.args()) {
8149  llvm::APSInt Value(32, /*IsUnsigned=*/false);
8150  Expr::EvalResult Result;
8151  ListIsValueDep = ListIsValueDep || E->isValueDependent();
8152  if (!E->isValueDependent()) {
8153  ExprResult ICE = VerifyIntegerConstantExpression(E, &Value);
8154  if (ICE.isInvalid())
8155  return;
8156  if (!Value.isNonNegative()) {
8157  Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer)
8158  << CI << /*non-negative*/ 1;
8159  return;
8160  }
8161  E = ICE.get();
8162  }
8163  Args.push_back(E);
8164  Values.push_back(Value.getExtValue());
8165  }
8166 
8167  // Check that the list is consecutive.
8168  if (!ListIsValueDep && Values.size() > 1) {
8169  bool ListIsAscending = Values[0] < Values[1];
8170  for (int I = 0, E = Values.size() - 1; I < E; ++I) {
8171  if (Values[I + 1] != Values[I] + (ListIsAscending ? 1 : -1)) {
8172  Diag(CI.getLoc(), diag::err_bankbits_non_consecutive) << &TmpAttr;
8173  return;
8174  }
8175  }
8176  }
8177 
8178  // Check or add the related numbanks attribute.
8179  if (auto *NBA = D->getAttr<SYCLIntelNumBanksAttr>()) {
8180  Expr *E = NBA->getValue();
8181  if (!E->isValueDependent()) {
8182  Expr::EvalResult Result;
8183  E->EvaluateAsInt(Result, Context);
8184  llvm::APSInt Value = Result.Val.getInt();
8185  if (Args.size() != Value.ceilLogBase2()) {
8186  Diag(TmpAttr.getLoc(), diag::err_bankbits_numbanks_conflicting);
8187  return;
8188  }
8189  }
8190  } else {
8191  llvm::APInt Num(32, (unsigned)(1 << Args.size()));
8192  Expr *NBE =
8193  IntegerLiteral::Create(Context, Num, Context.IntTy, SourceLocation());
8194  D->addAttr(SYCLIntelNumBanksAttr::CreateImplicit(Context, NBE));
8195  }
8196 
8197  // Check attribute applies to field, constant variables, local variables,
8198  // static variables, agent memory arguments, non-static data members,
8199  // and device_global variables for the device compilation.
8200  if (Context.getLangOpts().SYCLIsDevice &&
8201  CheckValidFPGAMemoryAttributesVar(*this, D)) {
8202  Diag(CI.getLoc(), diag::err_fpga_attribute_incorrect_variable)
8203  << CI << /*agent memory arguments*/ 1;
8204  return;
8205  }
8206 
8207  if (!D->hasAttr<SYCLIntelMemoryAttr>())
8208  D->addAttr(SYCLIntelMemoryAttr::CreateImplicit(
8209  Context, SYCLIntelMemoryAttr::Default));
8210 
8211  D->addAttr(::new (Context)
8212  SYCLIntelBankBitsAttr(Context, CI, Args.data(), Args.size()));
8213 }
8214 
8216  Expr *E) {
8217  if (!E->isValueDependent()) {
8218  // Validate that we have an integer constant expression and then store the
8219  // converted constant expression into the semantic attribute so that we
8220  // don't have to evaluate it again later.
8221  llvm::APSInt ArgVal;
8222  ExprResult Res = VerifyIntegerConstantExpression(E, &ArgVal);
8223  if (Res.isInvalid())
8224  return;
8225  E = Res.get();
8226  // This attribute requires a non-negative value.
8227  if (ArgVal < 0) {
8228  Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer)
8229  << CI << /*non-negative*/ 1;
8230  return;
8231  }
8232 
8233  // Check attribute applies to field as well as const variables, non-static
8234  // local variables, non-static data members, and device_global variables.
8235  // for the device compilation.
8236  if (const auto *VD = dyn_cast<VarDecl>(D)) {
8237  if (Context.getLangOpts().SYCLIsDevice &&
8238  (!(isa<FieldDecl>(D) ||
8239  (VD->getKind() != Decl::ImplicitParam &&
8240  VD->getKind() != Decl::NonTypeTemplateParm &&
8241  VD->getKind() != Decl::ParmVar &&
8242  (VD->hasLocalStorage() ||
8243  SYCL().isTypeDecoratedWithDeclAttribute<SYCLDeviceGlobalAttr>(
8244  VD->getType())))))) {
8245  Diag(CI.getLoc(), diag::err_fpga_attribute_invalid_decl) << CI;
8246  return;
8247  }
8248  }
8249 
8250  // Check to see if there's a duplicate attribute with different values
8251  // already applied to the declaration.
8252  if (const auto *DeclAttr = D->getAttr<SYCLIntelPrivateCopiesAttr>()) {
8253  // If the other attribute argument is instantiation dependent, we won't
8254  // have converted it to a constant expression yet and thus we test
8255  // whether this is a null pointer.
8256  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
8257  if (ArgVal != DeclExpr->getResultAsAPSInt()) {
8258  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << CI;
8259  Diag(DeclAttr->getLoc(), diag::note_previous_attribute);
8260  }
8261  // Drop the duplicate attribute.
8262  return;
8263  }
8264  }
8265  }
8266 
8267  // If the declaration does not have [[intel::fpga_memory]]
8268  // attribute, this creates default implicit memory.
8269  if (!D->hasAttr<SYCLIntelMemoryAttr>())
8270  D->addAttr(SYCLIntelMemoryAttr::CreateImplicit(
8271  Context, SYCLIntelMemoryAttr::Default));
8272 
8273  D->addAttr(::new (Context) SYCLIntelPrivateCopiesAttr(Context, CI, E));
8274 }
8275 
8276 static void handleSYCLIntelPrivateCopiesAttr(Sema &S, Decl *D,
8277  const ParsedAttr &A) {
8279 }
8280 
8282  const AttributeCommonInfo &CI,
8283  Expr *E) {
8284  if (!E->isValueDependent()) {
8285  // Validate that we have an integer constant expression and then store the
8286  // converted constant expression into the semantic attribute so that we
8287  // don't have to evaluate it again later.
8288  llvm::APSInt ArgVal;
8289  ExprResult Res = VerifyIntegerConstantExpression(E, &ArgVal);
8290  if (Res.isInvalid())
8291  return;
8292  E = Res.get();
8293 
8294  // This attribute accepts values 0 and 1 only.
8295  if (ArgVal < 0 || ArgVal > 1) {
8296  Diag(E->getBeginLoc(), diag::err_attribute_argument_is_not_valid) << CI;
8297  return;
8298  }
8299 
8300  // Check attribute applies to field, constant variables, local variables,
8301  // static variables, agent memory arguments, non-static data members,
8302  // and device_global variables for the device compilation.
8303  if (Context.getLangOpts().SYCLIsDevice &&
8304  CheckValidFPGAMemoryAttributesVar(*this, D)) {
8305  Diag(CI.getLoc(), diag::err_fpga_attribute_incorrect_variable)
8306  << CI << /*agent memory arguments*/ 1;
8307  return;
8308  }
8309 
8310  // Check to see if there's a duplicate attribute with different values
8311  // already applied to the declaration.
8312  if (const auto *DeclAttr = D->getAttr<SYCLIntelForcePow2DepthAttr>()) {
8313  // If the other attribute argument is instantiation dependent, we won't
8314  // have converted it to a constant expression yet and thus we test
8315  // whether this is a null pointer.
8316  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
8317  if (ArgVal != DeclExpr->getResultAsAPSInt()) {
8318  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << CI;
8319  Diag(DeclAttr->getLoc(), diag::note_previous_attribute);
8320  }
8321  // If there is no mismatch, drop any duplicate attributes.
8322  return;
8323  }
8324  }
8325  }
8326 
8327  // If the declaration does not have an [[intel::fpga_memory]]
8328  // attribute, this creates one as an implicit attribute.
8329  if (!D->hasAttr<SYCLIntelMemoryAttr>())
8330  D->addAttr(SYCLIntelMemoryAttr::CreateImplicit(
8331  Context, SYCLIntelMemoryAttr::Default));
8332 
8333  D->addAttr(::new (Context) SYCLIntelForcePow2DepthAttr(Context, CI, E));
8334 }
8335 
8336 SYCLIntelForcePow2DepthAttr *
8338  const SYCLIntelForcePow2DepthAttr &A) {
8339  // Check to see if there's a duplicate attribute with different values
8340  // already applied to the declaration.
8341  if (const auto *DeclAttr = D->getAttr<SYCLIntelForcePow2DepthAttr>()) {
8342  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getValue())) {
8343  if (const auto *MergeExpr = dyn_cast<ConstantExpr>(A.getValue())) {
8344  if (DeclExpr->getResultAsAPSInt() != MergeExpr->getResultAsAPSInt()) {
8345  Diag(DeclAttr->getLoc(), diag::warn_duplicate_attribute) << &A;
8346  Diag(A.getLoc(), diag::note_previous_attribute);
8347  }
8348  // If there is no mismatch, drop any duplicate attributes.
8349  return nullptr;
8350  }
8351  }
8352  }
8353 
8354  return ::new (Context) SYCLIntelForcePow2DepthAttr(Context, A, A.getValue());
8355 }
8356 
8357 static void handleSYCLIntelForcePow2DepthAttr(Sema &S, Decl *D,
8358  const ParsedAttr &A) {
8360 }
8361 
8362 static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8363  ParamIdx ArgCount;
8364 
8365  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0),
8366  ArgCount,
8367  true /* CanIndexImplicitThis */))
8368  return;
8369 
8370  // ArgCount isn't a parameter index [0;n), it's a count [1;n]
8371  D->addAttr(::new (S.Context)
8372  XRayLogArgsAttr(S.Context, AL, ArgCount.getSourceIndex()));
8373 }
8374 
8375 static void handlePatchableFunctionEntryAttr(Sema &S, Decl *D,
8376  const ParsedAttr &AL) {
8377  uint32_t Count = 0, Offset = 0;
8378  if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Count, 0, true))
8379  return;
8380  if (AL.getNumArgs() == 2) {
8381  Expr *Arg = AL.getArgAsExpr(1);
8382  if (!checkUInt32Argument(S, AL, Arg, Offset, 1, true))
8383  return;
8384  if (Count < Offset) {
8385  S.Diag(getAttrLoc(AL), diag::err_attribute_argument_out_of_range)
8386  << &AL << 0 << Count << Arg->getBeginLoc();
8387  return;
8388  }
8389  }
8390  D->addAttr(::new (S.Context)
8391  PatchableFunctionEntryAttr(S.Context, AL, Count, Offset));
8392 }
8393 
8395  Expr *E) {
8396  VarDecl *VD = cast<VarDecl>(D);
8397  QualType Ty = VD->getType();
8398  // TODO: Applicable only on pipe storages. Currently they are defined
8399  // as structures inside of SYCL headers. Add a check for pipe_storage_t
8400  // when it is ready.
8401  if (!Ty->isStructureType()) {
8402  Diag(CI.getLoc(), diag::err_attribute_wrong_decl_type_str)
8403  << CI << CI.isRegularKeywordAttribute()
8404  << "SYCL pipe storage declaration";
8405  return;
8406  }
8407 
8408  if (!E->isValueDependent()) {
8409  // Validate that we have an integer constant expression and then store the
8410  // converted constant expression into the semantic attribute so that we
8411  // don't have to evaluate it again later.
8412  llvm::APSInt ArgVal;
8413  ExprResult Res = VerifyIntegerConstantExpression(E, &ArgVal);
8414  if (Res.isInvalid())
8415  return;
8416  E = Res.get();
8417 
8418  // This attribute requires a non-negative value.
8419  if (ArgVal < 0) {
8420  Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer)
8421  << CI << /*non-negative*/ 1;
8422  return;
8423  }
8424 
8425  // Check to see if there's a duplicate attribute with different values
8426  // already applied to the declaration.
8427  if (const auto *DeclAttr = D->getAttr<SYCLIntelPipeIOAttr>()) {
8428  // If the other attribute argument is instantiation dependent, we won't
8429  // have converted it to a constant expression yet and thus we test
8430  // whether this is a null pointer.
8431  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getID())) {
8432  if (ArgVal != DeclExpr->getResultAsAPSInt()) {
8433  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << CI;
8434  Diag(DeclAttr->getLoc(), diag::note_previous_attribute);
8435  }
8436  // Drop the duplicate attribute.
8437  return;
8438  }
8439  }
8440  }
8441 
8442  D->addAttr(::new (Context) SYCLIntelPipeIOAttr(Context, CI, E));
8443 }
8444 
8445 SYCLIntelPipeIOAttr *
8446 Sema::MergeSYCLIntelPipeIOAttr(Decl *D, const SYCLIntelPipeIOAttr &A) {
8447  // Check to see if there's a duplicate attribute with different values
8448  // already applied to the declaration.
8449  if (const auto *DeclAttr = D->getAttr<SYCLIntelPipeIOAttr>()) {
8450  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getID())) {
8451  if (const auto *MergeExpr = dyn_cast<ConstantExpr>(A.getID())) {
8452  if (DeclExpr->getResultAsAPSInt() != MergeExpr->getResultAsAPSInt()) {
8453  Diag(DeclAttr->getLoc(), diag::err_disallowed_duplicate_attribute)
8454  << &A;
8455  Diag(A.getLoc(), diag::note_conflicting_attribute);
8456  }
8457  // Do not add a duplicate attribute.
8458  return nullptr;
8459  }
8460  }
8461  }
8462 
8463  return ::new (Context) SYCLIntelPipeIOAttr(Context, A, A.getID());
8464 }
8465 
8466 static void handleSYCLIntelPipeIOAttr(Sema &S, Decl *D, const ParsedAttr &A) {
8467  Expr *E = A.getArgAsExpr(0);
8468  S.addSYCLIntelPipeIOAttr(D, A, E);
8469 }
8470 
8471 SYCLIntelMaxConcurrencyAttr *Sema::MergeSYCLIntelMaxConcurrencyAttr(
8472  Decl *D, const SYCLIntelMaxConcurrencyAttr &A) {
8473  // Check to see if there's a duplicate attribute with different values
8474  // already applied to the declaration.
8475  if (const auto *DeclAttr = D->getAttr<SYCLIntelMaxConcurrencyAttr>()) {
8476  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getNExpr())) {
8477  if (const auto *MergeExpr = dyn_cast<ConstantExpr>(A.getNExpr())) {
8478  if (DeclExpr->getResultAsAPSInt() != MergeExpr->getResultAsAPSInt()) {
8479  Diag(DeclAttr->getLoc(), diag::warn_duplicate_attribute) << &A;
8480  Diag(A.getLoc(), diag::note_previous_attribute);
8481  }
8482  // Do not add a duplicate attribute.
8483  return nullptr;
8484  }
8485  }
8486  }
8487 
8488  return ::new (Context) SYCLIntelMaxConcurrencyAttr(Context, A, A.getNExpr());
8489 }
8490 
8492  const AttributeCommonInfo &CI,
8493  Expr *E) {
8494  if (!E->isValueDependent()) {
8495  llvm::APSInt ArgVal;
8496  ExprResult Res = VerifyIntegerConstantExpression(E, &ArgVal);
8497  if (Res.isInvalid())
8498  return;
8499  E = Res.get();
8500 
8501  // This attribute requires a non-negative value.
8502  if (ArgVal < 0) {
8503  Diag(E->getExprLoc(), diag::err_attribute_requires_positive_integer)
8504  << CI << /*non-negative*/ 1;
8505  return;
8506  }
8507 
8508  // Check to see if there's a duplicate attribute with different values
8509  // already applied to the declaration.
8510  if (const auto *DeclAttr = D->getAttr<SYCLIntelMaxConcurrencyAttr>()) {
8511  // If the other attribute argument is instantiation dependent, we won't
8512  // have converted it to a constant expression yet and thus we test
8513  // whether this is a null pointer.
8514  if (const auto *DeclExpr = dyn_cast<ConstantExpr>(DeclAttr->getNExpr())) {
8515  if (ArgVal != DeclExpr->getResultAsAPSInt()) {
8516  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << CI;
8517  Diag(DeclAttr->getLoc(), diag::note_previous_attribute);
8518  }
8519  // Drop the duplicate attribute.
8520  return;
8521  }
8522  }
8523  }
8524 
8525  D->addAttr(::new (Context) SYCLIntelMaxConcurrencyAttr(Context, CI, E));
8526 }
8527 
8528 static void handleSYCLIntelMaxConcurrencyAttr(Sema &S, Decl *D,
8529  const ParsedAttr &A) {
8530  Expr *E = A.getArgAsExpr(0);
8531  S.AddSYCLIntelMaxConcurrencyAttr(D, A, E);
8532 }
8533 
8534 // Checks if an expression is a valid filter list for an add_ir_attributes_*
8535 // attribute. Returns true if an error occured.
8536 static bool checkAddIRAttributesFilterListExpr(Expr *FilterListArg, Sema &S,
8537  const AttributeCommonInfo &CI) {
8538  const auto *FilterListE = cast<InitListExpr>(FilterListArg);
8539  for (const Expr *FilterElemE : FilterListE->inits())
8540  if (!isa<StringLiteral>(FilterElemE))
8541  return S.Diag(FilterElemE->getBeginLoc(),
8542  diag::err_sycl_add_ir_attribute_invalid_filter)
8543  << CI;
8544  return false;
8545 }
8546 
8547 // Returns true if a type is either an array of char or a pointer to char.
8548 static bool isAddIRAttributesValidStringType(QualType T) {
8549  if (!T->isArrayType() && !T->isPointerType())
8550  return false;
8551  QualType ElemT = T->isArrayType()
8552  ? cast<ArrayType>(T.getTypePtr())->getElementType()
8553  : T->getPointeeType();
8554  return ElemT.isConstQualified() && ElemT->isCharType();
8555 }
8556 
8557 // Checks if an expression is a valid attribute name for an add_ir_attributes_*
8558 // attribute. Returns true if an error occured.
8559 static bool checkAddIRAttributesNameExpr(Expr *NameArg, Sema &S,
8560  const AttributeCommonInfo &CI) {
8561  // Only strings and const char * are valid name arguments.
8562  if (isAddIRAttributesValidStringType(NameArg->getType()))
8563  return false;
8564 
8565  return S.Diag(NameArg->getBeginLoc(),
8566  diag::err_sycl_add_ir_attribute_invalid_name)
8567  << CI;
8568 }
8569 
8570 // Checks if an expression is a valid attribute value for an add_ir_attributes_*
8571 // attribute. Returns true if an error occured.
8572 static bool checkAddIRAttributesValueExpr(Expr *ValArg, Sema &S,
8573  const AttributeCommonInfo &CI) {
8574  QualType ValType = ValArg->getType();
8575  if (isAddIRAttributesValidStringType(ValType) || ValType->isNullPtrType() ||
8576  ValType->isIntegralOrEnumerationType() || ValType->isFloatingType())
8577  return false;
8578 
8579  return S.Diag(ValArg->getBeginLoc(),
8580  diag::err_sycl_add_ir_attribute_invalid_value)
8581  << CI;
8582 }
8583 
8584 // Checks and evaluates arguments of an add_ir_attributes_* attribute. Returns
8585 // true if an error occured.
8586 static bool evaluateAddIRAttributesArgs(Expr **Args, size_t ArgsSize, Sema &S,
8587  const AttributeCommonInfo &CI) {
8588  ASTContext &Context = S.getASTContext();
8589 
8590  // Check filter list if it is the first argument.
8591  bool HasFilter = ArgsSize && isa<InitListExpr>(Args[0]);
8592  if (HasFilter && checkAddIRAttributesFilterListExpr(Args[0], S, CI))
8593  return true;
8594 
8596  bool HasDependentArg = false;
8597  for (unsigned I = HasFilter; I < ArgsSize; I++) {
8598  Expr *&E = Args[I];
8599 
8600  if (isa<InitListExpr>(E))
8601  return S.Diag(E->getBeginLoc(),
8602  diag::err_sycl_add_ir_attr_filter_list_invalid_arg)
8603  << CI;
8604 
8605  if (E->isValueDependent() || E->isTypeDependent()) {
8606  HasDependentArg = true;
8607  continue;
8608  }
8609 
8610  Expr::EvalResult Eval;
8611  Eval.Diag = &Notes;
8612  if (!E->EvaluateAsConstantExpr(Eval, Context) || !Notes.empty()) {
8613  S.Diag(E->getBeginLoc(), diag::err_attribute_argument_n_type)
8614  << CI << (I + 1) << AANT_ArgumentConstantExpr;
8615  for (auto &Note : Notes)
8616  S.Diag(Note.first, Note.second);
8617  return true;
8618  }
8619  assert(Eval.Val.hasValue());
8620  E = ConstantExpr::Create(Context, E, Eval.Val);
8621  }
8622 
8623  // If there are no dependent expressions, check for expected number of args.
8624  if (!HasDependentArg && ArgsSize && (ArgsSize - HasFilter) & 1)
8625  return S.Diag(CI.getLoc(), diag::err_sycl_add_ir_attribute_must_have_pairs)
8626  << CI;
8627 
8628  // If there are no dependent expressions, check argument types.
8629  // First half of the arguments are names, the second half are values.
8630  unsigned MidArg = (ArgsSize - HasFilter) / 2 + HasFilter;
8631  if (!HasDependentArg) {
8632  for (unsigned I = HasFilter; I < ArgsSize; ++I) {
8633  if ((I < MidArg && checkAddIRAttributesNameExpr(Args[I], S, CI)) ||
8634  (I >= MidArg && checkAddIRAttributesValueExpr(Args[I], S, CI)))
8635  return true;
8636  }
8637  }
8638  return false;
8639 }
8640 
8641 static bool hasDependentExpr(Expr **Exprs, const size_t ExprsSize) {
8642  return std::any_of(Exprs, Exprs + ExprsSize, [](const Expr *E) {
8643  return E->isValueDependent() || E->isTypeDependent();
8644  });
8645 }
8646 
8647 static bool hasSameSYCLAddIRAttributes(
8648  const SmallVector<std::pair<std::string, std::string>, 4> &LAttrs,
8649  const SmallVector<std::pair<std::string, std::string>, 4> &RAttrs) {
8650  std::set<std::pair<std::string, std::string>> LNameValSet{LAttrs.begin(),
8651  LAttrs.end()};
8652  std::set<std::pair<std::string, std::string>> RNameValSet{RAttrs.begin(),
8653  RAttrs.end()};
8654  return LNameValSet == RNameValSet;
8655 }
8656 
8657 template <typename AddIRAttrT>
8658 static bool checkSYCLAddIRAttributesMergeability(const AddIRAttrT &NewAttr,
8659  const AddIRAttrT &ExistingAttr,
8660  Sema &S) {
8661  ASTContext &Context = S.getASTContext();
8662  // If there are no dependent argument expressions and the filters or the
8663  // attributes are different, then fail due to differing duplicates.
8664  if (!hasDependentExpr(NewAttr.args_begin(), NewAttr.args_size()) &&
8665  !hasDependentExpr(ExistingAttr.args_begin(), ExistingAttr.args_size()) &&
8666  (NewAttr.getAttributeFilter() != ExistingAttr.getAttributeFilter() ||
8667  !hasSameSYCLAddIRAttributes(
8668  NewAttr.getAttributeNameValuePairs(Context),
8669  ExistingAttr.getAttributeNameValuePairs(Context)))) {
8670  S.Diag(ExistingAttr.getLoc(), diag::err_duplicate_attribute) << &NewAttr;
8671  S.Diag(NewAttr.getLoc(), diag::note_conflicting_attribute);
8672  return true;
8673  }
8674  return false;
8675 }
8676 
8678  const auto *AddIRFuncAttr = D->getAttr<SYCLAddIRAttributesFunctionAttr>();
8679 
8680  // If there is no such attribute there is nothing to check. If there are
8681  // dependent arguments we cannot know the actual number of arguments so we
8682  // defer the check.
8683  if (!AddIRFuncAttr ||
8684  hasDependentExpr(AddIRFuncAttr->args_begin(), AddIRFuncAttr->args_size()))
8685  return;
8686 
8687  // If there are no name-value pairs in the attribute it will not have an
8688  // effect and we can skip the check. The filter is ignored.
8689  size_t NumArgsWithoutFilter =
8690  AddIRFuncAttr->args_size() - (AddIRFuncAttr->hasFilterList() ? 1 : 0);
8691  if (NumArgsWithoutFilter == 0)
8692  return;
8693 
8694  // "sycl-single-task" is present on all single_task invocations, implicitly
8695  // added by the SYCL headers. It can only conflict with max_global_work_dim,
8696  // but the value will be the same so there is no need for a warning.
8697  if (NumArgsWithoutFilter == 2) {
8698  auto NameValuePairs = AddIRFuncAttr->getAttributeNameValuePairs(Context);
8699  if (NameValuePairs.size() > 0 &&
8700  NameValuePairs[0].first == "sycl-single-task")
8701  return;
8702  }
8703 
8704  // If there are potentially conflicting attributes, we issue a warning.
8705  for (const auto *Attr : std::vector<AttributeCommonInfo *>{
8706  D->getAttr<SYCLReqdWorkGroupSizeAttr>(),
8707  D->getAttr<IntelReqdSubGroupSizeAttr>(),
8708  D->getAttr<SYCLWorkGroupSizeHintAttr>(),
8709  D->getAttr<SYCLDeviceHasAttr>()})
8710  if (Attr)
8711  Diag(Attr->getLoc(), diag::warn_sycl_old_and_new_kernel_attributes)
8712  << Attr;
8713 }
8714 
8715 SYCLAddIRAttributesFunctionAttr *Sema::MergeSYCLAddIRAttributesFunctionAttr(
8716  Decl *D, const SYCLAddIRAttributesFunctionAttr &A) {
8717  if (const auto *ExistingAttr =
8718  D->getAttr<SYCLAddIRAttributesFunctionAttr>()) {
8719  checkSYCLAddIRAttributesMergeability(A, *ExistingAttr, *this);
8720  return nullptr;
8721  }
8722  return A.clone(Context);
8723 }
8724 
8726  const AttributeCommonInfo &CI,
8727  MutableArrayRef<Expr *> Args) {
8728  if (const auto *FuncD = dyn_cast<FunctionDecl>(D)) {
8729  if (FuncD->isDefaulted()) {
8730  Diag(CI.getLoc(), diag::err_disallow_attribute_on_func) << CI << 0;
8731  return;
8732  }
8733  if (FuncD->isDeleted()) {
8734  Diag(CI.getLoc(), diag::err_disallow_attribute_on_func) << CI << 1;
8735  return;
8736  }
8737  }
8738 
8739  auto *Attr = SYCLAddIRAttributesFunctionAttr::Create(Context, Args.data(),
8740  Args.size(), CI);
8741  if (evaluateAddIRAttributesArgs(Attr->args_begin(), Attr->args_size(), *this,
8742  CI))
8743  return;
8744  D->addAttr(Attr);
8745 
8746  // There are compile-time SYCL properties which we would like to turn into
8747  // attributes to enable compiler diagnostics.
8748  // At the moment the only such property is related to virtual functions and
8749  // it is turned into sycl_device attribute. This is a tiny optimization to
8750  // avoid deep dive into the attribute if we already know that a declaration
8751  // is a device declaration. It may have to be removed later if/when we add
8752  // handling of more compile-time properties here.
8753  if (D->hasAttr<SYCLDeviceAttr>())
8754  return;
8755 
8756  // SYCL Headers use template magic to pass key=value pairs to the attribute
8757  // and we should make sure that all template instantiations are done before
8758  // accessing attribute arguments.
8759  if (hasDependentExpr(Attr->args_begin(), Attr->args_size()))
8760  return;
8761 
8763  Attr->getFilteredAttributeNameValuePairs(Context);
8764 
8765  for (const auto &[Key, Value] : Pairs) {
8766  if (Key == "indirectly-callable") {
8767  D->addAttr(SYCLDeviceAttr::CreateImplicit(Context));
8768  break;
8769  }
8770  }
8771 }
8772 
8773 static void handleSYCLAddIRAttributesFunctionAttr(Sema &S, Decl *D,
8774  const ParsedAttr &A) {
8776  Args.reserve(A.getNumArgs() - 1);
8777  for (unsigned I = 0; I < A.getNumArgs(); I++) {
8778  assert(A.isArgExpr(I));
8779  Args.push_back(A.getArgAsExpr(I));
8780  }
8781 
8782  S.AddSYCLAddIRAttributesFunctionAttr(D, A, Args);
8783 }
8784 
8785 SYCLAddIRAttributesKernelParameterAttr *
8787  Decl *D, const SYCLAddIRAttributesKernelParameterAttr &A) {
8788  if (const auto *ExistingAttr =
8789  D->getAttr<SYCLAddIRAttributesKernelParameterAttr>()) {
8790  checkSYCLAddIRAttributesMergeability(A, *ExistingAttr, *this);
8791  return nullptr;
8792  }
8793  return A.clone(Context);
8794 }
8795 
8797  Decl *D, const AttributeCommonInfo &CI, MutableArrayRef<Expr *> Args) {
8798  auto *Attr = SYCLAddIRAttributesKernelParameterAttr::Create(
8799  Context, Args.data(), Args.size(), CI);
8800  if (evaluateAddIRAttributesArgs(Attr->args_begin(), Attr->args_size(), *this,
8801  CI))
8802  return;
8803  D->addAttr(Attr);
8804 }
8805 
8806 static void handleSYCLAddIRAttributesKernelParameterAttr(Sema &S, Decl *D,
8807  const ParsedAttr &A) {
8809  Args.reserve(A.getNumArgs() - 1);
8810  for (unsigned I = 0; I < A.getNumArgs(); I++) {
8811  assert(A.getArgAsExpr(I));
8812  Args.push_back(A.getArgAsExpr(I));
8813  }
8814 
8816 }
8817 
8818 SYCLAddIRAttributesGlobalVariableAttr *
8820  Decl *D, const SYCLAddIRAttributesGlobalVariableAttr &A) {
8821  if (const auto *ExistingAttr =
8822  D->getAttr<SYCLAddIRAttributesGlobalVariableAttr>()) {
8823  checkSYCLAddIRAttributesMergeability(A, *ExistingAttr, *this);
8824  return nullptr;
8825  }
8826  return A.clone(Context);
8827 }
8828 
8830  Decl *D, const AttributeCommonInfo &CI, MutableArrayRef<Expr *> Args) {
8831  auto *Attr = SYCLAddIRAttributesGlobalVariableAttr::Create(
8832  Context, Args.data(), Args.size(), CI);
8833  if (evaluateAddIRAttributesArgs(Attr->args_begin(), Attr->args_size(), *this,
8834  CI))
8835  return;
8836  D->addAttr(Attr);
8837 }
8838 
8839 static void handleSYCLAddIRAttributesGlobalVariableAttr(Sema &S, Decl *D,
8840  const ParsedAttr &A) {
8842  Args.reserve(A.getNumArgs() - 1);
8843  for (unsigned I = 0; I < A.getNumArgs(); I++) {
8844  assert(A.getArgAsExpr(I));
8845  Args.push_back(A.getArgAsExpr(I));
8846  }
8847 
8849 }
8850 
8851 SYCLAddIRAnnotationsMemberAttr *Sema::MergeSYCLAddIRAnnotationsMemberAttr(
8852  Decl *D, const SYCLAddIRAnnotationsMemberAttr &A) {
8853  if (const auto *ExistingAttr = D->getAttr<SYCLAddIRAnnotationsMemberAttr>()) {
8854  checkSYCLAddIRAttributesMergeability(A, *ExistingAttr, *this);
8855  return nullptr;
8856  }
8857  return A.clone(Context);
8858 }
8859 
8861  const AttributeCommonInfo &CI,
8862  MutableArrayRef<Expr *> Args) {
8863  auto *Attr = SYCLAddIRAnnotationsMemberAttr::Create(Context, Args.data(),
8864  Args.size(), CI);
8865  if (evaluateAddIRAttributesArgs(Attr->args_begin(), Attr->args_size(), *this,
8866  CI))
8867  return;
8868  D->addAttr(Attr);
8869 }
8870 
8871 static void handleSYCLAddIRAnnotationsMemberAttr(Sema &S, Decl *D,
8872  const ParsedAttr &A) {
8874  Args.reserve(A.getNumArgs());
8875  for (unsigned I = 0; I < A.getNumArgs(); I++) {
8876  assert(A.getArgAsExpr(I));
8877  Args.push_back(A.getArgAsExpr(I));
8878  }
8879 
8880  S.AddSYCLAddIRAnnotationsMemberAttr(D, A, Args);
8881 }
8882 
8883 namespace {
8884 struct IntrinToName {
8885  uint32_t Id;
8886  int32_t FullName;
8887  int32_t ShortName;
8888 };
8889 } // unnamed namespace
8890 
8891 static bool ArmBuiltinAliasValid(unsigned BuiltinID, StringRef AliasName,
8893  const char *IntrinNames) {
8894  AliasName.consume_front("__arm_");
8895  const IntrinToName *It =
8896  llvm::lower_bound(Map, BuiltinID, [](const IntrinToName &L, unsigned Id) {
8897  return L.Id < Id;
8898  });
8899  if (It == Map.end() || It->Id != BuiltinID)
8900  return false;
8901  StringRef FullName(&IntrinNames[It->FullName]);
8902  if (AliasName == FullName)
8903  return true;
8904  if (It->ShortName == -1)
8905  return false;
8906  StringRef ShortName(&IntrinNames[It->ShortName]);
8907  return AliasName == ShortName;
8908 }
8909 
8910 static bool ArmMveAliasValid(unsigned BuiltinID, StringRef AliasName) {
8911 #include "clang/Basic/arm_mve_builtin_aliases.inc"
8912  // The included file defines:
8913  // - ArrayRef<IntrinToName> Map
8914  // - const char IntrinNames[]
8915  return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
8916 }
8917 
8918 static bool ArmCdeAliasValid(unsigned BuiltinID, StringRef AliasName) {
8919 #include "clang/Basic/arm_cde_builtin_aliases.inc"
8920  return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames);
8921 }
8922 
8923 static bool ArmSveAliasValid(ASTContext &Context, unsigned BuiltinID,
8924  StringRef AliasName) {
8925  if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
8926  BuiltinID = Context.BuiltinInfo.getAuxBuiltinID(BuiltinID);
8927  return BuiltinID >= AArch64::FirstSVEBuiltin &&
8928  BuiltinID <= AArch64::LastSVEBuiltin;
8929 }
8930 
8931 static bool ArmSmeAliasValid(ASTContext &Context, unsigned BuiltinID,
8932  StringRef AliasName) {
8933  if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
8934  BuiltinID = Context.BuiltinInfo.getAuxBuiltinID(BuiltinID);
8935  return BuiltinID >= AArch64::FirstSMEBuiltin &&
8936  BuiltinID <= AArch64::LastSMEBuiltin;
8937 }
8938 
8939 static void handleArmBuiltinAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
8940  if (!AL.isArgIdent(0)) {
8941  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
8942  << AL << 1 << AANT_ArgumentIdentifier;
8943  return;
8944  }
8945 
8946  IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident;
8947  unsigned BuiltinID = Ident->getBuiltinID();
8948  StringRef AliasName = cast<FunctionDecl>(D)->getIdentifier()->getName();
8949 
8950  bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
8951  if ((IsAArch64 && !ArmSveAliasValid(S.Context, BuiltinID, AliasName) &&
8952  !ArmSmeAliasValid(S.Context, BuiltinID, AliasName)) ||
8953  (!IsAArch64 && !ArmMveAliasValid(BuiltinID, AliasName) &&
8954  !ArmCdeAliasValid(BuiltinID, AliasName))) {
8955  S.Diag(AL.getLoc(), diag::err_attribute_arm_builtin_alias);
8956  return;
8957  }
8958 
8959  D->addAttr(::new (S.Context) ArmBuiltinAliasAttr(S.Context, AL, Ident));
8960 }
8961 
8962 static bool RISCVAliasValid(unsigned BuiltinID, StringRef AliasName) {
8963  return BuiltinID >= RISCV::FirstRVVBuiltin &&
8964  BuiltinID <= RISCV::LastRVVBuiltin;
8965 }
8966 
8967 static bool SYCLAliasValid(ASTContext &Context, unsigned BuiltinID) {
8968  constexpr llvm::StringLiteral Prefix = "__builtin_intel_sycl";
8969  return Context.BuiltinInfo.getName(BuiltinID).starts_with(Prefix);
8970 }
8971 
8972 static void handleBuiltinAliasAttr(Sema &S, Decl *D,
8973  const ParsedAttr &AL) {
8974  if (!AL.isArgIdent(0)) {
8975  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
8976  << AL << 1 << AANT_ArgumentIdentifier;
8977  return;
8978  }
8979 
8980  IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident;
8981  unsigned BuiltinID = Ident->getBuiltinID();
8982  StringRef AliasName = cast<FunctionDecl>(D)->getIdentifier()->getName();
8983 
8984  bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
8985  bool IsARM = S.Context.getTargetInfo().getTriple().isARM();
8986  bool IsRISCV = S.Context.getTargetInfo().getTriple().isRISCV();
8987  bool IsHLSL = S.Context.getLangOpts().HLSL;
8988  bool IsSYCL = S.Context.getLangOpts().isSYCL();
8989  if ((IsAArch64 && !ArmSveAliasValid(S.Context, BuiltinID, AliasName)) ||
8990  (IsARM && !ArmMveAliasValid(BuiltinID, AliasName) &&
8991  !ArmCdeAliasValid(BuiltinID, AliasName)) ||
8992  (IsRISCV && !RISCVAliasValid(BuiltinID, AliasName)) ||
8993  (IsSYCL && !SYCLAliasValid(S.Context, BuiltinID)) ||
8994  (!IsAArch64 && !IsARM && !IsRISCV && !IsHLSL && !IsSYCL)) {
8995  S.Diag(AL.getLoc(), diag::err_attribute_builtin_alias) << AL;
8996  return;
8997  }
8998 
8999  D->addAttr(::new (S.Context) BuiltinAliasAttr(S.Context, AL, Ident));
9000 }
9001 
9002 static void handleNullableTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
9003  if (AL.isUsedAsTypeAttr())
9004  return;
9005 
9006  if (auto *CRD = dyn_cast<CXXRecordDecl>(D);
9007  !CRD || !(CRD->isClass() || CRD->isStruct())) {
9008  S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type_str)
9009  << AL << AL.isRegularKeywordAttribute() << "classes";
9010  return;
9011  }
9012 
9013  handleSimpleAttribute<TypeNullableAttr>(S, D, AL);
9014 }
9015 
9016 static void handlePreferredTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
9017  if (!AL.hasParsedType()) {
9018  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
9019  return;
9020  }
9021 
9022  TypeSourceInfo *ParmTSI = nullptr;
9023  QualType QT = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
9024  assert(ParmTSI && "no type source info for attribute argument");
9025  S.RequireCompleteType(ParmTSI->getTypeLoc().getBeginLoc(), QT,
9026  diag::err_incomplete_type);
9027 
9028  D->addAttr(::new (S.Context) PreferredTypeAttr(S.Context, AL, ParmTSI));
9029 }
9030 
9031 //===----------------------------------------------------------------------===//
9032 // Checker-specific attribute handlers.
9033 //===----------------------------------------------------------------------===//
9034 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) {
9035  return QT->isDependentType() || QT->isObjCRetainableType();
9036 }
9037 
9038 static bool isValidSubjectOfNSAttribute(QualType QT) {
9039  return QT->isDependentType() || QT->isObjCObjectPointerType() ||
9040  QT->isObjCNSObjectType();
9041 }
9042 
9043 static bool isValidSubjectOfCFAttribute(QualType QT) {
9044  return QT->isDependentType() || QT->isPointerType() ||
9045  isValidSubjectOfNSAttribute(QT);
9046 }
9047 
9048 static bool isValidSubjectOfOSAttribute(QualType QT) {
9049  if (QT->isDependentType())
9050  return true;
9051  QualType PT = QT->getPointeeType();
9052  return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr;
9053 }
9054 
9056  RetainOwnershipKind K,
9057  bool IsTemplateInstantiation) {
9058  ValueDecl *VD = cast<ValueDecl>(D);
9059  switch (K) {
9061  handleSimpleAttributeOrDiagnose<OSConsumedAttr>(
9062  *this, VD, CI, isValidSubjectOfOSAttribute(VD->getType()),
9063  diag::warn_ns_attribute_wrong_parameter_type,
9064  /*ExtraArgs=*/CI.getRange(), "os_consumed", /*pointers*/ 1);
9065  return;
9066  case RetainOwnershipKind::NS:
9067  handleSimpleAttributeOrDiagnose<NSConsumedAttr>(
9068  *this, VD, CI, isValidSubjectOfNSAttribute(VD->getType()),
9069 
9070  // These attributes are normally just advisory, but in ARC, ns_consumed
9071  // is significant. Allow non-dependent code to contain inappropriate
9072  // attributes even in ARC, but require template instantiations to be
9073  // set up correctly.
9074  ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount)
9075  ? diag::err_ns_attribute_wrong_parameter_type
9076  : diag::warn_ns_attribute_wrong_parameter_type),
9077  /*ExtraArgs=*/CI.getRange(), "ns_consumed", /*objc pointers*/ 0);
9078  return;
9079  case RetainOwnershipKind::CF:
9080  handleSimpleAttributeOrDiagnose<CFConsumedAttr>(
9081  *this, VD, CI, isValidSubjectOfCFAttribute(VD->getType()),
9082  diag::warn_ns_attribute_wrong_parameter_type,
9083  /*ExtraArgs=*/CI.getRange(), "cf_consumed", /*pointers*/ 1);
9084  return;
9085  }
9086 }
9087 
9089 parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) {
9090  switch (AL.getKind()) {
9091  case ParsedAttr::AT_CFConsumed:
9092  case ParsedAttr::AT_CFReturnsRetained:
9093  case ParsedAttr::AT_CFReturnsNotRetained:
9095  case ParsedAttr::AT_OSConsumesThis:
9096  case ParsedAttr::AT_OSConsumed:
9097  case ParsedAttr::AT_OSReturnsRetained:
9098  case ParsedAttr::AT_OSReturnsNotRetained:
9099  case ParsedAttr::AT_OSReturnsRetainedOnZero:
9100  case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
9102  case ParsedAttr::AT_NSConsumesSelf:
9103  case ParsedAttr::AT_NSConsumed:
9104  case ParsedAttr::AT_NSReturnsRetained:
9105  case ParsedAttr::AT_NSReturnsNotRetained:
9106  case ParsedAttr::AT_NSReturnsAutoreleased:
9108  default:
9109  llvm_unreachable("Wrong argument supplied");
9110  }
9111 }
9112 
9114  if (isValidSubjectOfNSReturnsRetainedAttribute(QT))
9115  return false;
9116 
9117  Diag(Loc, diag::warn_ns_attribute_wrong_return_type)
9118  << "'ns_returns_retained'" << 0 << 0;
9119  return true;
9120 }
9121 
9122 /// \return whether the parameter is a pointer to OSObject pointer.
9123 static bool isValidOSObjectOutParameter(const Decl *D) {
9124  const auto *PVD = dyn_cast<ParmVarDecl>(D);
9125  if (!PVD)
9126  return false;
9127  QualType QT = PVD->getType();
9128  QualType PT = QT->getPointeeType();
9129  return !PT.isNull() && isValidSubjectOfOSAttribute(PT);
9130 }
9131 
9132 static void handleXReturnsXRetainedAttr(Sema &S, Decl *D,
9133  const ParsedAttr &AL) {
9134  QualType ReturnType;
9135  Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL);
9136 
9137  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
9138  ReturnType = MD->getReturnType();
9139  } else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
9140  (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) {
9141  return; // ignore: was handled as a type attribute
9142  } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
9143  ReturnType = PD->getType();
9144  } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
9145  ReturnType = FD->getReturnType();
9146  } else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) {
9147  // Attributes on parameters are used for out-parameters,
9148  // passed as pointers-to-pointers.
9149  unsigned DiagID = K == Sema::RetainOwnershipKind::CF
9150  ? /*pointer-to-CF-pointer*/2
9151  : /*pointer-to-OSObject-pointer*/3;
9152  ReturnType = Param->getType()->getPointeeType();
9153  if (ReturnType.isNull()) {
9154  S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
9155  << AL << DiagID << AL.getRange();
9156  return;
9157  }
9158  } else if (AL.isUsedAsTypeAttr()) {
9159  return;
9160  } else {
9161  AttributeDeclKind ExpectedDeclKind;
9162  switch (AL.getKind()) {
9163  default: llvm_unreachable("invalid ownership attribute");
9164  case ParsedAttr::AT_NSReturnsRetained:
9165  case ParsedAttr::AT_NSReturnsAutoreleased:
9166  case ParsedAttr::AT_NSReturnsNotRetained:
9167  ExpectedDeclKind = ExpectedFunctionOrMethod;
9168  break;
9169 
9170  case ParsedAttr::AT_OSReturnsRetained:
9171  case ParsedAttr::AT_OSReturnsNotRetained:
9172  case ParsedAttr::AT_CFReturnsRetained:
9173  case ParsedAttr::AT_CFReturnsNotRetained:
9174  ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
9175  break;
9176  }
9177  S.Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type)
9178  << AL.getRange() << AL << AL.isRegularKeywordAttribute()
9179  << ExpectedDeclKind;
9180  return;
9181  }
9182 
9183  bool TypeOK;
9184  bool Cf;
9185  unsigned ParmDiagID = 2; // Pointer-to-CF-pointer
9186  switch (AL.getKind()) {
9187  default: llvm_unreachable("invalid ownership attribute");
9188  case ParsedAttr::AT_NSReturnsRetained:
9189  TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType);
9190  Cf = false;
9191  break;
9192 
9193  case ParsedAttr::AT_NSReturnsAutoreleased:
9194  case ParsedAttr::AT_NSReturnsNotRetained:
9195  TypeOK = isValidSubjectOfNSAttribute(ReturnType);
9196  Cf = false;
9197  break;
9198 
9199  case ParsedAttr::AT_CFReturnsRetained:
9200  case ParsedAttr::AT_CFReturnsNotRetained:
9201  TypeOK = isValidSubjectOfCFAttribute(ReturnType);
9202  Cf = true;
9203  break;
9204 
9205  case ParsedAttr::AT_OSReturnsRetained:
9206  case ParsedAttr::AT_OSReturnsNotRetained:
9207  TypeOK = isValidSubjectOfOSAttribute(ReturnType);
9208  Cf = true;
9209  ParmDiagID = 3; // Pointer-to-OSObject-pointer
9210  break;
9211  }
9212 
9213  if (!TypeOK) {
9214  if (AL.isUsedAsTypeAttr())
9215  return;
9216 
9217  if (isa<ParmVarDecl>(D)) {
9218  S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
9219  << AL << ParmDiagID << AL.getRange();
9220  } else {
9221  // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
9222  enum : unsigned {
9223  Function,
9224  Method,
9225  Property
9226  } SubjectKind = Function;
9227  if (isa<ObjCMethodDecl>(D))
9228  SubjectKind = Method;
9229  else if (isa<ObjCPropertyDecl>(D))
9230  SubjectKind = Property;
9231  S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
9232  << AL << SubjectKind << Cf << AL.getRange();
9233  }
9234  return;
9235  }
9236 
9237  switch (AL.getKind()) {
9238  default:
9239  llvm_unreachable("invalid ownership attribute");
9240  case ParsedAttr::AT_NSReturnsAutoreleased:
9241  handleSimpleAttribute<NSReturnsAutoreleasedAttr>(S, D, AL);
9242  return;
9243  case ParsedAttr::AT_CFReturnsNotRetained:
9244  handleSimpleAttribute<CFReturnsNotRetainedAttr>(S, D, AL);
9245  return;
9246  case ParsedAttr::AT_NSReturnsNotRetained:
9247  handleSimpleAttribute<NSReturnsNotRetainedAttr>(S, D, AL);
9248  return;
9249  case ParsedAttr::AT_CFReturnsRetained:
9250  handleSimpleAttribute<CFReturnsRetainedAttr>(S, D, AL);
9251  return;
9252  case ParsedAttr::AT_NSReturnsRetained:
9253  handleSimpleAttribute<NSReturnsRetainedAttr>(S, D, AL);
9254  return;
9255  case ParsedAttr::AT_OSReturnsRetained:
9256  handleSimpleAttribute<OSReturnsRetainedAttr>(S, D, AL);
9257  return;
9258  case ParsedAttr::AT_OSReturnsNotRetained:
9259  handleSimpleAttribute<OSReturnsNotRetainedAttr>(S, D, AL);
9260  return;
9261  };
9262 }
9263 
9264 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
9265  const ParsedAttr &Attrs) {
9266  const int EP_ObjCMethod = 1;
9267  const int EP_ObjCProperty = 2;
9268 
9269  SourceLocation loc = Attrs.getLoc();
9270  QualType resultType;
9271  if (isa<ObjCMethodDecl>(D))
9272  resultType = cast<ObjCMethodDecl>(D)->getReturnType();
9273  else
9274  resultType = cast<ObjCPropertyDecl>(D)->getType();
9275 
9276  if (!resultType->isReferenceType() &&
9277  (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
9278  S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
9279  << SourceRange(loc) << Attrs
9280  << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
9281  << /*non-retainable pointer*/ 2;
9282 
9283  // Drop the attribute.
9284  return;
9285  }
9286 
9287  D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(S.Context, Attrs));
9288 }
9289 
9290 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
9291  const ParsedAttr &Attrs) {
9292  const auto *Method = cast<ObjCMethodDecl>(D);
9293 
9294  const DeclContext *DC = Method->getDeclContext();
9295  if (const auto *PDecl = dyn_cast_if_present<ObjCProtocolDecl>(DC)) {
9296  S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
9297  << 0;
9298  S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
9299  return;
9300  }
9301  if (Method->getMethodFamily() == OMF_dealloc) {
9302  S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
9303  << 1;
9304  return;
9305  }
9306 
9307  D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(S.Context, Attrs));
9308 }
9309 
9310 static void handleNSErrorDomain(Sema &S, Decl *D, const ParsedAttr &Attr) {
9311  if (!isa<TagDecl>(D)) {
9312  S.Diag(D->getBeginLoc(), diag::err_nserrordomain_invalid_decl) << 0;
9313  return;
9314  }
9315 
9316  IdentifierLoc *IdentLoc =
9317  Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
9318  if (!IdentLoc || !IdentLoc->Ident) {
9319  // Try to locate the argument directly.
9321  if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0))
9322  Loc = Attr.getArgAsExpr(0)->getBeginLoc();
9323 
9324  S.Diag(Loc, diag::err_nserrordomain_invalid_decl) << 0;
9325  return;
9326  }
9327 
9328  // Verify that the identifier is a valid decl in the C decl namespace.
9329  LookupResult Result(S, DeclarationName(IdentLoc->Ident), SourceLocation(),
9330  Sema::LookupNameKind::LookupOrdinaryName);
9331  if (!S.LookupName(Result, S.TUScope) || !Result.getAsSingle<VarDecl>()) {
9332  S.Diag(IdentLoc->Loc, diag::err_nserrordomain_invalid_decl)
9333  << 1 << IdentLoc->Ident;
9334  return;
9335  }
9336 
9337  D->addAttr(::new (S.Context)
9338  NSErrorDomainAttr(S.Context, Attr, IdentLoc->Ident));
9339 }
9340 
9341 static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
9342  IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
9343 
9344  if (!Parm) {
9345  S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
9346  return;
9347  }
9348 
9349  // Typedefs only allow objc_bridge(id) and have some additional checking.
9350  if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
9351  if (!Parm->Ident->isStr("id")) {
9352  S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL;
9353  return;
9354  }
9355 
9356  // Only allow 'cv void *'.
9357  QualType T = TD->getUnderlyingType();
9358  if (!T->isVoidPointerType()) {
9359  S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
9360  return;
9361  }
9362  }
9363 
9364  D->addAttr(::new (S.Context) ObjCBridgeAttr(S.Context, AL, Parm->Ident));
9365 }
9366 
9367 static void handleObjCBridgeMutableAttr(Sema &S, Decl *D,
9368  const ParsedAttr &AL) {
9369  IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
9370 
9371  if (!Parm) {
9372  S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
9373  return;
9374  }
9375 
9376  D->addAttr(::new (S.Context)
9377  ObjCBridgeMutableAttr(S.Context, AL, Parm->Ident));
9378 }
9379 
9380 static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D,
9381  const ParsedAttr &AL) {
9382  IdentifierInfo *RelatedClass =
9383  AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr;
9384  if (!RelatedClass) {
9385  S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
9386  return;
9387  }
9389  AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr;
9391  AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr;
9392  D->addAttr(::new (S.Context) ObjCBridgeRelatedAttr(
9393  S.Context, AL, RelatedClass, ClassMethod, InstanceMethod));
9394 }
9395 
9396 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
9397  const ParsedAttr &AL) {
9398  DeclContext *Ctx = D->getDeclContext();
9399 
9400  // This attribute can only be applied to methods in interfaces or class
9401  // extensions.
9402  if (!isa<ObjCInterfaceDecl>(Ctx) &&
9403  !(isa<ObjCCategoryDecl>(Ctx) &&
9404  cast<ObjCCategoryDecl>(Ctx)->IsClassExtension())) {
9405  S.Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
9406  return;
9407  }
9408 
9409  ObjCInterfaceDecl *IFace;
9410  if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Ctx))
9411  IFace = CatDecl->getClassInterface();
9412  else
9413  IFace = cast<ObjCInterfaceDecl>(Ctx);
9414 
9415  if (!IFace)
9416  return;
9417 
9419  D->addAttr(::new (S.Context) ObjCDesignatedInitializerAttr(S.Context, AL));
9420 }
9421 
9422 static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) {
9423  StringRef MetaDataName;
9424  if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName))
9425  return;
9426  D->addAttr(::new (S.Context)
9427  ObjCRuntimeNameAttr(S.Context, AL, MetaDataName));
9428 }
9429 
9430 // When a user wants to use objc_boxable with a union or struct
9431 // but they don't have access to the declaration (legacy/third-party code)
9432 // then they can 'enable' this feature with a typedef:
9433 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
9434 static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) {
9435  bool notify = false;
9436 
9437  auto *RD = dyn_cast<RecordDecl>(D);
9438  if (RD && RD->getDefinition()) {
9439  RD = RD->getDefinition();
9440  notify = true;
9441  }
9442 
9443  if (RD) {
9444  ObjCBoxableAttr *BoxableAttr =
9445  ::new (S.Context) ObjCBoxableAttr(S.Context, AL);
9446  RD->addAttr(BoxableAttr);
9447  if (notify) {
9448  // we need to notify ASTReader/ASTWriter about
9449  // modification of existing declaration
9451  L->AddedAttributeToRecord(BoxableAttr, RD);
9452  }
9453  }
9454 }
9455 
9456 static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
9457  if (hasDeclarator(D))
9458  return;
9459 
9460  S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type)
9461  << AL.getRange() << AL << AL.isRegularKeywordAttribute()
9462  << ExpectedVariable;
9463 }
9464 
9465 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
9466  const ParsedAttr &AL) {
9467  const auto *VD = cast<ValueDecl>(D);
9468  QualType QT = VD->getType();
9469 
9470  if (!QT->isDependentType() &&
9471  !QT->isObjCLifetimeType()) {
9472  S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type)
9473  << QT;
9474  return;
9475  }
9476 
9477  Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime();
9478 
9479  // If we have no lifetime yet, check the lifetime we're presumably
9480  // going to infer.
9481  if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType())
9482  Lifetime = QT->getObjCARCImplicitLifetime();
9483 
9484  switch (Lifetime) {
9485  case Qualifiers::OCL_None:
9486  assert(QT->isDependentType() &&
9487  "didn't infer lifetime for non-dependent type?");
9488  break;
9489 
9490  case Qualifiers::OCL_Weak: // meaningful
9491  case Qualifiers::OCL_Strong: // meaningful
9492  break;
9493 
9496  S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
9497  << (Lifetime == Qualifiers::OCL_Autoreleasing);
9498  break;
9499  }
9500 
9501  D->addAttr(::new (S.Context) ObjCPreciseLifetimeAttr(S.Context, AL));
9502 }
9503 
9504 static void handleSwiftAttrAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
9505  // Make sure that there is a string literal as the annotation's single
9506  // argument.
9507  StringRef Str;
9508  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
9509  return;
9510 
9511  D->addAttr(::new (S.Context) SwiftAttrAttr(S.Context, AL, Str));
9512 }
9513 
9514 static void handleSwiftBridge(Sema &S, Decl *D, const ParsedAttr &AL) {
9515  // Make sure that there is a string literal as the annotation's single
9516  // argument.
9517  StringRef BT;
9518  if (!S.checkStringLiteralArgumentAttr(AL, 0, BT))
9519  return;
9520 
9521  // Warn about duplicate attributes if they have different arguments, but drop
9522  // any duplicate attributes regardless.
9523  if (const auto *Other = D->getAttr<SwiftBridgeAttr>()) {
9524  if (Other->getSwiftType() != BT)
9525  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
9526  return;
9527  }
9528 
9529  D->addAttr(::new (S.Context) SwiftBridgeAttr(S.Context, AL, BT));
9530 }
9531 
9532 static bool isErrorParameter(Sema &S, QualType QT) {
9533  const auto *PT = QT->getAs<PointerType>();
9534  if (!PT)
9535  return false;
9536 
9537  QualType Pointee = PT->getPointeeType();
9538 
9539  // Check for NSError**.
9540  if (const auto *OPT = Pointee->getAs<ObjCObjectPointerType>())
9541  if (const auto *ID = OPT->getInterfaceDecl())
9542  if (ID->getIdentifier() == S.ObjC().getNSErrorIdent())
9543  return true;
9544 
9545  // Check for CFError**.
9546  if (const auto *PT = Pointee->getAs<PointerType>())
9547  if (const auto *RT = PT->getPointeeType()->getAs<RecordType>())
9548  if (S.ObjC().isCFError(RT->getDecl()))
9549  return true;
9550 
9551  return false;
9552 }
9553 
9554 static void handleSwiftError(Sema &S, Decl *D, const ParsedAttr &AL) {
9555  auto hasErrorParameter = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
9556  for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); I != E; ++I) {
9557  if (isErrorParameter(S, getFunctionOrMethodParamType(D, I)))
9558  return true;
9559  }
9560 
9561  S.Diag(AL.getLoc(), diag::err_attr_swift_error_no_error_parameter)
9562  << AL << isa<ObjCMethodDecl>(D);
9563  return false;
9564  };
9565 
9566  auto hasPointerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
9567  // - C, ObjC, and block pointers are definitely okay.
9568  // - References are definitely not okay.
9569  // - nullptr_t is weird, but acceptable.
9571  if (RT->hasPointerRepresentation() && !RT->isReferenceType())
9572  return true;
9573 
9574  S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type)
9575  << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D)
9576  << /*pointer*/ 1;
9577  return false;
9578  };
9579 
9580  auto hasIntegerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool {
9582  if (RT->isIntegralType(S.Context))
9583  return true;
9584 
9585  S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type)
9586  << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D)
9587  << /*integral*/ 0;
9588  return false;
9589  };
9590 
9591  if (D->isInvalidDecl())
9592  return;
9593 
9594  IdentifierLoc *Loc = AL.getArgAsIdent(0);
9595  SwiftErrorAttr::ConventionKind Convention;
9596  if (!SwiftErrorAttr::ConvertStrToConventionKind(Loc->Ident->getName(),
9597  Convention)) {
9598  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
9599  << AL << Loc->Ident;
9600  return;
9601  }
9602 
9603  switch (Convention) {
9604  case SwiftErrorAttr::None:
9605  // No additional validation required.
9606  break;
9607 
9608  case SwiftErrorAttr::NonNullError:
9609  if (!hasErrorParameter(S, D, AL))
9610  return;
9611  break;
9612 
9613  case SwiftErrorAttr::NullResult:
9614  if (!hasErrorParameter(S, D, AL) || !hasPointerResult(S, D, AL))
9615  return;
9616  break;
9617 
9618  case SwiftErrorAttr::NonZeroResult:
9619  case SwiftErrorAttr::ZeroResult:
9620  if (!hasErrorParameter(S, D, AL) || !hasIntegerResult(S, D, AL))
9621  return;
9622  break;
9623  }
9624 
9625  D->addAttr(::new (S.Context) SwiftErrorAttr(S.Context, AL, Convention));
9626 }
9627 
9628 static void checkSwiftAsyncErrorBlock(Sema &S, Decl *D,
9629  const SwiftAsyncErrorAttr *ErrorAttr,
9630  const SwiftAsyncAttr *AsyncAttr) {
9631  if (AsyncAttr->getKind() == SwiftAsyncAttr::None) {
9632  if (ErrorAttr->getConvention() != SwiftAsyncErrorAttr::None) {
9633  S.Diag(AsyncAttr->getLocation(),
9634  diag::err_swift_async_error_without_swift_async)
9635  << AsyncAttr << isa<ObjCMethodDecl>(D);
9636  }
9637  return;
9638  }
9639 
9640  const ParmVarDecl *HandlerParam = getFunctionOrMethodParam(
9641  D, AsyncAttr->getCompletionHandlerIndex().getASTIndex());
9642  // handleSwiftAsyncAttr already verified the type is correct, so no need to
9643  // double-check it here.
9644  const auto *FuncTy = HandlerParam->getType()
9646  ->getPointeeType()
9647  ->getAs<FunctionProtoType>();
9648  ArrayRef<QualType> BlockParams;
9649  if (FuncTy)
9650  BlockParams = FuncTy->getParamTypes();
9651 
9652  switch (ErrorAttr->getConvention()) {
9653  case SwiftAsyncErrorAttr::ZeroArgument:
9654  case SwiftAsyncErrorAttr::NonZeroArgument: {
9655  uint32_t ParamIdx = ErrorAttr->getHandlerParamIdx();
9656  if (ParamIdx == 0 || ParamIdx > BlockParams.size()) {
9657  S.Diag(ErrorAttr->getLocation(),
9658  diag::err_attribute_argument_out_of_bounds) << ErrorAttr << 2;
9659  return;
9660  }
9661  QualType ErrorParam = BlockParams[ParamIdx - 1];
9662  if (!ErrorParam->isIntegralType(S.Context)) {
9663  StringRef ConvStr =
9664  ErrorAttr->getConvention() == SwiftAsyncErrorAttr::ZeroArgument
9665  ? "zero_argument"
9666  : "nonzero_argument";
9667  S.Diag(ErrorAttr->getLocation(), diag::err_swift_async_error_non_integral)
9668  << ErrorAttr << ConvStr << ParamIdx << ErrorParam;
9669  return;
9670  }
9671  break;
9672  }
9673  case SwiftAsyncErrorAttr::NonNullError: {
9674  bool AnyErrorParams = false;
9675  for (QualType Param : BlockParams) {
9676  // Check for NSError *.
9677  if (const auto *ObjCPtrTy = Param->getAs<ObjCObjectPointerType>()) {
9678  if (const auto *ID = ObjCPtrTy->getInterfaceDecl()) {
9679  if (ID->getIdentifier() == S.ObjC().getNSErrorIdent()) {
9680  AnyErrorParams = true;
9681  break;
9682  }
9683  }
9684  }
9685  // Check for CFError *.
9686  if (const auto *PtrTy = Param->getAs<PointerType>()) {
9687  if (const auto *RT = PtrTy->getPointeeType()->getAs<RecordType>()) {
9688  if (S.ObjC().isCFError(RT->getDecl())) {
9689  AnyErrorParams = true;
9690  break;
9691  }
9692  }
9693  }
9694  }
9695 
9696  if (!AnyErrorParams) {
9697  S.Diag(ErrorAttr->getLocation(),
9698  diag::err_swift_async_error_no_error_parameter)
9699  << ErrorAttr << isa<ObjCMethodDecl>(D);
9700  return;
9701  }
9702  break;
9703  }
9705  break;
9706  }
9707 }
9708 
9709 static void handleSwiftAsyncError(Sema &S, Decl *D, const ParsedAttr &AL) {
9710  IdentifierLoc *IDLoc = AL.getArgAsIdent(0);
9711  SwiftAsyncErrorAttr::ConventionKind ConvKind;
9712  if (!SwiftAsyncErrorAttr::ConvertStrToConventionKind(IDLoc->Ident->getName(),
9713  ConvKind)) {
9714  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
9715  << AL << IDLoc->Ident;
9716  return;
9717  }
9718 
9719  uint32_t ParamIdx = 0;
9720  switch (ConvKind) {
9721  case SwiftAsyncErrorAttr::ZeroArgument:
9722  case SwiftAsyncErrorAttr::NonZeroArgument: {
9723  if (!AL.checkExactlyNumArgs(S, 2))
9724  return;
9725 
9726  Expr *IdxExpr = AL.getArgAsExpr(1);
9727  if (!checkUInt32Argument(S, AL, IdxExpr, ParamIdx))
9728  return;
9729  break;
9730  }
9731  case SwiftAsyncErrorAttr::NonNullError:
9733  if (!AL.checkExactlyNumArgs(S, 1))
9734  return;
9735  break;
9736  }
9737  }
9738 
9739  auto *ErrorAttr =
9740  ::new (S.Context) SwiftAsyncErrorAttr(S.Context, AL, ConvKind, ParamIdx);
9741  D->addAttr(ErrorAttr);
9742 
9743  if (auto *AsyncAttr = D->getAttr<SwiftAsyncAttr>())
9744  checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
9745 }
9746 
9747 // For a function, this will validate a compound Swift name, e.g.
9748 // <code>init(foo:bar:baz:)</code> or <code>controllerForName(_:)</code>, and
9749 // the function will output the number of parameter names, and whether this is a
9750 // single-arg initializer.
9751 //
9752 // For a type, enum constant, property, or variable declaration, this will
9753 // validate either a simple identifier, or a qualified
9754 // <code>context.identifier</code> name.
9755 static bool
9756 validateSwiftFunctionName(Sema &S, const ParsedAttr &AL, SourceLocation Loc,
9757  StringRef Name, unsigned &SwiftParamCount,
9758  bool &IsSingleParamInit) {
9759  SwiftParamCount = 0;
9760  IsSingleParamInit = false;
9761 
9762  // Check whether this will be mapped to a getter or setter of a property.
9763  bool IsGetter = false, IsSetter = false;
9764  if (Name.consume_front("getter:"))
9765  IsGetter = true;
9766  else if (Name.consume_front("setter:"))
9767  IsSetter = true;
9768 
9769  if (Name.back() != ')') {
9770  S.Diag(Loc, diag::warn_attr_swift_name_function) << AL;
9771  return false;
9772  }
9773 
9774  bool IsMember = false;
9775  StringRef ContextName, BaseName, Parameters;
9776 
9777  std::tie(BaseName, Parameters) = Name.split('(');
9778 
9779  // Split at the first '.', if it exists, which separates the context name
9780  // from the base name.
9781  std::tie(ContextName, BaseName) = BaseName.split('.');
9782  if (BaseName.empty()) {
9783  BaseName = ContextName;
9784  ContextName = StringRef();
9785  } else if (ContextName.empty() || !isValidAsciiIdentifier(ContextName)) {
9786  S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
9787  << AL << /*context*/ 1;
9788  return false;
9789  } else {
9790  IsMember = true;
9791  }
9792 
9793  if (!isValidAsciiIdentifier(BaseName) || BaseName == "_") {
9794  S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
9795  << AL << /*basename*/ 0;
9796  return false;
9797  }
9798 
9799  bool IsSubscript = BaseName == "subscript";
9800  // A subscript accessor must be a getter or setter.
9801  if (IsSubscript && !IsGetter && !IsSetter) {
9802  S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
9803  << AL << /* getter or setter */ 0;
9804  return false;
9805  }
9806 
9807  if (Parameters.empty()) {
9808  S.Diag(Loc, diag::warn_attr_swift_name_missing_parameters) << AL;
9809  return false;
9810  }
9811 
9812  assert(Parameters.back() == ')' && "expected ')'");
9813  Parameters = Parameters.drop_back(); // ')'
9814 
9815  if (Parameters.empty()) {
9816  // Setters and subscripts must have at least one parameter.
9817  if (IsSubscript) {
9818  S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
9819  << AL << /* have at least one parameter */1;
9820  return false;
9821  }
9822 
9823  if (IsSetter) {
9824  S.Diag(Loc, diag::warn_attr_swift_name_setter_parameters) << AL;
9825  return false;
9826  }
9827 
9828  return true;
9829  }
9830 
9831  if (Parameters.back() != ':') {
9832  S.Diag(Loc, diag::warn_attr_swift_name_function) << AL;
9833  return false;
9834  }
9835 
9836  StringRef CurrentParam;
9837  std::optional<unsigned> SelfLocation;
9838  unsigned NewValueCount = 0;
9839  std::optional<unsigned> NewValueLocation;
9840  do {
9841  std::tie(CurrentParam, Parameters) = Parameters.split(':');
9842 
9843  if (!isValidAsciiIdentifier(CurrentParam)) {
9844  S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier)
9845  << AL << /*parameter*/2;
9846  return false;
9847  }
9848 
9849  if (IsMember && CurrentParam == "self") {
9850  // "self" indicates the "self" argument for a member.
9851 
9852  // More than one "self"?
9853  if (SelfLocation) {
9854  S.Diag(Loc, diag::warn_attr_swift_name_multiple_selfs) << AL;
9855  return false;
9856  }
9857 
9858  // The "self" location is the current parameter.
9859  SelfLocation = SwiftParamCount;
9860  } else if (CurrentParam == "newValue") {
9861  // "newValue" indicates the "newValue" argument for a setter.
9862 
9863  // There should only be one 'newValue', but it's only significant for
9864  // subscript accessors, so don't error right away.
9865  ++NewValueCount;
9866 
9867  NewValueLocation = SwiftParamCount;
9868  }
9869 
9870  ++SwiftParamCount;
9871  } while (!Parameters.empty());
9872 
9873  // Only instance subscripts are currently supported.
9874  if (IsSubscript && !SelfLocation) {
9875  S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter)
9876  << AL << /*have a 'self:' parameter*/2;
9877  return false;
9878  }
9879 
9880  IsSingleParamInit =
9881  SwiftParamCount == 1 && BaseName == "init" && CurrentParam != "_";
9882 
9883  // Check the number of parameters for a getter/setter.
9884  if (IsGetter || IsSetter) {
9885  // Setters have one parameter for the new value.
9886  unsigned NumExpectedParams = IsGetter ? 0 : 1;
9887  unsigned ParamDiag =
9888  IsGetter ? diag::warn_attr_swift_name_getter_parameters
9889  : diag::warn_attr_swift_name_setter_parameters;
9890 
9891  // Instance methods have one parameter for "self".
9892  if (SelfLocation)
9893  ++NumExpectedParams;
9894 
9895  // Subscripts may have additional parameters beyond the expected params for
9896  // the index.
9897  if (IsSubscript) {
9898  if (SwiftParamCount < NumExpectedParams) {
9899  S.Diag(Loc, ParamDiag) << AL;
9900  return false;
9901  }
9902 
9903  // A subscript setter must explicitly label its newValue parameter to
9904  // distinguish it from index parameters.
9905  if (IsSetter) {
9906  if (!NewValueLocation) {
9907  S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_no_newValue)
9908  << AL;
9909  return false;
9910  }
9911  if (NewValueCount > 1) {
9912  S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_multiple_newValues)
9913  << AL;
9914  return false;
9915  }
9916  } else {
9917  // Subscript getters should have no 'newValue:' parameter.
9918  if (NewValueLocation) {
9919  S.Diag(Loc, diag::warn_attr_swift_name_subscript_getter_newValue)
9920  << AL;
9921  return false;
9922  }
9923  }
9924  } else {
9925  // Property accessors must have exactly the number of expected params.
9926  if (SwiftParamCount != NumExpectedParams) {
9927  S.Diag(Loc, ParamDiag) << AL;
9928  return false;
9929  }
9930  }
9931  }
9932 
9933  return true;
9934 }
9935 
9936 bool Sema::DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
9937  const ParsedAttr &AL, bool IsAsync) {
9938  if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
9939  ArrayRef<ParmVarDecl*> Params;
9940  unsigned ParamCount;
9941 
9942  if (const auto *Method = dyn_cast<ObjCMethodDecl>(D)) {
9943  ParamCount = Method->getSelector().getNumArgs();
9944  Params = Method->parameters().slice(0, ParamCount);
9945  } else {
9946  const auto *F = cast<FunctionDecl>(D);
9947 
9948  ParamCount = F->getNumParams();
9949  Params = F->parameters();
9950 
9951  if (!F->hasWrittenPrototype()) {
9952  Diag(Loc, diag::warn_attribute_wrong_decl_type)
9953  << AL << AL.isRegularKeywordAttribute()
9955  return false;
9956  }
9957  }
9958 
9959  // The async name drops the last callback parameter.
9960  if (IsAsync) {
9961  if (ParamCount == 0) {
9962  Diag(Loc, diag::warn_attr_swift_name_decl_missing_params)
9963  << AL << isa<ObjCMethodDecl>(D);
9964  return false;
9965  }
9966  ParamCount -= 1;
9967  }
9968 
9969  unsigned SwiftParamCount;
9970  bool IsSingleParamInit;
9971  if (!validateSwiftFunctionName(*this, AL, Loc, Name,
9972  SwiftParamCount, IsSingleParamInit))
9973  return false;
9974 
9975  bool ParamCountValid;
9976  if (SwiftParamCount == ParamCount) {
9977  ParamCountValid = true;
9978  } else if (SwiftParamCount > ParamCount) {
9979  ParamCountValid = IsSingleParamInit && ParamCount == 0;
9980  } else {
9981  // We have fewer Swift parameters than Objective-C parameters, but that
9982  // might be because we've transformed some of them. Check for potential
9983  // "out" parameters and err on the side of not warning.
9984  unsigned MaybeOutParamCount =
9985  llvm::count_if(Params, [](const ParmVarDecl *Param) -> bool {
9986  QualType ParamTy = Param->getType();
9987  if (ParamTy->isReferenceType() || ParamTy->isPointerType())
9988  return !ParamTy->getPointeeType().isConstQualified();
9989  return false;
9990  });
9991 
9992  ParamCountValid = SwiftParamCount + MaybeOutParamCount >= ParamCount;
9993  }
9994 
9995  if (!ParamCountValid) {
9996  Diag(Loc, diag::warn_attr_swift_name_num_params)
9997  << (SwiftParamCount > ParamCount) << AL << ParamCount
9998  << SwiftParamCount;
9999  return false;
10000  }
10001  } else if ((isa<EnumConstantDecl>(D) || isa<ObjCProtocolDecl>(D) ||
10002  isa<ObjCInterfaceDecl>(D) || isa<ObjCPropertyDecl>(D) ||
10003  isa<VarDecl>(D) || isa<TypedefNameDecl>(D) || isa<TagDecl>(D) ||
10004  isa<IndirectFieldDecl>(D) || isa<FieldDecl>(D)) &&
10005  !IsAsync) {
10006  StringRef ContextName, BaseName;
10007 
10008  std::tie(ContextName, BaseName) = Name.split('.');
10009  if (BaseName.empty()) {
10010  BaseName = ContextName;
10011  ContextName = StringRef();
10012  } else if (!isValidAsciiIdentifier(ContextName)) {
10013  Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL
10014  << /*context*/1;
10015  return false;
10016  }
10017 
10018  if (!isValidAsciiIdentifier(BaseName)) {
10019  Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL
10020  << /*basename*/0;
10021  return false;
10022  }
10023  } else {
10024  Diag(Loc, diag::warn_attr_swift_name_decl_kind) << AL;
10025  return false;
10026  }
10027  return true;
10028 }
10029 
10030 static void handleSwiftName(Sema &S, Decl *D, const ParsedAttr &AL) {
10031  StringRef Name;
10033  if (!S.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc))
10034  return;
10035 
10036  if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/false))
10037  return;
10038 
10039  D->addAttr(::new (S.Context) SwiftNameAttr(S.Context, AL, Name));
10040 }
10041 
10042 static void handleSwiftAsyncName(Sema &S, Decl *D, const ParsedAttr &AL) {
10043  StringRef Name;
10045  if (!S.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc))
10046  return;
10047 
10048  if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/true))
10049  return;
10050 
10051  D->addAttr(::new (S.Context) SwiftAsyncNameAttr(S.Context, AL, Name));
10052 }
10053 
10054 static void handleSwiftNewType(Sema &S, Decl *D, const ParsedAttr &AL) {
10055  // Make sure that there is an identifier as the annotation's single argument.
10056  if (!AL.checkExactlyNumArgs(S, 1))
10057  return;
10058 
10059  if (!AL.isArgIdent(0)) {
10060  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
10061  << AL << AANT_ArgumentIdentifier;
10062  return;
10063  }
10064 
10065  SwiftNewTypeAttr::NewtypeKind Kind;
10066  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
10067  if (!SwiftNewTypeAttr::ConvertStrToNewtypeKind(II->getName(), Kind)) {
10068  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
10069  return;
10070  }
10071 
10072  if (!isa<TypedefNameDecl>(D)) {
10073  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str)
10074  << AL << AL.isRegularKeywordAttribute() << "typedefs";
10075  return;
10076  }
10077 
10078  D->addAttr(::new (S.Context) SwiftNewTypeAttr(S.Context, AL, Kind));
10079 }
10080 
10081 static void handleSwiftAsyncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
10082  if (!AL.isArgIdent(0)) {
10083  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
10084  << AL << 1 << AANT_ArgumentIdentifier;
10085  return;
10086  }
10087 
10089  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
10090  if (!SwiftAsyncAttr::ConvertStrToKind(II->getName(), Kind)) {
10091  S.Diag(AL.getLoc(), diag::err_swift_async_no_access) << AL << II;
10092  return;
10093  }
10094 
10095  ParamIdx Idx;
10096  if (Kind == SwiftAsyncAttr::None) {
10097  // If this is 'none', then there shouldn't be any additional arguments.
10098  if (!AL.checkExactlyNumArgs(S, 1))
10099  return;
10100  } else {
10101  // Non-none swift_async requires a completion handler index argument.
10102  if (!AL.checkExactlyNumArgs(S, 2))
10103  return;
10104 
10105  Expr *HandlerIdx = AL.getArgAsExpr(1);
10106  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, HandlerIdx, Idx))
10107  return;
10108 
10109  const ParmVarDecl *CompletionBlock =
10111  QualType CompletionBlockType = CompletionBlock->getType();
10112  if (!CompletionBlockType->isBlockPointerType()) {
10113  S.Diag(CompletionBlock->getLocation(),
10114  diag::err_swift_async_bad_block_type)
10115  << CompletionBlock->getType();
10116  return;
10117  }
10118  QualType BlockTy =
10119  CompletionBlockType->castAs<BlockPointerType>()->getPointeeType();
10120  if (!BlockTy->castAs<FunctionType>()->getReturnType()->isVoidType()) {
10121  S.Diag(CompletionBlock->getLocation(),
10122  diag::err_swift_async_bad_block_type)
10123  << CompletionBlock->getType();
10124  return;
10125  }
10126  }
10127 
10128  auto *AsyncAttr =
10129  ::new (S.Context) SwiftAsyncAttr(S.Context, AL, Kind, Idx);
10130  D->addAttr(AsyncAttr);
10131 
10132  if (auto *ErrorAttr = D->getAttr<SwiftAsyncErrorAttr>())
10133  checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr);
10134 }
10135 
10136 //===----------------------------------------------------------------------===//
10137 // Microsoft specific attribute handlers.
10138 //===----------------------------------------------------------------------===//
10139 
10140 UuidAttr *Sema::mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
10141  StringRef UuidAsWritten, MSGuidDecl *GuidDecl) {
10142  if (const auto *UA = D->getAttr<UuidAttr>()) {
10143  if (declaresSameEntity(UA->getGuidDecl(), GuidDecl))
10144  return nullptr;
10145  if (!UA->getGuid().empty()) {
10146  Diag(UA->getLocation(), diag::err_mismatched_uuid);
10147  Diag(CI.getLoc(), diag::note_previous_uuid);
10148  D->dropAttr<UuidAttr>();
10149  }
10150  }
10151 
10152  return ::new (Context) UuidAttr(Context, CI, UuidAsWritten, GuidDecl);
10153 }
10154 
10155 static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
10156  if (!S.LangOpts.CPlusPlus) {
10157  S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
10158  << AL << AttributeLangSupport::C;
10159  return;
10160  }
10161 
10162  StringRef OrigStrRef;
10163  SourceLocation LiteralLoc;
10164  if (!S.checkStringLiteralArgumentAttr(AL, 0, OrigStrRef, &LiteralLoc))
10165  return;
10166 
10167  // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
10168  // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
10169  StringRef StrRef = OrigStrRef;
10170  if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
10171  StrRef = StrRef.drop_front().drop_back();
10172 
10173  // Validate GUID length.
10174  if (StrRef.size() != 36) {
10175  S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
10176  return;
10177  }
10178 
10179  for (unsigned i = 0; i < 36; ++i) {
10180  if (i == 8 || i == 13 || i == 18 || i == 23) {
10181  if (StrRef[i] != '-') {
10182  S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
10183  return;
10184  }
10185  } else if (!isHexDigit(StrRef[i])) {
10186  S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
10187  return;
10188  }
10189  }
10190 
10191  // Convert to our parsed format and canonicalize.
10192  MSGuidDecl::Parts Parsed;
10193  StrRef.substr(0, 8).getAsInteger(16, Parsed.Part1);
10194  StrRef.substr(9, 4).getAsInteger(16, Parsed.Part2);
10195  StrRef.substr(14, 4).getAsInteger(16, Parsed.Part3);
10196  for (unsigned i = 0; i != 8; ++i)
10197  StrRef.substr(19 + 2 * i + (i >= 2 ? 1 : 0), 2)
10198  .getAsInteger(16, Parsed.Part4And5[i]);
10199  MSGuidDecl *Guid = S.Context.getMSGuidDecl(Parsed);
10200 
10201  // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
10202  // the only thing in the [] list, the [] too), and add an insertion of
10203  // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas
10204  // separating attributes nor of the [ and the ] are in the AST.
10205  // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
10206  // on cfe-dev.
10207  if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
10208  S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated);
10209 
10210  UuidAttr *UA = S.mergeUuidAttr(D, AL, OrigStrRef, Guid);
10211  if (UA)
10212  D->addAttr(UA);
10213 }
10214 
10215 static void handleHLSLNumThreadsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
10216  llvm::VersionTuple SMVersion =
10217  S.Context.getTargetInfo().getTriple().getOSVersion();
10218  uint32_t ZMax = 1024;
10219  uint32_t ThreadMax = 1024;
10220  if (SMVersion.getMajor() <= 4) {
10221  ZMax = 1;
10222  ThreadMax = 768;
10223  } else if (SMVersion.getMajor() == 5) {
10224  ZMax = 64;
10225  ThreadMax = 1024;
10226  }
10227 
10228  uint32_t X;
10229  if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), X))
10230  return;
10231  if (X > 1024) {
10232  S.Diag(AL.getArgAsExpr(0)->getExprLoc(),
10233  diag::err_hlsl_numthreads_argument_oor) << 0 << 1024;
10234  return;
10235  }
10236  uint32_t Y;
10237  if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(1), Y))
10238  return;
10239  if (Y > 1024) {
10240  S.Diag(AL.getArgAsExpr(1)->getExprLoc(),
10241  diag::err_hlsl_numthreads_argument_oor) << 1 << 1024;
10242  return;
10243  }
10244  uint32_t Z;
10245  if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(2), Z))
10246  return;
10247  if (Z > ZMax) {
10248  S.Diag(AL.getArgAsExpr(2)->getExprLoc(),
10249  diag::err_hlsl_numthreads_argument_oor) << 2 << ZMax;
10250  return;
10251  }
10252 
10253  if (X * Y * Z > ThreadMax) {
10254  S.Diag(AL.getLoc(), diag::err_hlsl_numthreads_invalid) << ThreadMax;
10255  return;
10256  }
10257 
10258  HLSLNumThreadsAttr *NewAttr = S.HLSL().mergeNumThreadsAttr(D, AL, X, Y, Z);
10259  if (NewAttr)
10260  D->addAttr(NewAttr);
10261 }
10262 
10263 static bool isLegalTypeForHLSLSV_DispatchThreadID(QualType T) {
10265  return false;
10266  if (const auto *VT = T->getAs<VectorType>())
10267  return VT->getNumElements() <= 3;
10268  return true;
10269 }
10270 
10271 static void handleHLSLSV_DispatchThreadIDAttr(Sema &S, Decl *D,
10272  const ParsedAttr &AL) {
10273  // FIXME: support semantic on field.
10274  // See https://github.com/llvm/llvm-project/issues/57889.
10275  if (isa<FieldDecl>(D)) {
10276  S.Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_ast_node)
10277  << AL << "parameter";
10278  return;
10279  }
10280 
10281  auto *VD = cast<ValueDecl>(D);
10282  if (!isLegalTypeForHLSLSV_DispatchThreadID(VD->getType())) {
10283  S.Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_type)
10284  << AL << "uint/uint2/uint3";
10285  return;
10286  }
10287 
10288  D->addAttr(::new (S.Context) HLSLSV_DispatchThreadIDAttr(S.Context, AL));
10289 }
10290 
10291 static void handleHLSLPackOffsetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
10292  if (!isa<VarDecl>(D) || !isa<HLSLBufferDecl>(D->getDeclContext())) {
10293  S.Diag(AL.getLoc(), diag::err_hlsl_attr_invalid_ast_node)
10294  << AL << "shader constant in a constant buffer";
10295  return;
10296  }
10297 
10298  uint32_t SubComponent;
10299  if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), SubComponent))
10300  return;
10301  uint32_t Component;
10302  if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(1), Component))
10303  return;
10304 
10305  QualType T = cast<VarDecl>(D)->getType().getCanonicalType();
10306  // Check if T is an array or struct type.
10307  // TODO: mark matrix type as aggregate type.
10308  bool IsAggregateTy = (T->isArrayType() || T->isStructureType());
10309 
10310  // Check Component is valid for T.
10311  if (Component) {
10312  unsigned Size = S.getASTContext().getTypeSize(T);
10313  if (IsAggregateTy || Size > 128) {
10314  S.Diag(AL.getLoc(), diag::err_hlsl_packoffset_cross_reg_boundary);
10315  return;
10316  } else {
10317  // Make sure Component + sizeof(T) <= 4.
10318  if ((Component * 32 + Size) > 128) {
10319  S.Diag(AL.getLoc(), diag::err_hlsl_packoffset_cross_reg_boundary);
10320  return;
10321  }
10322  QualType EltTy = T;
10323  if (const auto *VT = T->getAs<VectorType>())
10324  EltTy = VT->getElementType();
10325  unsigned Align = S.getASTContext().getTypeAlign(EltTy);
10326  if (Align > 32 && Component == 1) {
10327  // NOTE: Component 3 will hit err_hlsl_packoffset_cross_reg_boundary.
10328  // So we only need to check Component 1 here.
10329  S.Diag(AL.getLoc(), diag::err_hlsl_packoffset_alignment_mismatch)
10330  << Align << EltTy;
10331  return;
10332  }
10333  }
10334  }
10335 
10336  D->addAttr(::new (S.Context)
10337  HLSLPackOffsetAttr(S.Context, AL, SubComponent, Component));
10338 }
10339 
10340 static void handleHLSLShaderAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
10341  StringRef Str;
10342  SourceLocation ArgLoc;
10343  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
10344  return;
10345 
10346  HLSLShaderAttr::ShaderType ShaderType;
10347  if (!HLSLShaderAttr::ConvertStrToShaderType(Str, ShaderType)) {
10348  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
10349  << AL << Str << ArgLoc;
10350  return;
10351  }
10352 
10353  // FIXME: check function match the shader stage.
10354 
10355  HLSLShaderAttr *NewAttr = S.HLSL().mergeShaderAttr(D, AL, ShaderType);
10356  if (NewAttr)
10357  D->addAttr(NewAttr);
10358 }
10359 
10360 static void handleHLSLResourceBindingAttr(Sema &S, Decl *D,
10361  const ParsedAttr &AL) {
10362  StringRef Space = "space0";
10363  StringRef Slot = "";
10364 
10365  if (!AL.isArgIdent(0)) {
10366  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
10367  << AL << AANT_ArgumentIdentifier;
10368  return;
10369  }
10370 
10371  IdentifierLoc *Loc = AL.getArgAsIdent(0);
10372  StringRef Str = Loc->Ident->getName();
10373  SourceLocation ArgLoc = Loc->Loc;
10374 
10375  SourceLocation SpaceArgLoc;
10376  if (AL.getNumArgs() == 2) {
10377  Slot = Str;
10378  if (!AL.isArgIdent(1)) {
10379  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
10380  << AL << AANT_ArgumentIdentifier;
10381  return;
10382  }
10383 
10384  IdentifierLoc *Loc = AL.getArgAsIdent(1);
10385  Space = Loc->Ident->getName();
10386  SpaceArgLoc = Loc->Loc;
10387  } else {
10388  Slot = Str;
10389  }
10390 
10391  // Validate.
10392  if (!Slot.empty()) {
10393  switch (Slot[0]) {
10394  case 'u':
10395  case 'b':
10396  case 's':
10397  case 't':
10398  break;
10399  default:
10400  S.Diag(ArgLoc, diag::err_hlsl_unsupported_register_type)
10401  << Slot.substr(0, 1);
10402  return;
10403  }
10404 
10405  StringRef SlotNum = Slot.substr(1);
10406  unsigned Num = 0;
10407  if (SlotNum.getAsInteger(10, Num)) {
10408  S.Diag(ArgLoc, diag::err_hlsl_unsupported_register_number);
10409  return;
10410  }
10411  }
10412 
10413  if (!Space.starts_with("space")) {
10414  S.Diag(SpaceArgLoc, diag::err_hlsl_expected_space) << Space;
10415  return;
10416  }
10417  StringRef SpaceNum = Space.substr(5);
10418  unsigned Num = 0;
10419  if (SpaceNum.getAsInteger(10, Num)) {
10420  S.Diag(SpaceArgLoc, diag::err_hlsl_expected_space) << Space;
10421  return;
10422  }
10423 
10424  // FIXME: check reg type match decl. Issue
10425  // https://github.com/llvm/llvm-project/issues/57886.
10426  HLSLResourceBindingAttr *NewAttr =
10427  HLSLResourceBindingAttr::Create(S.getASTContext(), Slot, Space, AL);
10428  if (NewAttr)
10429  D->addAttr(NewAttr);
10430 }
10431 
10432 static void handleHLSLParamModifierAttr(Sema &S, Decl *D,
10433  const ParsedAttr &AL) {
10434  HLSLParamModifierAttr *NewAttr = S.HLSL().mergeParamModifierAttr(
10435  D, AL,
10436  static_cast<HLSLParamModifierAttr::Spelling>(AL.getSemanticSpelling()));
10437  if (NewAttr)
10438  D->addAttr(NewAttr);
10439 }
10440 
10441 static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
10442  if (!S.LangOpts.CPlusPlus) {
10443  S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
10444  << AL << AttributeLangSupport::C;
10445  return;
10446  }
10447  MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
10448  D, AL, /*BestCase=*/true, (MSInheritanceModel)AL.getSemanticSpelling());
10449  if (IA) {
10450  D->addAttr(IA);
10451  S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
10452  }
10453 }
10454 
10455 static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
10456  const auto *VD = cast<VarDecl>(D);
10457  if (!S.Context.getTargetInfo().isTLSSupported()) {
10458  S.Diag(AL.getLoc(), diag::err_thread_unsupported);
10459  return;
10460  }
10461  if (VD->getTSCSpec() != TSCS_unspecified) {
10462  S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable);
10463  return;
10464  }
10465  if (VD->hasLocalStorage()) {
10466  S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
10467  return;
10468  }
10469  D->addAttr(::new (S.Context) ThreadAttr(S.Context, AL));
10470 }
10471 
10472 static void handleMSConstexprAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
10474  S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
10475  << AL << AL.getRange();
10476  return;
10477  }
10478  auto *FD = cast<FunctionDecl>(D);
10479  if (FD->isConstexprSpecified() || FD->isConsteval()) {
10480  S.Diag(AL.getLoc(), diag::err_ms_constexpr_cannot_be_applied)
10481  << FD->isConsteval() << FD;
10482  return;
10483  }
10484  if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
10485  if (!S.getLangOpts().CPlusPlus20 && MD->isVirtual()) {
10486  S.Diag(AL.getLoc(), diag::err_ms_constexpr_cannot_be_applied)
10487  << /*virtual*/ 2 << MD;
10488  return;
10489  }
10490  }
10491  D->addAttr(::new (S.Context) MSConstexprAttr(S.Context, AL));
10492 }
10493 
10494 static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
10496  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
10497  StringRef Tag;
10498  if (!S.checkStringLiteralArgumentAttr(AL, I, Tag))
10499  return;
10500  Tags.push_back(Tag);
10501  }
10502 
10503  if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
10504  if (!NS->isInline()) {
10505  S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
10506  return;
10507  }
10508  if (NS->isAnonymousNamespace()) {
10509  S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
10510  return;
10511  }
10512  if (AL.getNumArgs() == 0)
10513  Tags.push_back(NS->getName());
10514  } else if (!AL.checkAtLeastNumArgs(S, 1))
10515  return;
10516 
10517  // Store tags sorted and without duplicates.
10518  llvm::sort(Tags);
10519  Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
10520 
10521  D->addAttr(::new (S.Context)
10522  AbiTagAttr(S.Context, AL, Tags.data(), Tags.size()));
10523 }
10524 
10525 static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
10526  // Check the attribute arguments.
10527  if (AL.getNumArgs() > 1) {
10528  S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
10529  return;
10530  }
10531 
10532  StringRef Str;
10533  SourceLocation ArgLoc;
10534 
10535  if (AL.getNumArgs() == 0)
10536  Str = "";
10537  else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
10538  return;
10539 
10540  ARMInterruptAttr::InterruptType Kind;
10541  if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
10542  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
10543  << ArgLoc;
10544  return;
10545  }
10546 
10547  D->addAttr(::new (S.Context) ARMInterruptAttr(S.Context, AL, Kind));
10548 }
10549 
10550 static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
10551  // MSP430 'interrupt' attribute is applied to
10552  // a function with no parameters and void return type.
10553  if (!isFunctionOrMethod(D)) {
10554  S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
10556  return;
10557  }
10558 
10559  if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
10560  S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
10561  << /*MSP430*/ 1 << 0;
10562  return;
10563  }
10564 
10565  if (!getFunctionOrMethodResultType(D)->isVoidType()) {
10566  S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
10567  << /*MSP430*/ 1 << 1;
10568  return;
10569  }
10570 
10571  // The attribute takes one integer argument.
10572  if (!AL.checkExactlyNumArgs(S, 1))
10573  return;
10574 
10575  if (!AL.isArgExpr(0)) {
10576  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
10578  return;
10579  }
10580 
10581  Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
10582  std::optional<llvm::APSInt> NumParams = llvm::APSInt(32);
10583  if (!(NumParams = NumParamsExpr->getIntegerConstantExpr(S.Context))) {
10584  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
10586  << NumParamsExpr->getSourceRange();
10587  return;
10588  }
10589  // The argument should be in range 0..63.
10590  unsigned Num = NumParams->getLimitedValue(255);
10591  if (Num > 63) {
10592  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
10593  << AL << (int)NumParams->getSExtValue()
10594  << NumParamsExpr->getSourceRange();
10595  return;
10596  }
10597 
10598  D->addAttr(::new (S.Context) MSP430InterruptAttr(S.Context, AL, Num));
10599  D->addAttr(UsedAttr::CreateImplicit(S.Context));
10600 }
10601 
10602 static void handleMipsInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
10603  // Only one optional argument permitted.
10604  if (AL.getNumArgs() > 1) {
10605  S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
10606  return;
10607  }
10608 
10609  StringRef Str;
10610  SourceLocation ArgLoc;
10611 
10612  if (AL.getNumArgs() == 0)
10613  Str = "";
10614  else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
10615  return;
10616 
10617  // Semantic checks for a function with the 'interrupt' attribute for MIPS:
10618  // a) Must be a function.
10619  // b) Must have no parameters.
10620  // c) Must have the 'void' return type.
10621  // d) Cannot have the 'mips16' attribute, as that instruction set
10622  // lacks the 'eret' instruction.
10623  // e) The attribute itself must either have no argument or one of the
10624  // valid interrupt types, see [MipsInterruptDocs].
10625 
10626  if (!isFunctionOrMethod(D)) {
10627  S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
10629  return;
10630  }
10631 
10632  if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
10633  S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
10634  << /*MIPS*/ 0 << 0;
10635  return;
10636  }
10637 
10638  if (!getFunctionOrMethodResultType(D)->isVoidType()) {
10639  S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
10640  << /*MIPS*/ 0 << 1;
10641  return;
10642  }
10643 
10644  // We still have to do this manually because the Interrupt attributes are
10645  // a bit special due to sharing their spellings across targets.
10646  if (checkAttrMutualExclusion<Mips16Attr>(S, D, AL))
10647  return;
10648 
10649  MipsInterruptAttr::InterruptType Kind;
10650  if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
10651  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
10652  << AL << "'" + std::string(Str) + "'";
10653  return;
10654  }
10655 
10656  D->addAttr(::new (S.Context) MipsInterruptAttr(S.Context, AL, Kind));
10657 }
10658 
10659 static void handleM68kInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
10660  if (!AL.checkExactlyNumArgs(S, 1))
10661  return;
10662 
10663  if (!AL.isArgExpr(0)) {
10664  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
10666  return;
10667  }
10668 
10669  // FIXME: Check for decl - it should be void ()(void).
10670 
10671  Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
10672  auto MaybeNumParams = NumParamsExpr->getIntegerConstantExpr(S.Context);
10673  if (!MaybeNumParams) {
10674  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
10676  << NumParamsExpr->getSourceRange();
10677  return;
10678  }
10679 
10680  unsigned Num = MaybeNumParams->getLimitedValue(255);
10681  if ((Num & 1) || Num > 30) {
10682  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
10683  << AL << (int)MaybeNumParams->getSExtValue()
10684  << NumParamsExpr->getSourceRange();
10685  return;
10686  }
10687 
10688  D->addAttr(::new (S.Context) M68kInterruptAttr(S.Context, AL, Num));
10689  D->addAttr(UsedAttr::CreateImplicit(S.Context));
10690 }
10691 
10692 static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
10693  // Semantic checks for a function with the 'interrupt' attribute.
10694  // a) Must be a function.
10695  // b) Must have the 'void' return type.
10696  // c) Must take 1 or 2 arguments.
10697  // d) The 1st argument must be a pointer.
10698  // e) The 2nd argument (if any) must be an unsigned integer.
10699  if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
10701  cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
10702  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
10703  << AL << AL.isRegularKeywordAttribute()
10705  return;
10706  }
10707  // Interrupt handler must have void return type.
10708  if (!getFunctionOrMethodResultType(D)->isVoidType()) {
10710  diag::err_anyx86_interrupt_attribute)
10711  << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
10712  ? 0
10713  : 1)
10714  << 0;
10715  return;
10716  }
10717  // Interrupt handler must have 1 or 2 parameters.
10718  unsigned NumParams = getFunctionOrMethodNumParams(D);
10719  if (NumParams < 1 || NumParams > 2) {
10720  S.Diag(D->getBeginLoc(), diag::err_anyx86_interrupt_attribute)
10721  << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
10722  ? 0
10723  : 1)
10724  << 1;
10725  return;
10726  }
10727  // The first argument must be a pointer.
10730  diag::err_anyx86_interrupt_attribute)
10731  << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
10732  ? 0
10733  : 1)
10734  << 2;
10735  return;
10736  }
10737  // The second argument, if present, must be an unsigned integer.
10738  unsigned TypeSize =
10739  S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
10740  ? 64
10741  : 32;
10742  if (NumParams == 2 &&
10743  (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
10744  S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
10746  diag::err_anyx86_interrupt_attribute)
10747  << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
10748  ? 0
10749  : 1)
10750  << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
10751  return;
10752  }
10753  D->addAttr(::new (S.Context) AnyX86InterruptAttr(S.Context, AL));
10754  D->addAttr(UsedAttr::CreateImplicit(S.Context));
10755 }
10756 
10757 static void handleAVRInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
10758  if (!isFunctionOrMethod(D)) {
10759  S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
10761  return;
10762  }
10763 
10764  if (!AL.checkExactlyNumArgs(S, 0))
10765  return;
10766 
10767  handleSimpleAttribute<AVRInterruptAttr>(S, D, AL);
10768 }
10769 
10770 static void handleAVRSignalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
10771  if (!isFunctionOrMethod(D)) {
10772  S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
10774  return;
10775  }
10776 
10777  if (!AL.checkExactlyNumArgs(S, 0))
10778  return;
10779 
10780  handleSimpleAttribute<AVRSignalAttr>(S, D, AL);
10781 }
10782 
10783 static void handleBPFPreserveAIRecord(Sema &S, RecordDecl *RD) {
10784  // Add preserve_access_index attribute to all fields and inner records.
10785  for (auto *D : RD->decls()) {
10786  if (D->hasAttr<BPFPreserveAccessIndexAttr>())
10787  continue;
10788 
10789  D->addAttr(BPFPreserveAccessIndexAttr::CreateImplicit(S.Context));
10790  if (auto *Rec = dyn_cast<RecordDecl>(D))
10791  handleBPFPreserveAIRecord(S, Rec);
10792  }
10793 }
10794 
10795 static void handleBPFPreserveAccessIndexAttr(Sema &S, Decl *D,
10796  const ParsedAttr &AL) {
10797  auto *Rec = cast<RecordDecl>(D);
10798  handleBPFPreserveAIRecord(S, Rec);
10799  Rec->addAttr(::new (S.Context) BPFPreserveAccessIndexAttr(S.Context, AL));
10800 }
10801 
10802 static bool hasBTFDeclTagAttr(Decl *D, StringRef Tag) {
10803  for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) {
10804  if (I->getBTFDeclTag() == Tag)
10805  return true;
10806  }
10807  return false;
10808 }
10809 
10810 static void handleBTFDeclTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
10811  StringRef Str;
10812  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
10813  return;
10814  if (hasBTFDeclTagAttr(D, Str))
10815  return;
10816 
10817  D->addAttr(::new (S.Context) BTFDeclTagAttr(S.Context, AL, Str));
10818 }
10819 
10820 BTFDeclTagAttr *Sema::mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL) {
10821  if (hasBTFDeclTagAttr(D, AL.getBTFDeclTag()))
10822  return nullptr;
10823  return ::new (Context) BTFDeclTagAttr(Context, AL, AL.getBTFDeclTag());
10824 }
10825 
10826 static void handleWebAssemblyExportNameAttr(Sema &S, Decl *D,
10827  const ParsedAttr &AL) {
10828  if (!isFunctionOrMethod(D)) {
10829  S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
10831  return;
10832  }
10833 
10834  auto *FD = cast<FunctionDecl>(D);
10835  if (FD->isThisDeclarationADefinition()) {
10836  S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
10837  return;
10838  }
10839 
10840  StringRef Str;
10841  SourceLocation ArgLoc;
10842  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
10843  return;
10844 
10845  D->addAttr(::new (S.Context) WebAssemblyExportNameAttr(S.Context, AL, Str));
10846  D->addAttr(UsedAttr::CreateImplicit(S.Context));
10847 }
10848 
10849 WebAssemblyImportModuleAttr *
10850 Sema::mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL) {
10851  auto *FD = cast<FunctionDecl>(D);
10852 
10853  if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
10854  if (ExistingAttr->getImportModule() == AL.getImportModule())
10855  return nullptr;
10856  Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 0
10857  << ExistingAttr->getImportModule() << AL.getImportModule();
10858  Diag(AL.getLoc(), diag::note_previous_attribute);
10859  return nullptr;
10860  }
10861  if (FD->hasBody()) {
10862  Diag(AL.getLoc(), diag::warn_import_on_definition) << 0;
10863  return nullptr;
10864  }
10865  return ::new (Context) WebAssemblyImportModuleAttr(Context, AL,
10866  AL.getImportModule());
10867 }
10868 
10869 WebAssemblyImportNameAttr *
10870 Sema::mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL) {
10871  auto *FD = cast<FunctionDecl>(D);
10872 
10873  if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportNameAttr>()) {
10874  if (ExistingAttr->getImportName() == AL.getImportName())
10875  return nullptr;
10876  Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 1
10877  << ExistingAttr->getImportName() << AL.getImportName();
10878  Diag(AL.getLoc(), diag::note_previous_attribute);
10879  return nullptr;
10880  }
10881  if (FD->hasBody()) {
10882  Diag(AL.getLoc(), diag::warn_import_on_definition) << 1;
10883  return nullptr;
10884  }
10885  return ::new (Context) WebAssemblyImportNameAttr(Context, AL,
10886  AL.getImportName());
10887 }
10888 
10889 static void
10890 handleWebAssemblyImportModuleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
10891  auto *FD = cast<FunctionDecl>(D);
10892 
10893  StringRef Str;
10894  SourceLocation ArgLoc;
10895  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
10896  return;
10897  if (FD->hasBody()) {
10898  S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 0;
10899  return;
10900  }
10901 
10902  FD->addAttr(::new (S.Context)
10903  WebAssemblyImportModuleAttr(S.Context, AL, Str));
10904 }
10905 
10906 static void
10907 handleWebAssemblyImportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
10908  auto *FD = cast<FunctionDecl>(D);
10909 
10910  StringRef Str;
10911  SourceLocation ArgLoc;
10912  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
10913  return;
10914  if (FD->hasBody()) {
10915  S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 1;
10916  return;
10917  }
10918 
10919  FD->addAttr(::new (S.Context) WebAssemblyImportNameAttr(S.Context, AL, Str));
10920 }
10921 
10922 static void handleRISCVInterruptAttr(Sema &S, Decl *D,
10923  const ParsedAttr &AL) {
10924  // Warn about repeated attributes.
10925  if (const auto *A = D->getAttr<RISCVInterruptAttr>()) {
10926  S.Diag(AL.getRange().getBegin(),
10927  diag::warn_riscv_repeated_interrupt_attribute);
10928  S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute);
10929  return;
10930  }
10931 
10932  // Check the attribute argument. Argument is optional.
10933  if (!AL.checkAtMostNumArgs(S, 1))
10934  return;
10935 
10936  StringRef Str;
10937  SourceLocation ArgLoc;
10938 
10939  // 'machine'is the default interrupt mode.
10940  if (AL.getNumArgs() == 0)
10941  Str = "machine";
10942  else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
10943  return;
10944 
10945  // Semantic checks for a function with the 'interrupt' attribute:
10946  // - Must be a function.
10947  // - Must have no parameters.
10948  // - Must have the 'void' return type.
10949  // - The attribute itself must either have no argument or one of the
10950  // valid interrupt types, see [RISCVInterruptDocs].
10951 
10952  if (D->getFunctionType() == nullptr) {
10953  S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
10955  return;
10956  }
10957 
10958  if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
10959  S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
10960  << /*RISC-V*/ 2 << 0;
10961  return;
10962  }
10963 
10964  if (!getFunctionOrMethodResultType(D)->isVoidType()) {
10965  S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
10966  << /*RISC-V*/ 2 << 1;
10967  return;
10968  }
10969 
10970  RISCVInterruptAttr::InterruptType Kind;
10971  if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
10972  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
10973  << ArgLoc;
10974  return;
10975  }
10976 
10977  D->addAttr(::new (S.Context) RISCVInterruptAttr(S.Context, AL, Kind));
10978 }
10979 
10980 static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
10981  // Dispatch the interrupt attribute based on the current target.
10982  switch (S.Context.getTargetInfo().getTriple().getArch()) {
10983  case llvm::Triple::msp430:
10984  handleMSP430InterruptAttr(S, D, AL);
10985  break;
10986  case llvm::Triple::mipsel:
10987  case llvm::Triple::mips:
10988  handleMipsInterruptAttr(S, D, AL);
10989  break;
10990  case llvm::Triple::m68k:
10991  handleM68kInterruptAttr(S, D, AL);
10992  break;
10993  case llvm::Triple::x86:
10994  case llvm::Triple::x86_64:
10995  handleAnyX86InterruptAttr(S, D, AL);
10996  break;
10997  case llvm::Triple::avr:
10998  handleAVRInterruptAttr(S, D, AL);
10999  break;
11000  case llvm::Triple::riscv32:
11001  case llvm::Triple::riscv64:
11002  handleRISCVInterruptAttr(S, D, AL);
11003  break;
11004  default:
11005  handleARMInterruptAttr(S, D, AL);
11006  break;
11007  }
11008 }
11009 
11010 static bool
11011 checkAMDGPUFlatWorkGroupSizeArguments(Sema &S, Expr *MinExpr, Expr *MaxExpr,
11012  const AMDGPUFlatWorkGroupSizeAttr &Attr) {
11013  // Accept template arguments for now as they depend on something else.
11014  // We'll get to check them when they eventually get instantiated.
11015  if (MinExpr->isValueDependent() || MaxExpr->isValueDependent())
11016  return false;
11017 
11018  uint32_t Min = 0;
11019  if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
11020  return true;
11021 
11022  uint32_t Max = 0;
11023  if (!checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
11024  return true;
11025 
11026  if (Min == 0 && Max != 0) {
11027  S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
11028  << &Attr << 0;
11029  return true;
11030  }
11031  if (Min > Max) {
11032  S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
11033  << &Attr << 1;
11034  return true;
11035  }
11036 
11037  return false;
11038 }
11039 
11040 AMDGPUFlatWorkGroupSizeAttr *
11042  Expr *MinExpr, Expr *MaxExpr) {
11043  AMDGPUFlatWorkGroupSizeAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
11044 
11045  if (checkAMDGPUFlatWorkGroupSizeArguments(*this, MinExpr, MaxExpr, TmpAttr))
11046  return nullptr;
11047  return ::new (Context)
11048  AMDGPUFlatWorkGroupSizeAttr(Context, CI, MinExpr, MaxExpr);
11049 }
11050 
11052  const AttributeCommonInfo &CI,
11053  Expr *MinExpr, Expr *MaxExpr) {
11054  if (auto *Attr = CreateAMDGPUFlatWorkGroupSizeAttr(CI, MinExpr, MaxExpr))
11055  D->addAttr(Attr);
11056 }
11057 
11058 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
11059  const ParsedAttr &AL) {
11060  Expr *MinExpr = AL.getArgAsExpr(0);
11061  Expr *MaxExpr = AL.getArgAsExpr(1);
11062 
11063  S.addAMDGPUFlatWorkGroupSizeAttr(D, AL, MinExpr, MaxExpr);
11064 }
11065 
11066 static bool checkAMDGPUWavesPerEUArguments(Sema &S, Expr *MinExpr,
11067  Expr *MaxExpr,
11068  const AMDGPUWavesPerEUAttr &Attr) {
11069  if (S.DiagnoseUnexpandedParameterPack(MinExpr) ||
11070  (MaxExpr && S.DiagnoseUnexpandedParameterPack(MaxExpr)))
11071  return true;
11072 
11073  // Accept template arguments for now as they depend on something else.
11074  // We'll get to check them when they eventually get instantiated.
11075  if (MinExpr->isValueDependent() || (MaxExpr && MaxExpr->isValueDependent()))
11076  return false;
11077 
11078  uint32_t Min = 0;
11079  if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
11080  return true;
11081 
11082  uint32_t Max = 0;
11083  if (MaxExpr && !checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
11084  return true;
11085 
11086  if (Min == 0 && Max != 0) {
11087  S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
11088  << &Attr << 0;
11089  return true;
11090  }
11091  if (Max != 0 && Min > Max) {
11092  S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
11093  << &Attr << 1;
11094  return true;
11095  }
11096 
11097  return false;
11098 }
11099 
11100 AMDGPUWavesPerEUAttr *
11102  Expr *MaxExpr) {
11103  AMDGPUWavesPerEUAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
11104 
11105  if (checkAMDGPUWavesPerEUArguments(*this, MinExpr, MaxExpr, TmpAttr))
11106  return nullptr;
11107 
11108  return ::new (Context) AMDGPUWavesPerEUAttr(Context, CI, MinExpr, MaxExpr);
11109 }
11110 
11112  Expr *MinExpr, Expr *MaxExpr) {
11113  if (auto *Attr = CreateAMDGPUWavesPerEUAttr(CI, MinExpr, MaxExpr))
11114  D->addAttr(Attr);
11115 }
11116 
11117 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
11118  if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2))
11119  return;
11120 
11121  Expr *MinExpr = AL.getArgAsExpr(0);
11122  Expr *MaxExpr = (AL.getNumArgs() > 1) ? AL.getArgAsExpr(1) : nullptr;
11123 
11124  S.addAMDGPUWavesPerEUAttr(D, AL, MinExpr, MaxExpr);
11125 }
11126 
11127 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
11128  uint32_t NumSGPR = 0;
11129  Expr *NumSGPRExpr = AL.getArgAsExpr(0);
11130  if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR))
11131  return;
11132 
11133  D->addAttr(::new (S.Context) AMDGPUNumSGPRAttr(S.Context, AL, NumSGPR));
11134 }
11135 
11136 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
11137  uint32_t NumVGPR = 0;
11138  Expr *NumVGPRExpr = AL.getArgAsExpr(0);
11139  if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR))
11140  return;
11141 
11142  D->addAttr(::new (S.Context) AMDGPUNumVGPRAttr(S.Context, AL, NumVGPR));
11143 }
11144 
11145 static bool
11146 checkAMDGPUMaxNumWorkGroupsArguments(Sema &S, Expr *XExpr, Expr *YExpr,
11147  Expr *ZExpr,
11148  const AMDGPUMaxNumWorkGroupsAttr &Attr) {
11149  if (S.DiagnoseUnexpandedParameterPack(XExpr) ||
11150  (YExpr && S.DiagnoseUnexpandedParameterPack(YExpr)) ||
11151  (ZExpr && S.DiagnoseUnexpandedParameterPack(ZExpr)))
11152  return true;
11153 
11154  // Accept template arguments for now as they depend on something else.
11155  // We'll get to check them when they eventually get instantiated.
11156  if (XExpr->isValueDependent() || (YExpr && YExpr->isValueDependent()) ||
11157  (ZExpr && ZExpr->isValueDependent()))
11158  return false;
11159 
11160  uint32_t NumWG = 0;
11161  Expr *Exprs[3] = {XExpr, YExpr, ZExpr};
11162  for (int i = 0; i < 3; i++) {
11163  if (Exprs[i]) {
11164  if (!checkUInt32Argument(S, Attr, Exprs[i], NumWG, i,
11165  /*StrictlyUnsigned=*/true))
11166  return true;
11167  if (NumWG == 0) {
11168  S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
11169  << &Attr << Exprs[i]->getSourceRange();
11170  return true;
11171  }
11172  }
11173  }
11174 
11175  return false;
11176 }
11177 
11178 AMDGPUMaxNumWorkGroupsAttr *
11180  Expr *XExpr, Expr *YExpr, Expr *ZExpr) {
11181  AMDGPUMaxNumWorkGroupsAttr TmpAttr(Context, CI, XExpr, YExpr, ZExpr);
11182 
11183  if (checkAMDGPUMaxNumWorkGroupsArguments(*this, XExpr, YExpr, ZExpr, TmpAttr))
11184  return nullptr;
11185 
11186  return ::new (Context)
11187  AMDGPUMaxNumWorkGroupsAttr(Context, CI, XExpr, YExpr, ZExpr);
11188 }
11189 
11191  Expr *XExpr, Expr *YExpr,
11192  Expr *ZExpr) {
11193  if (auto *Attr = CreateAMDGPUMaxNumWorkGroupsAttr(CI, XExpr, YExpr, ZExpr))
11194  D->addAttr(Attr);
11195 }
11196 
11197 static void handleAMDGPUMaxNumWorkGroupsAttr(Sema &S, Decl *D,
11198  const ParsedAttr &AL) {
11199  Expr *YExpr = (AL.getNumArgs() > 1) ? AL.getArgAsExpr(1) : nullptr;
11200  Expr *ZExpr = (AL.getNumArgs() > 2) ? AL.getArgAsExpr(2) : nullptr;
11201  S.addAMDGPUMaxNumWorkGroupsAttr(D, AL, AL.getArgAsExpr(0), YExpr, ZExpr);
11202 }
11203 
11204 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
11205  const ParsedAttr &AL) {
11206  // If we try to apply it to a function pointer, don't warn, but don't
11207  // do anything, either. It doesn't matter anyway, because there's nothing
11208  // special about calling a force_align_arg_pointer function.
11209  const auto *VD = dyn_cast<ValueDecl>(D);
11210  if (VD && VD->getType()->isFunctionPointerType())
11211  return;
11212  // Also don't warn on function pointer typedefs.
11213  const auto *TD = dyn_cast<TypedefNameDecl>(D);
11214  if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
11215  TD->getUnderlyingType()->isFunctionType()))
11216  return;
11217  // Attribute can only be applied to function types.
11218  if (!isa<FunctionDecl>(D)) {
11219  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
11221  return;
11222  }
11223 
11224  D->addAttr(::new (S.Context) X86ForceAlignArgPointerAttr(S.Context, AL));
11225 }
11226 
11227 static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) {
11228  uint32_t Version;
11229  Expr *VersionExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
11230  if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Version))
11231  return;
11232 
11233  // TODO: Investigate what happens with the next major version of MSVC.
11234  if (Version != LangOptions::MSVC2015 / 100) {
11235  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
11236  << AL << Version << VersionExpr->getSourceRange();
11237  return;
11238  }
11239 
11240  // The attribute expects a "major" version number like 19, but new versions of
11241  // MSVC have moved to updating the "minor", or less significant numbers, so we
11242  // have to multiply by 100 now.
11243  Version *= 100;
11244 
11245  D->addAttr(::new (S.Context) LayoutVersionAttr(S.Context, AL, Version));
11246 }
11247 
11248 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D,
11249  const AttributeCommonInfo &CI) {
11250  if (D->hasAttr<DLLExportAttr>()) {
11251  Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'dllimport'";
11252  return nullptr;
11253  }
11254 
11255  if (D->hasAttr<DLLImportAttr>())
11256  return nullptr;
11257 
11258  return ::new (Context) DLLImportAttr(Context, CI);
11259 }
11260 
11261 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D,
11262  const AttributeCommonInfo &CI) {
11263  if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
11264  Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
11265  D->dropAttr<DLLImportAttr>();
11266  }
11267 
11268  if (D->hasAttr<DLLExportAttr>())
11269  return nullptr;
11270 
11271  return ::new (Context) DLLExportAttr(Context, CI);
11272 }
11273 
11274 static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) {
11275  if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
11277  S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) << A;
11278  return;
11279  }
11280 
11281  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
11282  if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport &&
11284  // MinGW doesn't allow dllimport on inline functions.
11285  S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
11286  << A;
11287  return;
11288  }
11289  }
11290 
11291  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
11293  MD->getParent()->isLambda()) {
11294  S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A;
11295  return;
11296  }
11297  }
11298 
11299  Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport
11300  ? (Attr *)S.mergeDLLExportAttr(D, A)
11301  : (Attr *)S.mergeDLLImportAttr(D, A);
11302  if (NewAttr)
11303  D->addAttr(NewAttr);
11304 }
11305 
11306 MSInheritanceAttr *
11308  bool BestCase,
11309  MSInheritanceModel Model) {
11310  if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
11311  if (IA->getInheritanceModel() == Model)
11312  return nullptr;
11313  Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
11314  << 1 /*previous declaration*/;
11315  Diag(CI.getLoc(), diag::note_previous_ms_inheritance);
11316  D->dropAttr<MSInheritanceAttr>();
11317  }
11318 
11319  auto *RD = cast<CXXRecordDecl>(D);
11320  if (RD->hasDefinition()) {
11321  if (checkMSInheritanceAttrOnDefinition(RD, CI.getRange(), BestCase,
11322  Model)) {
11323  return nullptr;
11324  }
11325  } else {
11326  if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
11327  Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
11328  << 1 /*partial specialization*/;
11329  return nullptr;
11330  }
11331  if (RD->getDescribedClassTemplate()) {
11332  Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
11333  << 0 /*primary template*/;
11334  return nullptr;
11335  }
11336  }
11337 
11338  return ::new (Context) MSInheritanceAttr(Context, CI, BestCase);
11339 }
11340 
11341 static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
11342  // The capability attributes take a single string parameter for the name of
11343  // the capability they represent. The lockable attribute does not take any
11344  // parameters. However, semantically, both attributes represent the same
11345  // concept, and so they use the same semantic attribute. Eventually, the
11346  // lockable attribute will be removed.
11347  //
11348  // For backward compatibility, any capability which has no specified string
11349  // literal will be considered a "mutex."
11350  StringRef N("mutex");
11351  SourceLocation LiteralLoc;
11352  if (AL.getKind() == ParsedAttr::AT_Capability &&
11353  !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc))
11354  return;
11355 
11356  D->addAttr(::new (S.Context) CapabilityAttr(S.Context, AL, N));
11357 }
11358 
11359 static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
11360  SmallVector<Expr*, 1> Args;
11361  if (!checkLockFunAttrCommon(S, D, AL, Args))
11362  return;
11363 
11364  D->addAttr(::new (S.Context)
11365  AssertCapabilityAttr(S.Context, AL, Args.data(), Args.size()));
11366 }
11367 
11368 static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
11369  const ParsedAttr &AL) {
11370  SmallVector<Expr*, 1> Args;
11371  if (!checkLockFunAttrCommon(S, D, AL, Args))
11372  return;
11373 
11374  D->addAttr(::new (S.Context) AcquireCapabilityAttr(S.Context, AL, Args.data(),
11375  Args.size()));
11376 }
11377 
11378 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
11379  const ParsedAttr &AL) {
11380  SmallVector<Expr*, 2> Args;
11381  if (!checkTryLockFunAttrCommon(S, D, AL, Args))
11382  return;
11383 
11384  D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(
11385  S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
11386 }
11387 
11388 static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
11389  const ParsedAttr &AL) {
11390  // Check that all arguments are lockable objects.
11392  checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, true);
11393 
11394  D->addAttr(::new (S.Context) ReleaseCapabilityAttr(S.Context, AL, Args.data(),
11395  Args.size()));
11396 }
11397 
11398 static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
11399  const ParsedAttr &AL) {
11400  if (!AL.checkAtLeastNumArgs(S, 1))
11401  return;
11402 
11403  // check that all arguments are lockable objects
11404  SmallVector<Expr*, 1> Args;
11405  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
11406  if (Args.empty())
11407  return;
11408 
11409  RequiresCapabilityAttr *RCA = ::new (S.Context)
11410  RequiresCapabilityAttr(S.Context, AL, Args.data(), Args.size());
11411 
11412  D->addAttr(RCA);
11413 }
11414 
11415 static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
11416  if (const auto *NSD = dyn_cast<NamespaceDecl>(D)) {
11417  if (NSD->isAnonymousNamespace()) {
11418  S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace);
11419  // Do not want to attach the attribute to the namespace because that will
11420  // cause confusing diagnostic reports for uses of declarations within the
11421  // namespace.
11422  return;
11423  }
11426  S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using)
11427  << AL;
11428  return;
11429  }
11430 
11431  // Handle the cases where the attribute has a text message.
11432  StringRef Str, Replacement;
11433  if (AL.isArgExpr(0) && AL.getArgAsExpr(0) &&
11434  !S.checkStringLiteralArgumentAttr(AL, 0, Str))
11435  return;
11436 
11437  // Support a single optional message only for Declspec and [[]] spellings.
11438  if (AL.isDeclspecAttribute() || AL.isStandardAttributeSyntax())
11439  AL.checkAtMostNumArgs(S, 1);
11440  else if (AL.isArgExpr(1) && AL.getArgAsExpr(1) &&
11441  !S.checkStringLiteralArgumentAttr(AL, 1, Replacement))
11442  return;
11443 
11444  if (!S.getLangOpts().CPlusPlus14 && AL.isCXX11Attribute() && !AL.isGNUScope())
11445  S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL;
11446 
11447  D->addAttr(::new (S.Context) DeprecatedAttr(S.Context, AL, Str, Replacement));
11448 }
11449 
11450 static bool isGlobalVar(const Decl *D) {
11451  if (const auto *S = dyn_cast<VarDecl>(D))
11452  return S->hasGlobalStorage();
11453  return false;
11454 }
11455 
11456 static bool isSanitizerAttributeAllowedOnGlobals(StringRef Sanitizer) {
11457  return Sanitizer == "address" || Sanitizer == "hwaddress" ||
11458  Sanitizer == "memtag";
11459 }
11460 
11461 static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
11462  if (!AL.checkAtLeastNumArgs(S, 1))
11463  return;
11464 
11465  std::vector<StringRef> Sanitizers;
11466 
11467  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
11468  StringRef SanitizerName;
11469  SourceLocation LiteralLoc;
11470 
11471  if (!S.checkStringLiteralArgumentAttr(AL, I, SanitizerName, &LiteralLoc))
11472  return;
11473 
11474  if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) ==
11475  SanitizerMask() &&
11476  SanitizerName != "coverage")
11477  S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
11478  else if (isGlobalVar(D) && !isSanitizerAttributeAllowedOnGlobals(SanitizerName))
11479  S.Diag(D->getLocation(), diag::warn_attribute_type_not_supported_global)
11480  << AL << SanitizerName;
11481  Sanitizers.push_back(SanitizerName);
11482  }
11483 
11484  D->addAttr(::new (S.Context) NoSanitizeAttr(S.Context, AL, Sanitizers.data(),
11485  Sanitizers.size()));
11486 }
11487 
11488 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
11489  const ParsedAttr &AL) {
11490  StringRef AttrName = AL.getAttrName()->getName();
11491  normalizeName(AttrName);
11492  StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
11493  .Case("no_address_safety_analysis", "address")
11494  .Case("no_sanitize_address", "address")
11495  .Case("no_sanitize_thread", "thread")
11496  .Case("no_sanitize_memory", "memory");
11497  if (isGlobalVar(D) && SanitizerName != "address")
11498  S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
11500 
11501  // FIXME: Rather than create a NoSanitizeSpecificAttr, this creates a
11502  // NoSanitizeAttr object; but we need to calculate the correct spelling list
11503  // index rather than incorrectly assume the index for NoSanitizeSpecificAttr
11504  // has the same spellings as the index for NoSanitizeAttr. We don't have a
11505  // general way to "translate" between the two, so this hack attempts to work
11506  // around the issue with hard-coded indices. This is critical for calling
11507  // getSpelling() or prettyPrint() on the resulting semantic attribute object
11508  // without failing assertions.
11509  unsigned TranslatedSpellingIndex = 0;
11510  if (AL.isStandardAttributeSyntax())
11511  TranslatedSpellingIndex = 1;
11512 
11513  AttributeCommonInfo Info = AL;
11514  Info.setAttributeSpellingListIndex(TranslatedSpellingIndex);
11515  D->addAttr(::new (S.Context)
11516  NoSanitizeAttr(S.Context, Info, &SanitizerName, 1));
11517 }
11518 
11519 static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
11520  if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, AL))
11521  D->addAttr(Internal);
11522 }
11523 
11524 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
11525  if (S.LangOpts.getOpenCLCompatibleVersion() < 200)
11526  S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version)
11527  << AL << "2.0" << 1;
11528  else
11529  S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored)
11530  << AL << S.LangOpts.getOpenCLVersionString();
11531 }
11532 
11533 static void handleOpenCLAccessAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
11534  if (D->isInvalidDecl())
11535  return;
11536 
11537  // Check if there is only one access qualifier.
11538  if (D->hasAttr<OpenCLAccessAttr>()) {
11539  if (D->getAttr<OpenCLAccessAttr>()->getSemanticSpelling() ==
11540  AL.getSemanticSpelling()) {
11541  S.Diag(AL.getLoc(), diag::warn_duplicate_declspec)
11542  << AL.getAttrName()->getName() << AL.getRange();
11543  } else {
11544  S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers)
11545  << D->getSourceRange();
11546  D->setInvalidDecl(true);
11547  return;
11548  }
11549  }
11550 
11551  // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that
11552  // an image object can be read and written. OpenCL v2.0 s6.13.6 - A kernel
11553  // cannot read from and write to the same pipe object. Using the read_write
11554  // (or __read_write) qualifier with the pipe qualifier is a compilation error.
11555  // OpenCL v3.0 s6.8 - For OpenCL C 2.0, or with the
11556  // __opencl_c_read_write_images feature, image objects specified as arguments
11557  // to a kernel can additionally be declared to be read-write.
11558  // C++ for OpenCL 1.0 inherits rule from OpenCL C v2.0.
11559  // C++ for OpenCL 2021 inherits rule from OpenCL C v3.0.
11560  if (const auto *PDecl = dyn_cast<ParmVarDecl>(D)) {
11561  const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
11562  if (AL.getAttrName()->getName().contains("read_write")) {
11563  bool ReadWriteImagesUnsupported =
11564  (S.getLangOpts().getOpenCLCompatibleVersion() < 200) ||
11565  (S.getLangOpts().getOpenCLCompatibleVersion() == 300 &&
11566  !S.getOpenCLOptions().isSupported("__opencl_c_read_write_images",
11567  S.getLangOpts()));
11568  if (ReadWriteImagesUnsupported || DeclTy->isPipeType()) {
11569  S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write)
11570  << AL << PDecl->getType() << DeclTy->isImageType();
11571  D->setInvalidDecl(true);
11572  return;
11573  }
11574  }
11575  }
11576 
11577  D->addAttr(::new (S.Context) OpenCLAccessAttr(S.Context, AL));
11578 }
11579 
11580 static void handleZeroCallUsedRegsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
11581  // Check that the argument is a string literal.
11582  StringRef KindStr;
11583  SourceLocation LiteralLoc;
11584  if (!S.checkStringLiteralArgumentAttr(AL, 0, KindStr, &LiteralLoc))
11585  return;
11586 
11587  ZeroCallUsedRegsAttr::ZeroCallUsedRegsKind Kind;
11588  if (!ZeroCallUsedRegsAttr::ConvertStrToZeroCallUsedRegsKind(KindStr, Kind)) {
11589  S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
11590  << AL << KindStr;
11591  return;
11592  }
11593 
11594  D->dropAttr<ZeroCallUsedRegsAttr>();
11595  D->addAttr(ZeroCallUsedRegsAttr::Create(S.Context, Kind, AL));
11596 }
11597 
11598 static const RecordDecl *GetEnclosingNamedOrTopAnonRecord(const FieldDecl *FD) {
11599  const auto *RD = FD->getParent();
11600  // An unnamed struct is anonymous struct only if it's not instantiated.
11601  // However, the struct may not be fully processed yet to determine
11602  // whether it's anonymous or not. In that case, this function treats it as
11603  // an anonymous struct and tries to find a named parent.
11604  while (RD && (RD->isAnonymousStructOrUnion() ||
11605  (!RD->isCompleteDefinition() && RD->getName().empty()))) {
11606  const auto *Parent = dyn_cast<RecordDecl>(RD->getParent());
11607  if (!Parent)
11608  break;
11609  RD = Parent;
11610  }
11611  return RD;
11612 }
11613 
11614 static bool
11615 CheckCountExpr(Sema &S, FieldDecl *FD, Expr *E,
11617  if (FD->getParent()->isUnion()) {
11618  S.Diag(FD->getBeginLoc(), diag::err_counted_by_attr_in_union)
11619  << FD->getSourceRange();
11620  return true;
11621  }
11622 
11623  if (!E->getType()->isIntegerType() || E->getType()->isBooleanType()) {
11624  S.Diag(E->getBeginLoc(), diag::err_counted_by_attr_argument_not_integer)
11625  << E->getSourceRange();
11626  return true;
11627  }
11628 
11629  LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel =
11631 
11633  StrictFlexArraysLevel, true)) {
11634  // The "counted_by" attribute must be on a flexible array member.
11635  SourceRange SR = FD->getLocation();
11636  S.Diag(SR.getBegin(),
11637  diag::err_counted_by_attr_not_on_flexible_array_member)
11638  << SR;
11639  return true;
11640  }
11641 
11642  auto *DRE = dyn_cast<DeclRefExpr>(E);
11643  if (!DRE) {
11644  S.Diag(E->getBeginLoc(),
11645  diag::err_counted_by_attr_only_support_simple_decl_reference)
11646  << E->getSourceRange();
11647  return true;
11648  }
11649 
11650  auto *CountDecl = DRE->getDecl();
11651  FieldDecl *CountFD = dyn_cast<FieldDecl>(CountDecl);
11652  if (auto *IFD = dyn_cast<IndirectFieldDecl>(CountDecl)) {
11653  CountFD = IFD->getAnonField();
11654  }
11655  if (!CountFD) {
11656  S.Diag(E->getBeginLoc(), diag::err_counted_by_must_be_in_structure)
11657  << CountDecl << E->getSourceRange();
11658 
11659  S.Diag(CountDecl->getBeginLoc(),
11660  diag::note_flexible_array_counted_by_attr_field)
11661  << CountDecl << CountDecl->getSourceRange();
11662  return true;
11663  }
11664 
11665  if (FD->getParent() != CountFD->getParent()) {
11666  if (CountFD->getParent()->isUnion()) {
11667  S.Diag(CountFD->getBeginLoc(), diag::err_counted_by_attr_refer_to_union)
11668  << CountFD->getSourceRange();
11669  return true;
11670  }
11671  // Whether CountRD is an anonymous struct is not determined at this
11672  // point. Thus, an additional diagnostic in case it's not anonymous struct
11673  // is done later in `Parser::ParseStructDeclaration`.
11674  auto *RD = GetEnclosingNamedOrTopAnonRecord(FD);
11675  auto *CountRD = GetEnclosingNamedOrTopAnonRecord(CountFD);
11676 
11677  if (RD != CountRD) {
11678  S.Diag(E->getBeginLoc(),
11679  diag::err_flexible_array_count_not_in_same_struct)
11680  << CountFD << E->getSourceRange();
11681  S.Diag(CountFD->getBeginLoc(),
11682  diag::note_flexible_array_counted_by_attr_field)
11683  << CountFD << CountFD->getSourceRange();
11684  return true;
11685  }
11686  }
11687 
11688  Decls.push_back(TypeCoupledDeclRefInfo(CountFD, /*IsDref*/ false));
11689  return false;
11690 }
11691 
11692 static void handleCountedByAttrField(Sema &S, Decl *D, const ParsedAttr &AL) {
11693  auto *FD = dyn_cast<FieldDecl>(D);
11694  assert(FD);
11695 
11696  auto *CountExpr = AL.getArgAsExpr(0);
11697  if (!CountExpr)
11698  return;
11699 
11701  if (CheckCountExpr(S, FD, CountExpr, Decls))
11702  return;
11703 
11704  QualType CAT = S.BuildCountAttributedArrayType(FD->getType(), CountExpr);
11705  FD->setType(CAT);
11706 }
11707 
11708 static void handleFunctionReturnThunksAttr(Sema &S, Decl *D,
11709  const ParsedAttr &AL) {
11710  StringRef KindStr;
11711  SourceLocation LiteralLoc;
11712  if (!S.checkStringLiteralArgumentAttr(AL, 0, KindStr, &LiteralLoc))
11713  return;
11714 
11716  if (!FunctionReturnThunksAttr::ConvertStrToKind(KindStr, Kind)) {
11717  S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
11718  << AL << KindStr;
11719  return;
11720  }
11721  // FIXME: it would be good to better handle attribute merging rather than
11722  // silently replacing the existing attribute, so long as it does not break
11723  // the expected codegen tests.
11724  D->dropAttr<FunctionReturnThunksAttr>();
11725  D->addAttr(FunctionReturnThunksAttr::Create(S.Context, Kind, AL));
11726 }
11727 
11728 bool isDeviceAspectType(const QualType Ty) {
11729  const EnumType *ET = Ty->getAs<EnumType>();
11730  if (!ET)
11731  return false;
11732 
11733  if (const auto *Attr = ET->getDecl()->getAttr<SYCLTypeAttr>())
11734  return Attr->getType() == SYCLTypeAttr::aspect;
11735 
11736  return false;
11737 }
11738 
11739 SYCLDeviceHasAttr *Sema::MergeSYCLDeviceHasAttr(Decl *D,
11740  const SYCLDeviceHasAttr &A) {
11741  if (const auto *ExistingAttr = D->getAttr<SYCLDeviceHasAttr>()) {
11742  Diag(ExistingAttr->getLoc(), diag::warn_duplicate_attribute_exact) << &A;
11743  Diag(A.getLoc(), diag::note_previous_attribute);
11744  return nullptr;
11745  }
11746 
11748  for (auto *E : A.aspects())
11749  Args.push_back(E);
11750  return ::new (Context)
11751  SYCLDeviceHasAttr(Context, A, Args.data(), Args.size());
11752 }
11753 
11755  Expr **Exprs, unsigned Size) {
11756 
11757  SYCLDeviceHasAttr TmpAttr(Context, CI, Exprs, Size);
11758  SmallVector<Expr *, 5> Aspects;
11759  for (auto *E : TmpAttr.aspects())
11760  if (!isa<PackExpansionExpr>(E) && !isDeviceAspectType(E->getType()))
11761  Diag(E->getExprLoc(), diag::err_sycl_invalid_aspect_argument) << CI;
11762 
11763  if (const auto *ExistingAttr = D->getAttr<SYCLDeviceHasAttr>()) {
11764  Diag(CI.getLoc(), diag::warn_duplicate_attribute_exact) << CI;
11765  Diag(ExistingAttr->getLoc(), diag::note_previous_attribute);
11766  return;
11767  }
11768 
11769  D->addAttr(::new (Context) SYCLDeviceHasAttr(Context, CI, Exprs, Size));
11770 }
11771 
11772 static void handleSYCLDeviceHasAttr(Sema &S, Decl *D, const ParsedAttr &A) {
11773  // Ignore the attribute if compiling for the host side because aspects may not
11774  // be marked properly for such compilation
11775  if (!S.Context.getLangOpts().SYCLIsDevice)
11776  return;
11777 
11779  for (unsigned I = 0; I < A.getNumArgs(); ++I)
11780  Args.push_back(A.getArgAsExpr(I));
11781 
11782  S.AddSYCLDeviceHasAttr(D, A, Args.data(), Args.size());
11783 }
11784 
11785 SYCLUsesAspectsAttr *
11786 Sema::MergeSYCLUsesAspectsAttr(Decl *D, const SYCLUsesAspectsAttr &A) {
11787  if (const auto *ExistingAttr = D->getAttr<SYCLUsesAspectsAttr>()) {
11788  Diag(ExistingAttr->getLoc(), diag::warn_duplicate_attribute_exact) << &A;
11789  Diag(A.getLoc(), diag::note_previous_attribute);
11790  return nullptr;
11791  }
11792 
11794  for (auto *E : A.aspects())
11795  Args.push_back(E);
11796  return ::new (Context)
11797  SYCLUsesAspectsAttr(Context, A, Args.data(), Args.size());
11798 }
11799 
11801  Expr **Exprs, unsigned Size) {
11802 
11803  SYCLUsesAspectsAttr TmpAttr(Context, CI, Exprs, Size);
11804  SmallVector<Expr *, 5> Aspects;
11805  for (auto *E : TmpAttr.aspects())
11806  if (!isDeviceAspectType(E->getType()))
11807  Diag(E->getExprLoc(), diag::err_sycl_invalid_aspect_argument) << CI;
11808 
11809  if (const auto *ExistingAttr = D->getAttr<SYCLUsesAspectsAttr>()) {
11810  Diag(CI.getLoc(), diag::warn_duplicate_attribute_exact) << CI;
11811  Diag(ExistingAttr->getLoc(), diag::note_previous_attribute);
11812  return;
11813  }
11814 
11815  D->addAttr(::new (Context) SYCLUsesAspectsAttr(Context, CI, Exprs, Size));
11816 }
11817 
11818 static void handleSYCLUsesAspectsAttr(Sema &S, Decl *D, const ParsedAttr &A) {
11819  // Ignore the attribute if compiling for the host because aspects may not be
11820  // marked properly for such compilation
11821  if (!S.Context.getLangOpts().SYCLIsDevice)
11822  return;
11823 
11825  for (unsigned I = 0; I < A.getNumArgs(); ++I)
11826  Args.push_back(A.getArgAsExpr(I));
11827 
11828  S.AddSYCLUsesAspectsAttr(D, A, Args.data(), Args.size());
11829 }
11830 
11831 static void handleAvailableOnlyInDefaultEvalMethod(Sema &S, Decl *D,
11832  const ParsedAttr &AL) {
11833  assert(isa<TypedefNameDecl>(D) && "This attribute only applies to a typedef");
11834  handleSimpleAttribute<AvailableOnlyInDefaultEvalMethodAttr>(S, D, AL);
11835 }
11836 
11837 static void handleNoMergeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
11838  auto *VDecl = dyn_cast<VarDecl>(D);
11839  if (VDecl && !VDecl->isFunctionPointerType()) {
11840  S.Diag(AL.getLoc(), diag::warn_attribute_ignored_non_function_pointer)
11841  << AL << VDecl;
11842  return;
11843  }
11844  D->addAttr(NoMergeAttr::Create(S.Context, AL));
11845 }
11846 
11847 static void handleNoUniqueAddressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
11848  D->addAttr(NoUniqueAddressAttr::Create(S.Context, AL));
11849 }
11850 
11851 static void handleSYCLKernelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
11852  // The 'sycl_kernel' attribute applies only to function templates.
11853  const auto *FD = cast<FunctionDecl>(D);
11854  const FunctionTemplateDecl *FT = FD->getDescribedFunctionTemplate();
11855  assert(FT && "Function template is expected");
11856 
11857  // Function template must have at least two template parameters so it
11858  // can be used in OpenCL kernel generation.
11859  const TemplateParameterList *TL = FT->getTemplateParameters();
11860  if (TL->size() < 2) {
11861  S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_template_params);
11862  return;
11863  }
11864 
11865  // The first two template parameters must be typenames.
11866  for (unsigned I = 0; I < 2 && I < TL->size(); ++I) {
11867  const NamedDecl *TParam = TL->getParam(I);
11868  if (isa<NonTypeTemplateParmDecl>(TParam)) {
11869  S.Diag(FT->getLocation(),
11870  diag::warn_sycl_kernel_invalid_template_param_type);
11871  return;
11872  }
11873  }
11874 
11875  // Function must have at least one parameter.
11876  if (getFunctionOrMethodNumParams(D) < 1) {
11877  S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_function_params);
11878  return;
11879  }
11880 
11881  // Function must return void.
11883  if (!RetTy->isVoidType()) {
11884  S.Diag(FT->getLocation(), diag::warn_sycl_kernel_return_type);
11885  return;
11886  }
11887 
11888  handleSimpleAttribute<SYCLKernelAttr>(S, D, AL);
11889 }
11890 
11891 SYCLTypeAttr *Sema::MergeSYCLTypeAttr(Decl *D, const AttributeCommonInfo &CI,
11892  SYCLTypeAttr::SYCLType TypeName) {
11893  if (const auto *ExistingAttr = D->getAttr<SYCLTypeAttr>()) {
11894  if (ExistingAttr->getType() != TypeName) {
11895  Diag(ExistingAttr->getLoc(), diag::err_duplicate_attribute)
11896  << ExistingAttr;
11897  Diag(CI.getLoc(), diag::note_previous_attribute);
11898  }
11899  // Do not add duplicate attribute
11900  return nullptr;
11901  }
11902  return ::new (Context) SYCLTypeAttr(Context, CI, TypeName);
11903 }
11904 
11905 static void handleSYCLTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
11906  if (!AL.isArgIdent(0)) {
11907  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
11908  << AL << AANT_ArgumentIdentifier;
11909  return;
11910  }
11911 
11912  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
11913  SYCLTypeAttr::SYCLType Type;
11914 
11915  if (!SYCLTypeAttr::ConvertStrToSYCLType(II->getName(), Type)) {
11916  S.Diag(AL.getLoc(), diag::err_attribute_argument_not_supported) << AL << II;
11917  return;
11918  }
11919 
11920  if (SYCLTypeAttr *NewAttr = S.MergeSYCLTypeAttr(D, AL, Type))
11921  D->addAttr(NewAttr);
11922 }
11923 
11924 static void handleDestroyAttr(Sema &S, Decl *D, const ParsedAttr &A) {
11925  if (!cast<VarDecl>(D)->hasGlobalStorage()) {
11926  S.Diag(D->getLocation(), diag::err_destroy_attr_on_non_static_var)
11927  << (A.getKind() == ParsedAttr::AT_AlwaysDestroy);
11928  return;
11929  }
11930 
11931  if (A.getKind() == ParsedAttr::AT_AlwaysDestroy)
11932  handleSimpleAttribute<AlwaysDestroyAttr>(S, D, A);
11933  else
11934  handleSimpleAttribute<NoDestroyAttr>(S, D, A);
11935 }
11936 
11937 static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
11938  assert(cast<VarDecl>(D)->getStorageDuration() == SD_Automatic &&
11939  "uninitialized is only valid on automatic duration variables");
11940  D->addAttr(::new (S.Context) UninitializedAttr(S.Context, AL));
11941 }
11942 
11943 static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD,
11944  bool DiagnoseFailure) {
11945  QualType Ty = VD->getType();
11946  if (!Ty->isObjCRetainableType()) {
11947  if (DiagnoseFailure) {
11948  S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
11949  << 0;
11950  }
11951  return false;
11952  }
11953 
11955 
11956  // SemaObjC::inferObjCARCLifetime must run after processing decl attributes
11957  // (because __block lowers to an attribute), so if the lifetime hasn't been
11958  // explicitly specified, infer it locally now.
11959  if (LifetimeQual == Qualifiers::OCL_None)
11960  LifetimeQual = Ty->getObjCARCImplicitLifetime();
11961 
11962  // The attributes only really makes sense for __strong variables; ignore any
11963  // attempts to annotate a parameter with any other lifetime qualifier.
11964  if (LifetimeQual != Qualifiers::OCL_Strong) {
11965  if (DiagnoseFailure) {
11966  S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
11967  << 1;
11968  }
11969  return false;
11970  }
11971 
11972  // Tampering with the type of a VarDecl here is a bit of a hack, but we need
11973  // to ensure that the variable is 'const' so that we can error on
11974  // modification, which can otherwise over-release.
11975  VD->setType(Ty.withConst());
11976  VD->setARCPseudoStrong(true);
11977  return true;
11978 }
11979 
11980 static void handleObjCExternallyRetainedAttr(Sema &S, Decl *D,
11981  const ParsedAttr &AL) {
11982  if (auto *VD = dyn_cast<VarDecl>(D)) {
11983  assert(!isa<ParmVarDecl>(VD) && "should be diagnosed automatically");
11984  if (!VD->hasLocalStorage()) {
11985  S.Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
11986  << 0;
11987  return;
11988  }
11989 
11990  if (!tryMakeVariablePseudoStrong(S, VD, /*DiagnoseFailure=*/true))
11991  return;
11992 
11993  handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
11994  return;
11995  }
11996 
11997  // If D is a function-like declaration (method, block, or function), then we
11998  // make every parameter psuedo-strong.
11999  unsigned NumParams =
12001  for (unsigned I = 0; I != NumParams; ++I) {
12002  auto *PVD = const_cast<ParmVarDecl *>(getFunctionOrMethodParam(D, I));
12003  QualType Ty = PVD->getType();
12004 
12005  // If a user wrote a parameter with __strong explicitly, then assume they
12006  // want "real" strong semantics for that parameter. This works because if
12007  // the parameter was written with __strong, then the strong qualifier will
12008  // be non-local.
12011  continue;
12012 
12013  tryMakeVariablePseudoStrong(S, PVD, /*DiagnoseFailure=*/false);
12014  }
12015  handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
12016 }
12017 
12018 static void handleMIGServerRoutineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
12019  // Check that the return type is a `typedef int kern_return_t` or a typedef
12020  // around it, because otherwise MIG convention checks make no sense.
12021  // BlockDecl doesn't store a return type, so it's annoying to check,
12022  // so let's skip it for now.
12023  if (!isa<BlockDecl>(D)) {
12025  bool IsKernReturnT = false;
12026  while (const auto *TT = T->getAs<TypedefType>()) {
12027  IsKernReturnT = (TT->getDecl()->getName() == "kern_return_t");
12028  T = TT->desugar();
12029  }
12030  if (!IsKernReturnT || T.getCanonicalType() != S.getASTContext().IntTy) {
12031  S.Diag(D->getBeginLoc(),
12032  diag::warn_mig_server_routine_does_not_return_kern_return_t);
12033  return;
12034  }
12035  }
12036 
12037  handleSimpleAttribute<MIGServerRoutineAttr>(S, D, AL);
12038 }
12039 
12040 static void handleMSAllocatorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
12041  // Warn if the return type is not a pointer or reference type.
12042  if (auto *FD = dyn_cast<FunctionDecl>(D)) {
12043  QualType RetTy = FD->getReturnType();
12044  if (!RetTy->isPointerType() && !RetTy->isReferenceType()) {
12045  S.Diag(AL.getLoc(), diag::warn_declspec_allocator_nonpointer)
12046  << AL.getRange() << RetTy;
12047  return;
12048  }
12049  }
12050 
12051  handleSimpleAttribute<MSAllocatorAttr>(S, D, AL);
12052 }
12053 
12054 static void handleAcquireHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
12055  if (AL.isUsedAsTypeAttr())
12056  return;
12057  // Warn if the parameter is definitely not an output parameter.
12058  if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
12059  if (PVD->getType()->isIntegerType()) {
12060  S.Diag(AL.getLoc(), diag::err_attribute_output_parameter)
12061  << AL.getRange();
12062  return;
12063  }
12064  }
12065  StringRef Argument;
12066  if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
12067  return;
12068  D->addAttr(AcquireHandleAttr::Create(S.Context, Argument, AL));
12069 }
12070 
12071 template<typename Attr>
12072 static void handleHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
12073  StringRef Argument;
12074  if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
12075  return;
12076  D->addAttr(Attr::Create(S.Context, Argument, AL));
12077 }
12078 
12079 template<typename Attr>
12080 static void handleUnsafeBufferUsage(Sema &S, Decl *D, const ParsedAttr &AL) {
12081  D->addAttr(Attr::Create(S.Context, AL));
12082 }
12083 
12084 static void handleCFGuardAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
12085  // The guard attribute takes a single identifier argument.
12086 
12087  if (!AL.isArgIdent(0)) {
12088  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
12089  << AL << AANT_ArgumentIdentifier;
12090  return;
12091  }
12092 
12093  CFGuardAttr::GuardArg Arg;
12094  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
12095  if (!CFGuardAttr::ConvertStrToGuardArg(II->getName(), Arg)) {
12096  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
12097  return;
12098  }
12099 
12100  D->addAttr(::new (S.Context) CFGuardAttr(S.Context, AL, Arg));
12101 }
12102 
12103 
12104 template <typename AttrTy>
12105 static const AttrTy *findEnforceTCBAttrByName(Decl *D, StringRef Name) {
12106  auto Attrs = D->specific_attrs<AttrTy>();
12107  auto I = llvm::find_if(Attrs,
12108  [Name](const AttrTy *A) {
12109  return A->getTCBName() == Name;
12110  });
12111  return I == Attrs.end() ? nullptr : *I;
12112 }
12113 
12114 template <typename AttrTy, typename ConflictingAttrTy>
12115 static void handleEnforceTCBAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
12116  StringRef Argument;
12117  if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument))
12118  return;
12119 
12120  // A function cannot be have both regular and leaf membership in the same TCB.
12121  if (const ConflictingAttrTy *ConflictingAttr =
12122  findEnforceTCBAttrByName<ConflictingAttrTy>(D, Argument)) {
12123  // We could attach a note to the other attribute but in this case
12124  // there's no need given how the two are very close to each other.
12125  S.Diag(AL.getLoc(), diag::err_tcb_conflicting_attributes)
12126  << AL.getAttrName()->getName() << ConflictingAttr->getAttrName()->getName()
12127  << Argument;
12128 
12129  // Error recovery: drop the non-leaf attribute so that to suppress
12130  // all future warnings caused by erroneous attributes. The leaf attribute
12131  // needs to be kept because it can only suppresses warnings, not cause them.
12132  D->dropAttr<EnforceTCBAttr>();
12133  return;
12134  }
12135 
12136  D->addAttr(AttrTy::Create(S.Context, Argument, AL));
12137 }
12138 
12139 template <typename AttrTy, typename ConflictingAttrTy>
12140 static AttrTy *mergeEnforceTCBAttrImpl(Sema &S, Decl *D, const AttrTy &AL) {
12141  // Check if the new redeclaration has different leaf-ness in the same TCB.
12142  StringRef TCBName = AL.getTCBName();
12143  if (const ConflictingAttrTy *ConflictingAttr =
12144  findEnforceTCBAttrByName<ConflictingAttrTy>(D, TCBName)) {
12145  S.Diag(ConflictingAttr->getLoc(), diag::err_tcb_conflicting_attributes)
12146  << ConflictingAttr->getAttrName()->getName()
12147  << AL.getAttrName()->getName() << TCBName;
12148 
12149  // Add a note so that the user could easily find the conflicting attribute.
12150  S.Diag(AL.getLoc(), diag::note_conflicting_attribute);
12151 
12152  // More error recovery.
12153  D->dropAttr<EnforceTCBAttr>();
12154  return nullptr;
12155  }
12156 
12157  ASTContext &Context = S.getASTContext();
12158  return ::new(Context) AttrTy(Context, AL, AL.getTCBName());
12159 }
12160 
12161 EnforceTCBAttr *Sema::mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL) {
12162  return mergeEnforceTCBAttrImpl<EnforceTCBAttr, EnforceTCBLeafAttr>(
12163  *this, D, AL);
12164 }
12165 
12166 EnforceTCBLeafAttr *Sema::mergeEnforceTCBLeafAttr(
12167  Decl *D, const EnforceTCBLeafAttr &AL) {
12168  return mergeEnforceTCBAttrImpl<EnforceTCBLeafAttr, EnforceTCBAttr>(
12169  *this, D, AL);
12170 }
12171 
12172 //===----------------------------------------------------------------------===//
12173 // Top Level Sema Entry Points
12174 //===----------------------------------------------------------------------===//
12175 
12176 static bool IsDeclLambdaCallOperator(Decl *D) {
12177  if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
12178  return MD->getParent()->isLambda() &&
12179  MD->getOverloadedOperator() == OverloadedOperatorKind::OO_Call;
12180  return false;
12181 }
12182 
12183 // Returns true if the attribute must delay setting its arguments until after
12184 // template instantiation, and false otherwise.
12185 static bool MustDelayAttributeArguments(const ParsedAttr &AL) {
12186  // Only attributes that accept expression parameter packs can delay arguments.
12187  if (!AL.acceptsExprPack())
12188  return false;
12189 
12190  bool AttrHasVariadicArg = AL.hasVariadicArg();
12191  unsigned AttrNumArgs = AL.getNumArgMembers();
12192  for (size_t I = 0; I < std::min(AL.getNumArgs(), AttrNumArgs); ++I) {
12193  bool IsLastAttrArg = I == (AttrNumArgs - 1);
12194  // If the argument is the last argument and it is variadic it can contain
12195  // any expression.
12196  if (IsLastAttrArg && AttrHasVariadicArg)
12197  return false;
12198  Expr *E = AL.getArgAsExpr(I);
12199  bool ArgMemberCanHoldExpr = AL.isParamExpr(I);
12200  // If the expression is a pack expansion then arguments must be delayed
12201  // unless the argument is an expression and it is the last argument of the
12202  // attribute.
12203  if (isa<PackExpansionExpr>(E))
12204  return !(IsLastAttrArg && ArgMemberCanHoldExpr);
12205  // Last case is if the expression is value dependent then it must delay
12206  // arguments unless the corresponding argument is able to hold the
12207  // expression.
12208  if (E->isValueDependent() && !ArgMemberCanHoldExpr)
12209  return true;
12210  }
12211  return false;
12212 }
12213 
12214 static bool checkArmNewAttrMutualExclusion(
12215  Sema &S, const ParsedAttr &AL, const FunctionProtoType *FPT,
12216  FunctionType::ArmStateValue CurrentState, StringRef StateName) {
12217  auto CheckForIncompatibleAttr =
12218  [&](FunctionType::ArmStateValue IncompatibleState,
12219  StringRef IncompatibleStateName) {
12220  if (CurrentState == IncompatibleState) {
12221  S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
12222  << (std::string("'__arm_new(\"") + StateName.str() + "\")'")
12223  << (std::string("'") + IncompatibleStateName.str() + "(\"" +
12224  StateName.str() + "\")'")
12225  << true;
12226  AL.setInvalid();
12227  }
12228  };
12229 
12230  CheckForIncompatibleAttr(FunctionType::ARM_In, "__arm_in");
12231  CheckForIncompatibleAttr(FunctionType::ARM_Out, "__arm_out");
12232  CheckForIncompatibleAttr(FunctionType::ARM_InOut, "__arm_inout");
12233  CheckForIncompatibleAttr(FunctionType::ARM_Preserves, "__arm_preserves");
12234  return AL.isInvalid();
12235 }
12236 
12237 static void handleArmNewAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
12238  if (!AL.getNumArgs()) {
12239  S.Diag(AL.getLoc(), diag::err_missing_arm_state) << AL;
12240  AL.setInvalid();
12241  return;
12242  }
12243 
12244  std::vector<StringRef> NewState;
12245  if (const auto *ExistingAttr = D->getAttr<ArmNewAttr>()) {
12246  for (StringRef S : ExistingAttr->newArgs())
12247  NewState.push_back(S);
12248  }
12249 
12250  bool HasZA = false;
12251  bool HasZT0 = false;
12252  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
12253  StringRef StateName;
12254  SourceLocation LiteralLoc;
12255  if (!S.checkStringLiteralArgumentAttr(AL, I, StateName, &LiteralLoc))
12256  return;
12257 
12258  if (StateName == "za")
12259  HasZA = true;
12260  else if (StateName == "zt0")
12261  HasZT0 = true;
12262  else {
12263  S.Diag(LiteralLoc, diag::err_unknown_arm_state) << StateName;
12264  AL.setInvalid();
12265  return;
12266  }
12267 
12268  if (!llvm::is_contained(NewState, StateName)) // Avoid adding duplicates.
12269  NewState.push_back(StateName);
12270  }
12271 
12272  if (auto *FPT = dyn_cast<FunctionProtoType>(D->getFunctionType())) {
12273  FunctionType::ArmStateValue ZAState =
12275  if (HasZA && ZAState != FunctionType::ARM_None &&
12276  checkArmNewAttrMutualExclusion(S, AL, FPT, ZAState, "za"))
12277  return;
12278  FunctionType::ArmStateValue ZT0State =
12280  if (HasZT0 && ZT0State != FunctionType::ARM_None &&
12281  checkArmNewAttrMutualExclusion(S, AL, FPT, ZT0State, "zt0"))
12282  return;
12283  }
12284 
12285  D->dropAttr<ArmNewAttr>();
12286  D->addAttr(::new (S.Context)
12287  ArmNewAttr(S.Context, AL, NewState.data(), NewState.size()));
12288 }
12289 
12290 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
12291 /// the attribute applies to decls. If the attribute is a type attribute, just
12292 /// silently ignore it if a GNU attribute.
12293 static void
12294 ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, const ParsedAttr &AL,
12295  const Sema::ProcessDeclAttributeOptions &Options) {
12296  if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
12297  return;
12298 
12299  // Ignore C++11 attributes on declarator chunks: they appertain to the type
12300  // instead.
12301  if (AL.isCXX11Attribute() && !Options.IncludeCXX11Attributes &&
12302  (!IsDeclLambdaCallOperator(D) || !AL.supportsNonconformingLambdaSyntax()))
12303  return;
12304 
12305  // Unknown attributes are automatically warned on. Target-specific attributes
12306  // which do not apply to the current target architecture are treated as
12307  // though they were unknown attributes.
12308  const TargetInfo *Aux = S.Context.getAuxTargetInfo();
12309  if (AL.getKind() == ParsedAttr::UnknownAttribute ||
12310  !(AL.existsInTarget(S.Context.getTargetInfo()) ||
12311  (S.Context.getLangOpts().SYCLIsDevice &&
12312  Aux && AL.existsInTarget(*Aux)))) {
12313  S.Diag(AL.getLoc(),
12315  ? (unsigned)diag::err_keyword_not_supported_on_target
12316  : AL.isDeclspecAttribute()
12317  ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
12318  : (unsigned)diag::warn_unknown_attribute_ignored)
12319  << AL << AL.getRange();
12320  return;
12321  }
12322 
12323  // Check if argument population must delayed to after template instantiation.
12324  bool MustDelayArgs = MustDelayAttributeArguments(AL);
12325 
12326  // Argument number check must be skipped if arguments are delayed.
12327  if (S.checkCommonAttributeFeatures(D, AL, MustDelayArgs))
12328  return;
12329 
12330  if (MustDelayArgs) {
12331  AL.handleAttrWithDelayedArgs(S, D);
12332  return;
12333  }
12334 
12335  switch (AL.getKind()) {
12336  default:
12338  break;
12339  if (!AL.isStmtAttr()) {
12340  assert(AL.isTypeAttr() && "Non-type attribute not handled");
12341  }
12342  if (AL.isTypeAttr()) {
12343  if (Options.IgnoreTypeAttributes)
12344  break;
12346  // Non-[[]] type attributes are handled in processTypeAttrs(); silently
12347  // move on.
12348  break;
12349  }
12350 
12351  // According to the C and C++ standards, we should never see a
12352  // [[]] type attribute on a declaration. However, we have in the past
12353  // allowed some type attributes to "slide" to the `DeclSpec`, so we need
12354  // to continue to support this legacy behavior. We only do this, however,
12355  // if
12356  // - we actually have a `DeclSpec`, i.e. if we're looking at a
12357  // `DeclaratorDecl`, or
12358  // - we are looking at an alias-declaration, where historically we have
12359  // allowed type attributes after the identifier to slide to the type.
12361  isa<DeclaratorDecl, TypeAliasDecl>(D)) {
12362  // Suggest moving the attribute to the type instead, but only for our
12363  // own vendor attributes; moving other vendors' attributes might hurt
12364  // portability.
12365  if (AL.isClangScope()) {
12366  S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl)
12367  << AL << D->getLocation();
12368  }
12369 
12370  // Allow this type attribute to be handled in processTypeAttrs();
12371  // silently move on.
12372  break;
12373  }
12374 
12375  if (AL.getKind() == ParsedAttr::AT_Regparm) {
12376  // `regparm` is a special case: It's a type attribute but we still want
12377  // to treat it as if it had been written on the declaration because that
12378  // way we'll be able to handle it directly in `processTypeAttr()`.
12379  // If we treated `regparm` it as if it had been written on the
12380  // `DeclSpec`, the logic in `distributeFunctionTypeAttrFromDeclSepc()`
12381  // would try to move it to the declarator, but that doesn't work: We
12382  // can't remove the attribute from the list of declaration attributes
12383  // because it might be needed by other declarators in the same
12384  // declaration.
12385  break;
12386  }
12387 
12388  if (AL.getKind() == ParsedAttr::AT_VectorSize) {
12389  // `vector_size` is a special case: It's a type attribute semantically,
12390  // but GCC expects the [[]] syntax to be written on the declaration (and
12391  // warns that the attribute has no effect if it is placed on the
12392  // decl-specifier-seq).
12393  // Silently move on and allow the attribute to be handled in
12394  // processTypeAttr().
12395  break;
12396  }
12397 
12398  if (AL.getKind() == ParsedAttr::AT_NoDeref) {
12399  // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
12400  // See https://github.com/llvm/llvm-project/issues/55790 for details.
12401  // We allow processTypeAttrs() to emit a warning and silently move on.
12402  break;
12403  }
12404  }
12405  // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a
12406  // statement attribute is not written on a declaration, but this code is
12407  // needed for type attributes as well as statement attributes in Attr.td
12408  // that do not list any subjects.
12409  S.Diag(AL.getLoc(), diag::err_attribute_invalid_on_decl)
12410  << AL << AL.isRegularKeywordAttribute() << D->getLocation();
12411  break;
12412  case ParsedAttr::AT_Interrupt:
12413  handleInterruptAttr(S, D, AL);
12414  break;
12415  case ParsedAttr::AT_X86ForceAlignArgPointer:
12416  handleX86ForceAlignArgPointerAttr(S, D, AL);
12417  break;
12418  case ParsedAttr::AT_ReadOnlyPlacement:
12419  handleSimpleAttribute<ReadOnlyPlacementAttr>(S, D, AL);
12420  break;
12421  case ParsedAttr::AT_DLLExport:
12422  case ParsedAttr::AT_DLLImport:
12423  handleDLLAttr(S, D, AL);
12424  break;
12425  case ParsedAttr::AT_AMDGPUFlatWorkGroupSize:
12426  handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL);
12427  break;
12428  case ParsedAttr::AT_AMDGPUWavesPerEU:
12429  handleAMDGPUWavesPerEUAttr(S, D, AL);
12430  break;
12431  case ParsedAttr::AT_AMDGPUNumSGPR:
12432  handleAMDGPUNumSGPRAttr(S, D, AL);
12433  break;
12434  case ParsedAttr::AT_AMDGPUNumVGPR:
12435  handleAMDGPUNumVGPRAttr(S, D, AL);
12436  break;
12437  case ParsedAttr::AT_AMDGPUMaxNumWorkGroups:
12438  handleAMDGPUMaxNumWorkGroupsAttr(S, D, AL);
12439  break;
12440  case ParsedAttr::AT_AVRSignal:
12441  handleAVRSignalAttr(S, D, AL);
12442  break;
12443  case ParsedAttr::AT_BPFPreserveAccessIndex:
12444  handleBPFPreserveAccessIndexAttr(S, D, AL);
12445  break;
12446  case ParsedAttr::AT_BPFPreserveStaticOffset:
12447  handleSimpleAttribute<BPFPreserveStaticOffsetAttr>(S, D, AL);
12448  break;
12449  case ParsedAttr::AT_BTFDeclTag:
12450  handleBTFDeclTagAttr(S, D, AL);
12451  break;
12452  case ParsedAttr::AT_WebAssemblyExportName:
12453  handleWebAssemblyExportNameAttr(S, D, AL);
12454  break;
12455  case ParsedAttr::AT_WebAssemblyImportModule:
12456  handleWebAssemblyImportModuleAttr(S, D, AL);
12457  break;
12458  case ParsedAttr::AT_WebAssemblyImportName:
12459  handleWebAssemblyImportNameAttr(S, D, AL);
12460  break;
12461  case ParsedAttr::AT_IBOutlet:
12462  handleIBOutlet(S, D, AL);
12463  break;
12464  case ParsedAttr::AT_IBOutletCollection:
12465  handleIBOutletCollection(S, D, AL);
12466  break;
12467  case ParsedAttr::AT_IFunc:
12468  handleIFuncAttr(S, D, AL);
12469  break;
12470  case ParsedAttr::AT_Alias:
12471  handleAliasAttr(S, D, AL);
12472  break;
12473  case ParsedAttr::AT_Aligned:
12474  handleAlignedAttr(S, D, AL);
12475  break;
12476  case ParsedAttr::AT_AlignValue:
12477  handleAlignValueAttr(S, D, AL);
12478  break;
12479  case ParsedAttr::AT_AllocSize:
12480  handleAllocSizeAttr(S, D, AL);
12481  break;
12482  case ParsedAttr::AT_AlwaysInline:
12483  handleAlwaysInlineAttr(S, D, AL);
12484  break;
12485  case ParsedAttr::AT_AnalyzerNoReturn:
12486  handleAnalyzerNoReturnAttr(S, D, AL);
12487  break;
12488  case ParsedAttr::AT_TLSModel:
12489  handleTLSModelAttr(S, D, AL);
12490  break;
12491  case ParsedAttr::AT_Annotate:
12492  handleAnnotateAttr(S, D, AL);
12493  break;
12494  case ParsedAttr::AT_Availability:
12495  handleAvailabilityAttr(S, D, AL);
12496  break;
12497  case ParsedAttr::AT_CarriesDependency:
12498  handleDependencyAttr(S, scope, D, AL);
12499  break;
12500  case ParsedAttr::AT_CPUDispatch:
12501  case ParsedAttr::AT_CPUSpecific:
12502  handleCPUSpecificAttr(S, D, AL);
12503  break;
12504  case ParsedAttr::AT_Common:
12505  handleCommonAttr(S, D, AL);
12506  break;
12507  case ParsedAttr::AT_CUDAConstant:
12508  handleConstantAttr(S, D, AL);
12509  break;
12510  case ParsedAttr::AT_PassObjectSize:
12511  handlePassObjectSizeAttr(S, D, AL);
12512  break;
12513  case ParsedAttr::AT_Constructor:
12514  handleConstructorAttr(S, D, AL);
12515  break;
12516  case ParsedAttr::AT_Deprecated:
12517  handleDeprecatedAttr(S, D, AL);
12518  break;
12519  case ParsedAttr::AT_Destructor:
12520  handleDestructorAttr(S, D, AL);
12521  break;
12522  case ParsedAttr::AT_EnableIf:
12523  handleEnableIfAttr(S, D, AL);
12524  break;
12525  case ParsedAttr::AT_Error:
12526  handleErrorAttr(S, D, AL);
12527  break;
12528  case ParsedAttr::AT_ExcludeFromExplicitInstantiation:
12529  handleExcludeFromExplicitInstantiationAttr(S, D, AL);
12530  break;
12531  case ParsedAttr::AT_DiagnoseIf:
12532  handleDiagnoseIfAttr(S, D, AL);
12533  break;
12534  case ParsedAttr::AT_DiagnoseAsBuiltin:
12535  handleDiagnoseAsBuiltinAttr(S, D, AL);
12536  break;
12537  case ParsedAttr::AT_NoBuiltin:
12538  handleNoBuiltinAttr(S, D, AL);
12539  break;
12540  case ParsedAttr::AT_ExtVectorType:
12541  handleExtVectorTypeAttr(S, D, AL);
12542  break;
12543  case ParsedAttr::AT_ExternalSourceSymbol:
12544  handleExternalSourceSymbolAttr(S, D, AL);
12545  break;
12546  case ParsedAttr::AT_MinSize:
12547  handleMinSizeAttr(S, D, AL);
12548  break;
12549  case ParsedAttr::AT_OptimizeNone:
12550  handleOptimizeNoneAttr(S, D, AL);
12551  break;
12552  case ParsedAttr::AT_EnumExtensibility:
12553  handleEnumExtensibilityAttr(S, D, AL);
12554  break;
12555  case ParsedAttr::AT_SYCLKernel:
12556  handleSYCLKernelAttr(S, D, AL);
12557  break;
12558  case ParsedAttr::AT_SYCLSimd:
12559  handleSimpleAttribute<SYCLSimdAttr>(S, D, AL);
12560  break;
12561  case ParsedAttr::AT_SYCLSpecialClass:
12562  handleSimpleAttribute<SYCLSpecialClassAttr>(S, D, AL);
12563  break;
12564  case ParsedAttr::AT_SYCLType:
12565  handleSYCLTypeAttr(S, D, AL);
12566  break;
12567  case ParsedAttr::AT_SYCLDevice:
12568  handleSYCLDeviceAttr(S, D, AL);
12569  break;
12570  case ParsedAttr::AT_SYCLDeviceIndirectlyCallable:
12571  handleSYCLDeviceIndirectlyCallableAttr(S, D, AL);
12572  break;
12573  case ParsedAttr::AT_SYCLGlobalVar:
12574  handleSYCLGlobalVarAttr(S, D, AL);
12575  break;
12576  case ParsedAttr::AT_SYCLRegisterNum:
12577  handleSYCLRegisterNumAttr(S, D, AL);
12578  break;
12579  case ParsedAttr::AT_SYCLIntelESimdVectorize:
12580  handleSYCLIntelESimdVectorizeAttr(S, D, AL);
12581  break;
12582  case ParsedAttr::AT_SYCLDeviceHas:
12583  handleSYCLDeviceHasAttr(S, D, AL);
12584  break;
12585  case ParsedAttr::AT_SYCLUsesAspects:
12586  handleSYCLUsesAspectsAttr(S, D, AL);
12587  break;
12588  case ParsedAttr::AT_Format:
12589  handleFormatAttr(S, D, AL);
12590  break;
12591  case ParsedAttr::AT_FormatArg:
12592  handleFormatArgAttr(S, D, AL);
12593  break;
12594  case ParsedAttr::AT_Callback:
12595  handleCallbackAttr(S, D, AL);
12596  break;
12597  case ParsedAttr::AT_CalledOnce:
12598  handleCalledOnceAttr(S, D, AL);
12599  break;
12600  case ParsedAttr::AT_NVPTXKernel:
12601  case ParsedAttr::AT_CUDAGlobal:
12602  handleGlobalAttr(S, D, AL);
12603  break;
12604  case ParsedAttr::AT_CUDADevice:
12605  handleDeviceAttr(S, D, AL);
12606  break;
12607  case ParsedAttr::AT_HIPManaged:
12608  handleManagedAttr(S, D, AL);
12609  break;
12610  case ParsedAttr::AT_GNUInline:
12611  handleGNUInlineAttr(S, D, AL);
12612  break;
12613  case ParsedAttr::AT_CUDALaunchBounds:
12614  handleLaunchBoundsAttr(S, D, AL);
12615  break;
12616  case ParsedAttr::AT_Restrict:
12617  handleRestrictAttr(S, D, AL);
12618  break;
12619  case ParsedAttr::AT_Mode:
12620  handleModeAttr(S, D, AL);
12621  break;
12622  case ParsedAttr::AT_NonNull:
12623  if (auto *PVD = dyn_cast<ParmVarDecl>(D))
12624  handleNonNullAttrParameter(S, PVD, AL);
12625  else
12626  handleNonNullAttr(S, D, AL);
12627  break;
12628  case ParsedAttr::AT_ReturnsNonNull:
12629  handleReturnsNonNullAttr(S, D, AL);
12630  break;
12631  case ParsedAttr::AT_NoEscape:
12632  handleNoEscapeAttr(S, D, AL);
12633  break;
12634  case ParsedAttr::AT_MaybeUndef:
12635  handleSimpleAttribute<MaybeUndefAttr>(S, D, AL);
12636  break;
12637  case ParsedAttr::AT_AssumeAligned:
12638  handleAssumeAlignedAttr(S, D, AL);
12639  break;
12640  case ParsedAttr::AT_AllocAlign:
12641  handleAllocAlignAttr(S, D, AL);
12642  break;
12643  case ParsedAttr::AT_Ownership:
12644  handleOwnershipAttr(S, D, AL);
12645  break;
12646  case ParsedAttr::AT_Naked:
12647  handleNakedAttr(S, D, AL);
12648  break;
12649  case ParsedAttr::AT_NoReturn:
12650  handleNoReturnAttr(S, D, AL);
12651  break;
12652  case ParsedAttr::AT_CXX11NoReturn:
12653  handleStandardNoReturnAttr(S, D, AL);
12654  break;
12655  case ParsedAttr::AT_AnyX86NoCfCheck:
12656  handleNoCfCheckAttr(S, D, AL);
12657  break;
12658  case ParsedAttr::AT_NoThrow:
12659  if (!AL.isUsedAsTypeAttr())
12660  handleSimpleAttribute<NoThrowAttr>(S, D, AL);
12661  break;
12662  case ParsedAttr::AT_CUDAShared:
12663  handleSharedAttr(S, D, AL);
12664  break;
12665  case ParsedAttr::AT_VecReturn:
12666  handleVecReturnAttr(S, D, AL);
12667  break;
12668  case ParsedAttr::AT_ObjCOwnership:
12669  handleObjCOwnershipAttr(S, D, AL);
12670  break;
12671  case ParsedAttr::AT_ObjCPreciseLifetime:
12672  handleObjCPreciseLifetimeAttr(S, D, AL);
12673  break;
12674  case ParsedAttr::AT_ObjCReturnsInnerPointer:
12675  handleObjCReturnsInnerPointerAttr(S, D, AL);
12676  break;
12677  case ParsedAttr::AT_ObjCRequiresSuper:
12678  handleObjCRequiresSuperAttr(S, D, AL);
12679  break;
12680  case ParsedAttr::AT_ObjCBridge:
12681  handleObjCBridgeAttr(S, D, AL);
12682  break;
12683  case ParsedAttr::AT_ObjCBridgeMutable:
12684  handleObjCBridgeMutableAttr(S, D, AL);
12685  break;
12686  case ParsedAttr::AT_ObjCBridgeRelated:
12687  handleObjCBridgeRelatedAttr(S, D, AL);
12688  break;
12689  case ParsedAttr::AT_ObjCDesignatedInitializer:
12690  handleObjCDesignatedInitializer(S, D, AL);
12691  break;
12692  case ParsedAttr::AT_ObjCRuntimeName:
12693  handleObjCRuntimeName(S, D, AL);
12694  break;
12695  case ParsedAttr::AT_ObjCBoxable:
12696  handleObjCBoxable(S, D, AL);
12697  break;
12698  case ParsedAttr::AT_NSErrorDomain:
12699  handleNSErrorDomain(S, D, AL);
12700  break;
12701  case ParsedAttr::AT_CFConsumed:
12702  case ParsedAttr::AT_NSConsumed:
12703  case ParsedAttr::AT_OSConsumed:
12704  S.AddXConsumedAttr(D, AL, parsedAttrToRetainOwnershipKind(AL),
12705  /*IsTemplateInstantiation=*/false);
12706  break;
12707  case ParsedAttr::AT_OSReturnsRetainedOnZero:
12708  handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnZeroAttr>(
12709  S, D, AL, isValidOSObjectOutParameter(D),
12710  diag::warn_ns_attribute_wrong_parameter_type,
12711  /*Extra Args=*/AL, /*pointer-to-OSObject-pointer*/ 3, AL.getRange());
12712  break;
12713  case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
12714  handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnNonZeroAttr>(
12715  S, D, AL, isValidOSObjectOutParameter(D),
12716  diag::warn_ns_attribute_wrong_parameter_type,
12717  /*Extra Args=*/AL, /*pointer-to-OSObject-poointer*/ 3, AL.getRange());
12718  break;
12719  case ParsedAttr::AT_NSReturnsAutoreleased:
12720  case ParsedAttr::AT_NSReturnsNotRetained:
12721  case ParsedAttr::AT_NSReturnsRetained:
12722  case ParsedAttr::AT_CFReturnsNotRetained:
12723  case ParsedAttr::AT_CFReturnsRetained:
12724  case ParsedAttr::AT_OSReturnsNotRetained:
12725  case ParsedAttr::AT_OSReturnsRetained:
12726  handleXReturnsXRetainedAttr(S, D, AL);
12727  break;
12728  case ParsedAttr::AT_WorkGroupSizeHint:
12729  handleWorkGroupSizeHint(S, D, AL);
12730  break;
12731  case ParsedAttr::AT_ReqdWorkGroupSize:
12732  handleReqdWorkGroupSize(S, D, AL);
12733  break;
12734  case ParsedAttr::AT_SYCLIntelMaxWorkGroupSize:
12735  handleSYCLIntelMaxWorkGroupSize(S, D, AL);
12736  break;
12737  case ParsedAttr::AT_SYCLIntelMinWorkGroupsPerComputeUnit:
12738  handleSYCLIntelMinWorkGroupsPerComputeUnit(S, D, AL);
12739  break;
12740  case ParsedAttr::AT_SYCLIntelMaxWorkGroupsPerMultiprocessor:
12741  handleSYCLIntelMaxWorkGroupsPerMultiprocessor(S, D, AL);
12742  break;
12743  case ParsedAttr::AT_IntelReqdSubGroupSize:
12744  handleIntelReqdSubGroupSize(S, D, AL);
12745  break;
12746  case ParsedAttr::AT_IntelNamedSubGroupSize:
12747  handleIntelNamedSubGroupSize(S, D, AL);
12748  break;
12749  case ParsedAttr::AT_SYCLIntelNumSimdWorkItems:
12750  handleSYCLIntelNumSimdWorkItemsAttr(S, D, AL);
12751  break;
12752  case ParsedAttr::AT_SYCLIntelSchedulerTargetFmaxMhz:
12753  handleSYCLIntelSchedulerTargetFmaxMhzAttr(S, D, AL);
12754  break;
12755  case ParsedAttr::AT_SYCLIntelMaxGlobalWorkDim:
12756  handleSYCLIntelMaxGlobalWorkDimAttr(S, D, AL);
12757  break;
12758  case ParsedAttr::AT_SYCLIntelNoGlobalWorkOffset:
12759  handleSYCLIntelNoGlobalWorkOffsetAttr(S, D, AL);
12760  break;
12761  case ParsedAttr::AT_SYCLIntelUseStallEnableClusters:
12762  handleSYCLIntelUseStallEnableClustersAttr(S, D, AL);
12763  break;
12764  case ParsedAttr::AT_SYCLIntelLoopFuse:
12765  handleSYCLIntelLoopFuseAttr(S, D, AL);
12766  break;
12767  case ParsedAttr::AT_SYCLIntelInitiationInterval:
12769  break;
12770  case ParsedAttr::AT_VecTypeHint:
12771  handleVecTypeHint(S, D, AL);
12772  break;
12773  case ParsedAttr::AT_InitPriority:
12774  handleInitPriorityAttr(S, D, AL);
12775  break;
12776  case ParsedAttr::AT_Packed:
12777  handlePackedAttr(S, D, AL);
12778  break;
12779  case ParsedAttr::AT_PreferredName:
12780  handlePreferredName(S, D, AL);
12781  break;
12782  case ParsedAttr::AT_Section:
12783  handleSectionAttr(S, D, AL);
12784  break;
12785  case ParsedAttr::AT_CodeModel:
12786  handleCodeModelAttr(S, D, AL);
12787  break;
12788  case ParsedAttr::AT_RandomizeLayout:
12789  handleRandomizeLayoutAttr(S, D, AL);
12790  break;
12791  case ParsedAttr::AT_NoRandomizeLayout:
12792  handleNoRandomizeLayoutAttr(S, D, AL);
12793  break;
12794  case ParsedAttr::AT_CodeSeg:
12795  handleCodeSegAttr(S, D, AL);
12796  break;
12797  case ParsedAttr::AT_Target:
12798  handleTargetAttr(S, D, AL);
12799  break;
12800  case ParsedAttr::AT_TargetVersion:
12801  handleTargetVersionAttr(S, D, AL);
12802  break;
12803  case ParsedAttr::AT_TargetClones:
12804  handleTargetClonesAttr(S, D, AL);
12805  break;
12806  case ParsedAttr::AT_MinVectorWidth:
12807  handleMinVectorWidthAttr(S, D, AL);
12808  break;
12809  case ParsedAttr::AT_Unavailable:
12810  handleAttrWithMessage<UnavailableAttr>(S, D, AL);
12811  break;
12812  case ParsedAttr::AT_OMPAssume:
12813  handleOMPAssumeAttr(S, D, AL);
12814  break;
12815  case ParsedAttr::AT_ObjCDirect:
12816  handleObjCDirectAttr(S, D, AL);
12817  break;
12818  case ParsedAttr::AT_ObjCDirectMembers:
12819  handleObjCDirectMembersAttr(S, D, AL);
12820  handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL);
12821  break;
12822  case ParsedAttr::AT_ObjCExplicitProtocolImpl:
12823  handleObjCSuppresProtocolAttr(S, D, AL);
12824  break;
12825  case ParsedAttr::AT_Unused:
12826  handleUnusedAttr(S, D, AL);
12827  break;
12828  case ParsedAttr::AT_Visibility:
12829  handleVisibilityAttr(S, D, AL, false);
12830  break;
12831  case ParsedAttr::AT_TypeVisibility:
12832  handleVisibilityAttr(S, D, AL, true);
12833  break;
12834  case ParsedAttr::AT_WarnUnusedResult:
12835  handleWarnUnusedResult(S, D, AL);
12836  break;
12837  case ParsedAttr::AT_WeakRef:
12838  handleWeakRefAttr(S, D, AL);
12839  break;
12840  case ParsedAttr::AT_WeakImport:
12841  handleWeakImportAttr(S, D, AL);
12842  break;
12843  case ParsedAttr::AT_TransparentUnion:
12844  handleTransparentUnionAttr(S, D, AL);
12845  break;
12846  case ParsedAttr::AT_ObjCMethodFamily:
12847  handleObjCMethodFamilyAttr(S, D, AL);
12848  break;
12849  case ParsedAttr::AT_ObjCNSObject:
12850  handleObjCNSObject(S, D, AL);
12851  break;
12852  case ParsedAttr::AT_ObjCIndependentClass:
12853  handleObjCIndependentClass(S, D, AL);
12854  break;
12855  case ParsedAttr::AT_Blocks:
12856  handleBlocksAttr(S, D, AL);
12857  break;
12858  case ParsedAttr::AT_Sentinel:
12859  handleSentinelAttr(S, D, AL);
12860  break;
12861  case ParsedAttr::AT_Cleanup:
12862  handleCleanupAttr(S, D, AL);
12863  break;
12864  case ParsedAttr::AT_NoDebug:
12865  handleNoDebugAttr(S, D, AL);
12866  break;
12867  case ParsedAttr::AT_CmseNSEntry:
12868  handleCmseNSEntryAttr(S, D, AL);
12869  break;
12870  case ParsedAttr::AT_StdCall:
12871  case ParsedAttr::AT_CDecl:
12872  case ParsedAttr::AT_FastCall:
12873  case ParsedAttr::AT_ThisCall:
12874  case ParsedAttr::AT_Pascal:
12875  case ParsedAttr::AT_RegCall:
12876  case ParsedAttr::AT_SwiftCall:
12877  case ParsedAttr::AT_SwiftAsyncCall:
12878  case ParsedAttr::AT_VectorCall:
12879  case ParsedAttr::AT_MSABI:
12880  case ParsedAttr::AT_SysVABI:
12881  case ParsedAttr::AT_Pcs:
12882  case ParsedAttr::AT_IntelOclBicc:
12883  case ParsedAttr::AT_PreserveMost:
12884  case ParsedAttr::AT_PreserveAll:
12885  case ParsedAttr::AT_AArch64VectorPcs:
12886  case ParsedAttr::AT_AArch64SVEPcs:
12887  case ParsedAttr::AT_AMDGPUKernelCall:
12888  case ParsedAttr::AT_M68kRTD:
12889  case ParsedAttr::AT_PreserveNone:
12890  case ParsedAttr::AT_RISCVVectorCC:
12891  handleCallConvAttr(S, D, AL);
12892  break;
12893  case ParsedAttr::AT_Suppress:
12894  handleSuppressAttr(S, D, AL);
12895  break;
12896  case ParsedAttr::AT_Owner:
12897  case ParsedAttr::AT_Pointer:
12898  handleLifetimeCategoryAttr(S, D, AL);
12899  break;
12900  case ParsedAttr::AT_OpenCLAccess:
12901  handleOpenCLAccessAttr(S, D, AL);
12902  break;
12903  case ParsedAttr::AT_OpenCLNoSVM:
12904  handleOpenCLNoSVMAttr(S, D, AL);
12905  break;
12906  case ParsedAttr::AT_SwiftContext:
12908  break;
12909  case ParsedAttr::AT_SwiftAsyncContext:
12911  break;
12912  case ParsedAttr::AT_SwiftErrorResult:
12914  break;
12915  case ParsedAttr::AT_SwiftIndirectResult:
12917  break;
12918  case ParsedAttr::AT_InternalLinkage:
12919  handleInternalLinkageAttr(S, D, AL);
12920  break;
12921  case ParsedAttr::AT_ZeroCallUsedRegs:
12922  handleZeroCallUsedRegsAttr(S, D, AL);
12923  break;
12924  case ParsedAttr::AT_FunctionReturnThunks:
12925  handleFunctionReturnThunksAttr(S, D, AL);
12926  break;
12927  case ParsedAttr::AT_NoMerge:
12928  handleNoMergeAttr(S, D, AL);
12929  break;
12930  case ParsedAttr::AT_NoUniqueAddress:
12931  handleNoUniqueAddressAttr(S, D, AL);
12932  break;
12933 
12934  case ParsedAttr::AT_AvailableOnlyInDefaultEvalMethod:
12935  handleAvailableOnlyInDefaultEvalMethod(S, D, AL);
12936  break;
12937 
12938  case ParsedAttr::AT_CountedBy:
12939  handleCountedByAttrField(S, D, AL);
12940  break;
12941 
12942  // Microsoft attributes:
12943  case ParsedAttr::AT_LayoutVersion:
12944  handleLayoutVersion(S, D, AL);
12945  break;
12946  case ParsedAttr::AT_Uuid:
12947  handleUuidAttr(S, D, AL);
12948  break;
12949  case ParsedAttr::AT_MSInheritance:
12950  handleMSInheritanceAttr(S, D, AL);
12951  break;
12952  case ParsedAttr::AT_Thread:
12953  handleDeclspecThreadAttr(S, D, AL);
12954  break;
12955  case ParsedAttr::AT_MSConstexpr:
12956  handleMSConstexprAttr(S, D, AL);
12957  break;
12958 
12959  // HLSL attributes:
12960  case ParsedAttr::AT_HLSLNumThreads:
12961  handleHLSLNumThreadsAttr(S, D, AL);
12962  break;
12963  case ParsedAttr::AT_HLSLSV_GroupIndex:
12964  handleSimpleAttribute<HLSLSV_GroupIndexAttr>(S, D, AL);
12965  break;
12966  case ParsedAttr::AT_HLSLSV_DispatchThreadID:
12967  handleHLSLSV_DispatchThreadIDAttr(S, D, AL);
12968  break;
12969  case ParsedAttr::AT_HLSLPackOffset:
12970  handleHLSLPackOffsetAttr(S, D, AL);
12971  break;
12972  case ParsedAttr::AT_HLSLShader:
12973  handleHLSLShaderAttr(S, D, AL);
12974  break;
12975  case ParsedAttr::AT_HLSLResourceBinding:
12976  handleHLSLResourceBindingAttr(S, D, AL);
12977  break;
12978  case ParsedAttr::AT_HLSLParamModifier:
12979  handleHLSLParamModifierAttr(S, D, AL);
12980  break;
12981 
12982  case ParsedAttr::AT_AbiTag:
12983  handleAbiTagAttr(S, D, AL);
12984  break;
12985  case ParsedAttr::AT_CFGuard:
12986  handleCFGuardAttr(S, D, AL);
12987  break;
12988 
12989  // Thread safety attributes:
12990  case ParsedAttr::AT_AssertExclusiveLock:
12991  handleAssertExclusiveLockAttr(S, D, AL);
12992  break;
12993  case ParsedAttr::AT_AssertSharedLock:
12994  handleAssertSharedLockAttr(S, D, AL);
12995  break;
12996  case ParsedAttr::AT_PtGuardedVar:
12997  handlePtGuardedVarAttr(S, D, AL);
12998  break;
12999  case ParsedAttr::AT_NoSanitize:
13000  handleNoSanitizeAttr(S, D, AL);
13001  break;
13002  case ParsedAttr::AT_NoSanitizeSpecific:
13003  handleNoSanitizeSpecificAttr(S, D, AL);
13004  break;
13005  case ParsedAttr::AT_GuardedBy:
13006  handleGuardedByAttr(S, D, AL);
13007  break;
13008  case ParsedAttr::AT_PtGuardedBy:
13009  handlePtGuardedByAttr(S, D, AL);
13010  break;
13011  case ParsedAttr::AT_ExclusiveTrylockFunction:
13012  handleExclusiveTrylockFunctionAttr(S, D, AL);
13013  break;
13014  case ParsedAttr::AT_LockReturned:
13015  handleLockReturnedAttr(S, D, AL);
13016  break;
13017  case ParsedAttr::AT_LocksExcluded:
13018  handleLocksExcludedAttr(S, D, AL);
13019  break;
13020  case ParsedAttr::AT_SharedTrylockFunction:
13021  handleSharedTrylockFunctionAttr(S, D, AL);
13022  break;
13023  case ParsedAttr::AT_AcquiredBefore:
13024  handleAcquiredBeforeAttr(S, D, AL);
13025  break;
13026  case ParsedAttr::AT_AcquiredAfter:
13027  handleAcquiredAfterAttr(S, D, AL);
13028  break;
13029 
13030  // Capability analysis attributes.
13031  case ParsedAttr::AT_Capability:
13032  case ParsedAttr::AT_Lockable:
13033  handleCapabilityAttr(S, D, AL);
13034  break;
13035  case ParsedAttr::AT_RequiresCapability:
13036  handleRequiresCapabilityAttr(S, D, AL);
13037  break;
13038 
13039  case ParsedAttr::AT_AssertCapability:
13040  handleAssertCapabilityAttr(S, D, AL);
13041  break;
13042  case ParsedAttr::AT_AcquireCapability:
13043  handleAcquireCapabilityAttr(S, D, AL);
13044  break;
13045  case ParsedAttr::AT_ReleaseCapability:
13046  handleReleaseCapabilityAttr(S, D, AL);
13047  break;
13048  case ParsedAttr::AT_TryAcquireCapability:
13049  handleTryAcquireCapabilityAttr(S, D, AL);
13050  break;
13051 
13052  // Consumed analysis attributes.
13053  case ParsedAttr::AT_Consumable:
13054  handleConsumableAttr(S, D, AL);
13055  break;
13056  case ParsedAttr::AT_CallableWhen:
13057  handleCallableWhenAttr(S, D, AL);
13058  break;
13059  case ParsedAttr::AT_ParamTypestate:
13060  handleParamTypestateAttr(S, D, AL);
13061  break;
13062  case ParsedAttr::AT_ReturnTypestate:
13063  handleReturnTypestateAttr(S, D, AL);
13064  break;
13065  case ParsedAttr::AT_SetTypestate:
13066  handleSetTypestateAttr(S, D, AL);
13067  break;
13068  case ParsedAttr::AT_TestTypestate:
13069  handleTestTypestateAttr(S, D, AL);
13070  break;
13071 
13072  // Type safety attributes.
13073  case ParsedAttr::AT_ArgumentWithTypeTag:
13074  handleArgumentWithTypeTagAttr(S, D, AL);
13075  break;
13076  case ParsedAttr::AT_TypeTagForDatatype:
13077  handleTypeTagForDatatypeAttr(S, D, AL);
13078  break;
13079 
13080  // Intel FPGA specific attributes
13081  case ParsedAttr::AT_SYCLIntelDoublePump:
13082  handleSYCLIntelDoublePumpAttr(S, D, AL);
13083  break;
13084  case ParsedAttr::AT_SYCLIntelSinglePump:
13085  handleSYCLIntelSinglePumpAttr(S, D, AL);
13086  break;
13087  case ParsedAttr::AT_SYCLIntelMemory:
13088  handleSYCLIntelMemoryAttr(S, D, AL);
13089  break;
13090  case ParsedAttr::AT_SYCLIntelRegister:
13091  handleSYCLIntelRegisterAttr(S, D, AL);
13092  break;
13093  case ParsedAttr::AT_SYCLIntelBankWidth:
13094  handleSYCLIntelBankWidthAttr(S, D, AL);
13095  break;
13096  case ParsedAttr::AT_SYCLIntelNumBanks:
13097  handleSYCLIntelNumBanksAttr(S, D, AL);
13098  break;
13099  case ParsedAttr::AT_SYCLIntelPrivateCopies:
13100  handleSYCLIntelPrivateCopiesAttr(S, D, AL);
13101  break;
13102  case ParsedAttr::AT_SYCLIntelMaxReplicates:
13103  handleSYCLIntelMaxReplicatesAttr(S, D, AL);
13104  break;
13105  case ParsedAttr::AT_SYCLIntelSimpleDualPort:
13106  handleIntelSimpleDualPortAttr(S, D, AL);
13107  break;
13108  case ParsedAttr::AT_SYCLIntelMerge:
13109  handleSYCLIntelMergeAttr(S, D, AL);
13110  break;
13111  case ParsedAttr::AT_SYCLIntelBankBits:
13112  handleSYCLIntelBankBitsAttr(S, D, AL);
13113  break;
13114  case ParsedAttr::AT_SYCLIntelForcePow2Depth:
13115  handleSYCLIntelForcePow2DepthAttr(S, D, AL);
13116  break;
13117  case ParsedAttr::AT_SYCLIntelPipeIO:
13118  handleSYCLIntelPipeIOAttr(S, D, AL);
13119  break;
13120  case ParsedAttr::AT_SYCLIntelMaxConcurrency:
13122  break;
13123  case ParsedAttr::AT_SYCLAddIRAttributesFunction:
13124  handleSYCLAddIRAttributesFunctionAttr(S, D, AL);
13125  break;
13126  case ParsedAttr::AT_SYCLAddIRAttributesKernelParameter:
13127  handleSYCLAddIRAttributesKernelParameterAttr(S, D, AL);
13128  break;
13129  case ParsedAttr::AT_SYCLAddIRAttributesGlobalVariable:
13130  handleSYCLAddIRAttributesGlobalVariableAttr(S, D, AL);
13131  break;
13132  case ParsedAttr::AT_SYCLAddIRAnnotationsMember:
13133  handleSYCLAddIRAnnotationsMemberAttr(S, D, AL);
13134  break;
13135 
13136  // Swift attributes.
13137  case ParsedAttr::AT_SwiftAsyncName:
13138  handleSwiftAsyncName(S, D, AL);
13139  break;
13140  case ParsedAttr::AT_SwiftAttr:
13141  handleSwiftAttrAttr(S, D, AL);
13142  break;
13143  case ParsedAttr::AT_SwiftBridge:
13144  handleSwiftBridge(S, D, AL);
13145  break;
13146  case ParsedAttr::AT_SwiftError:
13147  handleSwiftError(S, D, AL);
13148  break;
13149  case ParsedAttr::AT_SwiftName:
13150  handleSwiftName(S, D, AL);
13151  break;
13152  case ParsedAttr::AT_SwiftNewType:
13153  handleSwiftNewType(S, D, AL);
13154  break;
13155  case ParsedAttr::AT_SwiftAsync:
13156  handleSwiftAsyncAttr(S, D, AL);
13157  break;
13158  case ParsedAttr::AT_SwiftAsyncError:
13159  handleSwiftAsyncError(S, D, AL);
13160  break;
13161 
13162  // XRay attributes.
13163  case ParsedAttr::AT_XRayLogArgs:
13164  handleXRayLogArgsAttr(S, D, AL);
13165  break;
13166 
13167  case ParsedAttr::AT_PatchableFunctionEntry:
13168  handlePatchableFunctionEntryAttr(S, D, AL);
13169  break;
13170 
13171  case ParsedAttr::AT_AlwaysDestroy:
13172  case ParsedAttr::AT_NoDestroy:
13173  handleDestroyAttr(S, D, AL);
13174  break;
13175 
13176  case ParsedAttr::AT_Uninitialized:
13177  handleUninitializedAttr(S, D, AL);
13178  break;
13179 
13180  case ParsedAttr::AT_ObjCExternallyRetained:
13181  handleObjCExternallyRetainedAttr(S, D, AL);
13182  break;
13183 
13184  case ParsedAttr::AT_MIGServerRoutine:
13185  handleMIGServerRoutineAttr(S, D, AL);
13186  break;
13187 
13188  case ParsedAttr::AT_MSAllocator:
13189  handleMSAllocatorAttr(S, D, AL);
13190  break;
13191 
13192  case ParsedAttr::AT_ArmBuiltinAlias:
13193  handleArmBuiltinAliasAttr(S, D, AL);
13194  break;
13195 
13196  case ParsedAttr::AT_ArmLocallyStreaming:
13197  handleSimpleAttribute<ArmLocallyStreamingAttr>(S, D, AL);
13198  break;
13199 
13200  case ParsedAttr::AT_ArmNew:
13201  handleArmNewAttr(S, D, AL);
13202  break;
13203 
13204  case ParsedAttr::AT_AcquireHandle:
13205  handleAcquireHandleAttr(S, D, AL);
13206  break;
13207 
13208  case ParsedAttr::AT_ReleaseHandle:
13209  handleHandleAttr<ReleaseHandleAttr>(S, D, AL);
13210  break;
13211 
13212  case ParsedAttr::AT_UnsafeBufferUsage:
13213  handleUnsafeBufferUsage<UnsafeBufferUsageAttr>(S, D, AL);
13214  break;
13215 
13216  case ParsedAttr::AT_UseHandle:
13217  handleHandleAttr<UseHandleAttr>(S, D, AL);
13218  break;
13219 
13220  case ParsedAttr::AT_EnforceTCB:
13221  handleEnforceTCBAttr<EnforceTCBAttr, EnforceTCBLeafAttr>(S, D, AL);
13222  break;
13223 
13224  case ParsedAttr::AT_EnforceTCBLeaf:
13225  handleEnforceTCBAttr<EnforceTCBLeafAttr, EnforceTCBAttr>(S, D, AL);
13226  break;
13227 
13228  case ParsedAttr::AT_BuiltinAlias:
13229  handleBuiltinAliasAttr(S, D, AL);
13230  break;
13231 
13232  case ParsedAttr::AT_PreferredType:
13233  handlePreferredTypeAttr(S, D, AL);
13234  break;
13235 
13236  case ParsedAttr::AT_UsingIfExists:
13237  handleSimpleAttribute<UsingIfExistsAttr>(S, D, AL);
13238  break;
13239 
13240  case ParsedAttr::AT_TypeNullable:
13241  handleNullableTypeAttr(S, D, AL);
13242  break;
13243  }
13244 }
13245 
13246 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified
13247 /// attribute list to the specified decl, ignoring any type attributes.
13249  Scope *S, Decl *D, const ParsedAttributesView &AttrList,
13250  const ProcessDeclAttributeOptions &Options) {
13251  if (AttrList.empty())
13252  return;
13253 
13254  for (const ParsedAttr &AL : AttrList)
13255  ProcessDeclAttribute(*this, S, D, AL, Options);
13256 
13257  // FIXME: We should be able to handle these cases in TableGen.
13258  // GCC accepts
13259  // static int a9 __attribute__((weakref));
13260  // but that looks really pointless. We reject it.
13261  if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
13262  Diag(AttrList.begin()->getLoc(), diag::err_attribute_weakref_without_alias)
13263  << cast<NamedDecl>(D);
13264  D->dropAttr<WeakRefAttr>();
13265  return;
13266  }
13267 
13268  // FIXME: We should be able to handle this in TableGen as well. It would be
13269  // good to have a way to specify "these attributes must appear as a group",
13270  // for these. Additionally, it would be good to have a way to specify "these
13271  // attribute must never appear as a group" for attributes like cold and hot.
13272  if (!(D->hasAttr<OpenCLKernelAttr>() ||
13273  LangOpts.SYCLIsDevice || LangOpts.SYCLIsHost)) {
13274  // These attributes cannot be applied to a non-kernel function.
13275  if (const auto *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
13276  // FIXME: This emits a different error message than
13277  // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
13278  Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
13279  D->setInvalidDecl();
13280  } else if (const auto *A = D->getAttr<WorkGroupSizeHintAttr>()) {
13281  Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
13282  D->setInvalidDecl();
13283  } else if (const auto *A = D->getAttr<SYCLReqdWorkGroupSizeAttr>()) {
13284  Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
13285  D->setInvalidDecl();
13286  } else if (const auto *A = D->getAttr<SYCLWorkGroupSizeHintAttr>()) {
13287  Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
13288  D->setInvalidDecl();
13289  } else if (const auto *A = D->getAttr<SYCLIntelMaxWorkGroupSizeAttr>()) {
13290  Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
13291  D->setInvalidDecl();
13292  } else if (const auto *A =
13293  D->getAttr<SYCLIntelMinWorkGroupsPerComputeUnitAttr>()) {
13294  Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
13295  D->setInvalidDecl();
13296  } else if (const auto *A =
13297  D->getAttr<SYCLIntelMaxWorkGroupsPerMultiprocessorAttr>()) {
13298  Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
13299  D->setInvalidDecl();
13300  } else if (const auto *A = D->getAttr<SYCLIntelNoGlobalWorkOffsetAttr>()) {
13301  Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
13302  D->setInvalidDecl();
13303  } else if (const auto *A = D->getAttr<VecTypeHintAttr>()) {
13304  Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
13305  D->setInvalidDecl();
13306  } else if (const auto *A = D->getAttr<IntelReqdSubGroupSizeAttr>()) {
13307  Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
13308  D->setInvalidDecl();
13309  } else if (!D->hasAttr<CUDAGlobalAttr>()) {
13310  if (const auto *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
13311  Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
13312  << A << A->isRegularKeywordAttribute() << ExpectedKernelFunction;
13313  D->setInvalidDecl();
13314  } else if (const auto *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
13315  Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
13316  << A << A->isRegularKeywordAttribute() << ExpectedKernelFunction;
13317  D->setInvalidDecl();
13318  } else if (const auto *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
13319  Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
13320  << A << A->isRegularKeywordAttribute() << ExpectedKernelFunction;
13321  D->setInvalidDecl();
13322  } else if (const auto *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
13323  Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
13324  << A << A->isRegularKeywordAttribute() << ExpectedKernelFunction;
13325  D->setInvalidDecl();
13326  }
13327  }
13328  }
13329 
13330  // Do this check after processing D's attributes because the attribute
13331  // objc_method_family can change whether the given method is in the init
13332  // family, and it can be applied after objc_designated_initializer. This is a
13333  // bit of a hack, but we need it to be compatible with versions of clang that
13334  // processed the attribute list in the wrong order.
13335  if (D->hasAttr<ObjCDesignatedInitializerAttr>() &&
13336  cast<ObjCMethodDecl>(D)->getMethodFamily() != OMF_init) {
13337  Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
13338  D->dropAttr<ObjCDesignatedInitializerAttr>();
13339  }
13340 }
13341 
13342 // Helper for delayed processing TransparentUnion or BPFPreserveAccessIndexAttr
13343 // attribute.
13345  const ParsedAttributesView &AttrList) {
13346  for (const ParsedAttr &AL : AttrList)
13347  if (AL.getKind() == ParsedAttr::AT_TransparentUnion) {
13348  handleTransparentUnionAttr(*this, D, AL);
13349  break;
13350  }
13351 
13352  // For BPFPreserveAccessIndexAttr, we want to populate the attributes
13353  // to fields and inner records as well.
13354  if (D && D->hasAttr<BPFPreserveAccessIndexAttr>())
13355  handleBPFPreserveAIRecord(*this, cast<RecordDecl>(D));
13356 }
13357 
13358 // Annotation attributes are the only attributes allowed after an access
13359 // specifier.
13361  AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList) {
13362  for (const ParsedAttr &AL : AttrList) {
13363  if (AL.getKind() == ParsedAttr::AT_Annotate) {
13364  ProcessDeclAttribute(*this, nullptr, ASDecl, AL,
13365  ProcessDeclAttributeOptions());
13366  } else {
13367  Diag(AL.getLoc(), diag::err_only_annotate_after_access_spec);
13368  return true;
13369  }
13370  }
13371  return false;
13372 }
13373 
13374 /// checkUnusedDeclAttributes - Check a list of attributes to see if it
13375 /// contains any decl attributes that we should warn about.
13376 static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A) {
13377  for (const ParsedAttr &AL : A) {
13378  // Only warn if the attribute is an unignored, non-type attribute.
13379  if (AL.isUsedAsTypeAttr() || AL.isInvalid())
13380  continue;
13382  continue;
13383 
13384  if (AL.getKind() == ParsedAttr::UnknownAttribute) {
13385  S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
13386  << AL << AL.getRange();
13387  } else {
13388  S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) << AL
13389  << AL.getRange();
13390  }
13391  }
13392 }
13393 
13394 /// checkUnusedDeclAttributes - Given a declarator which is not being
13395 /// used to build a declaration, complain about any decl attributes
13396 /// which might be lying around on it.
13398  ::checkUnusedDeclAttributes(*this, D.getDeclarationAttributes());
13399  ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes());
13400  ::checkUnusedDeclAttributes(*this, D.getAttributes());
13401  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
13402  ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
13403 }
13404 
13405 /// DeclClonePragmaWeak - clone existing decl (maybe definition),
13406 /// \#pragma weak needs a non-definition decl and source may not have one.
13408  SourceLocation Loc) {
13409  assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
13410  NamedDecl *NewD = nullptr;
13411  if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
13412  FunctionDecl *NewFD;
13413  // FIXME: Missing call to CheckFunctionDeclaration().
13414  // FIXME: Mangling?
13415  // FIXME: Is the qualifier info correct?
13416  // FIXME: Is the DeclContext correct?
13417  NewFD = FunctionDecl::Create(
13418  FD->getASTContext(), FD->getDeclContext(), Loc, Loc,
13419  DeclarationName(II), FD->getType(), FD->getTypeSourceInfo(), SC_None,
13420  getCurFPFeatures().isFPConstrained(), false /*isInlineSpecified*/,
13421  FD->hasPrototype(), ConstexprSpecKind::Unspecified,
13423  NewD = NewFD;
13424 
13425  if (FD->getQualifier())
13426  NewFD->setQualifierInfo(FD->getQualifierLoc());
13427 
13428  // Fake up parameter variables; they are declared as if this were
13429  // a typedef.
13430  QualType FDTy = FD->getType();
13431  if (const auto *FT = FDTy->getAs<FunctionProtoType>()) {
13433  for (const auto &AI : FT->param_types()) {
13434  ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
13435  Param->setScopeInfo(0, Params.size());
13436  Params.push_back(Param);
13437  }
13438  NewFD->setParams(Params);
13439  }
13440  } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
13441  NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
13442  VD->getInnerLocStart(), VD->getLocation(), II,
13443  VD->getType(), VD->getTypeSourceInfo(),
13444  VD->getStorageClass());
13445  if (VD->getQualifier())
13446  cast<VarDecl>(NewD)->setQualifierInfo(VD->getQualifierLoc());
13447  }
13448  return NewD;
13449 }
13450 
13451 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
13452 /// applied to it, possibly with an alias.
13453 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W) {
13454  if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
13455  IdentifierInfo *NDId = ND->getIdentifier();
13456  NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
13457  NewD->addAttr(
13458  AliasAttr::CreateImplicit(Context, NDId->getName(), W.getLocation()));
13459  NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
13460  WeakTopLevelDecl.push_back(NewD);
13461  // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
13462  // to insert Decl at TU scope, sorry.
13463  DeclContext *SavedContext = CurContext;
13464  CurContext = Context.getTranslationUnitDecl();
13465  NewD->setDeclContext(CurContext);
13466  NewD->setLexicalDeclContext(CurContext);
13467  PushOnScopeChains(NewD, S);
13468  CurContext = SavedContext;
13469  } else { // just add weak to existing
13470  ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation()));
13471  }
13472 }
13473 
13474 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
13475  // It's valid to "forward-declare" #pragma weak, in which case we
13476  // have to do this.
13477  LoadExternalWeakUndeclaredIdentifiers();
13478  if (WeakUndeclaredIdentifiers.empty())
13479  return;
13480  NamedDecl *ND = nullptr;
13481  if (auto *VD = dyn_cast<VarDecl>(D))
13482  if (VD->isExternC())
13483  ND = VD;
13484  if (auto *FD = dyn_cast<FunctionDecl>(D))
13485  if (FD->isExternC())
13486  ND = FD;
13487  if (!ND)
13488  return;
13489  if (IdentifierInfo *Id = ND->getIdentifier()) {
13490  auto I = WeakUndeclaredIdentifiers.find(Id);
13491  if (I != WeakUndeclaredIdentifiers.end()) {
13492  auto &WeakInfos = I->second;
13493  for (const auto &W : WeakInfos)
13494  DeclApplyPragmaWeak(S, ND, W);
13495  std::remove_reference_t<decltype(WeakInfos)> EmptyWeakInfos;
13496  WeakInfos.swap(EmptyWeakInfos);
13497  }
13498  }
13499 }
13500 
13501 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
13502 /// it, apply them to D. This is a bit tricky because PD can have attributes
13503 /// specified in many different places, and we need to find and apply them all.
13504 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
13505  // Ordering of attributes can be important, so we take care to process
13506  // attributes in the order in which they appeared in the source code.
13507 
13508  // First, process attributes that appeared on the declaration itself (but
13509  // only if they don't have the legacy behavior of "sliding" to the DeclSepc).
13510  ParsedAttributesView NonSlidingAttrs;
13511  for (ParsedAttr &AL : PD.getDeclarationAttributes()) {
13513  // Skip processing the attribute, but do check if it appertains to the
13514  // declaration. This is needed for the `MatrixType` attribute, which,
13515  // despite being a type attribute, defines a `SubjectList` that only
13516  // allows it to be used on typedef declarations.
13517  AL.diagnoseAppertainsTo(*this, D);
13518  } else {
13519  NonSlidingAttrs.addAtEnd(&AL);
13520  }
13521  }
13522  ProcessDeclAttributeList(S, D, NonSlidingAttrs);
13523 
13524  // Apply decl attributes from the DeclSpec if present.
13525  if (!PD.getDeclSpec().getAttributes().empty()) {
13526  ProcessDeclAttributeList(S, D, PD.getDeclSpec().getAttributes(),
13527  ProcessDeclAttributeOptions()
13528  .WithIncludeCXX11Attributes(false)
13529  .WithIgnoreTypeAttributes(true));
13530  }
13531 
13532  // Walk the declarator structure, applying decl attributes that were in a type
13533  // position to the decl itself. This handles cases like:
13534  // int *__attr__(x)** D;
13535  // when X is a decl attribute.
13536  for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i) {
13537  ProcessDeclAttributeList(S, D, PD.getTypeObject(i).getAttrs(),
13538  ProcessDeclAttributeOptions()
13539  .WithIncludeCXX11Attributes(false)
13540  .WithIgnoreTypeAttributes(true));
13541  }
13542 
13543  // Finally, apply any attributes on the decl itself.
13544  ProcessDeclAttributeList(S, D, PD.getAttributes());
13545 
13546  // Apply additional attributes specified by '#pragma clang attribute'.
13547  AddPragmaAttributes(S, D);
13548 
13549  // Look for API notes that map to attributes.
13550  ProcessAPINotes(D);
13551 }
13552 
13553 /// Is the given declaration allowed to use a forbidden type?
13554 /// If so, it'll still be annotated with an attribute that makes it
13555 /// illegal to actually use.
13556 static bool isForbiddenTypeAllowed(Sema &S, Decl *D,
13557  const DelayedDiagnostic &diag,
13558  UnavailableAttr::ImplicitReason &reason) {
13559  // Private ivars are always okay. Unfortunately, people don't
13560  // always properly make their ivars private, even in system headers.
13561  // Plus we need to make fields okay, too.
13562  if (!isa<FieldDecl>(D) && !isa<ObjCPropertyDecl>(D) &&
13563  !isa<FunctionDecl>(D))
13564  return false;
13565 
13566  // Silently accept unsupported uses of __weak in both user and system
13567  // declarations when it's been disabled, for ease of integration with
13568  // -fno-objc-arc files. We do have to take some care against attempts
13569  // to define such things; for now, we've only done that for ivars
13570  // and properties.
13571  if ((isa<ObjCIvarDecl>(D) || isa<ObjCPropertyDecl>(D))) {
13572  if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
13573  diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
13574  reason = UnavailableAttr::IR_ForbiddenWeak;
13575  return true;
13576  }
13577  }
13578 
13579  // Allow all sorts of things in system headers.
13581  // Currently, all the failures dealt with this way are due to ARC
13582  // restrictions.
13583  reason = UnavailableAttr::IR_ARCForbiddenType;
13584  return true;
13585  }
13586 
13587  return false;
13588 }
13589 
13590 /// Handle a delayed forbidden-type diagnostic.
13591 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD,
13592  Decl *D) {
13593  auto Reason = UnavailableAttr::IR_None;
13594  if (D && isForbiddenTypeAllowed(S, D, DD, Reason)) {
13595  assert(Reason && "didn't set reason?");
13596  D->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", Reason, DD.Loc));
13597  return;
13598  }
13599  if (S.getLangOpts().ObjCAutoRefCount)
13600  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
13601  // FIXME: we may want to suppress diagnostics for all
13602  // kind of forbidden type messages on unavailable functions.
13603  if (FD->hasAttr<UnavailableAttr>() &&
13605  diag::err_arc_array_param_no_ownership) {
13606  DD.Triggered = true;
13607  return;
13608  }
13609  }
13610 
13611  S.Diag(DD.Loc, DD.getForbiddenTypeDiagnostic())
13613  DD.Triggered = true;
13614 }
13615 
13616 
13617 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
13618  assert(DelayedDiagnostics.getCurrentPool());
13619  DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
13620  DelayedDiagnostics.popWithoutEmitting(state);
13621 
13622  // When delaying diagnostics to run in the context of a parsed
13623  // declaration, we only want to actually emit anything if parsing
13624  // succeeds.
13625  if (!decl) return;
13626 
13627  // We emit all the active diagnostics in this pool or any of its
13628  // parents. In general, we'll get one pool for the decl spec
13629  // and a child pool for each declarator; in a decl group like:
13630  // deprecated_typedef foo, *bar, baz();
13631  // only the declarator pops will be passed decls. This is correct;
13632  // we really do need to consider delayed diagnostics from the decl spec
13633  // for each of the different declarations.
13634  const DelayedDiagnosticPool *pool = &poppedPool;
13635  do {
13636  bool AnyAccessFailures = false;
13638  i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
13639  // This const_cast is a bit lame. Really, Triggered should be mutable.
13640  DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
13641  if (diag.Triggered)
13642  continue;
13643 
13644  switch (diag.Kind) {
13646  // Don't bother giving deprecation/unavailable diagnostics if
13647  // the decl is invalid.
13648  if (!decl->isInvalidDecl())
13649  handleDelayedAvailabilityCheck(diag, decl);
13650  break;
13651 
13653  // Only produce one access control diagnostic for a structured binding
13654  // declaration: we don't need to tell the user that all the fields are
13655  // inaccessible one at a time.
13656  if (AnyAccessFailures && isa<DecompositionDecl>(decl))
13657  continue;
13658  HandleDelayedAccessCheck(diag, decl);
13659  if (diag.Triggered)
13660  AnyAccessFailures = true;
13661  break;
13662 
13664  handleDelayedForbiddenType(*this, diag, decl);
13665  break;
13666  }
13667  }
13668  } while ((pool = pool->getParent()));
13669 }
13670 
13671 /// Given a set of delayed diagnostics, re-emit them as if they had
13672 /// been delayed in the current context instead of in the given pool.
13673 /// Essentially, this just moves them to the current pool.
13675  DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
13676  assert(curPool && "re-emitting in undelayed context not supported");
13677  curPool->steal(pool);
13678 }
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3299
NodeId Parent
Definition: ASTDiff.cpp:191
int Id
Definition: ASTDiff.cpp:190
static char ID
Definition: Arena.cpp:183
static SmallString< 64 > normalizeName(const IdentifierInfo *Name, const IdentifierInfo *Scope, AttributeCommonInfo::Syntax SyntaxUsed)
Definition: Attributes.cpp:131
#define SM(sm)
Definition: Cuda.cpp:83
llvm::APSInt APSInt
static CudaArch getCudaArch(CodeGenModule &CGM)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
Defines the clang::Expr interface and subclasses for C++ expressions.
int Priority
Definition: Format.cpp:2979
unsigned Offset
Definition: Format.cpp:2977
Defines helper utilities for supporting the HLSL runtime environment.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
#define X(type, name)
Definition: Value.h:143
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::raw_ostream & OS
Definition: Logger.cpp:24
llvm::MachO::Target Target
Definition: MachO.h:50
llvm::MachO::Record Record
Definition: MachO.h:31
static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y)
Check whether the two versions match.
Definition: ObjCMT.cpp:1068
Defines the clang::Preprocessor interface.
static void ProcessAPINotes(Sema &S, Decl *D, const api_notes::CommonEntityInfo &Info, VersionedInfoMetadata Metadata)
This file declares semantic analysis for CUDA constructs.
static bool isCFStringType(QualType T, ASTContext &Ctx)
static bool isNSStringType(QualType T, ASTContext &Ctx, bool AllowNSAttributedString=false)
static const ParmVarDecl * getFunctionOrMethodParam(const Decl *D, unsigned Idx)
static bool isFunctionOrMethodVariadic(const Decl *D)
static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx)
static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr, uint32_t &Val, unsigned Idx=UINT_MAX, bool StrictlyUnsigned=false)
If Expr is a valid integer constant, get the value of the integer expression and return success or fa...
static bool checkAttrMutualExclusion(Sema &S, Decl *D, const AttributeCommonInfo &AL)
Diagnose mutually exclusive attributes when present on a given declaration.
static bool isFunctionOrMethod(const Decl *D)
isFunctionOrMethod - Return true if the given decl has function type (function or function-typed vari...
static bool hasDeclarator(const Decl *D)
Return true if the given decl has a declarator that should have been processed by Sema::GetTypeForDec...
static bool isFunctionOrMethodOrBlock(const Decl *D)
Return true if the given decl has function type (function or function-typed variable) or an Objective...
static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D)
static unsigned getNumAttributeArgs(const ParsedAttr &AL)
static bool hasFunctionProto(const Decl *D)
hasFunctionProto - Return true if the given decl has a argument information.
static unsigned getFunctionOrMethodNumParams(const Decl *D)
getFunctionOrMethodNumParams - Return number of function or method parameters.
static bool isInstanceMethod(const Decl *D)
static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx)
static QualType getFunctionOrMethodResultType(const Decl *D)
static std::enable_if_t< std::is_base_of_v< Attr, AttrInfo >, SourceLocation > getAttrLoc(const AttrInfo &AL)
A helper function to provide Attribute Location for the Attr types AND the ParsedAttr.
static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr, int &Val, unsigned Idx=UINT_MAX)
Wrapper around checkUInt32Argument, with an extra check to be sure that the result will fit into a re...
This file declares semantic analysis for HLSL constructs.
SourceRange Range
Definition: SemaObjC.cpp:754
SourceLocation Loc
Definition: SemaObjC.cpp:755
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for SYCL constructs.
static Attr * handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * handleSYCLIntelInitiationIntervalAttr(Sema &S, Stmt *St, const ParsedAttr &A)
static Attr * handleMSConstexprAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * handleSYCLIntelMaxConcurrencyAttr(Sema &S, Stmt *St, const ParsedAttr &A)
static Attr * handleAlwaysInlineAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
static Attr * handleNoMergeAttr(Sema &S, Stmt *St, const ParsedAttr &A, SourceRange Range)
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Enumerates target-specific builtins in their own namespaces within namespace clang.
C Language Family Type Representation.
__DEVICE__ int min(int __a, int __b)
__DEVICE__ int max(int __a, int __b)
__device__ int
bool hasValue() const
Definition: APValue.h:399
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: ASTConsumer.h:112
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:185
MSGuidDecl * getMSGuidDecl(MSGuidDeclParts Parts) const
Return a declaration for the global GUID object representing the given GUID value.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
SourceManager & getSourceManager()
Definition: ASTContext.h:708
TypedefDecl * getObjCInstanceTypeDecl()
Retrieve the typedef declaration corresponding to the Objective-C "instancetype" type.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:651
MangleContext * createMangleContext(const TargetInfo *T=nullptr)
If T is null pointer, assume the target in ASTContext.
QualType getRealTypeForBitwidth(unsigned DestWidth, FloatModeKind ExplicitType) const
getRealTypeForBitwidth - sets floating point QualTy according to specified bitwidth.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2605
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
IdentifierTable & Idents
Definition: ASTContext.h:647
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:649
QualType getConstType(QualType T) const
Return the uniqued reference to the type for a const qualified type.
Definition: ASTContext.h:1313
const LangOptions & getLangOpts() const
Definition: ASTContext.h:778
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType IntTy
Definition: ASTContext.h:1103
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
Definition: ASTContext.h:1122
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2355
CanQualType VoidTy
Definition: ASTContext.h:1094
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:760
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
TargetCXXABI::Kind getCXXABIKind() const
Return the C++ ABI kind that should be used.
Definition: ASTContext.cpp:818
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:761
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1076
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2386
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2359
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
Represents an access specifier followed by colon ':'.
Definition: DeclCXX.h:86
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
Attr - This represents one attribute.
Definition: Attr.h:46
SourceLocation getLocation() const
Definition: Attr.h:99
SourceLocation getScopeLoc() const
void setAttributeSpellingListIndex(unsigned V)
std::string getNormalizedFullName() const
Gets the normalized full name, which consists of both scope and name and with surrounding underscores...
Definition: Attributes.cpp:155
unsigned getAttributeSpellingListIndex() const
const IdentifierInfo * getAttrName() const
SourceLocation getLoc() const
const IdentifierInfo * getScopeName() const
bool isStandardAttributeSyntax() const
The attribute is spelled [[]] in either C or C++ mode, including standard attributes spelled with a k...
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5992
Pointer to a block type.
Definition: Type.h:3360
This class is used for builtin types like 'int'.
Definition: Type.h:2988
bool isAuxBuiltinID(unsigned ID) const
Return true if builtin ID belongs to AuxTarget.
Definition: Builtins.h:262
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
static bool isBuiltinFunc(llvm::StringRef Name)
Returns true if this is a libc/libm function without the '__builtin_' prefix.
Definition: Builtins.cpp:63
unsigned getAuxBuiltinID(unsigned ID) const
Return real builtin ID (i.e.
Definition: Builtins.h:268
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
bool isVirtual() const
Definition: DeclCXX.h:2115
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2210
static bool isStaticOverloadedOperator(OverloadedOperatorKind OOK)
Returns true if the given operator is implicitly static in a record context.
Definition: DeclCXX.h:2102
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1548
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1022
bool hasDefinition() const
Definition: DeclCXX.h:571
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1897
MSInheritanceModel calculateInheritanceModel() const
Calculate what the inheritance model would be for this class.
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
Represents the this expression in C++.
Definition: ExprCXX.h:1148
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2872
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition: Expr.cpp:1549
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
Declaration of a class template.
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:1072
llvm::APSInt getResultAsAPSInt() const
Definition: Expr.cpp:401
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:350
const RelatedTargetVersionMapping * getVersionMapping(OSEnvPair Kind) const
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1369
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2342
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
bool isFileContext() const
Definition: DeclBase.h:2137
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1938
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2322
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1333
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
ValueDecl * getDecl()
Definition: Expr.h:1328
DeclarationNameInfo getNameInfo() const
Definition: Expr.h:1332
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:488
bool hasQualifier() const
Determine whether this declaration reference was preceded by a C++ nested-name-specifier,...
Definition: Expr.h:1343
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:870
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool hasAttrs() const
Definition: DeclBase.h:524
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
void addAttr(Attr *A)
Definition: DeclBase.cpp:991
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
AttrVec & getAttrs()
Definition: DeclBase.h:530
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
Definition: DeclBase.cpp:1132
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:227
bool canBeWeakImported(bool &IsDefinition) const
Determines whether this symbol can be weak-imported, e.g., whether it would be well-formed to add the...
Definition: DeclBase.cpp:791
bool isInvalidDecl() const
Definition: DeclBase.h:594
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
SourceLocation getLocation() const
Definition: DeclBase.h:445
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:565
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1039
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:437
void dropAttr()
Definition: DeclBase.h:562
static bool isFlexibleArrayMemberLike(ASTContext &Context, const Decl *D, QualType Ty, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution)
Whether it resembles a flexible array member.
Definition: DeclBase.cpp:413
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:336
bool hasAttr() const
Definition: DeclBase.h:583
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:340
Kind getKind() const
Definition: DeclBase.h:448
T * getAttr() const
Definition: DeclBase.h:579
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:433
DeclContext * getDeclContext()
Definition: DeclBase.h:454
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:847
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:814
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:829
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1989
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:823
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:2001
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:800
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:837
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1900
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2047
const ParsedAttributesView & getDeclarationAttributes() const
Definition: DeclSpec.h:2686
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2394
const ParsedAttributes & getAttributes() const
Definition: DeclSpec.h:2683
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2398
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5586
EnumDecl * getDecl() const
Definition: Type.h:5593
This represents one expression.
Definition: Expr.h:110
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
static bool isPotentialConstantExprUnevaluated(Expr *E, const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExprUnevaluated - Return true if this expression might be usable in a constant exp...
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3116
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates).
Definition: Expr.h:239
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:956
Represents a member of a struct/union/class.
Definition: Decl.h:3060
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4670
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3273
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:72
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:135
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:98
Represents a function declaration or definition.
Definition: Decl.h:1972
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4058
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2286
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3877
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3636
param_iterator param_end()
Definition: Decl.h:2699
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2833
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition: Decl.h:2608
QualType getReturnType() const
Definition: Decl.h:2757
param_iterator param_begin()
Definition: Decl.h:2698
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3093
bool isConstexprSpecified() const
Definition: Decl.h:2444
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2161
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2686
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3983
bool isConsteval() const
Definition: Decl.h:2447
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3696
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3160
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2811
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2709
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4667
QualType desugar() const
Definition: Type.h:5134
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
Definition: Type.h:5105
Declaration of a template function.
Definition: DeclTemplate.h:957
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4267
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition: Type.h:4554
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition: Type.h:4550
QualType getReturnType() const
Definition: Type.h:4584
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
One of these records is kept for each identifier that is lexed.
unsigned getBuiltinID() const
Return a value indicating whether this is a builtin function.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:1032
@ IncompleteOnly
Any trailing array member of undefined size is a FAM.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:482
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:666
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:517
std::string getOpenCLVersionString() const
Return the OpenCL C or C++ for OpenCL language name and version as a string.
Definition: LangOptions.cpp:79
bool isSYCL() const
Definition: LangOptions.h:749
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:63
void push_back(const T &LocalValue)
Represents the results of name lookup.
Definition: Lookup.h:46
A global _GUID constant.
Definition: DeclCXX.h:4289
Describes a module or submodule.
Definition: Module.h:105
This represents a decl that may have a name.
Definition: Decl.h:249
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
bool isCXXInstanceMember() const
Determine whether the given declaration is an instance member of a C++ class.
Definition: Decl.cpp:1963
bool isExternallyVisible() const
Definition: Decl.h:409
A C++ nested-name-specifier augmented with source location information.
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
void setHasDesignatedInitializers()
Indicate that this interface decl contains at least one initializer marked with the 'objc_designated_...
Definition: DeclObjC.cpp:1595
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition: Type.h:7019
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
bool allowsDirectDispatch() const
Does this runtime supports direct dispatch.
Definition: ObjCRuntime.h:467
static OpaquePtr getFromOpaquePtr(void *P)
Definition: Ownership.h:91
void * getAsOpaquePtr() const
Definition: Ownership.h:90
bool isSupported(llvm::StringRef Ext, const LangOptions &LO) const
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:254
unsigned getSourceIndex() const
Get the parameter index as it would normally be encoded for attributes at the source level of represe...
Definition: Attr.h:322
unsigned getASTIndex() const
Get the parameter index as it would normally be encoded at the AST level of representation: zero-orig...
Definition: Attr.h:333
A parameter attribute which changes the argument-passing ABI rule for the parameter.
Definition: Attr.h:222
Represents a parameter to a function.
Definition: Decl.h:1762
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1795
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2942
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:129
bool isPackExpansion() const
Definition: ParsedAttr.h:382
const ParsedType & getMatchingCType() const
Definition: ParsedAttr.h:458
IdentifierLoc * getArgAsIdent(unsigned Arg) const
Definition: ParsedAttr.h:406
unsigned getSemanticSpelling() const
If the parsed attribute has a semantic equivalent, and it would have a semantic Spelling enumeration ...
Definition: ParsedAttr.cpp:266
bool supportsNonconformingLambdaSyntax() const
Definition: ParsedAttr.cpp:222
bool existsInTarget(const TargetInfo &Target) const
Definition: ParsedAttr.cpp:201
bool checkExactlyNumArgs(class Sema &S, unsigned Num) const
Check if the attribute has exactly as many args as Num.
Definition: ParsedAttr.cpp:302
bool hasParsedType() const
Definition: ParsedAttr.h:352
const IdentifierLoc * getEnvironment() const
Definition: ParsedAttr.h:452
Expr * getArgAsExpr(unsigned Arg) const
Definition: ParsedAttr.h:398
void setInvalid(bool b=true) const
Definition: ParsedAttr.h:360
bool hasVariadicArg() const
Definition: ParsedAttr.cpp:270
void handleAttrWithDelayedArgs(Sema &S, Decl *D) const
Definition: ParsedAttr.cpp:282
const ParsedAttrInfo & getInfo() const
Definition: ParsedAttr.h:635
bool hasProcessingCache() const
Definition: ParsedAttr.h:362
SourceLocation getUnavailableLoc() const
Definition: ParsedAttr.h:434
bool diagnoseAppertainsTo(class Sema &S, const Decl *D) const
Definition: ParsedAttr.cpp:162
unsigned getProcessingCache() const
Definition: ParsedAttr.h:364
bool acceptsExprPack() const
Definition: ParsedAttr.cpp:264
SourceLocation getStrictLoc() const
Definition: ParsedAttr.h:428
bool isTypeAttr() const
Definition: ParsedAttr.cpp:197
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this attribute.
Definition: ParsedAttr.h:386
bool isArgIdent(unsigned Arg) const
Definition: ParsedAttr.h:402
bool getMustBeNull() const
Definition: ParsedAttr.h:470
bool checkAtLeastNumArgs(class Sema &S, unsigned Num) const
Check if the attribute has at least as many args as Num.
Definition: ParsedAttr.cpp:307
bool isUsedAsTypeAttr() const
Definition: ParsedAttr.h:374
unsigned getNumArgMembers() const
Definition: ParsedAttr.cpp:154
bool isStmtAttr() const
Definition: ParsedAttr.cpp:199
bool isPragmaClangAttribute() const
True if the attribute is specified using '#pragma clang attribute'.
Definition: ParsedAttr.h:378
bool slidesFromDeclToDeclSpecLegacyBehavior() const
Returns whether a [[]] attribute, if specified ahead of a declaration, should be applied to the decl-...
Definition: ParsedAttr.cpp:226
const AvailabilityChange & getAvailabilityObsoleted() const
Definition: ParsedAttr.h:422
AttributeCommonInfo::Kind getKind() const
Definition: ParsedAttr.h:632
void setProcessingCache(unsigned value) const
Definition: ParsedAttr.h:369
const Expr * getMessageExpr() const
Definition: ParsedAttr.h:440
bool isParamExpr(size_t N) const
Definition: ParsedAttr.cpp:278
bool isArgExpr(unsigned Arg) const
Definition: ParsedAttr.h:394
const AvailabilityChange & getAvailabilityDeprecated() const
Definition: ParsedAttr.h:416
bool getLayoutCompatible() const
Definition: ParsedAttr.h:464
const Expr * getReplacementExpr() const
Definition: ParsedAttr.h:446
ArgsUnion getArg(unsigned Arg) const
getArg - Return the specified argument.
Definition: ParsedAttr.h:389
SourceLocation getEllipsisLoc() const
Definition: ParsedAttr.h:383
const AvailabilityChange & getAvailabilityIntroduced() const
Definition: ParsedAttr.h:410
bool isInvalid() const
Definition: ParsedAttr.h:359
bool checkAtMostNumArgs(class Sema &S, unsigned Num) const
Check if the attribute has at most as many args as Num.
Definition: ParsedAttr.cpp:312
const ParsedType & getTypeArg() const
Definition: ParsedAttr.h:476
void addAtEnd(ParsedAttr *newAttr)
Definition: ParsedAttr.h:853
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3150
QualType getPointeeType() const
Definition: Type.h:3160
IdentifierTable & getIdentifierTable()
A (possibly-)qualified type.
Definition: Type.h:940
QualType withConst() const
Definition: Type.h:1154
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:1220
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7370
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7496
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7410
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1432
QualType getCanonicalType() const
Definition: Type.h:7422
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7464
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7443
const Type * getTypePtrOrNull() const
Definition: Type.h:7374
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:347
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:340
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:336
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:350
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:353
ObjCLifetime getObjCLifetime() const
Definition: Type.h:531
bool empty() const
Definition: Type.h:633
Represents a struct/union/class.
Definition: Decl.h:4171
field_iterator field_end() const
Definition: Decl.h:4380
field_range fields() const
Definition: Decl.h:4377
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4223
field_iterator field_begin() const
Definition: Decl.cpp:5073
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5560
RecordDecl * getDecl() const
Definition: Type.h:5570
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3391
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:262
@ FunctionDeclarationScope
This is a scope that corresponds to the parameters within a function prototype for a function declara...
Definition: Scope.h:91
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:57
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:136
CUDAFunctionTarget CurrentTarget()
Gets the CUDA target for the current context.
Definition: SemaCUDA.h:142
SemaDiagnosticBuilder DiagIfHostCode(SourceLocation Loc, unsigned DiagID)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as host cod...
Definition: SemaCUDA.cpp:927
HLSLNumThreadsAttr * mergeNumThreadsAttr(Decl *D, const AttributeCommonInfo &AL, int X, int Y, int Z)
Definition: SemaHLSL.cpp:128
HLSLShaderAttr * mergeShaderAttr(Decl *D, const AttributeCommonInfo &AL, HLSLShaderAttr::ShaderType ShaderType)
Definition: SemaHLSL.cpp:143
HLSLParamModifierAttr * mergeParamModifierAttr(Decl *D, const AttributeCommonInfo &AL, HLSLParamModifierAttr::Spelling Spelling)
Definition: SemaHLSL.cpp:156
bool isCFError(RecordDecl *D)
Definition: SemaObjC.cpp:1461
IdentifierInfo * getNSErrorIdent()
Retrieve the identifier "NSError".
Definition: SemaObjC.cpp:1265
static bool isTypeDecoratedWithDeclAttribute(QualType Ty)
Definition: SemaSYCL.h:363
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:462
void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, RetainOwnershipKind K, bool IsTemplateInstantiation)
SemaObjC & ObjC()
Definition: Sema.h:1012
InternalLinkageAttr * mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL)
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:520
SYCLIntelMaxConcurrencyAttr * MergeSYCLIntelMaxConcurrencyAttr(Decl *D, const SYCLIntelMaxConcurrencyAttr &A)
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7471
SYCLIntelMaxReplicatesAttr * MergeSYCLIntelMaxReplicatesAttr(Decl *D, const SYCLIntelMaxReplicatesAttr &A)
void AddSYCLIntelMaxConcurrencyAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
AddSYCLIntelMaxConcurrencyAttr - Adds a max_concurrency attribute to a particular declaration.
void ProcessDeclAttributeDelayed(Decl *D, const ParsedAttributesView &AttrList)
RetainOwnershipKind
Definition: Sema.h:3697
void AddSYCLIntelMaxReplicatesAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, bool InInstantiation=false)
AddModeAttr - Adds a mode attribute to a particular declaration.
SYCLIntelNumSimdWorkItemsAttr * MergeSYCLIntelNumSimdWorkItemsAttr(Decl *D, const SYCLIntelNumSimdWorkItemsAttr &A)
bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD=nullptr, CUDAFunctionTarget CFT=CUDAFunctionTarget::InvalidTarget)
Check validaty of calling convention attribute attr.
void ProcessPragmaWeak(Scope *S, Decl *D)
bool checkSectionName(SourceLocation LiteralLoc, StringRef Str)
bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A, bool SkipArgCountCheck=false)
Handles semantic checking for features that are common to all attributes, such as checking whether a ...
Definition: SemaAttr.cpp:1454
MinSizeAttr * mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI)
void AddSYCLIntelMaxWorkGroupsPerMultiprocessorAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2219
IntelNamedSubGroupSizeAttr * MergeIntelNamedSubGroupSizeAttr(Decl *D, const IntelNamedSubGroupSizeAttr &A)
void AddSYCLUsesAspectsAttr(Decl *D, const AttributeCommonInfo &CI, Expr **Exprs, unsigned Size)
ExtVectorDeclsType ExtVectorDecls
ExtVectorDecls - This is a list all the extended vector types.
Definition: Sema.h:3578
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
bool checkTargetClonesAttrString(SourceLocation LiteralLoc, StringRef Str, const StringLiteral *Literal, Decl *D, bool &HasDefault, bool &HasCommas, bool &HasNotDefault, SmallVectorImpl< SmallString< 64 >> &StringsBuffer)
MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model)
SYCLIntelLoopFuseAttr * MergeSYCLIntelLoopFuseAttr(Decl *D, const SYCLIntelLoopFuseAttr &A)
ASTContext & Context
Definition: Sema.h:857
bool AnyWorkGroupSizesDiffer(const Expr *LHSXDim, const Expr *LHSYDim, const Expr *LHSZDim, const Expr *RHSXDim, const Expr *RHSYDim, const Expr *RHSZDim)
void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks)
AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular declaration.
void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max)
addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a particular declaration.
void AddSYCLWorkGroupSizeHintAttr(Decl *D, const AttributeCommonInfo &CI, Expr *XDim, Expr *YDim, Expr *ZDim)
bool checkMSInheritanceAttrOnDefinition(CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceModel SemanticSpelling)
AMDGPUMaxNumWorkGroupsAttr * CreateAMDGPUMaxNumWorkGroupsAttr(const AttributeCommonInfo &CI, Expr *XExpr, Expr *YExpr, Expr *ZExpr)
Create an AMDGPUMaxNumWorkGroupsAttr attribute.
void AddSYCLDeviceHasAttr(Decl *D, const AttributeCommonInfo &CI, Expr **Exprs, unsigned Size)
SYCLAddIRAttributesGlobalVariableAttr * MergeSYCLAddIRAttributesGlobalVariableAttr(Decl *D, const SYCLAddIRAttributesGlobalVariableAttr &A)
SYCLDeviceHasAttr * MergeSYCLDeviceHasAttr(Decl *D, const SYCLDeviceHasAttr &A)
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
void redelayDiagnostics(sema::DelayedDiagnosticPool &pool)
void DiagnoseDeprecatedAttribute(const ParsedAttr &A, StringRef NewScope, StringRef NewName)
Emit a diagnostic about the given attribute having a deprecated name, and also emit a fixit hint to g...
llvm::Error isValidSectionSpecifier(StringRef Str)
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
void AddSYCLIntelBankWidthAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
void checkUnusedDeclAttributes(Declarator &D)
bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl)
Definition: SemaAttr.cpp:693
void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, ParameterABI ABI)
SYCLAddIRAttributesFunctionAttr * MergeSYCLAddIRAttributesFunctionAttr(Decl *D, const SYCLAddIRAttributesFunctionAttr &A)
@ UPPC_Expression
An arbitrary expression.
Definition: Sema.h:10895
CodeSegAttr * mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type)
void PopParsingDeclaration(ParsingDeclState state, Decl *decl)
void AddSYCLReqdWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *XDim, Expr *YDim, Expr *ZDim)
void CheckDeprecatedSYCLAttributeSpelling(const ParsedAttr &A, StringRef NewName="")
Diagnoses an attribute in the 'intelfpga' namespace and suggests using the attribute in the 'intel' n...
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList)
SYCLIntelPipeIOAttr * MergeSYCLIntelPipeIOAttr(Decl *D, const SYCLIntelPipeIOAttr &A)
void CheckAlignasUnderalignment(Decl *D)
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AttrList, const ProcessDeclAttributeOptions &Options=ProcessDeclAttributeOptions())
Preprocessor & PP
Definition: Sema.h:856
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
void AddSYCLAddIRAnnotationsMemberAttr(Decl *D, const AttributeCommonInfo &CI, MutableArrayRef< Expr * > Args)
bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value)
void AddSYCLIntelPrivateCopiesAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
const LangOptions & LangOpts
Definition: Sema.h:855
const LangOptions & getLangOpts() const
Definition: Sema.h:519
static const uint64_t MaximumAlignment
Definition: Sema.h:797
void CheckSYCLAddIRAttributesFunctionAttrConflicts(Decl *D)
void AddSYCLIntelNumBanksAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
EnforceTCBAttr * mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL)
CUDALaunchBoundsAttr * CreateLaunchBoundsAttr(const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks, Expr *MaxBlocks)
Create an CUDALaunchBoundsAttr attribute.
SYCLAddIRAnnotationsMemberAttr * MergeSYCLAddIRAnnotationsMemberAttr(Decl *D, const SYCLAddIRAnnotationsMemberAttr &A)
void AddSYCLIntelSchedulerTargetFmaxMhzAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition: Sema.cpp:1559
AMDGPUWavesPerEUAttr * CreateAMDGPUWavesPerEUAttr(const AttributeCommonInfo &CI, Expr *Min, Expr *Max)
Create an AMDGPUWavesPerEUAttr attribute.
IntelReqdSubGroupSizeAttr * MergeIntelReqdSubGroupSizeAttr(Decl *D, const IntelReqdSubGroupSizeAttr &A)
bool checkTargetVersionAttr(SourceLocation LiteralLoc, Decl *D, StringRef &Str, bool &isDefault)
UuidAttr * mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl)
bool isValidPointerAttrType(QualType T, bool RefOkay=false)
Determine if type T is a valid subject for a nonnull and similar attributes.
SYCLAddIRAttributesKernelParameterAttr * MergeSYCLAddIRAttributesKernelParameterAttr(Decl *D, const SYCLAddIRAttributesKernelParameterAttr &A)
void AddIntelReqdSubGroupSize(Decl *D, const AttributeCommonInfo &CI, Expr *E)
bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, const Expr *E, StringRef &Str, SourceLocation *ArgLocation=nullptr)
SYCLIntelESimdVectorizeAttr * MergeSYCLIntelESimdVectorizeAttr(Decl *D, const SYCLIntelESimdVectorizeAttr &A)
SYCLIntelSchedulerTargetFmaxMhzAttr * MergeSYCLIntelSchedulerTargetFmaxMhzAttr(Decl *D, const SYCLIntelSchedulerTargetFmaxMhzAttr &A)
ErrorAttr * mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI, StringRef NewUserDiagnostic)
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg)
VisibilityAttr * mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis)
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
SemaSYCL & SYCL()
Definition: Sema.h:1037
SYCLTypeAttr * MergeSYCLTypeAttr(Decl *D, const AttributeCommonInfo &CI, SYCLTypeAttr::SYCLType TypeName)
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:6200
SourceManager & getSourceManager() const
Definition: Sema.h:524
void AddSYCLIntelNoGlobalWorkOffsetAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc, const ParsedAttr &AL, bool IsAsync)
Do a check to make sure Name looks like a legal argument for the swift_name attribute applied to decl...
void AddSYCLAddIRAttributesKernelParameterAttr(Decl *D, const AttributeCommonInfo &CI, MutableArrayRef< Expr * > Args)
bool AllWorkGroupSizesSame(const Expr *LHSXDim, const Expr *LHSYDim, const Expr *LHSZDim, const Expr *RHSXDim, const Expr *RHSYDim, const Expr *RHSZDim)
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:10588
void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, Expr *OE)
AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular declaration.
void AddSYCLIntelMaxGlobalWorkDimAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
SYCLWorkGroupSizeHintAttr * MergeSYCLWorkGroupSizeHintAttr(Decl *D, const SYCLWorkGroupSizeHintAttr &A)
void AddSYCLIntelForcePow2DepthAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
SYCLIntelMaxGlobalWorkDimAttr * MergeSYCLIntelMaxGlobalWorkDimAttr(Decl *D, const SYCLIntelMaxGlobalWorkDimAttr &A)
void AddSYCLIntelBankBitsAttr(Decl *D, const AttributeCommonInfo &CI, Expr **Exprs, unsigned Size)
SemaHLSL & HLSL()
Definition: Sema.h:1007
SYCLIntelNumBanksAttr * MergeSYCLIntelNumBanksAttr(Decl *D, const SYCLIntelNumBanksAttr &A)
OptimizeNoneAttr * mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI)
SYCLIntelMaxWorkGroupSizeAttr * MergeSYCLIntelMaxWorkGroupSizeAttr(Decl *D, const SYCLIntelMaxWorkGroupSizeAttr &A)
void AddSYCLAddIRAttributesGlobalVariableAttr(Decl *D, const AttributeCommonInfo &CI, MutableArrayRef< Expr * > Args)
ASTContext & getASTContext() const
Definition: Sema.h:526
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition: SemaDecl.cpp:293
ASTConsumer & Consumer
Definition: Sema.h:858
bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str)
AlwaysInlineAttr * mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident)
void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max)
addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size attribute to a particular declar...
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
void addAMDGPUMaxNumWorkGroupsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *XExpr, Expr *YExpr, Expr *ZExpr)
addAMDGPUMaxNumWorkGroupsAttr - Adds an amdgpu_max_num_work_groups attribute to a particular declarat...
@ AP_PragmaClangAttribute
The availability attribute was applied using '#pragma clang attribute'.
Definition: Sema.h:3545
@ AP_InferredFromOtherPlatform
The availability attribute for a specific platform was inferred from an availability attribute for an...
Definition: Sema.h:3549
@ AP_Explicit
The availability attribute was specified explicitly next to the declaration.
Definition: Sema.h:3542
@ AMK_None
Don't merge availability attributes at all.
Definition: Sema.h:3339
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8923
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:829
SectionAttr * mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
SwiftNameAttr * mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority, IdentifierInfo *IIEnvironment)
bool CheckMaxAllowedWorkGroupSize(const Expr *RWGSXDim, const Expr *RWGSYDim, const Expr *RWGSZDim, const Expr *MWGSXDim, const Expr *MWGSYDim, const Expr *MWGSZDim)
bool CheckAttrTarget(const ParsedAttr &CurrAttr)
void AddSYCLIntelESimdVectorizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
SYCLIntelMaxWorkGroupsPerMultiprocessorAttr * MergeSYCLIntelMaxWorkGroupsPerMultiprocessorAttr(Decl *D, const SYCLIntelMaxWorkGroupsPerMultiprocessorAttr &A)
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10678
void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, bool IsPackExpansion)
AddAlignedAttr - Adds an aligned attribute to a particular declaration.
SYCLUsesAspectsAttr * MergeSYCLUsesAspectsAttr(Decl *D, const SYCLUsesAspectsAttr &A)
SYCLIntelForcePow2DepthAttr * MergeSYCLIntelForcePow2DepthAttr(Decl *D, const SYCLIntelForcePow2DepthAttr &A)
SYCLIntelBankWidthAttr * MergeSYCLIntelBankWidthAttr(Decl *D, const SYCLIntelBankWidthAttr &A)
void AddSYCLAddIRAttributesFunctionAttr(Decl *D, const AttributeCommonInfo &CI, MutableArrayRef< Expr * > Args)
TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis)
void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef< Expr * > Args)
AddAnnotationAttr - Adds an annotation Annot with Args arguments to D.
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W)
SYCLIntelMinWorkGroupsPerComputeUnitAttr * MergeSYCLIntelMinWorkGroupsPerComputeUnitAttr(Decl *D, const SYCLIntelMinWorkGroupsPerComputeUnitAttr &A)
bool CheckAttrNoArgs(const ParsedAttr &CurrAttr)
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
DarwinSDKInfo * getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc, StringRef Platform)
Definition: Sema.cpp:75
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
Definition: SemaExpr.cpp:9260
void AddSYCLIntelNumSimdWorkItemsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
AddAlignValueAttr - Adds an align_value attribute to a particular declaration.
void AddSYCLIntelMinWorkGroupsPerComputeUnitAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
BTFDeclTagAttr * mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL)
void AddSYCLIntelLoopFuseAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
SYCLIntelInitiationIntervalAttr * MergeSYCLIntelInitiationIntervalAttr(Decl *D, const SYCLIntelInitiationIntervalAttr &A)
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2820
SYCLReqdWorkGroupSizeAttr * MergeSYCLReqdWorkGroupSizeAttr(Decl *D, const SYCLReqdWorkGroupSizeAttr &A)
void addSYCLIntelPipeIOAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ID)
addSYCLIntelPipeIOAttr - Adds a pipe I/O attribute to a particular declaration.
void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ParamExpr)
AddAllocAlignAttr - Adds an alloc_align attribute to a particular declaration.
AMDGPUFlatWorkGroupSizeAttr * CreateAMDGPUFlatWorkGroupSizeAttr(const AttributeCommonInfo &CI, Expr *Min, Expr *Max)
Create an AMDGPUWavesPerEUAttr attribute.
QualType BuildCountAttributedArrayType(QualType WrappedTy, Expr *CountExpr)
Definition: SemaType.cpp:9440
SYCLIntelNoGlobalWorkOffsetAttr * MergeSYCLIntelNoGlobalWorkOffsetAttr(Decl *D, const SYCLIntelNoGlobalWorkOffsetAttr &A)
DLLImportAttr * mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI)
SemaCUDA & CUDA()
Definition: Sema.h:1002
void AddSYCLIntelInitiationIntervalAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E)
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:583
void AddSYCLIntelMaxWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *XDim, Expr *YDim, Expr *ZDim)
NamedDecl * DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II, SourceLocation Loc)
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
bool isValid() const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3710
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3690
bool isUnion() const
Definition: Decl.h:3793
TagKind getTagKind() const
Definition: Decl.h:3782
Exposes information about the current target.
Definition: TargetInfo.h:218
const llvm::VersionTuple & getSDKVersion() const
Definition: TargetInfo.h:1780
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:472
virtual CallingConv getDefaultCallingConv() const
Gets the default calling convention for the given target and declaration context.
Definition: TargetInfo.h:1661
virtual CallingConvCheckResult checkCallingConvention(CallingConv CC) const
Determines whether a given calling convention is valid for the target.
Definition: TargetInfo.h:1679
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1561
unsigned getMaxTLSAlign() const
Return the maximum alignment (in bits) of a TLS variable.
Definition: TargetInfo.h:1569
virtual unsigned getRegisterWidth() const
Return the "preferred" register width on this target.
Definition: TargetInfo.h:879
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1504
virtual bool doesFeatureAffectCodeGen(StringRef Feature) const
Returns true if feature has an impact on target code generation.
Definition: TargetInfo.h:1399
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
virtual bool validateCPUSpecificCPUDispatch(StringRef Name) const
Definition: TargetInfo.h:1522
virtual bool hasProtectedVisibility() const
Does this target support "protected" visibility?
Definition: TargetInfo.h:1290
unsigned getRegParmMax() const
Definition: TargetInfo.h:1555
virtual unsigned getUnwindWordWidth() const
Definition: TargetInfo.h:874
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
Definition: TargetInfo.h:1393
unsigned getCharWidth() const
Definition: TargetInfo.h:496
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
Definition: TargetInfo.cpp:582
virtual bool supportsTargetAttributeTune() const
Determine whether this TargetInfo supports tune in target attribute.
Definition: TargetInfo.h:1360
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1294
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1472
virtual bool isValidCPUName(StringRef Name) const
Determine whether this TargetInfo supports the given CPU name.
Definition: TargetInfo.h:1347
TargetOptions & getTargetOpts() const
Retrieve the target options.
Definition: TargetInfo.h:312
virtual bool validateBranchProtection(StringRef Spec, StringRef Arch, BranchProtectionInfo &BPI, StringRef &Err) const
Determine if this TargetInfo supports the given branch protection specification.
Definition: TargetInfo.h:1448
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6100
[BoundsSafety] Represents information of declarations referenced by the arguments of the counted_by a...
Definition: Type.h:3178
const Type * getTypeForDecl() const
Definition: Decl.h:3417
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7341
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7352
The base class of the type hierarchy.
Definition: Type.h:1813
bool isSizelessType() const
As an extension, we classify types as one of "sized" or "sizeless"; every type is one or the other.
Definition: Type.cpp:2463
bool isStructureType() const
Definition: Type.cpp:629
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1871
bool isBlockPointerType() const
Definition: Type.h:7631
bool isVoidType() const
Definition: Type.h:7938
bool isBooleanType() const
Definition: Type.h:8066
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:730
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2135
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:667
bool isVoidPointerType() const
Definition: Type.cpp:655
bool isArrayType() const
Definition: Type.h:7689
bool isCharType() const
Definition: Type.cpp:2078
bool isFunctionPointerType() const
Definition: Type.h:7657
bool isPointerType() const
Definition: Type.h:7623
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7978
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8226
bool isReferenceType() const
Definition: Type.h:7635
bool isObjCNSObjectType() const
Definition: Type.cpp:4885
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition: Type.cpp:1856
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2047
bool isAlignValT() const
Definition: Type.cpp:3079
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:695
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8053
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2225
bool isExtVectorType() const
Definition: Type.h:7733
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2668
bool isBitIntType() const
Definition: Type.h:7873
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:7713
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2660
bool isCARCBridgableType() const
Determine whether the given type T is a "bridgeable" C type.
Definition: Type.cpp:4931
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2320
bool isMemberPointerType() const
Definition: Type.h:7671
bool isObjCIdType() const
Definition: Type.h:7792
bool isObjCObjectType() const
Definition: Type.h:7763
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4917
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:4860
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2351
bool isObjCObjectPointerType() const
Definition: Type.h:7759
Visibility getVisibility() const
Determine the visibility of this type.
Definition: Type.h:2889
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2247
bool isVectorType() const
Definition: Type.h:7729
bool isFloatingType() const
Definition: Type.cpp:2238
bool isAnyPointerType() const
Definition: Type.h:7627
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8159
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition: Type.cpp:605
bool isNullPtrType() const
Definition: Type.h:7971
bool isObjCRetainableType() const
Definition: Type.cpp:4897
bool isTypedefNameType() const
Determines whether this type is written as a typedef-name.
Definition: Type.h:8087
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition: Type.h:8100
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3435
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4900
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3959
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3862
Represents a C++ using-declaration.
Definition: DeclCXX.h:3512
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:707
void setType(QualType newType)
Definition: Decl.h:719
QualType getType() const
Definition: Decl.h:718
Represents a variable declaration or definition.
Definition: Decl.h:919
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2152
TLSKind getTLSKind() const
Definition: Decl.cpp:2169
void setARCPseudoStrong(bool PS)
Definition: Decl.h:1529
bool isExceptionVariable() const
Determine whether this variable is the exception variable in a C++ catch statememt or an Objective-C ...
Definition: Decl.h:1475
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1205
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1172
@ TLS_None
Not a TLS variable.
Definition: Decl.h:939
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition: Decl.cpp:2246
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1156
Represents a GCC generic vector type.
Definition: Type.h:3980
Captures information about a #pragma weak directive.
Definition: Weak.h:25
SourceLocation getLocation() const
Definition: Weak.h:33
const IdentifierInfo * getAlias() const
Definition: Weak.h:32
A collection of diagnostics which were delayed.
void steal(DelayedDiagnosticPool &pool)
Steal the diagnostics from the given pool.
const DelayedDiagnosticPool * getParent() const
SmallVectorImpl< DelayedDiagnostic >::const_iterator pool_iterator
A diagnostic message which has been conditionally emitted pending the complete parsing of the current...
QualType getForbiddenTypeOperand() const
unsigned getForbiddenTypeDiagnostic() const
The diagnostic ID to emit.
unsigned getForbiddenTypeArgument() const
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition: limits.h:64
constexpr XRayInstrMask None
Definition: XRayInstr.h:38
bool isGlobalVar(Expr *E)
Definition: Transforms.cpp:196
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
uint32_t Literal
Literals are represented as positive integers.
Definition: CNFFormula.h:35
llvm::APInt APInt
Definition: Integral.h:29
bool Sub(InterpState &S, CodePtr OpPC)
Definition: Interp.h:330
unsigned llvm::PointerUnion< const Decl *, const Expr * > DeclTy
Definition: Descriptor.h:27
std::string toString(const til::SExpr *E)
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
bool isa(CodeGen::Address addr)
Definition: Address.h:294
AttributeDeclKind
These constants match the enumerated choices of warn_attribute_wrong_decl_type and err_attribute_wron...
Definition: ParsedAttr.h:1095
@ ExpectedFunctionMethodOrParameter
Definition: ParsedAttr.h:1101
@ ExpectedFunctionWithProtoType
Definition: ParsedAttr.h:1108
@ ExpectedFunctionMethodOrBlock
Definition: ParsedAttr.h:1100
@ ExpectedTypeOrNamespace
Definition: ParsedAttr.h:1105
@ ExpectedVariableFieldOrTag
Definition: ParsedAttr.h:1104
@ ExpectedVariableOrField
Definition: ParsedAttr.h:1103
@ ExpectedUnion
Definition: ParsedAttr.h:1097
@ ExpectedFunctionOrMethod
Definition: ParsedAttr.h:1099
@ ExpectedVariable
Definition: ParsedAttr.h:1102
@ ExpectedVariableOrFunction
Definition: ParsedAttr.h:1098
@ ExpectedKernelFunction
Definition: ParsedAttr.h:1107
@ ExpectedFunctionVariableOrClass
Definition: ParsedAttr.h:1106
@ ExpectedFunction
Definition: ParsedAttr.h:1096
CudaArch
Definition: Cuda.h:54
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
llvm::StringRef getParameterABISpelling(ParameterABI kind)
CUDAFunctionTarget
Definition: Cuda.h:132
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
CudaVersion ToCudaVersion(llvm::VersionTuple)
Definition: Cuda.cpp:66
LLVM_READONLY bool isValidAsciiIdentifier(StringRef S, bool AllowDollar=false)
Return true if this is a valid ASCII identifier.
Definition: CharInfo.h:244
CudaArch StringToCudaArch(llvm::StringRef S)
Definition: Cuda.cpp:169
@ SC_Extern
Definition: Specifiers.h:248
@ SC_Register
Definition: Specifiers.h:254
@ SC_Static
Definition: Specifiers.h:249
@ SC_None
Definition: Specifiers.h:247
@ TSCS_unspecified
Definition: Specifiers.h:233
Language
The language for the input, used to select and validate the language standard and possible actions.
Definition: LangStandard.h:23
AttributeArgumentNType
These constants match the enumerated choices of err_attribute_argument_n_type and err_attribute_argum...
Definition: ParsedAttr.h:1084
@ AANT_ArgumentIntegerConstant
Definition: ParsedAttr.h:1086
@ AANT_ArgumentBuiltinFunction
Definition: ParsedAttr.h:1090
@ AANT_ArgumentIntOrBool
Definition: ParsedAttr.h:1085
@ AANT_ArgumentConstantExpr
Definition: ParsedAttr.h:1089
@ AANT_ArgumentIdentifier
Definition: ParsedAttr.h:1088
@ AANT_ArgumentString
Definition: ParsedAttr.h:1087
@ SD_Automatic
Automatic storage duration (most local variables).
Definition: Specifiers.h:326
@ Property
The type of a property.
ParameterABI
Kinds of parameter ABI.
Definition: Specifiers.h:363
@ SwiftAsyncContext
This parameter (which must have pointer type) uses the special Swift asynchronous context-pointer ABI...
@ SwiftErrorResult
This parameter (which must have pointer-to-pointer type) uses the special Swift error-result ABI trea...
@ Ordinary
This parameter uses ordinary ABI rules for its type.
@ SwiftIndirectResult
This parameter (which must have pointer type) is a Swift indirect result parameter.
@ SwiftContext
This parameter (which must have pointer type) uses the special Swift context-pointer ABI treatment.
@ Struct
The "struct" keyword.
CudaVersion
Definition: Cuda.h:20
LLVM_READONLY bool isHexDigit(unsigned char c)
Return true if this character is an ASCII hex digit: [0-9a-fA-F].
Definition: CharInfo.h:145
SanitizerMask parseSanitizerValue(StringRef Value, bool AllowGroups)
Parse a single value from a -fsanitize= or -fno-sanitize= value list.
Definition: Sanitizers.cpp:29
FloatModeKind
Definition: TargetInfo.h:72
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
const FunctionProtoType * T
MSInheritanceModel
Assigned inheritance model for a class in the MS C++ ABI.
Definition: Specifiers.h:389
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1275
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_X86Pascal
Definition: Specifiers.h:281
@ CC_Swift
Definition: Specifiers.h:290
@ CC_IntelOclBicc
Definition: Specifiers.h:287
@ CC_PreserveMost
Definition: Specifiers.h:292
@ CC_Win64
Definition: Specifiers.h:282
@ CC_X86ThisCall
Definition: Specifiers.h:279
@ CC_AArch64VectorCall
Definition: Specifiers.h:294
@ CC_AAPCS
Definition: Specifiers.h:285
@ CC_PreserveNone
Definition: Specifiers.h:298
@ CC_C
Definition: Specifiers.h:276
@ CC_AMDGPUKernelCall
Definition: Specifiers.h:296
@ CC_M68kRTD
Definition: Specifiers.h:297
@ CC_SwiftAsync
Definition: Specifiers.h:291
@ CC_X86RegCall
Definition: Specifiers.h:284
@ CC_RISCVVectorCall
Definition: Specifiers.h:299
@ CC_X86VectorCall
Definition: Specifiers.h:280
@ CC_AArch64SVEPCS
Definition: Specifiers.h:295
@ CC_X86StdCall
Definition: Specifiers.h:277
@ CC_X86_64SysV
Definition: Specifiers.h:283
@ CC_PreserveAll
Definition: Specifiers.h:293
@ CC_X86FastCall
Definition: Specifiers.h:278
@ CC_AAPCS_VFP
Definition: Specifiers.h:286
@ Generic
not a target-specific vector type
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
@ Union
The "union" keyword introduces the elaborated-type-specifier.
bool IsArmStreamingFunction(const FunctionDecl *FD, bool IncludeLocallyStreaming)
Returns whether the given FunctionDecl has an __arm[_locally]_streaming attribute.
Definition: Decl.cpp:5764
@ Other
Other implicit parameter.
const char * CudaArchToString(CudaArch A)
Definition: Cuda.cpp:151
unsigned long uint64_t
Represents information about a change in availability for an entity, which is part of the encoding of...
Definition: ParsedAttr.h:48
VersionTuple Version
The version number at which the change occurred.
Definition: ParsedAttr.h:53
bool isValid() const
Determine whether this availability change is valid.
Definition: ParsedAttr.h:59
static constexpr OSEnvPair macOStoMacCatalystPair()
Returns the os-environment mapping pair that's used to represent the macOS -> Mac Catalyst version ma...
Definition: DarwinSDKInfo.h:49
static constexpr OSEnvPair iOStoWatchOSPair()
Returns the os-environment mapping pair that's used to represent the iOS -> watchOS version mapping.
Definition: DarwinSDKInfo.h:63
static constexpr OSEnvPair iOStoTvOSPair()
Returns the os-environment mapping pair that's used to represent the iOS -> tvOS version mapping.
Definition: DarwinSDKInfo.h:70
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
DeclarationName getName() const
getName - Returns the embedded declaration name.
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition: DeclSpec.h:1660
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:630
Wraps an identifier and optional source location for the identifier.
Definition: ParsedAttr.h:103
SourceLocation Loc
Definition: ParsedAttr.h:104
IdentifierInfo * Ident
Definition: ParsedAttr.h:105
Parts of a decomposed MSGuidDecl.
Definition: DeclCXX.h:4264
uint16_t Part2
...-89ab-...
Definition: DeclCXX.h:4268
uint32_t Part1
{01234567-...
Definition: DeclCXX.h:4266
uint16_t Part3
...-cdef-...
Definition: DeclCXX.h:4270
uint8_t Part4And5[8]
...-0123-456789abcdef}
Definition: DeclCXX.h:4272
virtual AttrHandling handleDeclAttribute(Sema &S, Decl *D, const ParsedAttr &Attr) const
If this ParsedAttrInfo knows how to handle this ParsedAttr applied to this Decl then do so and return...
Contains information gathered from parsing the contents of TargetAttr.
Definition: TargetInfo.h:57
std::vector< std::string > Features
Definition: TargetInfo.h:58
StringRef BranchProtection
Definition: TargetInfo.h:61