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/APValue.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Availability.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/DynamicRecursiveASTVisitor.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/Mangle.h"
27#include "clang/AST/Type.h"
28#include "clang/Basic/CharInfo.h"
29#include "clang/Basic/Cuda.h"
30#include "clang/Basic/DarwinSDKInfo.h"
31#include "clang/Basic/IdentifierTable.h"
32#include "clang/Basic/LangOptions.h"
33#include "clang/Basic/SourceLocation.h"
34#include "clang/Basic/SourceManager.h"
35#include "clang/Basic/TargetInfo.h"
36#include "clang/Lex/Preprocessor.h"
37#include "clang/Sema/Attr.h"
38#include "clang/Sema/DeclSpec.h"
39#include "clang/Sema/DelayedDiagnostic.h"
40#include "clang/Sema/Initialization.h"
41#include "clang/Sema/Lookup.h"
42#include "clang/Sema/ParsedAttr.h"
43#include "clang/Sema/Scope.h"
44#include "clang/Sema/ScopeInfo.h"
45#include "clang/Sema/Sema.h"
46#include "clang/Sema/SemaAMDGPU.h"
47#include "clang/Sema/SemaARM.h"
48#include "clang/Sema/SemaAVR.h"
49#include "clang/Sema/SemaBPF.h"
50#include "clang/Sema/SemaCUDA.h"
51#include "clang/Sema/SemaHLSL.h"
52#include "clang/Sema/SemaHexagon.h"
53#include "clang/Sema/SemaInternal.h"
54#include "clang/Sema/SemaM68k.h"
55#include "clang/Sema/SemaMIPS.h"
56#include "clang/Sema/SemaMSP430.h"
57#include "clang/Sema/SemaObjC.h"
58#include "clang/Sema/SemaOpenCL.h"
59#include "clang/Sema/SemaOpenMP.h"
60#include "clang/Sema/SemaPPC.h"
61#include "clang/Sema/SemaRISCV.h"
62#include "clang/Sema/SemaSYCL.h"
63#include "clang/Sema/SemaSwift.h"
64#include "clang/Sema/SemaWasm.h"
65#include "clang/Sema/SemaX86.h"
66#include "llvm/ADT/APSInt.h"
67#include "llvm/ADT/STLExtras.h"
68#include "llvm/ADT/StringExtras.h"
69#include "llvm/Demangle/Demangle.h"
70#include "llvm/IR/DerivedTypes.h"
71#include "llvm/MC/MCSectionMachO.h"
72#include "llvm/Support/Error.h"
73#include "llvm/Support/ErrorHandling.h"
74#include "llvm/Support/MathExtras.h"
75#include "llvm/Support/raw_ostream.h"
76#include "llvm/TargetParser/NVPTXTargetParser.h"
77#include "llvm/TargetParser/Triple.h"
78#include <optional>
79
80using namespace clang;
81using namespace sema;
82
83namespace AttributeLangSupport {
84 enum LANG {
85 C,
86 Cpp,
87 ObjC
88 };
89} // end namespace AttributeLangSupport
90
91static unsigned getNumAttributeArgs(const ParsedAttr &AL) {
92 // FIXME: Include the type in the argument list.
93 return AL.getNumArgs() + AL.hasParsedType();
94}
95
96SourceLocation Sema::getAttrLoc(const AttributeCommonInfo &CI) {
97 return CI.getLoc();
98}
99
100/// Wrapper around checkUInt32Argument, with an extra check to be sure
101/// that the result will fit into a regular (signed) int. All args have the same
102/// purpose as they do in checkUInt32Argument.
103template <typename AttrInfo>
104static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr,
105 int &Val, unsigned Idx = UINT_MAX) {
106 uint32_t UVal;
107 if (!S.checkUInt32Argument(AI, Expr, UVal, Idx))
108 return false;
109
110 if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
111 llvm::APSInt I(32); // for toString
112 I = UVal;
113 S.Diag(Loc: Expr->getExprLoc(), DiagID: diag::err_ice_too_large)
114 << toString(I, Radix: 10, Signed: false) << 32 << /* Unsigned */ 0;
115 return false;
116 }
117
118 Val = UVal;
119 return true;
120}
121
122bool Sema::checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
123 const Expr *E, StringRef &Str,
124 SourceLocation *ArgLocation) {
125 const auto *Literal = dyn_cast<StringLiteral>(Val: E->IgnoreParenCasts());
126 if (ArgLocation)
127 *ArgLocation = E->getBeginLoc();
128
129 if (!Literal || (!Literal->isUnevaluated() && !Literal->isOrdinary())) {
130 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_attribute_argument_type)
131 << CI << AANT_ArgumentString;
132 return false;
133 }
134
135 Str = Literal->getString();
136 return true;
137}
138
139bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum,
140 StringRef &Str,
141 SourceLocation *ArgLocation) {
142 // Look for identifiers. If we have one emit a hint to fix it to a literal.
143 if (AL.isArgIdent(Arg: ArgNum)) {
144 IdentifierLoc *Loc = AL.getArgAsIdent(Arg: ArgNum);
145 Diag(Loc: Loc->getLoc(), DiagID: diag::err_attribute_argument_type)
146 << AL << AANT_ArgumentString
147 << FixItHint::CreateInsertion(InsertionLoc: Loc->getLoc(), Code: "\"")
148 << FixItHint::CreateInsertion(InsertionLoc: getLocForEndOfToken(Loc: Loc->getLoc()), Code: "\"");
149 Str = Loc->getIdentifierInfo()->getName();
150 if (ArgLocation)
151 *ArgLocation = Loc->getLoc();
152 return true;
153 }
154
155 // Now check for an actual string literal.
156 Expr *ArgExpr = AL.getArgAsExpr(Arg: ArgNum);
157 const auto *Literal = dyn_cast<StringLiteral>(Val: ArgExpr->IgnoreParenCasts());
158 if (ArgLocation)
159 *ArgLocation = ArgExpr->getBeginLoc();
160
161 if (!Literal || (!Literal->isUnevaluated() && !Literal->isOrdinary())) {
162 Diag(Loc: ArgExpr->getBeginLoc(), DiagID: diag::err_attribute_argument_type)
163 << AL << AANT_ArgumentString;
164 return false;
165 }
166 Str = Literal->getString();
167 return checkStringLiteralArgumentAttr(CI: AL, E: ArgExpr, Str, ArgLocation);
168}
169
170/// Check if the passed-in expression is of type int or bool.
171static bool isIntOrBool(Expr *Exp) {
172 QualType QT = Exp->getType();
173 return QT->isBooleanType() || QT->isIntegerType();
174}
175
176
177// Check to see if the type is a smart pointer of some kind. We assume
178// it's a smart pointer if it defines both operator-> and operator*.
179static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordDecl *Record) {
180 auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record,
181 OverloadedOperatorKind Op) {
182 DeclContextLookupResult Result =
183 Record->lookup(Name: S.Context.DeclarationNames.getCXXOperatorName(Op));
184 return !Result.empty();
185 };
186
187 bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star);
188 bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow);
189 if (foundStarOperator && foundArrowOperator)
190 return true;
191
192 const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Val: Record);
193 if (!CXXRecord)
194 return false;
195
196 for (const auto &BaseSpecifier : CXXRecord->bases()) {
197 if (!foundStarOperator)
198 foundStarOperator = IsOverloadedOperatorPresent(
199 BaseSpecifier.getType()->getAsRecordDecl(), OO_Star);
200 if (!foundArrowOperator)
201 foundArrowOperator = IsOverloadedOperatorPresent(
202 BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow);
203 }
204
205 if (foundStarOperator && foundArrowOperator)
206 return true;
207
208 return false;
209}
210
211/// Check if passed in Decl is a pointer type.
212/// Note that this function may produce an error message.
213/// \return true if the Decl is a pointer type; false otherwise
214static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
215 const ParsedAttr &AL) {
216 const auto *VD = cast<ValueDecl>(Val: D);
217 QualType QT = VD->getType();
218 if (QT->isAnyPointerType())
219 return true;
220
221 if (const auto *RD = QT->getAsRecordDecl()) {
222 // If it's an incomplete type, it could be a smart pointer; skip it.
223 // (We don't want to force template instantiation if we can avoid it,
224 // since that would alter the order in which templates are instantiated.)
225 if (!RD->isCompleteDefinition())
226 return true;
227
228 if (threadSafetyCheckIsSmartPointer(S, Record: RD))
229 return true;
230 }
231
232 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_thread_attribute_decl_not_pointer) << AL << QT;
233 return false;
234}
235
236/// Checks that the passed in QualType either is of RecordType or points
237/// to RecordType. Returns the relevant RecordType, null if it does not exit.
238static const RecordDecl *getRecordDecl(QualType QT) {
239 if (const auto *RD = QT->getAsRecordDecl())
240 return RD;
241
242 // Now check if we point to a record.
243 if (const auto *PT = QT->getAsCanonical<PointerType>())
244 return PT->getPointeeType()->getAsRecordDecl();
245
246 return nullptr;
247}
248
249template <typename AttrType>
250static bool checkRecordDeclForAttr(const RecordDecl *RD) {
251 // Check if the record itself has the attribute.
252 if (RD->hasAttr<AttrType>())
253 return true;
254
255 // Else check if any base classes have the attribute.
256 if (const auto *CRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
257 if (!CRD->forallBases(BaseMatches: [](const CXXRecordDecl *Base) {
258 return !Base->hasAttr<AttrType>();
259 }))
260 return true;
261 }
262 return false;
263}
264
265static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
266 const auto *RD = getRecordDecl(QT: Ty);
267
268 if (!RD)
269 return false;
270
271 // Don't check for the capability if the class hasn't been defined yet.
272 if (!RD->isCompleteDefinition())
273 return true;
274
275 // Allow smart pointers to be used as capability objects.
276 // FIXME -- Check the type that the smart pointer points to.
277 if (threadSafetyCheckIsSmartPointer(S, Record: RD))
278 return true;
279
280 return checkRecordDeclForAttr<CapabilityAttr>(RD);
281}
282
283static bool checkRecordTypeForScopedCapability(Sema &S, QualType Ty) {
284 const auto *RD = getRecordDecl(QT: Ty);
285
286 if (!RD)
287 return false;
288
289 // Don't check for the capability if the class hasn't been defined yet.
290 if (!RD->isCompleteDefinition())
291 return true;
292
293 return checkRecordDeclForAttr<ScopedLockableAttr>(RD);
294}
295
296static bool checkTypedefTypeForCapability(QualType Ty) {
297 const auto *TD = Ty->getAs<TypedefType>();
298 if (!TD)
299 return false;
300
301 TypedefNameDecl *TN = TD->getDecl();
302 if (!TN)
303 return false;
304
305 return TN->hasAttr<CapabilityAttr>();
306}
307
308static bool typeHasCapability(Sema &S, QualType Ty) {
309 if (checkTypedefTypeForCapability(Ty))
310 return true;
311
312 if (checkRecordTypeForCapability(S, Ty))
313 return true;
314
315 return false;
316}
317
318static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
319 // Capability expressions are simple expressions involving the boolean logic
320 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
321 // a DeclRefExpr is found, its type should be checked to determine whether it
322 // is a capability or not.
323
324 if (const auto *E = dyn_cast<CastExpr>(Val: Ex))
325 return isCapabilityExpr(S, Ex: E->getSubExpr());
326 else if (const auto *E = dyn_cast<ParenExpr>(Val: Ex))
327 return isCapabilityExpr(S, Ex: E->getSubExpr());
328 else if (const auto *E = dyn_cast<UnaryOperator>(Val: Ex)) {
329 if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
330 E->getOpcode() == UO_Deref)
331 return isCapabilityExpr(S, Ex: E->getSubExpr());
332 return false;
333 } else if (const auto *E = dyn_cast<BinaryOperator>(Val: Ex)) {
334 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
335 return isCapabilityExpr(S, Ex: E->getLHS()) &&
336 isCapabilityExpr(S, Ex: E->getRHS());
337 return false;
338 }
339
340 return typeHasCapability(S, Ty: Ex->getType());
341}
342
343/// Checks that all attribute arguments, starting from Sidx, resolve to
344/// a capability object.
345/// \param Sidx The attribute argument index to start checking with.
346/// \param ParamIdxOk Whether an argument can be indexing into a function
347/// parameter list.
348static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
349 const ParsedAttr &AL,
350 SmallVectorImpl<Expr *> &Args,
351 unsigned Sidx = 0,
352 bool ParamIdxOk = false) {
353 if (Sidx == AL.getNumArgs()) {
354 // If we don't have any capability arguments, the attribute implicitly
355 // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're
356 // a non-static method, and that the class is a (scoped) capability.
357 const auto *MD = dyn_cast<const CXXMethodDecl>(Val: D);
358 if (MD && !MD->isStatic()) {
359 const CXXRecordDecl *RD = MD->getParent();
360 // FIXME -- need to check this again on template instantiation
361 if (!checkRecordDeclForAttr<CapabilityAttr>(RD) &&
362 !checkRecordDeclForAttr<ScopedLockableAttr>(RD))
363 S.Diag(Loc: AL.getLoc(),
364 DiagID: diag::warn_thread_attribute_not_on_capability_member)
365 << AL << MD->getParent();
366 } else {
367 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_thread_attribute_not_on_non_static_member)
368 << AL;
369 }
370 }
371
372 for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) {
373 Expr *ArgExp = AL.getArgAsExpr(Arg: Idx);
374
375 if (ArgExp->isTypeDependent()) {
376 // FIXME -- need to check this again on template instantiation
377 Args.push_back(Elt: ArgExp);
378 continue;
379 }
380
381 if (const auto *StrLit = dyn_cast<StringLiteral>(Val: ArgExp)) {
382 if (StrLit->getLength() == 0 ||
383 (StrLit->isOrdinary() && StrLit->getString() == "*")) {
384 // Pass empty strings to the analyzer without warnings.
385 // Treat "*" as the universal lock.
386 Args.push_back(Elt: ArgExp);
387 continue;
388 }
389
390 // We allow constant strings to be used as a placeholder for expressions
391 // that are not valid C++ syntax, but warn that they are ignored.
392 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_thread_attribute_ignored) << AL;
393 Args.push_back(Elt: ArgExp);
394 continue;
395 }
396
397 QualType ArgTy = ArgExp->getType();
398
399 // A pointer to member expression of the form &MyClass::mu is treated
400 // specially -- we need to look at the type of the member.
401 if (const auto *UOp = dyn_cast<UnaryOperator>(Val: ArgExp))
402 if (UOp->getOpcode() == UO_AddrOf)
403 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: UOp->getSubExpr()))
404 if (DRE->getDecl()->isCXXInstanceMember())
405 ArgTy = DRE->getDecl()->getType();
406
407 // First see if we can just cast to record type, or pointer to record type.
408 const auto *RD = getRecordDecl(QT: ArgTy);
409
410 // Now check if we index into a record type function param.
411 if (!RD && ParamIdxOk) {
412 const auto *FD = dyn_cast<FunctionDecl>(Val: D);
413 const auto *IL = dyn_cast<IntegerLiteral>(Val: ArgExp);
414 if(FD && IL) {
415 unsigned int NumParams = FD->getNumParams();
416 llvm::APInt ArgValue = IL->getValue();
417 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
418 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
419 if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
420 S.Diag(Loc: AL.getLoc(),
421 DiagID: diag::err_attribute_argument_out_of_bounds_extra_info)
422 << AL << Idx + 1 << NumParams;
423 continue;
424 }
425 ArgTy = FD->getParamDecl(i: ParamIdxFromZero)->getType();
426 }
427 }
428
429 // If the type does not have a capability, see if the components of the
430 // expression have capabilities. This allows for writing C code where the
431 // capability may be on the type, and the expression is a capability
432 // boolean logic expression. Eg) requires_capability(A || B && !C)
433 if (!typeHasCapability(S, Ty: ArgTy) && !isCapabilityExpr(S, Ex: ArgExp))
434 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_thread_attribute_argument_not_lockable)
435 << AL << ArgTy;
436
437 Args.push_back(Elt: ArgExp);
438 }
439}
440
441/// True if T names a function to call: a function pointer, a function
442/// reference, or a reference to a function pointer. Dependent types are also
443/// accepted, and re-checked after instantiation.
444static bool isCallbackOrDependent(QualType T) {
445 T = T.getNonReferenceType();
446 return T->isDependentType() || T->isFunctionPointerType() ||
447 T->isFunctionType();
448}
449
450/// Checks that thread-safety attributes on variables or fields apply only to
451/// function pointer or function reference types.
452static bool checkThreadSafetyValueDeclIsFunPtr(Sema &S, const ValueDecl *VD,
453 const AttributeCommonInfo &A) {
454 if (isCallbackOrDependent(T: VD->getType()))
455 return true;
456 S.Diag(Loc: A.getLoc(), DiagID: diag::warn_thread_attribute_not_on_fun_ptr)
457 << A << (isa<FieldDecl>(Val: VD) ? 1 : 0);
458 return false;
459}
460
461static bool checkFunParamsAreScopedLockable(Sema &S,
462 const ParmVarDecl *ParamDecl,
463 const AttributeCommonInfo &AL) {
464 QualType ParamType = ParamDecl->getType();
465 if (ParamType->isDependentType())
466 return true;
467 if (const auto *RefType = ParamType->getAs<ReferenceType>();
468 RefType &&
469 checkRecordTypeForScopedCapability(S, Ty: RefType->getPointeeType()))
470 return true;
471 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_thread_attribute_not_on_scoped_lockable_param)
472 << AL;
473 return false;
474}
475
476static bool checkThreadSafetyAttrSubject(Sema &S, Decl *D, const ParsedAttr &AL,
477 bool CheckParmVar = false) {
478 const auto *VD = dyn_cast<ValueDecl>(Val: D);
479 if (!VD || isa<FunctionDecl>(Val: VD))
480 return true;
481
482 if (CheckParmVar) {
483 if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: VD)) {
484 // A function-pointer or function-reference parameter is also valid here.
485 if (isCallbackOrDependent(T: PVD->getType()))
486 return true;
487 return checkFunParamsAreScopedLockable(S, ParamDecl: PVD, AL);
488 }
489 }
490
491 return checkThreadSafetyValueDeclIsFunPtr(S, VD, A: AL);
492}
493
494bool Sema::checkInstantiatedThreadSafetyAttrs(const Decl *D, const Attr *A) {
495 if (!isa<AssertCapabilityAttr, AcquireCapabilityAttr,
496 TryAcquireCapabilityAttr, ReleaseCapabilityAttr,
497 RequiresCapabilityAttr, LocksExcludedAttr, LockReturnedAttr>(Val: A))
498 return true;
499
500 const auto *VD = dyn_cast<ValueDecl>(Val: D);
501 if (!VD)
502 return true;
503
504 // Parameters of template functions need to be re-checked during
505 // instantiation because their types might have been dependent.
506 // lock_returned does not apply to scoped_lockable references.
507 if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: VD);
508 PVD && !isa<LockReturnedAttr>(Val: A)) {
509 if (isCallbackOrDependent(T: PVD->getType()))
510 return true;
511 return checkFunParamsAreScopedLockable(S&: *this, ParamDecl: PVD, AL: *A);
512 }
513
514 if (isa<FunctionDecl>(Val: VD))
515 return true;
516
517 return checkThreadSafetyValueDeclIsFunPtr(S&: *this, VD, A: *A);
518}
519
520//===----------------------------------------------------------------------===//
521// Attribute Implementations
522//===----------------------------------------------------------------------===//
523
524static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
525 if (!threadSafetyCheckIsPointer(S, D, AL))
526 return;
527
528 D->addAttr(A: ::new (S.Context) PtGuardedVarAttr(S.Context, AL));
529}
530
531static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
532 SmallVectorImpl<Expr *> &Args) {
533 if (!AL.checkAtLeastNumArgs(S, Num: 1))
534 return false;
535
536 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
537 return !Args.empty();
538}
539
540static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
541 SmallVector<Expr *, 1> Args;
542 if (!checkGuardedByAttrCommon(S, D, AL, Args))
543 return;
544
545 D->addAttr(A: ::new (S.Context)
546 GuardedByAttr(S.Context, AL, Args.data(), Args.size()));
547}
548
549static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
550 SmallVector<Expr *, 1> Args;
551 if (!checkGuardedByAttrCommon(S, D, AL, Args))
552 return;
553
554 if (!threadSafetyCheckIsPointer(S, D, AL))
555 return;
556
557 D->addAttr(A: ::new (S.Context)
558 PtGuardedByAttr(S.Context, AL, Args.data(), Args.size()));
559}
560
561static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
562 SmallVectorImpl<Expr *> &Args) {
563 if (!AL.checkAtLeastNumArgs(S, Num: 1))
564 return false;
565
566 // Check that this attribute only applies to lockable types.
567 QualType QT = cast<ValueDecl>(Val: D)->getType();
568 if (!QT->isDependentType() && !typeHasCapability(S, Ty: QT)) {
569 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_thread_attribute_decl_not_lockable) << AL;
570 return false;
571 }
572
573 // Check that all arguments are lockable objects.
574 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
575 if (Args.empty())
576 return false;
577
578 return true;
579}
580
581static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
582 SmallVector<Expr *, 1> Args;
583 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
584 return;
585
586 Expr **StartArg = &Args[0];
587 D->addAttr(A: ::new (S.Context)
588 AcquiredAfterAttr(S.Context, AL, StartArg, Args.size()));
589}
590
591static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
592 SmallVector<Expr *, 1> Args;
593 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
594 return;
595
596 Expr **StartArg = &Args[0];
597 D->addAttr(A: ::new (S.Context)
598 AcquiredBeforeAttr(S.Context, AL, StartArg, Args.size()));
599}
600
601static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
602 SmallVectorImpl<Expr *> &Args) {
603 // zero or more arguments ok
604 // check that all arguments are lockable objects
605 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, Sidx: 0, /*ParamIdxOk=*/true);
606
607 return true;
608}
609
610/// Checks to be sure that the given parameter number is in bounds, and
611/// is an integral type. Will emit appropriate diagnostics if this returns
612/// false.
613///
614/// AttrArgNo is used to actually retrieve the argument, so it's base-0.
615template <typename AttrInfo>
616static bool checkParamIsIntegerType(Sema &S, const Decl *D, const AttrInfo &AI,
617 unsigned AttrArgNo) {
618 assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument");
619 Expr *AttrArg = AI.getArgAsExpr(AttrArgNo);
620 ParamIdx Idx;
621 if (!S.checkFunctionOrMethodParameterIndex(D, AI, AttrArgNo + 1, AttrArg,
622 Idx))
623 return false;
624
625 QualType ParamTy = getFunctionOrMethodParamType(D, Idx: Idx.getASTIndex());
626 if (!ParamTy->isIntegerType() && !ParamTy->isCharType()) {
627 SourceLocation SrcLoc = AttrArg->getBeginLoc();
628 S.Diag(Loc: SrcLoc, DiagID: diag::err_attribute_integers_only)
629 << AI << getFunctionOrMethodParamRange(D, Idx: Idx.getASTIndex());
630 return false;
631 }
632 return true;
633}
634
635static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
636 if (!AL.checkAtLeastNumArgs(S, Num: 1) || !AL.checkAtMostNumArgs(S, Num: 2))
637 return;
638
639 assert(isFuncOrMethodForAttrSubject(D) && hasFunctionProto(D));
640
641 QualType RetTy = getFunctionOrMethodResultType(D);
642 if (!RetTy->isPointerType()) {
643 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_return_pointers_only) << AL;
644 return;
645 }
646
647 const Expr *SizeExpr = AL.getArgAsExpr(Arg: 0);
648 int SizeArgNoVal;
649 // Parameter indices are 1-indexed, hence Index=1
650 if (!checkPositiveIntArgument(S, AI: AL, Expr: SizeExpr, Val&: SizeArgNoVal, /*Idx=*/1))
651 return;
652 if (!checkParamIsIntegerType(S, D, AI: AL, /*AttrArgNo=*/0))
653 return;
654 ParamIdx SizeArgNo(SizeArgNoVal, D);
655
656 ParamIdx NumberArgNo;
657 if (AL.getNumArgs() == 2) {
658 const Expr *NumberExpr = AL.getArgAsExpr(Arg: 1);
659 int Val;
660 // Parameter indices are 1-based, hence Index=2
661 if (!checkPositiveIntArgument(S, AI: AL, Expr: NumberExpr, Val, /*Idx=*/2))
662 return;
663 if (!checkParamIsIntegerType(S, D, AI: AL, /*AttrArgNo=*/1))
664 return;
665 NumberArgNo = ParamIdx(Val, D);
666 }
667
668 D->addAttr(A: ::new (S.Context)
669 AllocSizeAttr(S.Context, AL, SizeArgNo, NumberArgNo));
670}
671
672static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
673 SmallVectorImpl<Expr *> &Args) {
674 if (!AL.checkAtLeastNumArgs(S, Num: 1))
675 return false;
676
677 if (!isIntOrBool(Exp: AL.getArgAsExpr(Arg: 0))) {
678 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_n_type)
679 << AL << 1 << AANT_ArgumentIntOrBool;
680 return false;
681 }
682
683 // check that all arguments are lockable objects
684 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, Sidx: 1);
685
686 return true;
687}
688
689static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
690 if (!checkThreadSafetyAttrSubject(S, D, AL))
691 return;
692
693 // check that the argument is lockable object
694 SmallVector<Expr*, 1> Args;
695 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
696 unsigned Size = Args.size();
697 if (Size == 0)
698 return;
699
700 D->addAttr(A: ::new (S.Context) LockReturnedAttr(S.Context, AL, Args[0]));
701}
702
703static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
704 if (!checkThreadSafetyAttrSubject(S, D, AL, /*CheckParmVar=*/true))
705 return;
706
707 if (!AL.checkAtLeastNumArgs(S, Num: 1))
708 return;
709
710 // check that all arguments are lockable objects
711 SmallVector<Expr*, 1> Args;
712 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
713 unsigned Size = Args.size();
714 if (Size == 0)
715 return;
716 Expr **StartArg = &Args[0];
717
718 D->addAttr(A: ::new (S.Context)
719 LocksExcludedAttr(S.Context, AL, StartArg, Size));
720}
721
722static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL,
723 Expr *&Cond, StringRef &Msg) {
724 Cond = AL.getArgAsExpr(Arg: 0);
725 if (!Cond->isTypeDependent()) {
726 ExprResult Converted = S.PerformContextuallyConvertToBool(From: Cond);
727 if (Converted.isInvalid())
728 return false;
729 Cond = Converted.get();
730 }
731
732 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 1, Str&: Msg))
733 return false;
734
735 if (Msg.empty())
736 Msg = "<no message provided>";
737
738 SmallVector<PartialDiagnosticAt, 8> Diags;
739 if (isa<FunctionDecl>(Val: D) && !Cond->isValueDependent() &&
740 !Expr::isPotentialConstantExprUnevaluated(E: Cond, FD: cast<FunctionDecl>(Val: D),
741 Diags)) {
742 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attr_cond_never_constant_expr) << AL;
743 for (const PartialDiagnosticAt &PDiag : Diags)
744 S.Diag(Loc: PDiag.first, PD: PDiag.second);
745 return false;
746 }
747 return true;
748}
749
750static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
751 S.Diag(Loc: AL.getLoc(), DiagID: diag::ext_clang_enable_if);
752
753 Expr *Cond;
754 StringRef Msg;
755 if (checkFunctionConditionAttr(S, D, AL, Cond, Msg))
756 D->addAttr(A: ::new (S.Context) EnableIfAttr(S.Context, AL, Cond, Msg));
757}
758
759static void handleErrorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
760 StringRef NewUserDiagnostic;
761 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: NewUserDiagnostic))
762 return;
763 if (ErrorAttr *EA = S.mergeErrorAttr(D, CI: AL, NewUserDiagnostic))
764 D->addAttr(A: EA);
765}
766
767static void handleExcludeFromExplicitInstantiationAttr(Sema &S, Decl *D,
768 const ParsedAttr &AL) {
769 const auto *PD = isa<CXXRecordDecl>(Val: D)
770 ? cast<DeclContext>(Val: D)
771 : D->getDeclContext()->getRedeclContext();
772 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: PD); RD && RD->isLocalClass()) {
773 S.Diag(Loc: AL.getLoc(),
774 DiagID: diag::warn_attribute_exclude_from_explicit_instantiation_local_class)
775 << AL << /*IsMember=*/!isa<CXXRecordDecl>(Val: D);
776 return;
777 }
778
779 if (auto *DA = getDLLAttr(D); DA && !DA->isInherited()) {
780 S.Diag(Loc: DA->getLoc(), DiagID: diag::warn_dllattr_ignored_exclusion_takes_precedence)
781 << DA << AL;
782 D->dropAttrs<DLLExportAttr, DLLImportAttr>();
783 }
784
785 D->addAttr(A: ::new (S.Context)
786 ExcludeFromExplicitInstantiationAttr(S.Context, AL));
787}
788
789namespace {
790/// Determines if a given Expr references any of the given function's
791/// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
792class ArgumentDependenceChecker : public DynamicRecursiveASTVisitor {
793#ifndef NDEBUG
794 const CXXRecordDecl *ClassType;
795#endif
796 llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
797 bool Result;
798
799public:
800 ArgumentDependenceChecker(const FunctionDecl *FD) {
801#ifndef NDEBUG
802 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
803 ClassType = MD->getParent();
804 else
805 ClassType = nullptr;
806#endif
807 Parms.insert(I: FD->param_begin(), E: FD->param_end());
808 }
809
810 bool referencesArgs(Expr *E) {
811 Result = false;
812 TraverseStmt(S: E);
813 return Result;
814 }
815
816 bool VisitCXXThisExpr(CXXThisExpr *E) override {
817 assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
818 "`this` doesn't refer to the enclosing class?");
819 Result = true;
820 return false;
821 }
822
823 bool VisitDeclRefExpr(DeclRefExpr *DRE) override {
824 if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: DRE->getDecl()))
825 if (Parms.count(Ptr: PVD)) {
826 Result = true;
827 return false;
828 }
829 return true;
830 }
831};
832}
833
834static void handleDiagnoseAsBuiltinAttr(Sema &S, Decl *D,
835 const ParsedAttr &AL) {
836 const auto *DeclFD = cast<FunctionDecl>(Val: D);
837
838 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(Val: DeclFD))
839 if (!MethodDecl->isStatic()) {
840 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_no_member_function) << AL;
841 return;
842 }
843
844 auto DiagnoseType = [&](unsigned Index, AttributeArgumentNType T) {
845 SourceLocation Loc = [&]() {
846 auto Union = AL.getArg(Arg: Index - 1);
847 if (auto *E = dyn_cast<Expr *>(Val&: Union))
848 return E->getBeginLoc();
849 return cast<IdentifierLoc *>(Val&: Union)->getLoc();
850 }();
851
852 S.Diag(Loc, DiagID: diag::err_attribute_argument_n_type) << AL << Index << T;
853 };
854
855 FunctionDecl *AttrFD = [&]() -> FunctionDecl * {
856 if (!AL.isArgExpr(Arg: 0))
857 return nullptr;
858 auto *F = dyn_cast_if_present<DeclRefExpr>(Val: AL.getArgAsExpr(Arg: 0));
859 if (!F)
860 return nullptr;
861 return dyn_cast_if_present<FunctionDecl>(Val: F->getFoundDecl());
862 }();
863
864 if (!AttrFD || !AttrFD->getBuiltinID(ConsiderWrapperFunctions: true)) {
865 DiagnoseType(1, AANT_ArgumentBuiltinFunction);
866 return;
867 }
868
869 if (AttrFD->getNumParams() != AL.getNumArgs() - 1) {
870 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments_for)
871 << AL << AttrFD << AttrFD->getNumParams();
872 return;
873 }
874
875 SmallVector<unsigned, 8> Indices;
876
877 for (unsigned I = 1; I < AL.getNumArgs(); ++I) {
878 if (!AL.isArgExpr(Arg: I)) {
879 DiagnoseType(I + 1, AANT_ArgumentIntegerConstant);
880 return;
881 }
882
883 const Expr *IndexExpr = AL.getArgAsExpr(Arg: I);
884 uint32_t Index;
885
886 if (!S.checkUInt32Argument(AI: AL, Expr: IndexExpr, Val&: Index, Idx: I + 1, StrictlyUnsigned: false))
887 return;
888
889 if (Index > DeclFD->getNumParams()) {
890 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_bounds_for_function)
891 << AL << Index << DeclFD << DeclFD->getNumParams();
892 return;
893 }
894
895 QualType T1 = AttrFD->getParamDecl(i: I - 1)->getType();
896 QualType T2 = DeclFD->getParamDecl(i: Index - 1)->getType();
897
898 if (T1.getCanonicalType().getUnqualifiedType() !=
899 T2.getCanonicalType().getUnqualifiedType()) {
900 S.Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_attribute_parameter_types)
901 << AL << Index << DeclFD << T2 << I << AttrFD << T1;
902 return;
903 }
904
905 Indices.push_back(Elt: Index - 1);
906 }
907
908 D->addAttr(A: ::new (S.Context) DiagnoseAsBuiltinAttr(
909 S.Context, AL, AttrFD, Indices.data(), Indices.size()));
910}
911
912static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
913 S.Diag(Loc: AL.getLoc(), DiagID: diag::ext_clang_diagnose_if);
914
915 Expr *Cond;
916 StringRef Msg;
917 if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg))
918 return;
919
920 StringRef DefaultSevStr;
921 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 2, Str&: DefaultSevStr))
922 return;
923
924 DiagnoseIfAttr::DefaultSeverity DefaultSev;
925 if (!DiagnoseIfAttr::ConvertStrToDefaultSeverity(Val: DefaultSevStr, Out&: DefaultSev)) {
926 S.Diag(Loc: AL.getArgAsExpr(Arg: 2)->getBeginLoc(),
927 DiagID: diag::err_diagnose_if_invalid_diagnostic_type);
928 return;
929 }
930
931 StringRef WarningGroup;
932 if (AL.getNumArgs() > 3) {
933 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 3, Str&: WarningGroup))
934 return;
935 if (WarningGroup.empty() ||
936 !S.getDiagnostics().getDiagnosticIDs()->getGroupForWarningOption(
937 WarningGroup)) {
938 S.Diag(Loc: AL.getArgAsExpr(Arg: 3)->getBeginLoc(),
939 DiagID: diag::err_diagnose_if_unknown_warning)
940 << WarningGroup;
941 return;
942 }
943 }
944
945 bool ArgDependent = false;
946 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D))
947 ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(E: Cond);
948 D->addAttr(A: ::new (S.Context) DiagnoseIfAttr(
949 S.Context, AL, Cond, Msg, DefaultSev, WarningGroup, ArgDependent,
950 cast<NamedDecl>(Val: D)));
951}
952
953static void handleCFIUncheckedCalleeAttr(Sema &S, Decl *D,
954 const ParsedAttr &Attrs) {
955 if (hasDeclarator(D))
956 return;
957
958 if (!isa<ObjCMethodDecl>(Val: D)) {
959 S.Diag(Loc: Attrs.getLoc(), DiagID: diag::warn_attribute_wrong_decl_type)
960 << Attrs << Attrs.isRegularKeywordAttribute()
961 << ExpectedFunctionOrMethod;
962 return;
963 }
964
965 D->addAttr(A: ::new (S.Context) CFIUncheckedCalleeAttr(S.Context, Attrs));
966}
967
968static void handleNoBuiltinAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
969 static constexpr const StringRef kWildcard = "*";
970
971 llvm::SmallVector<StringRef, 16> Names;
972 bool HasWildcard = false;
973
974 const auto AddBuiltinName = [&Names, &HasWildcard](StringRef Name) {
975 if (Name == kWildcard)
976 HasWildcard = true;
977 Names.push_back(Elt: Name);
978 };
979
980 // Add previously defined attributes.
981 if (const auto *NBA = D->getAttr<NoBuiltinAttr>())
982 for (StringRef BuiltinName : NBA->builtinNames())
983 AddBuiltinName(BuiltinName);
984
985 // Add current attributes.
986 if (AL.getNumArgs() == 0)
987 AddBuiltinName(kWildcard);
988 else
989 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
990 StringRef BuiltinName;
991 SourceLocation LiteralLoc;
992 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: I, Str&: BuiltinName, ArgLocation: &LiteralLoc))
993 return;
994
995 if (Builtin::Context::isBuiltinFunc(Name: BuiltinName))
996 AddBuiltinName(BuiltinName);
997 else
998 S.Diag(Loc: LiteralLoc, DiagID: diag::warn_attribute_no_builtin_invalid_builtin_name)
999 << BuiltinName << AL;
1000 }
1001
1002 // Repeating the same attribute is fine.
1003 llvm::sort(C&: Names);
1004 Names.erase(CS: llvm::unique(R&: Names), CE: Names.end());
1005
1006 // Empty no_builtin must be on its own.
1007 if (HasWildcard && Names.size() > 1)
1008 S.Diag(Loc: D->getLocation(),
1009 DiagID: diag::err_attribute_no_builtin_wildcard_or_builtin_name)
1010 << AL;
1011
1012 if (D->hasAttr<NoBuiltinAttr>())
1013 D->dropAttr<NoBuiltinAttr>();
1014 D->addAttr(A: ::new (S.Context)
1015 NoBuiltinAttr(S.Context, AL, Names.data(), Names.size()));
1016}
1017
1018static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1019 if (D->hasAttr<PassObjectSizeAttr>()) {
1020 S.Diag(Loc: D->getBeginLoc(), DiagID: diag::err_attribute_only_once_per_parameter) << AL;
1021 return;
1022 }
1023
1024 Expr *E = AL.getArgAsExpr(Arg: 0);
1025 uint32_t Type;
1026 if (!S.checkUInt32Argument(AI: AL, Expr: E, Val&: Type, /*Idx=*/1))
1027 return;
1028
1029 // pass_object_size's argument is passed in as the second argument of
1030 // __builtin_object_size. So, it has the same constraints as that second
1031 // argument; namely, it must be in the range [0, 3].
1032 if (Type > 3) {
1033 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_attribute_argument_out_of_range)
1034 << AL << 0 << 3 << E->getSourceRange();
1035 return;
1036 }
1037
1038 // pass_object_size is only supported on constant pointer parameters; as a
1039 // kindness to users, we allow the parameter to be non-const for declarations.
1040 // At this point, we have no clue if `D` belongs to a function declaration or
1041 // definition, so we defer the constness check until later.
1042 if (!cast<ParmVarDecl>(Val: D)->getType()->isPointerType()) {
1043 S.Diag(Loc: D->getBeginLoc(), DiagID: diag::err_attribute_pointers_only) << AL << 1;
1044 return;
1045 }
1046
1047 D->addAttr(A: ::new (S.Context) PassObjectSizeAttr(S.Context, AL, (int)Type));
1048}
1049
1050static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1051 ConsumableAttr::ConsumedState DefaultState;
1052
1053 if (AL.isArgIdent(Arg: 0)) {
1054 IdentifierLoc *IL = AL.getArgAsIdent(Arg: 0);
1055 if (!ConsumableAttr::ConvertStrToConsumedState(
1056 Val: IL->getIdentifierInfo()->getName(), Out&: DefaultState)) {
1057 S.Diag(Loc: IL->getLoc(), DiagID: diag::warn_attribute_type_not_supported)
1058 << AL << IL->getIdentifierInfo();
1059 return;
1060 }
1061 } else {
1062 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_type)
1063 << AL << AANT_ArgumentIdentifier;
1064 return;
1065 }
1066
1067 D->addAttr(A: ::new (S.Context) ConsumableAttr(S.Context, AL, DefaultState));
1068}
1069
1070static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1071 const ParsedAttr &AL) {
1072 QualType ThisType = MD->getFunctionObjectParameterType();
1073
1074 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1075 if (!RD->hasAttr<ConsumableAttr>()) {
1076 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attr_on_unconsumable_class) << RD;
1077
1078 return false;
1079 }
1080 }
1081
1082 return true;
1083}
1084
1085static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1086 if (!AL.checkAtLeastNumArgs(S, Num: 1))
1087 return;
1088
1089 if (!checkForConsumableClass(S, MD: cast<CXXMethodDecl>(Val: D), AL))
1090 return;
1091
1092 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1093 for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
1094 CallableWhenAttr::ConsumedState CallableState;
1095
1096 StringRef StateString;
1097 SourceLocation Loc;
1098 if (AL.isArgIdent(Arg: ArgIndex)) {
1099 IdentifierLoc *Ident = AL.getArgAsIdent(Arg: ArgIndex);
1100 StateString = Ident->getIdentifierInfo()->getName();
1101 Loc = Ident->getLoc();
1102 } else {
1103 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: ArgIndex, Str&: StateString, ArgLocation: &Loc))
1104 return;
1105 }
1106
1107 if (!CallableWhenAttr::ConvertStrToConsumedState(Val: StateString,
1108 Out&: CallableState)) {
1109 S.Diag(Loc, DiagID: diag::warn_attribute_type_not_supported) << AL << StateString;
1110 return;
1111 }
1112
1113 States.push_back(Elt: CallableState);
1114 }
1115
1116 D->addAttr(A: ::new (S.Context)
1117 CallableWhenAttr(S.Context, AL, States.data(), States.size()));
1118}
1119
1120static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1121 ParamTypestateAttr::ConsumedState ParamState;
1122
1123 if (AL.isArgIdent(Arg: 0)) {
1124 IdentifierLoc *Ident = AL.getArgAsIdent(Arg: 0);
1125 StringRef StateString = Ident->getIdentifierInfo()->getName();
1126
1127 if (!ParamTypestateAttr::ConvertStrToConsumedState(Val: StateString,
1128 Out&: ParamState)) {
1129 S.Diag(Loc: Ident->getLoc(), DiagID: diag::warn_attribute_type_not_supported)
1130 << AL << StateString;
1131 return;
1132 }
1133 } else {
1134 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_type)
1135 << AL << AANT_ArgumentIdentifier;
1136 return;
1137 }
1138
1139 // FIXME: This check is currently being done in the analysis. It can be
1140 // enabled here only after the parser propagates attributes at
1141 // template specialization definition, not declaration.
1142 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1143 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1144 //
1145 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1146 // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1147 // ReturnType.getAsString();
1148 // return;
1149 //}
1150
1151 D->addAttr(A: ::new (S.Context) ParamTypestateAttr(S.Context, AL, ParamState));
1152}
1153
1154static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1155 ReturnTypestateAttr::ConsumedState ReturnState;
1156
1157 if (AL.isArgIdent(Arg: 0)) {
1158 IdentifierLoc *IL = AL.getArgAsIdent(Arg: 0);
1159 if (!ReturnTypestateAttr::ConvertStrToConsumedState(
1160 Val: IL->getIdentifierInfo()->getName(), Out&: ReturnState)) {
1161 S.Diag(Loc: IL->getLoc(), DiagID: diag::warn_attribute_type_not_supported)
1162 << AL << IL->getIdentifierInfo();
1163 return;
1164 }
1165 } else {
1166 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_type)
1167 << AL << AANT_ArgumentIdentifier;
1168 return;
1169 }
1170
1171 // FIXME: This check is currently being done in the analysis. It can be
1172 // enabled here only after the parser propagates attributes at
1173 // template specialization definition, not declaration.
1174 // QualType ReturnType;
1175 //
1176 // if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1177 // ReturnType = Param->getType();
1178 //
1179 //} else if (const CXXConstructorDecl *Constructor =
1180 // dyn_cast<CXXConstructorDecl>(D)) {
1181 // ReturnType = Constructor->getFunctionObjectParameterType();
1182 //
1183 //} else {
1184 //
1185 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1186 //}
1187 //
1188 // const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1189 //
1190 // if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1191 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1192 // ReturnType.getAsString();
1193 // return;
1194 //}
1195
1196 D->addAttr(A: ::new (S.Context) ReturnTypestateAttr(S.Context, AL, ReturnState));
1197}
1198
1199static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1200 if (!checkForConsumableClass(S, MD: cast<CXXMethodDecl>(Val: D), AL))
1201 return;
1202
1203 SetTypestateAttr::ConsumedState NewState;
1204 if (AL.isArgIdent(Arg: 0)) {
1205 IdentifierLoc *Ident = AL.getArgAsIdent(Arg: 0);
1206 StringRef Param = Ident->getIdentifierInfo()->getName();
1207 if (!SetTypestateAttr::ConvertStrToConsumedState(Val: Param, Out&: NewState)) {
1208 S.Diag(Loc: Ident->getLoc(), DiagID: diag::warn_attribute_type_not_supported)
1209 << AL << Param;
1210 return;
1211 }
1212 } else {
1213 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_type)
1214 << AL << AANT_ArgumentIdentifier;
1215 return;
1216 }
1217
1218 D->addAttr(A: ::new (S.Context) SetTypestateAttr(S.Context, AL, NewState));
1219}
1220
1221static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1222 if (!checkForConsumableClass(S, MD: cast<CXXMethodDecl>(Val: D), AL))
1223 return;
1224
1225 TestTypestateAttr::ConsumedState TestState;
1226 if (AL.isArgIdent(Arg: 0)) {
1227 IdentifierLoc *Ident = AL.getArgAsIdent(Arg: 0);
1228 StringRef Param = Ident->getIdentifierInfo()->getName();
1229 if (!TestTypestateAttr::ConvertStrToConsumedState(Val: Param, Out&: TestState)) {
1230 S.Diag(Loc: Ident->getLoc(), DiagID: diag::warn_attribute_type_not_supported)
1231 << AL << Param;
1232 return;
1233 }
1234 } else {
1235 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_type)
1236 << AL << AANT_ArgumentIdentifier;
1237 return;
1238 }
1239
1240 D->addAttr(A: ::new (S.Context) TestTypestateAttr(S.Context, AL, TestState));
1241}
1242
1243static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1244 // Remember this typedef decl, we will need it later for diagnostics.
1245 if (isa<TypedefNameDecl>(Val: D))
1246 S.ExtVectorDecls.push_back(LocalValue: cast<TypedefNameDecl>(Val: D));
1247}
1248
1249static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1250 if (auto *TD = dyn_cast<TagDecl>(Val: D))
1251 TD->addAttr(A: ::new (S.Context) PackedAttr(S.Context, AL));
1252 else if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
1253 bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
1254 !FD->getType()->isIncompleteType() &&
1255 FD->isBitField() &&
1256 S.Context.getTypeAlign(T: FD->getType()) <= 8);
1257
1258 if (S.getASTContext().getTargetInfo().getTriple().isPS()) {
1259 if (BitfieldByteAligned)
1260 // The PS4/PS5 targets need to maintain ABI backwards compatibility.
1261 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_ignored_for_field_of_type)
1262 << AL << FD->getType();
1263 else
1264 FD->addAttr(A: ::new (S.Context) PackedAttr(S.Context, AL));
1265 } else {
1266 // Report warning about changed offset in the newer compiler versions.
1267 if (BitfieldByteAligned)
1268 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_packed_for_bitfield);
1269
1270 FD->addAttr(A: ::new (S.Context) PackedAttr(S.Context, AL));
1271 }
1272
1273 } else
1274 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_ignored) << AL;
1275}
1276
1277static void handlePreferredName(Sema &S, Decl *D, const ParsedAttr &AL) {
1278 auto *RD = cast<CXXRecordDecl>(Val: D);
1279 ClassTemplateDecl *CTD = RD->getDescribedClassTemplate();
1280 assert(CTD && "attribute does not appertain to this declaration");
1281
1282 ParsedType PT = AL.getTypeArg();
1283 TypeSourceInfo *TSI = nullptr;
1284 QualType T = S.GetTypeFromParser(Ty: PT, TInfo: &TSI);
1285 if (!TSI)
1286 TSI = S.Context.getTrivialTypeSourceInfo(T, Loc: AL.getLoc());
1287
1288 if (!T.hasQualifiers() && T->isTypedefNameType()) {
1289 // Find the template name, if this type names a template specialization.
1290 const TemplateDecl *Template = nullptr;
1291 if (const auto *CTSD = dyn_cast_if_present<ClassTemplateSpecializationDecl>(
1292 Val: T->getAsCXXRecordDecl())) {
1293 Template = CTSD->getSpecializedTemplate();
1294 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
1295 while (TST && TST->isTypeAlias())
1296 TST = TST->getAliasedType()->getAs<TemplateSpecializationType>();
1297 if (TST)
1298 Template = TST->getTemplateName().getAsTemplateDecl();
1299 }
1300
1301 if (Template && declaresSameEntity(D1: Template, D2: CTD)) {
1302 D->addAttr(A: ::new (S.Context) PreferredNameAttr(S.Context, AL, TSI));
1303 return;
1304 }
1305 }
1306
1307 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_not_typedef_for_specialization)
1308 << T << AL << CTD;
1309 if (const auto *TT = T->getAs<TypedefType>())
1310 S.Diag(Loc: TT->getDecl()->getLocation(), DiagID: diag::note_entity_declared_at)
1311 << TT->getDecl();
1312}
1313
1314static void handleNoSpecializations(Sema &S, Decl *D, const ParsedAttr &AL) {
1315 StringRef Message;
1316 if (AL.getNumArgs() != 0)
1317 S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: Message);
1318 D->getDescribedTemplate()->addAttr(
1319 A: NoSpecializationsAttr::Create(Ctx&: S.Context, Message, CommonInfo: AL));
1320}
1321
1322bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1323 if (T->isDependentType())
1324 return true;
1325 if (RefOkay) {
1326 if (T->isReferenceType())
1327 return true;
1328 } else {
1329 T = T.getNonReferenceType();
1330 }
1331
1332 // The nonnull attribute, and other similar attributes, can be applied to a
1333 // transparent union that contains a pointer type.
1334 if (const RecordType *UT = T->getAsUnionType()) {
1335 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
1336 if (UD->hasAttr<TransparentUnionAttr>()) {
1337 for (const auto *I : UD->fields()) {
1338 QualType QT = I->getType();
1339 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1340 return true;
1341 }
1342 }
1343 }
1344
1345 return T->isAnyPointerType() || T->isBlockPointerType();
1346}
1347
1348static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL,
1349 SourceRange AttrParmRange,
1350 SourceRange TypeRange,
1351 bool isReturnValue = false) {
1352 if (!S.isValidPointerAttrType(T)) {
1353 if (isReturnValue)
1354 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_return_pointers_only)
1355 << AL << AttrParmRange << TypeRange;
1356 else
1357 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_pointers_only)
1358 << AL << AttrParmRange << TypeRange << 0;
1359 return false;
1360 }
1361 return true;
1362}
1363
1364static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1365 SmallVector<ParamIdx, 8> NonNullArgs;
1366 for (unsigned I = 0; I < AL.getNumArgs(); ++I) {
1367 Expr *Ex = AL.getArgAsExpr(Arg: I);
1368 ParamIdx Idx;
1369 if (!S.checkFunctionOrMethodParameterIndex(
1370 D, AI: AL, AttrArgNum: I + 1, IdxExpr: Ex, Idx,
1371 /*CanIndexImplicitThis=*/false,
1372 /*CanIndexVariadicArguments=*/true))
1373 return;
1374
1375 // Is the function argument a pointer type?
1376 if (Idx.getASTIndex() < getFunctionOrMethodNumParams(D) &&
1377 !attrNonNullArgCheck(
1378 S, T: getFunctionOrMethodParamType(D, Idx: Idx.getASTIndex()), AL,
1379 AttrParmRange: Ex->getSourceRange(),
1380 TypeRange: getFunctionOrMethodParamRange(D, Idx: Idx.getASTIndex())))
1381 continue;
1382
1383 NonNullArgs.push_back(Elt: Idx);
1384 }
1385
1386 // If an argument was specified and there was an attribute ignored warning
1387 // issued for it, do not apply the nonnull attribute without any arguments as
1388 // that has incorrect semantics in a function like:
1389 // __attribute__((nonnull(1))) void f(int val, int *ptr);
1390 // because that will signal that 'ptr' is nonnull when it's not intended to
1391 // be marked as such. However, continue on if there is at least one valid
1392 // parameter index.
1393 if (AL.getNumArgs() != 0 && NonNullArgs.empty())
1394 return;
1395
1396 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1397 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1398 // check if the attribute came from a macro expansion or a template
1399 // instantiation.
1400 if (NonNullArgs.empty() && AL.getLoc().isFileID() &&
1401 !S.inTemplateInstantiation()) {
1402 bool AnyPointers = isFunctionOrMethodVariadic(D);
1403 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1404 I != E && !AnyPointers; ++I) {
1405 QualType T = getFunctionOrMethodParamType(D, Idx: I);
1406 if (S.isValidPointerAttrType(T))
1407 AnyPointers = true;
1408 }
1409
1410 if (!AnyPointers)
1411 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_nonnull_no_pointers);
1412 }
1413
1414 ParamIdx *Start = NonNullArgs.data();
1415 unsigned Size = NonNullArgs.size();
1416 llvm::array_pod_sort(Start, End: Start + Size);
1417 D->addAttr(A: ::new (S.Context) NonNullAttr(S.Context, AL, Start, Size));
1418}
1419
1420static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1421 const ParsedAttr &AL) {
1422 if (AL.getNumArgs() > 0) {
1423 if (D->getFunctionType()) {
1424 handleNonNullAttr(S, D, AL);
1425 } else {
1426 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_nonnull_parm_no_args)
1427 << D->getSourceRange();
1428 }
1429 return;
1430 }
1431
1432 // Is the argument a pointer type?
1433 if (!attrNonNullArgCheck(S, T: D->getType(), AL, AttrParmRange: SourceRange(),
1434 TypeRange: D->getSourceRange()))
1435 return;
1436
1437 D->addAttr(A: ::new (S.Context) NonNullAttr(S.Context, AL, nullptr, 0));
1438}
1439
1440static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1441 QualType ResultType = getFunctionOrMethodResultType(D);
1442 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1443 if (!attrNonNullArgCheck(S, T: ResultType, AL, AttrParmRange: SourceRange(), TypeRange: SR,
1444 /* isReturnValue */ true))
1445 return;
1446
1447 D->addAttr(A: ::new (S.Context) ReturnsNonNullAttr(S.Context, AL));
1448}
1449
1450static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1451 if (D->isInvalidDecl())
1452 return;
1453
1454 // noescape only applies to pointer types.
1455 QualType T = cast<ParmVarDecl>(Val: D)->getType();
1456 if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
1457 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_pointers_only)
1458 << AL << AL.getRange() << 0;
1459 return;
1460 }
1461
1462 D->addAttr(A: ::new (S.Context) NoEscapeAttr(S.Context, AL));
1463}
1464
1465static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1466 Expr *E = AL.getArgAsExpr(Arg: 0),
1467 *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(Arg: 1) : nullptr;
1468 S.AddAssumeAlignedAttr(D, CI: AL, E, OE);
1469}
1470
1471static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1472 S.AddAllocAlignAttr(D, CI: AL, ParamExpr: AL.getArgAsExpr(Arg: 0));
1473}
1474
1475void Sema::AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
1476 Expr *OE) {
1477 QualType ResultType = getFunctionOrMethodResultType(D);
1478 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1479 SourceLocation AttrLoc = CI.getLoc();
1480
1481 if (!isValidPointerAttrType(T: ResultType, /* RefOkay */ true)) {
1482 Diag(Loc: AttrLoc, DiagID: diag::warn_attribute_return_pointers_refs_only)
1483 << CI << CI.getRange() << SR;
1484 return;
1485 }
1486
1487 if (!E->isValueDependent()) {
1488 std::optional<llvm::APSInt> I = llvm::APSInt(64);
1489 if (!(I = E->getIntegerConstantExpr(Ctx: Context))) {
1490 if (OE)
1491 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_argument_n_type)
1492 << CI << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
1493 else
1494 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_argument_type)
1495 << CI << AANT_ArgumentIntegerConstant << E->getSourceRange();
1496 return;
1497 }
1498
1499 if (!I->isPowerOf2()) {
1500 Diag(Loc: AttrLoc, DiagID: diag::err_alignment_not_power_of_two)
1501 << E->getSourceRange();
1502 return;
1503 }
1504
1505 if (*I > Sema::MaximumAlignment)
1506 Diag(Loc: CI.getLoc(), DiagID: diag::warn_assume_aligned_too_great)
1507 << CI.getRange() << Sema::MaximumAlignment;
1508 }
1509
1510 if (OE && !OE->isValueDependent() && !OE->isIntegerConstantExpr(Ctx: Context)) {
1511 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_argument_n_type)
1512 << CI << 2 << AANT_ArgumentIntegerConstant << OE->getSourceRange();
1513 return;
1514 }
1515
1516 D->addAttr(A: ::new (Context) AssumeAlignedAttr(Context, CI, E, OE));
1517}
1518
1519void Sema::AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
1520 Expr *ParamExpr) {
1521 QualType ResultType = getFunctionOrMethodResultType(D);
1522 SourceLocation AttrLoc = CI.getLoc();
1523
1524 if (!isValidPointerAttrType(T: ResultType, /* RefOkay */ true)) {
1525 Diag(Loc: AttrLoc, DiagID: diag::warn_attribute_return_pointers_refs_only)
1526 << CI << CI.getRange() << getFunctionOrMethodResultSourceRange(D);
1527 return;
1528 }
1529
1530 ParamIdx Idx;
1531 if (!checkFunctionOrMethodParameterIndex(D, AI: CI,
1532 /*AttrArgNum=*/1, IdxExpr: ParamExpr, Idx))
1533 return;
1534
1535 QualType Ty = getFunctionOrMethodParamType(D, Idx: Idx.getASTIndex());
1536 if (!Ty->isDependentType() && !Ty->isIntegralType(Ctx: Context) &&
1537 !Ty->isAlignValT()) {
1538 Diag(Loc: ParamExpr->getBeginLoc(), DiagID: diag::err_attribute_integers_only)
1539 << CI << getFunctionOrMethodParamRange(D, Idx: Idx.getASTIndex());
1540 return;
1541 }
1542
1543 D->addAttr(A: ::new (Context) AllocAlignAttr(Context, CI, Idx));
1544}
1545
1546/// Normalize the attribute, __foo__ becomes foo.
1547/// Returns true if normalization was applied.
1548static bool normalizeName(StringRef &AttrName) {
1549 if (AttrName.size() > 4 && AttrName.starts_with(Prefix: "__") &&
1550 AttrName.ends_with(Suffix: "__")) {
1551 AttrName = AttrName.drop_front(N: 2).drop_back(N: 2);
1552 return true;
1553 }
1554 return false;
1555}
1556
1557static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1558 // This attribute must be applied to a function declaration. The first
1559 // argument to the attribute must be an identifier, the name of the resource,
1560 // for example: malloc. The following arguments must be argument indexes, the
1561 // arguments must be of integer type for Returns, otherwise of pointer type.
1562 // The difference between Holds and Takes is that a pointer may still be used
1563 // after being held. free() should be __attribute((ownership_takes)), whereas
1564 // a list append function may well be __attribute((ownership_holds)).
1565
1566 if (!AL.isArgIdent(Arg: 0)) {
1567 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_n_type)
1568 << AL << 1 << AANT_ArgumentIdentifier;
1569 return;
1570 }
1571
1572 // Figure out our Kind.
1573 OwnershipAttr::OwnershipKind K =
1574 OwnershipAttr(S.Context, AL, nullptr, nullptr, 0).getOwnKind();
1575
1576 // Check arguments.
1577 switch (K) {
1578 case OwnershipAttr::Takes:
1579 case OwnershipAttr::Holds:
1580 if (AL.getNumArgs() < 2) {
1581 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_too_few_arguments) << AL << 2;
1582 return;
1583 }
1584 break;
1585 case OwnershipAttr::Returns:
1586 if (AL.getNumArgs() > 2) {
1587 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_too_many_arguments) << AL << 2;
1588 return;
1589 }
1590 break;
1591 }
1592
1593 // Allow only pointers to be return type for functions with ownership_returns
1594 // attribute. This matches with current OwnershipAttr::Takes semantics
1595 if (K == OwnershipAttr::Returns &&
1596 !getFunctionOrMethodResultType(D)->isPointerType()) {
1597 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_ownership_takes_return_type) << AL;
1598 return;
1599 }
1600
1601 IdentifierInfo *Module = AL.getArgAsIdent(Arg: 0)->getIdentifierInfo();
1602
1603 StringRef ModuleName = Module->getName();
1604 if (normalizeName(AttrName&: ModuleName)) {
1605 Module = &S.PP.getIdentifierTable().get(Name: ModuleName);
1606 }
1607
1608 // Check if the new ownership_returns attribute does not contain
1609 // an index, but previous attributes do.
1610 if (K == OwnershipAttr::Returns && AL.getNumArgs() == 1) {
1611 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1612 if (I->getOwnKind() == OwnershipAttr::Returns && I->args_size() > 0) {
1613 S.Diag(Loc: I->getLocation(), DiagID: diag::err_ownership_returns_index_mismatch)
1614 << I->args_begin()->getSourceIndex() << 0;
1615 S.Diag(Loc: AL.getLoc(), DiagID: diag::note_ownership_returns_index_mismatch)
1616 << 0 << 1;
1617 return;
1618 }
1619 }
1620 }
1621
1622 SmallVector<ParamIdx, 8> OwnershipArgs;
1623 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1624 Expr *Ex = AL.getArgAsExpr(Arg: i);
1625 ParamIdx Idx;
1626 if (!S.checkFunctionOrMethodParameterIndex(D, AI: AL, AttrArgNum: i, IdxExpr: Ex, Idx))
1627 return;
1628
1629 // Is the function argument a pointer type?
1630 QualType T = getFunctionOrMethodParamType(D, Idx: Idx.getASTIndex());
1631 int Err = -1; // No error
1632 switch (K) {
1633 case OwnershipAttr::Takes:
1634 case OwnershipAttr::Holds:
1635 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1636 Err = 0;
1637 break;
1638 case OwnershipAttr::Returns:
1639 if (!T->isIntegerType())
1640 Err = 1;
1641 break;
1642 }
1643 if (-1 != Err) {
1644 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_ownership_type) << AL << Err
1645 << Ex->getSourceRange();
1646 return;
1647 }
1648
1649 // Check we don't have a conflict with another ownership attribute.
1650 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1651 // Cannot have two ownership attributes of different kinds for the same
1652 // index.
1653 if (I->getOwnKind() != K && llvm::is_contained(Range: I->args(), Element: Idx)) {
1654 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attributes_are_not_compatible)
1655 << AL << I
1656 << (AL.isRegularKeywordAttribute() ||
1657 I->isRegularKeywordAttribute());
1658 return;
1659 }
1660
1661 if (K == OwnershipAttr::Returns &&
1662 I->getOwnKind() == OwnershipAttr::Returns) {
1663 bool IHasArgs = I->args_size() > 0;
1664
1665 if (!IHasArgs || !llvm::is_contained(Range: I->args(), Element: Idx)) {
1666 unsigned IIdx = IHasArgs ? I->args_begin()->getSourceIndex() : 0;
1667
1668 S.Diag(Loc: I->getLocation(), DiagID: diag::err_ownership_returns_index_mismatch)
1669 << IIdx << (IHasArgs ? 0 : 1);
1670
1671 S.Diag(Loc: AL.getLoc(), DiagID: diag::note_ownership_returns_index_mismatch)
1672 << Idx.getSourceIndex() << 0 << Ex->getSourceRange();
1673 return;
1674 }
1675 } else if (K == OwnershipAttr::Takes &&
1676 I->getOwnKind() == OwnershipAttr::Takes) {
1677 if (I->getModule()->getName() != ModuleName) {
1678 S.Diag(Loc: I->getLocation(), DiagID: diag::err_ownership_takes_class_mismatch)
1679 << I->getModule()->getName();
1680 S.Diag(Loc: AL.getLoc(), DiagID: diag::note_ownership_takes_class_mismatch)
1681 << ModuleName << Ex->getSourceRange();
1682
1683 return;
1684 }
1685 }
1686 }
1687 OwnershipArgs.push_back(Elt: Idx);
1688 }
1689
1690 ParamIdx *Start = OwnershipArgs.data();
1691 unsigned Size = OwnershipArgs.size();
1692 llvm::array_pod_sort(Start, End: Start + Size);
1693 D->addAttr(A: ::new (S.Context)
1694 OwnershipAttr(S.Context, AL, Module, Start, Size));
1695}
1696
1697static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1698 // Check the attribute arguments.
1699 if (AL.getNumArgs() > 1) {
1700 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments) << AL << 1;
1701 return;
1702 }
1703
1704 // gcc rejects
1705 // class c {
1706 // static int a __attribute__((weakref ("v2")));
1707 // static int b() __attribute__((weakref ("f3")));
1708 // };
1709 // and ignores the attributes of
1710 // void f(void) {
1711 // static int a __attribute__((weakref ("v2")));
1712 // }
1713 // we reject them
1714 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1715 if (!Ctx->isFileContext()) {
1716 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_weakref_not_global_context)
1717 << cast<NamedDecl>(Val: D);
1718 return;
1719 }
1720
1721 // The GCC manual says
1722 //
1723 // At present, a declaration to which `weakref' is attached can only
1724 // be `static'.
1725 //
1726 // It also says
1727 //
1728 // Without a TARGET,
1729 // given as an argument to `weakref' or to `alias', `weakref' is
1730 // equivalent to `weak'.
1731 //
1732 // gcc 4.4.1 will accept
1733 // int a7 __attribute__((weakref));
1734 // as
1735 // int a7 __attribute__((weak));
1736 // This looks like a bug in gcc. We reject that for now. We should revisit
1737 // it if this behaviour is actually used.
1738
1739 // GCC rejects
1740 // static ((alias ("y"), weakref)).
1741 // Should we? How to check that weakref is before or after alias?
1742
1743 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1744 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1745 // StringRef parameter it was given anyway.
1746 StringRef Str;
1747 if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str))
1748 // GCC will accept anything as the argument of weakref. Should we
1749 // check for an existing decl?
1750 D->addAttr(A: ::new (S.Context) AliasAttr(S.Context, AL, Str));
1751
1752 D->addAttr(A: ::new (S.Context) WeakRefAttr(S.Context, AL));
1753}
1754
1755// Mark alias/ifunc target as used. Due to name mangling, we look up the
1756// demangled name ignoring parameters (not supported by microsoftDemangle
1757// https://github.com/llvm/llvm-project/issues/88825). This should handle the
1758// majority of use cases while leaving namespace scope names unmarked.
1759static void markUsedForAliasOrIfunc(Sema &S, Decl *D, const ParsedAttr &AL,
1760 StringRef Str) {
1761 std::unique_ptr<char, llvm::FreeDeleter> Demangled;
1762 if (S.getASTContext().getCXXABIKind() != TargetCXXABI::Microsoft)
1763 Demangled.reset(p: llvm::itaniumDemangle(mangled_name: Str, /*ParseParams=*/false));
1764 std::unique_ptr<MangleContext> MC(S.Context.createMangleContext());
1765 SmallString<256> Name;
1766
1767 const DeclarationNameInfo Target(
1768 &S.Context.Idents.get(Name: Demangled ? Demangled.get() : Str), AL.getLoc());
1769 LookupResult LR(S, Target, Sema::LookupOrdinaryName);
1770 if (S.LookupName(R&: LR, S: S.TUScope)) {
1771 for (NamedDecl *ND : LR) {
1772 if (!isa<FunctionDecl>(Val: ND) && !isa<VarDecl>(Val: ND))
1773 continue;
1774 if (MC->shouldMangleDeclName(D: ND)) {
1775 llvm::raw_svector_ostream Out(Name);
1776 Name.clear();
1777 MC->mangleName(GD: GlobalDecl(ND), Out);
1778 } else {
1779 Name = ND->getIdentifier()->getName();
1780 }
1781 if (Name == Str)
1782 ND->markUsed(C&: S.Context);
1783 }
1784 }
1785}
1786
1787static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1788 StringRef Str;
1789 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str))
1790 return;
1791
1792 // Aliases should be on declarations, not definitions.
1793 const auto *FD = cast<FunctionDecl>(Val: D);
1794 if (FD->isThisDeclarationADefinition()) {
1795 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_alias_is_definition) << FD << 1;
1796 return;
1797 }
1798
1799 markUsedForAliasOrIfunc(S, D, AL, Str);
1800 D->addAttr(A: ::new (S.Context) IFuncAttr(S.Context, AL, Str));
1801}
1802
1803static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1804 StringRef Str;
1805 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str))
1806 return;
1807
1808 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1809 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_alias_not_supported_on_darwin);
1810 return;
1811 }
1812
1813 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1814 CudaVersion Version =
1815 ToCudaVersion(S.Context.getTargetInfo().getSDKVersion());
1816 if (Version != CudaVersion::UNKNOWN && Version < CudaVersion::CUDA_100)
1817 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_alias_not_supported_on_nvptx);
1818 }
1819
1820 // Aliases should be on declarations, not definitions.
1821 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
1822 if (FD->isThisDeclarationADefinition()) {
1823 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_alias_is_definition) << FD << 0;
1824 return;
1825 }
1826 } else {
1827 const auto *VD = cast<VarDecl>(Val: D);
1828 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1829 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_alias_is_definition) << VD << 0;
1830 return;
1831 }
1832 }
1833
1834 markUsedForAliasOrIfunc(S, D, AL, Str);
1835 D->addAttr(A: ::new (S.Context) AliasAttr(S.Context, AL, Str));
1836}
1837
1838static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1839 StringRef Model;
1840 SourceLocation LiteralLoc;
1841 // Check that it is a string.
1842 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: Model, ArgLocation: &LiteralLoc))
1843 return;
1844
1845 // Check that the value.
1846 if (Model != "global-dynamic" && Model != "local-dynamic"
1847 && Model != "initial-exec" && Model != "local-exec") {
1848 S.Diag(Loc: LiteralLoc, DiagID: diag::err_attr_tlsmodel_arg);
1849 return;
1850 }
1851
1852 D->addAttr(A: ::new (S.Context) TLSModelAttr(S.Context, AL, Model));
1853}
1854
1855static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1856 QualType ResultType = getFunctionOrMethodResultType(D);
1857 if (!ResultType->isAnyPointerType() && !ResultType->isBlockPointerType()) {
1858 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_return_pointers_only)
1859 << AL << getFunctionOrMethodResultSourceRange(D);
1860 return;
1861 }
1862
1863 if (AL.getNumArgs() == 0) {
1864 D->addAttr(A: ::new (S.Context) RestrictAttr(S.Context, AL));
1865 return;
1866 }
1867
1868 if (AL.getAttributeSpellingListIndex() == RestrictAttr::Declspec_restrict) {
1869 // __declspec(restrict) accepts no arguments
1870 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments) << AL << 0;
1871 return;
1872 }
1873
1874 // [[gnu::malloc(deallocator)]] with args specifies a deallocator function
1875 Expr *DeallocE = AL.getArgAsExpr(Arg: 0);
1876 SourceLocation DeallocLoc = DeallocE->getExprLoc();
1877 FunctionDecl *DeallocFD = nullptr;
1878 DeclarationNameInfo DeallocNI;
1879
1880 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: DeallocE)) {
1881 DeallocFD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
1882 DeallocNI = DRE->getNameInfo();
1883 if (!DeallocFD) {
1884 S.Diag(Loc: DeallocLoc, DiagID: diag::err_attribute_malloc_arg_not_function)
1885 << 1 << DeallocNI.getName();
1886 return;
1887 }
1888 } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: DeallocE)) {
1889 DeallocFD = S.ResolveSingleFunctionTemplateSpecialization(ovl: ULE, Complain: true);
1890 DeallocNI = ULE->getNameInfo();
1891 if (!DeallocFD) {
1892 S.Diag(Loc: DeallocLoc, DiagID: diag::err_attribute_malloc_arg_not_function)
1893 << 2 << DeallocNI.getName();
1894 if (ULE->getType() == S.Context.OverloadTy)
1895 S.NoteAllOverloadCandidates(E: ULE);
1896 return;
1897 }
1898 } else {
1899 S.Diag(Loc: DeallocLoc, DiagID: diag::err_attribute_malloc_arg_not_function) << 0;
1900 return;
1901 }
1902
1903 // 2nd arg of [[gnu::malloc(deallocator, 2)]] with args specifies the param
1904 // of deallocator that deallocates the pointer (defaults to 1)
1905 ParamIdx DeallocPtrIdx;
1906 if (AL.getNumArgs() == 1) {
1907 DeallocPtrIdx = ParamIdx(1, DeallocFD);
1908
1909 // FIXME: We could probably be better about diagnosing that there IS no
1910 // argument, or that the function doesn't have a prototype, but this is how
1911 // GCC diagnoses this, and is reasonably clear.
1912 if (!DeallocPtrIdx.isValid() || !hasFunctionProto(D: DeallocFD) ||
1913 getFunctionOrMethodNumParams(D: DeallocFD) < 1 ||
1914 !getFunctionOrMethodParamType(D: DeallocFD, Idx: DeallocPtrIdx.getASTIndex())
1915 .getCanonicalType()
1916 ->isPointerType()) {
1917 S.Diag(Loc: DeallocLoc,
1918 DiagID: diag::err_attribute_malloc_arg_not_function_with_pointer_arg)
1919 << DeallocNI.getName();
1920 return;
1921 }
1922 } else {
1923 if (!S.checkFunctionOrMethodParameterIndex(
1924 D: DeallocFD, AI: AL, AttrArgNum: 2, IdxExpr: AL.getArgAsExpr(Arg: 1), Idx&: DeallocPtrIdx,
1925 /* CanIndexImplicitThis=*/false))
1926 return;
1927
1928 QualType DeallocPtrArgType =
1929 getFunctionOrMethodParamType(D: DeallocFD, Idx: DeallocPtrIdx.getASTIndex());
1930 if (!DeallocPtrArgType.getCanonicalType()->isPointerType()) {
1931 S.Diag(Loc: DeallocLoc,
1932 DiagID: diag::err_attribute_malloc_arg_refers_to_non_pointer_type)
1933 << DeallocPtrIdx.getSourceIndex() << DeallocPtrArgType
1934 << DeallocNI.getName();
1935 return;
1936 }
1937 }
1938
1939 // FIXME: we should add this attribute to Clang's AST, so that clang-analyzer
1940 // can use it, see -Wmismatched-dealloc in GCC for what we can do with this.
1941 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_form_ignored) << AL;
1942 D->addAttr(A: ::new (S.Context)
1943 RestrictAttr(S.Context, AL, DeallocE, DeallocPtrIdx));
1944}
1945
1946bool Sema::CheckSpanLikeType(const AttributeCommonInfo &CI,
1947 const QualType &Ty) {
1948 // Note that there may also be numerous cases of pointer + integer /
1949 // pointer + pointer / integer + pointer structures not actually exhibiting
1950 // a span-like semantics, so sometimes these heuristics expectedly
1951 // lead to false positive results.
1952 auto emitWarning = [this, &CI](unsigned NoteDiagID) {
1953 Diag(Loc: CI.getLoc(), DiagID: diag::warn_attribute_return_span_only) << CI;
1954 return Diag(Loc: CI.getLoc(), DiagID: NoteDiagID);
1955 };
1956 if (Ty->isDependentType())
1957 return false;
1958 // isCompleteType is used to force template class instantiation.
1959 if (!isCompleteType(Loc: CI.getLoc(), T: Ty))
1960 return emitWarning(diag::note_returned_incomplete_type);
1961 const RecordDecl *RD = Ty->getAsRecordDecl();
1962 if (!RD || RD->isUnion())
1963 return emitWarning(diag::note_returned_not_struct);
1964 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
1965 if (CXXRD->getNumBases() > 0) {
1966 return emitWarning(diag::note_type_inherits_from_base);
1967 }
1968 }
1969 auto FieldsBegin = RD->field_begin();
1970 auto FieldsCount = std::distance(first: FieldsBegin, last: RD->field_end());
1971 if (FieldsCount != 2)
1972 return emitWarning(diag::note_returned_not_two_field_struct) << FieldsCount;
1973 QualType FirstFieldType = FieldsBegin->getType();
1974 QualType SecondFieldType = std::next(x: FieldsBegin)->getType();
1975 auto validatePointerType = [](const QualType &T) {
1976 // It must not point to functions.
1977 return T->isPointerType() && !T->isFunctionPointerType();
1978 };
1979 auto checkIntegerType = [this, emitWarning](const QualType &T,
1980 const int FieldNo) -> bool {
1981 const auto *BT = dyn_cast<BuiltinType>(Val: T.getCanonicalType());
1982 if (!BT || !BT->isInteger())
1983 return emitWarning(diag::note_returned_not_integer_field) << FieldNo;
1984 auto IntSize = Context.getTypeSize(T: Context.IntTy);
1985 if (Context.getTypeSize(T: BT) < IntSize)
1986 return emitWarning(diag::note_returned_not_wide_enough_field)
1987 << FieldNo << IntSize;
1988 return false;
1989 };
1990 if (validatePointerType(FirstFieldType) &&
1991 validatePointerType(SecondFieldType)) {
1992 // Pointer + pointer.
1993 return false;
1994 } else if (validatePointerType(FirstFieldType)) {
1995 // Pointer + integer?
1996 return checkIntegerType(SecondFieldType, 2);
1997 } else if (validatePointerType(SecondFieldType)) {
1998 // Integer + pointer?
1999 return checkIntegerType(FirstFieldType, 1);
2000 }
2001 return emitWarning(diag::note_returned_not_span_struct);
2002}
2003
2004static void handleMallocSpanAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2005 QualType ResultType = getFunctionOrMethodResultType(D);
2006 if (!S.CheckSpanLikeType(CI: AL, Ty: ResultType))
2007 D->addAttr(A: ::new (S.Context) MallocSpanAttr(S.Context, AL));
2008}
2009
2010static void handleCPUSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2011 // Ensure we don't combine these with themselves, since that causes some
2012 // confusing behavior.
2013 if (AL.getParsedKind() == ParsedAttr::AT_CPUDispatch) {
2014 if (checkAttrMutualExclusion<CPUSpecificAttr>(S, D, AL))
2015 return;
2016
2017 if (const auto *Other = D->getAttr<CPUDispatchAttr>()) {
2018 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_disallowed_duplicate_attribute) << AL;
2019 S.Diag(Loc: Other->getLocation(), DiagID: diag::note_conflicting_attribute);
2020 return;
2021 }
2022 } else if (AL.getParsedKind() == ParsedAttr::AT_CPUSpecific) {
2023 if (checkAttrMutualExclusion<CPUDispatchAttr>(S, D, AL))
2024 return;
2025
2026 if (const auto *Other = D->getAttr<CPUSpecificAttr>()) {
2027 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_disallowed_duplicate_attribute) << AL;
2028 S.Diag(Loc: Other->getLocation(), DiagID: diag::note_conflicting_attribute);
2029 return;
2030 }
2031 }
2032
2033 FunctionDecl *FD = cast<FunctionDecl>(Val: D);
2034
2035 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
2036 if (MD->getParent()->isLambda()) {
2037 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_dll_lambda) << AL;
2038 return;
2039 }
2040 }
2041
2042 if (!AL.checkAtLeastNumArgs(S, Num: 1))
2043 return;
2044
2045 SmallVector<const IdentifierInfo *, 8> CPUs;
2046 for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); ++ArgNo) {
2047 if (!AL.isArgIdent(Arg: ArgNo)) {
2048 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_type)
2049 << AL << AANT_ArgumentIdentifier;
2050 return;
2051 }
2052
2053 IdentifierLoc *CPUArg = AL.getArgAsIdent(Arg: ArgNo);
2054 StringRef CPUName = CPUArg->getIdentifierInfo()->getName().trim();
2055
2056 if (!S.Context.getTargetInfo().validateCPUSpecificCPUDispatch(Name: CPUName)) {
2057 S.Diag(Loc: CPUArg->getLoc(), DiagID: diag::err_invalid_cpu_specific_dispatch_value)
2058 << CPUName << (AL.getKind() == ParsedAttr::AT_CPUDispatch);
2059 return;
2060 }
2061
2062 const TargetInfo &Target = S.Context.getTargetInfo();
2063 if (llvm::any_of(Range&: CPUs, P: [CPUName, &Target](const IdentifierInfo *Cur) {
2064 return Target.CPUSpecificManglingCharacter(Name: CPUName) ==
2065 Target.CPUSpecificManglingCharacter(Name: Cur->getName());
2066 })) {
2067 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_multiversion_duplicate_entries);
2068 return;
2069 }
2070 CPUs.push_back(Elt: CPUArg->getIdentifierInfo());
2071 }
2072
2073 FD->setIsMultiVersion(true);
2074 if (AL.getKind() == ParsedAttr::AT_CPUSpecific)
2075 D->addAttr(A: ::new (S.Context)
2076 CPUSpecificAttr(S.Context, AL, CPUs.data(), CPUs.size()));
2077 else
2078 D->addAttr(A: ::new (S.Context)
2079 CPUDispatchAttr(S.Context, AL, CPUs.data(), CPUs.size()));
2080}
2081
2082static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2083 if (S.LangOpts.CPlusPlus) {
2084 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_not_supported_in_lang)
2085 << AL << AttributeLangSupport::Cpp;
2086 return;
2087 }
2088
2089 D->addAttr(A: ::new (S.Context) CommonAttr(S.Context, AL));
2090}
2091
2092static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2093 if (AL.isDeclspecAttribute()) {
2094 const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
2095 const auto &Arch = Triple.getArch();
2096 if (Arch != llvm::Triple::x86 &&
2097 (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
2098 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_not_supported_on_arch)
2099 << AL << Triple.getArchName();
2100 return;
2101 }
2102
2103 // This form is not allowed to be written on a member function (static or
2104 // nonstatic) when in Microsoft compatibility mode.
2105 if (S.getLangOpts().MSVCCompat && isa<CXXMethodDecl>(Val: D)) {
2106 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_wrong_decl_type)
2107 << AL << AL.isRegularKeywordAttribute() << ExpectedNonMemberFunction;
2108 return;
2109 }
2110 }
2111
2112 D->addAttr(A: ::new (S.Context) NakedAttr(S.Context, AL));
2113}
2114
2115// FIXME: This is a best-effort heuristic.
2116// Currently only handles single throw expressions (optionally with
2117// ExprWithCleanups). We could expand this to perform control-flow analysis for
2118// more complex patterns.
2119static bool isKnownToAlwaysThrow(const FunctionDecl *FD) {
2120 const Stmt *Body = FD->getBody();
2121 if (!Body)
2122 return false;
2123 const Stmt *OnlyStmt = nullptr;
2124
2125 if (const auto *Compound = dyn_cast<CompoundStmt>(Val: Body)) {
2126 if (Compound->size() != 1)
2127 return false; // More than one statement, can't be known to always throw.
2128 OnlyStmt = *Compound->body_begin();
2129 } else {
2130 OnlyStmt = Body;
2131 }
2132
2133 // Unwrap ExprWithCleanups if necessary.
2134 if (const auto *EWC = dyn_cast<ExprWithCleanups>(Val: OnlyStmt)) {
2135 OnlyStmt = EWC->getSubExpr();
2136 }
2137
2138 if (isa<CXXThrowExpr>(Val: OnlyStmt)) {
2139 const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
2140 if (MD && MD->isVirtual()) {
2141 const auto *RD = MD->getParent();
2142 return MD->hasAttr<FinalAttr>() || (RD && RD->isEffectivelyFinal());
2143 }
2144 return true;
2145 }
2146 return false;
2147}
2148
2149void clang::inferNoReturnAttr(Sema &S, Decl *D) {
2150 auto *FD = dyn_cast<FunctionDecl>(Val: D);
2151 if (!FD)
2152 return;
2153
2154 // Skip explicit specializations here as they may have
2155 // a user-provided definition that may deliberately differ from the primary
2156 // template. If an explicit specialization truly never returns, the user
2157 // should explicitly mark it with [[noreturn]].
2158 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2159 return;
2160
2161 DiagnosticsEngine &Diags = S.getDiagnostics();
2162 if (Diags.isIgnored(DiagID: diag::warn_falloff_nonvoid, Loc: FD->getLocation()) &&
2163 Diags.isIgnored(DiagID: diag::warn_suggest_noreturn_function, Loc: FD->getLocation()))
2164 return;
2165
2166 if (!FD->isNoReturn() && !FD->hasAttr<InferredNoReturnAttr>() &&
2167 isKnownToAlwaysThrow(FD)) {
2168 FD->addAttr(A: InferredNoReturnAttr::CreateImplicit(Ctx&: S.Context));
2169
2170 // [[noreturn]] can only be added to lambdas since C++23
2171 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
2172 MD && !S.getLangOpts().CPlusPlus23 && isLambdaCallOperator(MD))
2173 return;
2174
2175 // Emit a diagnostic suggesting the function being marked [[noreturn]].
2176 S.Diag(Loc: FD->getLocation(), DiagID: diag::warn_suggest_noreturn_function)
2177 << /*isFunction=*/0 << FD;
2178 }
2179}
2180
2181static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2182 if (hasDeclarator(D)) return;
2183
2184 if (!isa<ObjCMethodDecl>(Val: D)) {
2185 S.Diag(Loc: Attrs.getLoc(), DiagID: diag::warn_attribute_wrong_decl_type)
2186 << Attrs << Attrs.isRegularKeywordAttribute()
2187 << ExpectedFunctionOrMethod;
2188 return;
2189 }
2190
2191 D->addAttr(A: ::new (S.Context) NoReturnAttr(S.Context, Attrs));
2192}
2193
2194static void handleStandardNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &A) {
2195 // The [[_Noreturn]] spelling is deprecated in C23, so if that was used,
2196 // issue an appropriate diagnostic. However, don't issue a diagnostic if the
2197 // attribute name comes from a macro expansion. We don't want to punish users
2198 // who write [[noreturn]] after including <stdnoreturn.h> (where 'noreturn'
2199 // is defined as a macro which expands to '_Noreturn').
2200 if (!S.getLangOpts().CPlusPlus &&
2201 A.getSemanticSpelling() == CXX11NoReturnAttr::C23_Noreturn &&
2202 !(A.getLoc().isMacroID() &&
2203 S.getSourceManager().isInSystemMacro(loc: A.getLoc())))
2204 S.Diag(Loc: A.getLoc(), DiagID: diag::warn_deprecated_noreturn_spelling) << A.getRange();
2205
2206 D->addAttr(A: ::new (S.Context) CXX11NoReturnAttr(S.Context, A));
2207}
2208
2209static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2210 if (!S.getLangOpts().CFProtectionBranch)
2211 S.Diag(Loc: Attrs.getLoc(), DiagID: diag::warn_nocf_check_attribute_ignored);
2212 else
2213 handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, CI: Attrs);
2214}
2215
2216bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) {
2217 if (!Attrs.checkExactlyNumArgs(S&: *this, Num: 0)) {
2218 Attrs.setInvalid();
2219 return true;
2220 }
2221
2222 return false;
2223}
2224
2225bool Sema::CheckAttrTarget(const ParsedAttr &AL) {
2226 // Check whether the attribute is valid on the current target.
2227 if (!AL.existsInTarget(Target: Context.getTargetInfo())) {
2228 if (AL.isRegularKeywordAttribute())
2229 Diag(Loc: AL.getLoc(), DiagID: diag::err_keyword_not_supported_on_target)
2230 << AL << AL.getRange();
2231 else
2232 DiagnoseUnknownAttribute(AL);
2233 AL.setInvalid();
2234 return true;
2235 }
2236 return false;
2237}
2238
2239static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2240
2241 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2242 // because 'analyzer_noreturn' does not impact the type.
2243 if (!isFunctionOrMethodOrBlockForAttrSubject(D)) {
2244 ValueDecl *VD = dyn_cast<ValueDecl>(Val: D);
2245 if (!VD || (!VD->getType()->isBlockPointerType() &&
2246 !VD->getType()->isFunctionPointerType())) {
2247 S.Diag(Loc: AL.getLoc(), DiagID: AL.isStandardAttributeSyntax()
2248 ? diag::err_attribute_wrong_decl_type
2249 : diag::warn_attribute_wrong_decl_type)
2250 << AL << AL.isRegularKeywordAttribute()
2251 << ExpectedFunctionMethodOrBlock;
2252 return;
2253 }
2254 }
2255
2256 D->addAttr(A: ::new (S.Context) AnalyzerNoReturnAttr(S.Context, AL));
2257}
2258
2259// PS3 PPU-specific.
2260static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2261 /*
2262 Returning a Vector Class in Registers
2263
2264 According to the PPU ABI specifications, a class with a single member of
2265 vector type is returned in memory when used as the return value of a
2266 function.
2267 This results in inefficient code when implementing vector classes. To return
2268 the value in a single vector register, add the vecreturn attribute to the
2269 class definition. This attribute is also applicable to struct types.
2270
2271 Example:
2272
2273 struct Vector
2274 {
2275 __vector float xyzw;
2276 } __attribute__((vecreturn));
2277
2278 Vector Add(Vector lhs, Vector rhs)
2279 {
2280 Vector result;
2281 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2282 return result; // This will be returned in a register
2283 }
2284 */
2285 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2286 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_repeat_attribute) << A;
2287 return;
2288 }
2289
2290 const auto *R = cast<RecordDecl>(Val: D);
2291 int count = 0;
2292
2293 if (!isa<CXXRecordDecl>(Val: R)) {
2294 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_vecreturn_only_vector_member);
2295 return;
2296 }
2297
2298 if (!cast<CXXRecordDecl>(Val: R)->isPOD()) {
2299 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_vecreturn_only_pod_record);
2300 return;
2301 }
2302
2303 for (const auto *I : R->fields()) {
2304 if ((count == 1) || !I->getType()->isVectorType()) {
2305 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_vecreturn_only_vector_member);
2306 return;
2307 }
2308 count++;
2309 }
2310
2311 D->addAttr(A: ::new (S.Context) VecReturnAttr(S.Context, AL));
2312}
2313
2314static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2315 bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName();
2316
2317 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2318 // about using it as an extension.
2319 if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
2320 S.Diag(Loc: AL.getLoc(), DiagID: diag::ext_cxx17_attr) << AL;
2321
2322 D->addAttr(A: ::new (S.Context) UnusedAttr(S.Context, AL));
2323}
2324
2325static ExprResult sharedGetConstructorDestructorAttrExpr(Sema &S,
2326 const ParsedAttr &AL) {
2327 // If no Expr node exists on the attribute, return a nullptr result (default
2328 // priority to be used). If Expr node exists but is not valid, return an
2329 // invalid result. Otherwise, return the Expr.
2330 Expr *E = nullptr;
2331 if (AL.getNumArgs() == 1) {
2332 E = AL.getArgAsExpr(Arg: 0);
2333 if (E->isValueDependent()) {
2334 if (!E->isTypeDependent() && !E->getType()->isIntegerType()) {
2335 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_type)
2336 << AL << AANT_ArgumentIntegerConstant << E->getSourceRange();
2337 return ExprError();
2338 }
2339 } else {
2340 uint32_t priority;
2341 if (!S.checkUInt32Argument(AI: AL, Expr: AL.getArgAsExpr(Arg: 0), Val&: priority)) {
2342 return ExprError();
2343 }
2344 return ConstantExpr::Create(Context: S.Context, E,
2345 Result: APValue(llvm::APSInt::getUnsigned(X: priority)));
2346 }
2347 }
2348 return E;
2349}
2350
2351static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2352 if (S.getLangOpts().HLSL && AL.getNumArgs()) {
2353 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_hlsl_init_priority_unsupported);
2354 return;
2355 }
2356 ExprResult E = sharedGetConstructorDestructorAttrExpr(S, AL);
2357 if (E.isInvalid())
2358 return;
2359 S.Diag(Loc: D->getLocation(), DiagID: diag::warn_global_constructor)
2360 << D->getSourceRange();
2361 D->addAttr(A: ConstructorAttr::Create(Ctx&: S.Context, Priority: E.get(), CommonInfo: AL));
2362}
2363
2364static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2365 ExprResult E = sharedGetConstructorDestructorAttrExpr(S, AL);
2366 if (E.isInvalid())
2367 return;
2368 S.Diag(Loc: D->getLocation(), DiagID: diag::warn_global_destructor) << D->getSourceRange();
2369 D->addAttr(A: DestructorAttr::Create(Ctx&: S.Context, Priority: E.get(), CommonInfo: AL));
2370}
2371
2372template <typename AttrTy>
2373static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) {
2374 // Handle the case where the attribute has a text message.
2375 StringRef Str;
2376 if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str))
2377 return;
2378
2379 D->addAttr(A: ::new (S.Context) AttrTy(S.Context, AL, Str));
2380}
2381
2382static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2383 const IdentifierInfo *Platform,
2384 VersionTuple Introduced,
2385 VersionTuple Deprecated,
2386 VersionTuple Obsoleted) {
2387 StringRef PlatformName
2388 = AvailabilityAttr::getPrettyPlatformName(Platform: Platform->getName());
2389 if (PlatformName.empty())
2390 PlatformName = Platform->getName();
2391
2392 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2393 // of these steps are needed).
2394 if (!Introduced.empty() && !Deprecated.empty() &&
2395 !(Introduced <= Deprecated)) {
2396 S.Diag(Loc: Range.getBegin(), DiagID: diag::warn_availability_version_ordering)
2397 << 1 << PlatformName << Deprecated.getAsString()
2398 << 0 << Introduced.getAsString();
2399 return true;
2400 }
2401
2402 if (!Introduced.empty() && !Obsoleted.empty() &&
2403 !(Introduced <= Obsoleted)) {
2404 S.Diag(Loc: Range.getBegin(), DiagID: diag::warn_availability_version_ordering)
2405 << 2 << PlatformName << Obsoleted.getAsString()
2406 << 0 << Introduced.getAsString();
2407 return true;
2408 }
2409
2410 if (!Deprecated.empty() && !Obsoleted.empty() &&
2411 !(Deprecated <= Obsoleted)) {
2412 S.Diag(Loc: Range.getBegin(), DiagID: diag::warn_availability_version_ordering)
2413 << 2 << PlatformName << Obsoleted.getAsString()
2414 << 1 << Deprecated.getAsString();
2415 return true;
2416 }
2417
2418 return false;
2419}
2420
2421/// Check whether the two versions match.
2422///
2423/// If either version tuple is empty, then they are assumed to match. If
2424/// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2425static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2426 bool BeforeIsOkay) {
2427 if (X.empty() || Y.empty())
2428 return true;
2429
2430 if (X == Y)
2431 return true;
2432
2433 if (BeforeIsOkay && X < Y)
2434 return true;
2435
2436 return false;
2437}
2438
2439AvailabilityAttr *Sema::mergeAvailabilityAttr(
2440 NamedDecl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Platform,
2441 bool Implicit, VersionTuple Introduced, VersionTuple Deprecated,
2442 VersionTuple Obsoleted, bool IsUnavailable, StringRef Message,
2443 bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK,
2444 int Priority, const IdentifierInfo *Environment,
2445 const IdentifierInfo *InferredPlatformII) {
2446 VersionTuple MergedIntroduced = Introduced;
2447 VersionTuple MergedDeprecated = Deprecated;
2448 VersionTuple MergedObsoleted = Obsoleted;
2449 bool FoundAny = false;
2450 bool OverrideOrImpl = false;
2451 switch (AMK) {
2452 case AvailabilityMergeKind::None:
2453 case AvailabilityMergeKind::Redeclaration:
2454 OverrideOrImpl = false;
2455 break;
2456
2457 case AvailabilityMergeKind::Override:
2458 case AvailabilityMergeKind::ProtocolImplementation:
2459 case AvailabilityMergeKind::OptionalProtocolImplementation:
2460 OverrideOrImpl = true;
2461 break;
2462 }
2463
2464 if (D->hasAttrs()) {
2465 AttrVec &Attrs = D->getAttrs();
2466 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2467 auto *OldAA = dyn_cast<AvailabilityAttr>(Val: Attrs[i]);
2468 if (!OldAA) {
2469 ++i;
2470 continue;
2471 }
2472
2473 const IdentifierInfo *OldEnvironment = OldAA->getEnvironment();
2474 if (OldEnvironment != Environment) {
2475 ++i;
2476 continue;
2477 }
2478
2479 if (OldAA->getPlatform() != Platform) {
2480 // If this new attr is for anyappleos and the old attr is for the
2481 // inferred platform, the existing explicit platform attr wins.
2482 if (InferredPlatformII) {
2483 if (OldAA->getPlatform() == InferredPlatformII)
2484 return nullptr;
2485 } else {
2486 // If this new attr is an explicit platform attr, check if the old
2487 // attr is an existing anyAppleOS attr whose inferred attr is for this
2488 // platform. If so, the explicit attr wins: erase the old attr.
2489 if (AvailabilityAttr *Inf = OldAA->getInferredAttrAs();
2490 Inf && Inf->getPlatform() == Platform) {
2491 Attrs.erase(CI: Attrs.begin() + i);
2492 --e;
2493 continue;
2494 }
2495 }
2496 ++i;
2497 continue;
2498 }
2499
2500 // If there is an existing availability attribute for this platform that
2501 // has a lower priority use the existing one and discard the new
2502 // attribute.
2503 if (OldAA->getPriority() < Priority)
2504 return nullptr;
2505
2506 // If there is an existing attribute for this platform that has a higher
2507 // priority than the new attribute then erase the old one and continue
2508 // processing the attributes.
2509 if (OldAA->getPriority() > Priority) {
2510 Attrs.erase(CI: Attrs.begin() + i);
2511 --e;
2512 continue;
2513 }
2514
2515 FoundAny = true;
2516 VersionTuple OldIntroduced = OldAA->getIntroduced();
2517 VersionTuple OldDeprecated = OldAA->getDeprecated();
2518 VersionTuple OldObsoleted = OldAA->getObsoleted();
2519 bool OldIsUnavailable = OldAA->getUnavailable();
2520
2521 if (!versionsMatch(X: OldIntroduced, Y: Introduced, BeforeIsOkay: OverrideOrImpl) ||
2522 !versionsMatch(X: Deprecated, Y: OldDeprecated, BeforeIsOkay: OverrideOrImpl) ||
2523 !versionsMatch(X: Obsoleted, Y: OldObsoleted, BeforeIsOkay: OverrideOrImpl) ||
2524 !(OldIsUnavailable == IsUnavailable ||
2525 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2526 if (OverrideOrImpl) {
2527 int Which = -1;
2528 VersionTuple FirstVersion;
2529 VersionTuple SecondVersion;
2530 if (!versionsMatch(X: OldIntroduced, Y: Introduced, BeforeIsOkay: OverrideOrImpl)) {
2531 Which = 0;
2532 FirstVersion = OldIntroduced;
2533 SecondVersion = Introduced;
2534 } else if (!versionsMatch(X: Deprecated, Y: OldDeprecated, BeforeIsOkay: OverrideOrImpl)) {
2535 Which = 1;
2536 FirstVersion = Deprecated;
2537 SecondVersion = OldDeprecated;
2538 } else if (!versionsMatch(X: Obsoleted, Y: OldObsoleted, BeforeIsOkay: OverrideOrImpl)) {
2539 Which = 2;
2540 FirstVersion = Obsoleted;
2541 SecondVersion = OldObsoleted;
2542 }
2543
2544 if (Which == -1) {
2545 Diag(Loc: OldAA->getLocation(),
2546 DiagID: diag::warn_mismatched_availability_override_unavail)
2547 << AvailabilityAttr::getPrettyPlatformName(Platform: Platform->getName())
2548 << (AMK == AvailabilityMergeKind::Override);
2549 } else if (Which != 1 && AMK == AvailabilityMergeKind::
2550 OptionalProtocolImplementation) {
2551 // Allow different 'introduced' / 'obsoleted' availability versions
2552 // on a method that implements an optional protocol requirement. It
2553 // makes less sense to allow this for 'deprecated' as the user can't
2554 // see if the method is 'deprecated' as 'respondsToSelector' will
2555 // still return true when the method is deprecated.
2556 ++i;
2557 continue;
2558 } else {
2559 Diag(Loc: OldAA->getLocation(),
2560 DiagID: diag::warn_mismatched_availability_override)
2561 << Which
2562 << AvailabilityAttr::getPrettyPlatformName(Platform: Platform->getName())
2563 << FirstVersion.getAsString() << SecondVersion.getAsString()
2564 << (AMK == AvailabilityMergeKind::Override);
2565 }
2566 if (AMK == AvailabilityMergeKind::Override)
2567 Diag(Loc: CI.getLoc(), DiagID: diag::note_overridden_method);
2568 else
2569 Diag(Loc: CI.getLoc(), DiagID: diag::note_protocol_method);
2570 } else {
2571 Diag(Loc: OldAA->getLocation(), DiagID: diag::warn_mismatched_availability);
2572 Diag(Loc: CI.getLoc(), DiagID: diag::note_previous_attribute);
2573 }
2574
2575 Attrs.erase(CI: Attrs.begin() + i);
2576 --e;
2577 continue;
2578 }
2579
2580 VersionTuple MergedIntroduced2 = MergedIntroduced;
2581 VersionTuple MergedDeprecated2 = MergedDeprecated;
2582 VersionTuple MergedObsoleted2 = MergedObsoleted;
2583
2584 if (MergedIntroduced2.empty())
2585 MergedIntroduced2 = OldIntroduced;
2586 if (MergedDeprecated2.empty())
2587 MergedDeprecated2 = OldDeprecated;
2588 if (MergedObsoleted2.empty())
2589 MergedObsoleted2 = OldObsoleted;
2590
2591 if (checkAvailabilityAttr(S&: *this, Range: OldAA->getRange(), Platform,
2592 Introduced: MergedIntroduced2, Deprecated: MergedDeprecated2,
2593 Obsoleted: MergedObsoleted2)) {
2594 Attrs.erase(CI: Attrs.begin() + i);
2595 --e;
2596 continue;
2597 }
2598
2599 MergedIntroduced = MergedIntroduced2;
2600 MergedDeprecated = MergedDeprecated2;
2601 MergedObsoleted = MergedObsoleted2;
2602 ++i;
2603 }
2604 }
2605
2606 if (FoundAny &&
2607 MergedIntroduced == Introduced &&
2608 MergedDeprecated == Deprecated &&
2609 MergedObsoleted == Obsoleted)
2610 return nullptr;
2611
2612 // Only create a new attribute if !OverrideOrImpl, but we want to do
2613 // the checking.
2614 if (!checkAvailabilityAttr(S&: *this, Range: CI.getRange(), Platform, Introduced: MergedIntroduced,
2615 Deprecated: MergedDeprecated, Obsoleted: MergedObsoleted) &&
2616 !OverrideOrImpl) {
2617 auto *Avail = ::new (Context) AvailabilityAttr(
2618 Context, CI, Platform, Introduced, Deprecated, Obsoleted, IsUnavailable,
2619 Message, IsStrict, Replacement, Priority, Environment,
2620 /*InferredAttr=*/nullptr);
2621 Avail->setImplicit(Implicit);
2622 return Avail;
2623 }
2624 return nullptr;
2625}
2626
2627AvailabilityAttr *Sema::mergeAndInferAvailabilityAttr(
2628 NamedDecl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Platform,
2629 bool Implicit, VersionTuple Introduced, VersionTuple Deprecated,
2630 VersionTuple Obsoleted, bool IsUnavailable, StringRef Message,
2631 bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK,
2632 int Priority, const IdentifierInfo *IIEnvironment,
2633 const IdentifierInfo *InferredPlatformII) {
2634 AvailabilityAttr *OrigAttr = mergeAvailabilityAttr(
2635 D, CI, Platform, Implicit, Introduced, Deprecated, Obsoleted,
2636 IsUnavailable, Message, IsStrict, Replacement, AMK, Priority,
2637 Environment: IIEnvironment, InferredPlatformII);
2638 if (!OrigAttr || !InferredPlatformII)
2639 return OrigAttr;
2640
2641 auto *InferredAttr = ::new (Context) AvailabilityAttr(
2642 Context, CI, InferredPlatformII, OrigAttr->getIntroduced(),
2643 OrigAttr->getDeprecated(), OrigAttr->getObsoleted(),
2644 OrigAttr->getUnavailable(), OrigAttr->getMessage(), OrigAttr->getStrict(),
2645 OrigAttr->getReplacement(),
2646 Priority == AP_PragmaClangAttribute
2647 ? AP_PragmaClangAttribute_InferredFromAnyAppleOS
2648 : AP_InferredFromAnyAppleOS,
2649 IIEnvironment, /*InferredAttr=*/nullptr);
2650 InferredAttr->setImplicit(true);
2651 OrigAttr->setInferredAttr(InferredAttr);
2652 return OrigAttr;
2653}
2654
2655/// Returns true if the given availability attribute should be inferred, and
2656/// adjusts the value of the attribute as necessary to facilitate that.
2657static bool shouldInferAvailabilityAttribute(const ParsedAttr &AL,
2658 IdentifierInfo *&II,
2659 bool &IsUnavailable,
2660 VersionTuple &Introduced,
2661 VersionTuple &Deprecated,
2662 VersionTuple &Obsolete, Sema &S) {
2663 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
2664 const ASTContext &Context = S.Context;
2665 if (TT.getOS() != llvm::Triple::XROS)
2666 return false;
2667 IdentifierInfo *NewII = nullptr;
2668 if (II->getName() == "ios")
2669 NewII = &Context.Idents.get(Name: "xros");
2670 else if (II->getName() == "ios_app_extension")
2671 NewII = &Context.Idents.get(Name: "xros_app_extension");
2672 if (!NewII)
2673 return false;
2674 II = NewII;
2675
2676 auto MakeUnavailable = [&]() {
2677 IsUnavailable = true;
2678 // Reset introduced, deprecated, obsoleted.
2679 Introduced = VersionTuple();
2680 Deprecated = VersionTuple();
2681 Obsolete = VersionTuple();
2682 };
2683
2684 const DarwinSDKInfo *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking(
2685 Loc: AL.getRange().getBegin(), Platform: "ios");
2686
2687 if (!SDKInfo) {
2688 MakeUnavailable();
2689 return true;
2690 }
2691 // Map from the fallback platform availability to the current platform
2692 // availability.
2693 const auto *Mapping = SDKInfo->getVersionMapping(Kind: DarwinSDKInfo::OSEnvPair(
2694 llvm::Triple::IOS, llvm::Triple::UnknownEnvironment, llvm::Triple::XROS,
2695 llvm::Triple::UnknownEnvironment));
2696 if (!Mapping) {
2697 MakeUnavailable();
2698 return true;
2699 }
2700
2701 if (!Introduced.empty()) {
2702 auto NewIntroduced = Mapping->mapIntroducedAvailabilityVersion(Key: Introduced);
2703 if (!NewIntroduced) {
2704 MakeUnavailable();
2705 return true;
2706 }
2707 Introduced = *NewIntroduced;
2708 }
2709
2710 if (!Obsolete.empty()) {
2711 auto NewObsolete =
2712 Mapping->mapDeprecatedObsoletedAvailabilityVersion(Key: Obsolete);
2713 if (!NewObsolete) {
2714 MakeUnavailable();
2715 return true;
2716 }
2717 Obsolete = *NewObsolete;
2718 }
2719
2720 if (!Deprecated.empty()) {
2721 auto NewDeprecated =
2722 Mapping->mapDeprecatedObsoletedAvailabilityVersion(Key: Deprecated);
2723 Deprecated = NewDeprecated ? *NewDeprecated : VersionTuple();
2724 }
2725
2726 return true;
2727}
2728
2729static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2730 if (isa<UsingDecl, UnresolvedUsingTypenameDecl, UnresolvedUsingValueDecl>(
2731 Val: D)) {
2732 S.Diag(Loc: AL.getRange().getBegin(), DiagID: diag::warn_deprecated_ignored_on_using)
2733 << AL;
2734 return;
2735 }
2736
2737 if (!AL.checkExactlyNumArgs(S, Num: 1))
2738 return;
2739 IdentifierLoc *Platform = AL.getArgAsIdent(Arg: 0);
2740
2741 IdentifierInfo *II = Platform->getIdentifierInfo();
2742 StringRef PrettyName = AvailabilityAttr::getPrettyPlatformName(Platform: II->getName());
2743 if (PrettyName.empty())
2744 S.Diag(Loc: Platform->getLoc(), DiagID: diag::warn_availability_unknown_platform)
2745 << Platform->getIdentifierInfo();
2746
2747 auto *ND = dyn_cast<NamedDecl>(Val: D);
2748 if (!ND) // We warned about this already, so just return.
2749 return;
2750
2751 AvailabilityChange Introduced = AL.getAvailabilityIntroduced();
2752 AvailabilityChange Deprecated = AL.getAvailabilityDeprecated();
2753 AvailabilityChange Obsoleted = AL.getAvailabilityObsoleted();
2754
2755 const llvm::Triple::OSType PlatformOS = AvailabilityAttr::getOSType(
2756 Platform: AvailabilityAttr::canonicalizePlatformName(Platform: II->getName()));
2757
2758 auto reportAndUpdateIfInvalidOS = [&](auto &InputVersion) -> void {
2759 const bool IsInValidRange =
2760 llvm::Triple::isValidVersionForOS(OSKind: PlatformOS, Version: InputVersion);
2761 // Canonicalize availability versions.
2762 auto CanonicalVersion = llvm::Triple::getCanonicalVersionForOS(
2763 OSKind: PlatformOS, Version: InputVersion, IsInValidRange);
2764 if (!IsInValidRange) {
2765 S.Diag(Loc: Platform->getLoc(), DiagID: diag::warn_availability_invalid_os_version)
2766 << InputVersion.getAsString() << PrettyName;
2767 S.Diag(Loc: Platform->getLoc(),
2768 DiagID: diag::note_availability_invalid_os_version_adjusted)
2769 << CanonicalVersion.getAsString();
2770 }
2771 InputVersion = CanonicalVersion;
2772 };
2773
2774 if (PlatformOS != llvm::Triple::OSType::UnknownOS) {
2775 reportAndUpdateIfInvalidOS(Introduced.Version);
2776 reportAndUpdateIfInvalidOS(Deprecated.Version);
2777 reportAndUpdateIfInvalidOS(Obsoleted.Version);
2778 }
2779
2780 bool IsUnavailable = AL.getUnavailableLoc().isValid();
2781 bool IsStrict = AL.getStrictLoc().isValid();
2782 StringRef Str;
2783 if (const auto *SE = dyn_cast_if_present<StringLiteral>(Val: AL.getMessageExpr()))
2784 Str = SE->getString();
2785 StringRef Replacement;
2786 if (const auto *SE =
2787 dyn_cast_if_present<StringLiteral>(Val: AL.getReplacementExpr()))
2788 Replacement = SE->getString();
2789
2790 if (II->isStr(Str: "swift")) {
2791 if (Introduced.isValid() || Obsoleted.isValid() ||
2792 (!IsUnavailable && !Deprecated.isValid())) {
2793 S.Diag(Loc: AL.getLoc(),
2794 DiagID: diag::warn_availability_swift_unavailable_deprecated_only);
2795 return;
2796 }
2797 }
2798
2799 if (II->isStr(Str: "fuchsia")) {
2800 std::optional<unsigned> Min, Sub;
2801 if ((Min = Introduced.Version.getMinor()) ||
2802 (Sub = Introduced.Version.getSubminor())) {
2803 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_availability_fuchsia_unavailable_minor);
2804 return;
2805 }
2806 }
2807
2808 if (S.getLangOpts().HLSL && IsStrict)
2809 S.Diag(Loc: AL.getStrictLoc(), DiagID: diag::err_availability_unexpected_parameter)
2810 << "strict" << /* HLSL */ 0;
2811
2812 int PriorityModifier = AL.isPragmaClangAttribute()
2813 ? Sema::AP_PragmaClangAttribute
2814 : Sema::AP_Explicit;
2815
2816 const IdentifierLoc *EnvironmentLoc = AL.getEnvironment();
2817 IdentifierInfo *IIEnvironment = nullptr;
2818 if (EnvironmentLoc) {
2819 if (S.getLangOpts().HLSL) {
2820 IIEnvironment = EnvironmentLoc->getIdentifierInfo();
2821 if (AvailabilityAttr::getEnvironmentType(
2822 Environment: EnvironmentLoc->getIdentifierInfo()->getName()) ==
2823 llvm::Triple::EnvironmentType::UnknownEnvironment)
2824 S.Diag(Loc: EnvironmentLoc->getLoc(),
2825 DiagID: diag::warn_availability_unknown_environment)
2826 << EnvironmentLoc->getIdentifierInfo();
2827 } else {
2828 S.Diag(Loc: EnvironmentLoc->getLoc(),
2829 DiagID: diag::err_availability_unexpected_parameter)
2830 << "environment" << /* C/C++ */ 1;
2831 }
2832 }
2833
2834 // Handle anyAppleOS: preserve the original anyappleos attr on the decl and
2835 // store the inferred platform-specific attr as a field on it.
2836 if (II->getName() == "anyappleos") {
2837 // Validate anyAppleOS versions; reject versions older than 26.0.
2838 auto ValidateVersion = [&](const llvm::VersionTuple &Version,
2839 SourceLocation Loc) -> bool {
2840 if (AvailabilitySpec::validateAnyAppleOSVersion(Version))
2841 return true;
2842 S.Diag(Loc, DiagID: diag::err_availability_invalid_anyappleos_version)
2843 << Version.getAsString();
2844 return false;
2845 };
2846
2847 // Validate the versions; bail out if any are invalid.
2848 bool Valid = ValidateVersion(Introduced.Version, Introduced.KeywordLoc);
2849 Valid &= ValidateVersion(Deprecated.Version, Deprecated.KeywordLoc);
2850 Valid &= ValidateVersion(Obsoleted.Version, Obsoleted.KeywordLoc);
2851 if (!Valid)
2852 return;
2853
2854 llvm::Triple T = S.Context.getTargetInfo().getTriple();
2855
2856 // Only create implicit attributes for Darwin OSes.
2857 if (!T.isOSDarwin())
2858 return;
2859
2860 StringRef PlatformName;
2861
2862 // Determine the platform name based on the target triple.
2863 if (T.isMacOSX())
2864 PlatformName = "macos";
2865 else if (T.getOS() == llvm::Triple::IOS && T.isMacCatalystEnvironment())
2866 PlatformName = "maccatalyst";
2867 else // For iOS, tvOS, watchOS, visionOS, bridgeOS, etc.
2868 PlatformName = llvm::Triple::getOSTypeName(Kind: T.getOS());
2869
2870 IdentifierInfo *InferredPlatformII = &S.Context.Idents.get(Name: PlatformName);
2871
2872 // Call mergeAvailabilityAttr for the original anyappleos attr. Pass
2873 // InferredPlatformII so the dedup loop can detect a conflicting explicit
2874 // platform attr (in which case mergeAvailabilityAttr returns null and we
2875 // add neither attr).
2876 AvailabilityAttr *OrigAttr = S.mergeAndInferAvailabilityAttr(
2877 D: ND, CI: AL, Platform: II, /*Implicit=*/false, Introduced: Introduced.Version, Deprecated: Deprecated.Version,
2878 Obsoleted: Obsoleted.Version, IsUnavailable, Message: Str, IsStrict, Replacement,
2879 AMK: AvailabilityMergeKind::None, Priority: PriorityModifier, IIEnvironment,
2880 InferredPlatformII);
2881 if (!OrigAttr)
2882 return;
2883 D->addAttr(A: OrigAttr);
2884 return;
2885 }
2886
2887 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2888 D: ND, CI: AL, Platform: II, Implicit: false /*Implicit*/, Introduced: Introduced.Version, Deprecated: Deprecated.Version,
2889 Obsoleted: Obsoleted.Version, IsUnavailable, Message: Str, IsStrict, Replacement,
2890 AMK: AvailabilityMergeKind::None, Priority: PriorityModifier, Environment: IIEnvironment);
2891 if (NewAttr)
2892 D->addAttr(A: NewAttr);
2893
2894 if (S.Context.getTargetInfo().getTriple().getOS() == llvm::Triple::XROS) {
2895 IdentifierInfo *NewII = II;
2896 bool NewIsUnavailable = IsUnavailable;
2897 VersionTuple NewIntroduced = Introduced.Version;
2898 VersionTuple NewDeprecated = Deprecated.Version;
2899 VersionTuple NewObsoleted = Obsoleted.Version;
2900 if (shouldInferAvailabilityAttribute(AL, II&: NewII, IsUnavailable&: NewIsUnavailable,
2901 Introduced&: NewIntroduced, Deprecated&: NewDeprecated,
2902 Obsolete&: NewObsoleted, S)) {
2903 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2904 D: ND, CI: AL, Platform: NewII, Implicit: true /*Implicit*/, Introduced: NewIntroduced, Deprecated: NewDeprecated,
2905 Obsoleted: NewObsoleted, IsUnavailable: NewIsUnavailable, Message: Str, IsStrict, Replacement,
2906 AMK: AvailabilityMergeKind::None,
2907 Priority: PriorityModifier + Sema::AP_InferredFromOtherPlatform, Environment: IIEnvironment);
2908 if (NewAttr)
2909 D->addAttr(A: NewAttr);
2910 }
2911 }
2912
2913 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2914 // matches before the start of the watchOS platform.
2915 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2916 IdentifierInfo *NewII = nullptr;
2917 if (II->getName() == "ios")
2918 NewII = &S.Context.Idents.get(Name: "watchos");
2919 else if (II->getName() == "ios_app_extension")
2920 NewII = &S.Context.Idents.get(Name: "watchos_app_extension");
2921
2922 if (NewII) {
2923 const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking();
2924 const auto *IOSToWatchOSMapping =
2925 SDKInfo ? SDKInfo->getVersionMapping(
2926 Kind: DarwinSDKInfo::OSEnvPair::iOStoWatchOSPair())
2927 : nullptr;
2928
2929 auto adjustWatchOSVersion =
2930 [IOSToWatchOSMapping](VersionTuple Version) -> VersionTuple {
2931 if (Version.empty())
2932 return Version;
2933 auto MinimumWatchOSVersion = VersionTuple(2, 0);
2934
2935 if (IOSToWatchOSMapping) {
2936 if (auto MappedVersion = IOSToWatchOSMapping->map(
2937 Key: Version, MinimumValue: MinimumWatchOSVersion, MaximumValue: std::nullopt)) {
2938 return *MappedVersion;
2939 }
2940 }
2941
2942 auto Major = Version.getMajor();
2943 auto NewMajor = Major;
2944 if (Major < 9)
2945 NewMajor = 0;
2946 else if (Major < 12)
2947 NewMajor = Major - 7;
2948 if (NewMajor >= 2) {
2949 if (Version.getMinor()) {
2950 if (Version.getSubminor())
2951 return VersionTuple(NewMajor, *Version.getMinor(),
2952 *Version.getSubminor());
2953 else
2954 return VersionTuple(NewMajor, *Version.getMinor());
2955 }
2956 return VersionTuple(NewMajor);
2957 }
2958
2959 return MinimumWatchOSVersion;
2960 };
2961
2962 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2963 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2964 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2965
2966 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2967 D: ND, CI: AL, Platform: NewII, Implicit: true /*Implicit*/, Introduced: NewIntroduced, Deprecated: NewDeprecated,
2968 Obsoleted: NewObsoleted, IsUnavailable, Message: Str, IsStrict, Replacement,
2969 AMK: AvailabilityMergeKind::None,
2970 Priority: PriorityModifier + Sema::AP_InferredFromOtherPlatform, Environment: IIEnvironment);
2971 if (NewAttr)
2972 D->addAttr(A: NewAttr);
2973 }
2974 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2975 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2976 // matches before the start of the tvOS platform.
2977 IdentifierInfo *NewII = nullptr;
2978 if (II->getName() == "ios")
2979 NewII = &S.Context.Idents.get(Name: "tvos");
2980 else if (II->getName() == "ios_app_extension")
2981 NewII = &S.Context.Idents.get(Name: "tvos_app_extension");
2982
2983 if (NewII) {
2984 const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking();
2985 const auto *IOSToTvOSMapping =
2986 SDKInfo ? SDKInfo->getVersionMapping(
2987 Kind: DarwinSDKInfo::OSEnvPair::iOStoTvOSPair())
2988 : nullptr;
2989
2990 auto AdjustTvOSVersion =
2991 [IOSToTvOSMapping](VersionTuple Version) -> VersionTuple {
2992 if (Version.empty())
2993 return Version;
2994
2995 if (IOSToTvOSMapping) {
2996 if (auto MappedVersion = IOSToTvOSMapping->map(
2997 Key: Version, MinimumValue: VersionTuple(0, 0), MaximumValue: std::nullopt)) {
2998 return *MappedVersion;
2999 }
3000 }
3001 return Version;
3002 };
3003
3004 auto NewIntroduced = AdjustTvOSVersion(Introduced.Version);
3005 auto NewDeprecated = AdjustTvOSVersion(Deprecated.Version);
3006 auto NewObsoleted = AdjustTvOSVersion(Obsoleted.Version);
3007
3008 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
3009 D: ND, CI: AL, Platform: NewII, Implicit: true /*Implicit*/, Introduced: NewIntroduced, Deprecated: NewDeprecated,
3010 Obsoleted: NewObsoleted, IsUnavailable, Message: Str, IsStrict, Replacement,
3011 AMK: AvailabilityMergeKind::None,
3012 Priority: PriorityModifier + Sema::AP_InferredFromOtherPlatform, Environment: IIEnvironment);
3013 if (NewAttr)
3014 D->addAttr(A: NewAttr);
3015 }
3016 } else if (S.Context.getTargetInfo().getTriple().getOS() ==
3017 llvm::Triple::IOS &&
3018 S.Context.getTargetInfo().getTriple().isMacCatalystEnvironment()) {
3019 auto GetSDKInfo = [&]() {
3020 return S.getDarwinSDKInfoForAvailabilityChecking(Loc: AL.getRange().getBegin(),
3021 Platform: "macOS");
3022 };
3023
3024 // Transcribe "ios" to "maccatalyst" (and add a new attribute).
3025 IdentifierInfo *NewII = nullptr;
3026 if (II->getName() == "ios")
3027 NewII = &S.Context.Idents.get(Name: "maccatalyst");
3028 else if (II->getName() == "ios_app_extension")
3029 NewII = &S.Context.Idents.get(Name: "maccatalyst_app_extension");
3030 if (NewII) {
3031 auto MinMacCatalystVersion = [](const VersionTuple &V) {
3032 if (V.empty())
3033 return V;
3034 if (V.getMajor() < 13 ||
3035 (V.getMajor() == 13 && V.getMinor() && *V.getMinor() < 1))
3036 return VersionTuple(13, 1); // The min Mac Catalyst version is 13.1.
3037 return V;
3038 };
3039 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
3040 D: ND, CI: AL, Platform: NewII, Implicit: true /*Implicit*/,
3041 Introduced: MinMacCatalystVersion(Introduced.Version),
3042 Deprecated: MinMacCatalystVersion(Deprecated.Version),
3043 Obsoleted: MinMacCatalystVersion(Obsoleted.Version), IsUnavailable, Message: Str,
3044 IsStrict, Replacement, AMK: AvailabilityMergeKind::None,
3045 Priority: PriorityModifier + Sema::AP_InferredFromOtherPlatform, Environment: IIEnvironment);
3046 if (NewAttr)
3047 D->addAttr(A: NewAttr);
3048 } else if (II->getName() == "macos" && GetSDKInfo() &&
3049 (!Introduced.Version.empty() || !Deprecated.Version.empty() ||
3050 !Obsoleted.Version.empty())) {
3051 if (const auto *MacOStoMacCatalystMapping =
3052 GetSDKInfo()->getVersionMapping(
3053 Kind: DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair())) {
3054 // Infer Mac Catalyst availability from the macOS availability attribute
3055 // if it has versioned availability. Don't infer 'unavailable'. This
3056 // inferred availability has lower priority than the other availability
3057 // attributes that are inferred from 'ios'.
3058 NewII = &S.Context.Idents.get(Name: "maccatalyst");
3059 auto RemapMacOSVersion =
3060 [&](const VersionTuple &V) -> std::optional<VersionTuple> {
3061 if (V.empty())
3062 return std::nullopt;
3063 // API_TO_BE_DEPRECATED is 100000.
3064 if (V.getMajor() == 100000)
3065 return VersionTuple(100000);
3066 // The minimum iosmac version is 13.1
3067 return MacOStoMacCatalystMapping->map(Key: V, MinimumValue: VersionTuple(13, 1),
3068 MaximumValue: std::nullopt);
3069 };
3070 std::optional<VersionTuple> NewIntroduced =
3071 RemapMacOSVersion(Introduced.Version),
3072 NewDeprecated =
3073 RemapMacOSVersion(Deprecated.Version),
3074 NewObsoleted =
3075 RemapMacOSVersion(Obsoleted.Version);
3076 if (NewIntroduced || NewDeprecated || NewObsoleted) {
3077 auto VersionOrEmptyVersion =
3078 [](const std::optional<VersionTuple> &V) -> VersionTuple {
3079 return V ? *V : VersionTuple();
3080 };
3081 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
3082 D: ND, CI: AL, Platform: NewII, Implicit: true /*Implicit*/,
3083 Introduced: VersionOrEmptyVersion(NewIntroduced),
3084 Deprecated: VersionOrEmptyVersion(NewDeprecated),
3085 Obsoleted: VersionOrEmptyVersion(NewObsoleted), /*IsUnavailable=*/false, Message: Str,
3086 IsStrict, Replacement, AMK: AvailabilityMergeKind::None,
3087 Priority: PriorityModifier + Sema::AP_InferredFromOtherPlatform +
3088 Sema::AP_InferredFromOtherPlatform,
3089 Environment: IIEnvironment);
3090 if (NewAttr)
3091 D->addAttr(A: NewAttr);
3092 }
3093 }
3094 }
3095 }
3096}
3097
3098static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
3099 const ParsedAttr &AL) {
3100 if (!AL.checkAtLeastNumArgs(S, Num: 1) || !AL.checkAtMostNumArgs(S, Num: 4))
3101 return;
3102
3103 StringRef Language;
3104 if (const auto *SE = dyn_cast_if_present<StringLiteral>(Val: AL.getArgAsExpr(Arg: 0)))
3105 Language = SE->getString();
3106 StringRef DefinedIn;
3107 if (const auto *SE = dyn_cast_if_present<StringLiteral>(Val: AL.getArgAsExpr(Arg: 1)))
3108 DefinedIn = SE->getString();
3109 bool IsGeneratedDeclaration = AL.getArgAsIdent(Arg: 2) != nullptr;
3110 StringRef USR;
3111 if (const auto *SE = dyn_cast_if_present<StringLiteral>(Val: AL.getArgAsExpr(Arg: 3)))
3112 USR = SE->getString();
3113
3114 D->addAttr(A: ::new (S.Context) ExternalSourceSymbolAttr(
3115 S.Context, AL, Language, DefinedIn, IsGeneratedDeclaration, USR));
3116}
3117
3118void Sema::mergeVisibilityType(Decl *D, SourceLocation Loc,
3119 VisibilityAttr::VisibilityType Value) {
3120 if (VisibilityAttr *Attr = D->getAttr<VisibilityAttr>()) {
3121 if (Attr->getVisibility() != Value)
3122 Diag(Loc, DiagID: diag::err_mismatched_visibility);
3123 } else
3124 D->addAttr(A: VisibilityAttr::CreateImplicit(Ctx&: Context, Visibility: Value));
3125}
3126
3127template <class T>
3128static T *mergeVisibilityAttr(Sema &S, Decl *D, const AttributeCommonInfo &CI,
3129 typename T::VisibilityType value) {
3130 T *existingAttr = D->getAttr<T>();
3131 if (existingAttr) {
3132 typename T::VisibilityType existingValue = existingAttr->getVisibility();
3133 if (existingValue == value)
3134 return nullptr;
3135 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
3136 S.Diag(Loc: CI.getLoc(), DiagID: diag::note_previous_attribute);
3137 D->dropAttr<T>();
3138 }
3139 return ::new (S.Context) T(S.Context, CI, value);
3140}
3141
3142VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D,
3143 const AttributeCommonInfo &CI,
3144 VisibilityAttr::VisibilityType Vis) {
3145 return ::mergeVisibilityAttr<VisibilityAttr>(S&: *this, D, CI, value: Vis);
3146}
3147
3148TypeVisibilityAttr *
3149Sema::mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3150 TypeVisibilityAttr::VisibilityType Vis) {
3151 return ::mergeVisibilityAttr<TypeVisibilityAttr>(S&: *this, D, CI, value: Vis);
3152}
3153
3154static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
3155 bool isTypeVisibility) {
3156 // Visibility attributes don't mean anything on a typedef.
3157 if (isa<TypedefNameDecl>(Val: D)) {
3158 S.Diag(Loc: AL.getRange().getBegin(), DiagID: diag::warn_attribute_ignored) << AL;
3159 return;
3160 }
3161
3162 // 'type_visibility' can only go on a type or namespace.
3163 if (isTypeVisibility && !(isa<TagDecl>(Val: D) || isa<ObjCInterfaceDecl>(Val: D) ||
3164 isa<NamespaceDecl>(Val: D))) {
3165 S.Diag(Loc: AL.getRange().getBegin(), DiagID: diag::err_attribute_wrong_decl_type)
3166 << AL << AL.isRegularKeywordAttribute() << ExpectedTypeOrNamespace;
3167 return;
3168 }
3169
3170 // Check that the argument is a string literal.
3171 StringRef TypeStr;
3172 SourceLocation LiteralLoc;
3173 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: TypeStr, ArgLocation: &LiteralLoc))
3174 return;
3175
3176 VisibilityAttr::VisibilityType type;
3177 if (!VisibilityAttr::ConvertStrToVisibilityType(Val: TypeStr, Out&: type)) {
3178 S.Diag(Loc: LiteralLoc, DiagID: diag::warn_attribute_type_not_supported) << AL
3179 << TypeStr;
3180 return;
3181 }
3182
3183 // Complain about attempts to use protected visibility on targets
3184 // (like Darwin) that don't support it.
3185 if (type == VisibilityAttr::Protected &&
3186 !S.Context.getTargetInfo().hasProtectedVisibility()) {
3187 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_protected_visibility);
3188 type = VisibilityAttr::Default;
3189 }
3190
3191 Attr *newAttr;
3192 if (isTypeVisibility) {
3193 newAttr = S.mergeTypeVisibilityAttr(
3194 D, CI: AL, Vis: (TypeVisibilityAttr::VisibilityType)type);
3195 } else {
3196 newAttr = S.mergeVisibilityAttr(D, CI: AL, Vis: type);
3197 }
3198 if (newAttr)
3199 D->addAttr(A: newAttr);
3200}
3201
3202static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3203 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
3204 if (AL.getNumArgs() > 0) {
3205 Expr *E = AL.getArgAsExpr(Arg: 0);
3206 std::optional<llvm::APSInt> Idx = llvm::APSInt(32);
3207 if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(Ctx: S.Context))) {
3208 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_n_type)
3209 << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
3210 return;
3211 }
3212
3213 if (Idx->isSigned() && Idx->isNegative()) {
3214 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_sentinel_less_than_zero)
3215 << E->getSourceRange();
3216 return;
3217 }
3218
3219 sentinel = Idx->getZExtValue();
3220 }
3221
3222 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
3223 if (AL.getNumArgs() > 1) {
3224 Expr *E = AL.getArgAsExpr(Arg: 1);
3225 std::optional<llvm::APSInt> Idx = llvm::APSInt(32);
3226 if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(Ctx: S.Context))) {
3227 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_n_type)
3228 << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
3229 return;
3230 }
3231 nullPos = Idx->getZExtValue();
3232
3233 if ((Idx->isSigned() && Idx->isNegative()) || nullPos > 1) {
3234 // FIXME: This error message could be improved, it would be nice
3235 // to say what the bounds actually are.
3236 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_sentinel_not_zero_or_one)
3237 << E->getSourceRange();
3238 return;
3239 }
3240 }
3241
3242 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
3243 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
3244 if (isa<FunctionNoProtoType>(Val: FT)) {
3245 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_sentinel_named_arguments);
3246 return;
3247 }
3248
3249 if (!cast<FunctionProtoType>(Val: FT)->isVariadic()) {
3250 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_sentinel_not_variadic) << 0;
3251 return;
3252 }
3253 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D)) {
3254 if (!MD->isVariadic()) {
3255 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_sentinel_not_variadic) << 0;
3256 return;
3257 }
3258 } else if (const auto *BD = dyn_cast<BlockDecl>(Val: D)) {
3259 if (!BD->isVariadic()) {
3260 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_sentinel_not_variadic) << 1;
3261 return;
3262 }
3263 } else if (const auto *V = dyn_cast<VarDecl>(Val: D)) {
3264 QualType Ty = V->getType();
3265 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
3266 const FunctionType *FT = Ty->isFunctionPointerType()
3267 ? D->getFunctionType()
3268 : Ty->castAs<BlockPointerType>()
3269 ->getPointeeType()
3270 ->castAs<FunctionType>();
3271 if (isa<FunctionNoProtoType>(Val: FT)) {
3272 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_sentinel_named_arguments);
3273 return;
3274 }
3275 if (!cast<FunctionProtoType>(Val: FT)->isVariadic()) {
3276 int m = Ty->isFunctionPointerType() ? 0 : 1;
3277 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_sentinel_not_variadic) << m;
3278 return;
3279 }
3280 } else {
3281 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_wrong_decl_type)
3282 << AL << AL.isRegularKeywordAttribute()
3283 << ExpectedFunctionMethodOrBlock;
3284 return;
3285 }
3286 } else {
3287 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_wrong_decl_type)
3288 << AL << AL.isRegularKeywordAttribute()
3289 << ExpectedFunctionMethodOrBlock;
3290 return;
3291 }
3292 D->addAttr(A: ::new (S.Context) SentinelAttr(S.Context, AL, sentinel, nullPos));
3293}
3294
3295static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
3296 if (D->getFunctionType() &&
3297 D->getFunctionType()->getReturnType()->isVoidType() &&
3298 !isa<CXXConstructorDecl>(Val: D)) {
3299 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_void_function_method) << AL << 0;
3300 return;
3301 }
3302 if (const auto *MD = dyn_cast<ObjCMethodDecl>(Val: D))
3303 if (MD->getReturnType()->isVoidType()) {
3304 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_void_function_method) << AL << 1;
3305 return;
3306 }
3307
3308 StringRef Str;
3309 if (AL.isStandardAttributeSyntax()) {
3310 // If this is spelled [[clang::warn_unused_result]] we look for an optional
3311 // string literal. This is not gated behind any specific version of the
3312 // standard.
3313 if (AL.isClangScope()) {
3314 if (AL.getNumArgs() == 1 &&
3315 !S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str, ArgLocation: nullptr))
3316 return;
3317 } else if (!AL.getScopeName()) {
3318 // The standard attribute cannot be applied to variable declarations such
3319 // as a function pointer.
3320 if (isa<VarDecl>(Val: D))
3321 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_wrong_decl_type)
3322 << AL << AL.isRegularKeywordAttribute()
3323 << ExpectedFunctionOrClassOrEnum;
3324
3325 // If this is spelled as the standard C++17 attribute, but not in C++17,
3326 // warn about using it as an extension. If there are attribute arguments,
3327 // then claim it's a C++20 extension instead. C23 supports this attribute
3328 // with the message; no extension warning is needed there beyond the one
3329 // already issued for accepting attributes in older modes.
3330 const LangOptions &LO = S.getLangOpts();
3331 if (AL.getNumArgs() == 1) {
3332 if (LO.CPlusPlus && !LO.CPlusPlus20)
3333 S.Diag(Loc: AL.getLoc(), DiagID: diag::ext_cxx20_attr) << AL;
3334
3335 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str, ArgLocation: nullptr))
3336 return;
3337 } else if (LO.CPlusPlus && !LO.CPlusPlus17)
3338 S.Diag(Loc: AL.getLoc(), DiagID: diag::ext_cxx17_attr) << AL;
3339 }
3340 }
3341
3342 if ((!AL.isGNUAttribute() &&
3343 !(AL.isStandardAttributeSyntax() && AL.isClangScope())) &&
3344 isa<TypedefNameDecl>(Val: D)) {
3345 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_unused_result_typedef_unsupported_spelling)
3346 << AL.isGNUScope();
3347 return;
3348 }
3349
3350 D->addAttr(A: ::new (S.Context) WarnUnusedResultAttr(S.Context, AL, Str));
3351}
3352
3353static 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(IsDefinition&: isDef)) {
3357 if (isDef)
3358 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_invalid_on_definition)
3359 << "weak_import";
3360 else if (isa<ObjCPropertyDecl>(Val: D) || isa<ObjCMethodDecl>(Val: D) ||
3361 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
3362 (isa<ObjCInterfaceDecl>(Val: D) || isa<EnumDecl>(Val: D)))) {
3363 // Nothing to warn about here.
3364 } else
3365 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_wrong_decl_type)
3366 << AL << AL.isRegularKeywordAttribute() << ExpectedVariableOrFunction;
3367
3368 return;
3369 }
3370
3371 D->addAttr(A: ::new (S.Context) WeakImportAttr(S.Context, AL));
3372}
3373
3374// Checks whether an argument of launch_bounds-like attribute is
3375// acceptable, performs implicit conversion to Rvalue, and returns
3376// non-nullptr Expr result on success. Otherwise, it returns nullptr
3377// and may output an error.
3378template <class Attribute>
3379static Expr *makeAttributeArgExpr(Sema &S, Expr *E, const Attribute &Attr,
3380 const unsigned Idx) {
3381 if (S.DiagnoseUnexpandedParameterPack(E))
3382 return nullptr;
3383
3384 // Accept template arguments for now as they depend on something else.
3385 // We'll get to check them when they eventually get instantiated.
3386 if (E->isValueDependent())
3387 return E;
3388
3389 std::optional<llvm::APSInt> I = llvm::APSInt(64);
3390 if (!(I = E->getIntegerConstantExpr(Ctx: S.Context))) {
3391 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_attribute_argument_n_type)
3392 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
3393 return nullptr;
3394 }
3395 // Make sure we can fit it in 32 bits.
3396 if (!I->isIntN(N: 32)) {
3397 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_ice_too_large)
3398 << toString(I: *I, Radix: 10, Signed: false) << 32 << /* Unsigned */ 1;
3399 return nullptr;
3400 }
3401 if (*I < 0)
3402 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_attribute_requires_positive_integer)
3403 << &Attr << /*non-negative*/ 1 << E->getSourceRange();
3404
3405 // We may need to perform implicit conversion of the argument.
3406 InitializedEntity Entity = InitializedEntity::InitializeParameter(
3407 Context&: S.Context, Type: S.Context.getConstType(T: S.Context.IntTy), /*consume*/ Consumed: false);
3408 ExprResult ValArg = S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: E);
3409 assert(!ValArg.isInvalid() &&
3410 "Unexpected PerformCopyInitialization() failure.");
3411
3412 return ValArg.getAs<Expr>();
3413}
3414
3415// Handles reqd_work_group_size and work_group_size_hint.
3416template <typename WorkGroupAttr>
3417static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
3418 Expr *WGSize[3];
3419 for (unsigned i = 0; i < 3; ++i) {
3420 if (Expr *E = makeAttributeArgExpr(S, E: AL.getArgAsExpr(Arg: i), Attr: AL, Idx: i))
3421 WGSize[i] = E;
3422 else
3423 return;
3424 }
3425
3426 auto IsZero = [&](Expr *E) {
3427 if (E->isValueDependent())
3428 return false;
3429 std::optional<llvm::APSInt> I = E->getIntegerConstantExpr(Ctx: S.Context);
3430 assert(I && "Non-integer constant expr");
3431 return I->isZero();
3432 };
3433
3434 if (!llvm::all_of(WGSize, IsZero)) {
3435 for (unsigned i = 0; i < 3; ++i) {
3436 const Expr *E = AL.getArgAsExpr(Arg: i);
3437 if (IsZero(WGSize[i])) {
3438 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_is_zero)
3439 << AL << E->getSourceRange();
3440 return;
3441 }
3442 }
3443 }
3444
3445 auto Equal = [&](Expr *LHS, Expr *RHS) {
3446 if (LHS->isValueDependent() || RHS->isValueDependent())
3447 return true;
3448 std::optional<llvm::APSInt> L = LHS->getIntegerConstantExpr(Ctx: S.Context);
3449 assert(L && "Non-integer constant expr");
3450 std::optional<llvm::APSInt> R = RHS->getIntegerConstantExpr(Ctx: S.Context);
3451 assert(L && "Non-integer constant expr");
3452 return L == R;
3453 };
3454
3455 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
3456 if (Existing &&
3457 !llvm::equal(std::initializer_list<Expr *>{Existing->getXDim(),
3458 Existing->getYDim(),
3459 Existing->getZDim()},
3460 WGSize, Equal))
3461 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_duplicate_attribute) << AL;
3462
3463 D->addAttr(A: ::new (S.Context)
3464 WorkGroupAttr(S.Context, AL, WGSize[0], WGSize[1], WGSize[2]));
3465}
3466
3467static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
3468 if (!AL.hasParsedType()) {
3469 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments) << AL << 1;
3470 return;
3471 }
3472
3473 TypeSourceInfo *ParmTSI = nullptr;
3474 QualType ParmType = S.GetTypeFromParser(Ty: AL.getTypeArg(), TInfo: &ParmTSI);
3475 assert(ParmTSI && "no type source info for attribute argument");
3476
3477 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
3478 (ParmType->isBooleanType() ||
3479 !ParmType->isIntegralType(Ctx: S.getASTContext()))) {
3480 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_invalid_argument) << 2 << AL;
3481 return;
3482 }
3483
3484 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
3485 if (!S.Context.hasSameType(T1: A->getTypeHint(), T2: ParmType)) {
3486 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_duplicate_attribute) << AL;
3487 return;
3488 }
3489 }
3490
3491 D->addAttr(A: ::new (S.Context) VecTypeHintAttr(S.Context, AL, ParmTSI));
3492}
3493
3494SectionAttr *Sema::mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3495 StringRef Name) {
3496 // Explicit or partial specializations do not inherit
3497 // the section attribute from the primary template.
3498 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
3499 if (CI.getAttributeSpellingListIndex() == SectionAttr::Declspec_allocate &&
3500 FD->isFunctionTemplateSpecialization())
3501 return nullptr;
3502 }
3503 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
3504 if (ExistingAttr->getName() == Name)
3505 return nullptr;
3506 Diag(Loc: ExistingAttr->getLocation(), DiagID: diag::warn_mismatched_section)
3507 << 1 /*section*/;
3508 Diag(Loc: CI.getLoc(), DiagID: diag::note_previous_attribute);
3509 return nullptr;
3510 }
3511 return ::new (Context) SectionAttr(Context, CI, Name);
3512}
3513
3514llvm::Error Sema::isValidSectionSpecifier(StringRef SecName) {
3515 if (!Context.getTargetInfo().getTriple().isOSDarwin())
3516 return llvm::Error::success();
3517
3518 // Let MCSectionMachO validate this.
3519 StringRef Segment, Section;
3520 unsigned TAA, StubSize;
3521 bool HasTAA;
3522 return llvm::MCSectionMachO::ParseSectionSpecifier(Spec: SecName, Segment, Section,
3523 TAA, TAAParsed&: HasTAA, StubSize);
3524}
3525
3526bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
3527 if (llvm::Error E = isValidSectionSpecifier(SecName)) {
3528 Diag(Loc: LiteralLoc, DiagID: diag::err_attribute_section_invalid_for_target)
3529 << toString(E: std::move(E)) << 1 /*'section'*/;
3530 return false;
3531 }
3532 return true;
3533}
3534
3535static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3536 // Make sure that there is a string literal as the sections's single
3537 // argument.
3538 StringRef Str;
3539 SourceLocation LiteralLoc;
3540 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str, ArgLocation: &LiteralLoc))
3541 return;
3542
3543 if (!S.checkSectionName(LiteralLoc, SecName: Str))
3544 return;
3545
3546 SectionAttr *NewAttr = S.mergeSectionAttr(D, CI: AL, Name: Str);
3547 if (NewAttr) {
3548 D->addAttr(A: NewAttr);
3549 if (isa<FunctionDecl, FunctionTemplateDecl, ObjCMethodDecl,
3550 ObjCPropertyDecl>(Val: D))
3551 S.UnifySection(SectionName: NewAttr->getName(),
3552 SectionFlags: ASTContext::PSF_Execute | ASTContext::PSF_Read,
3553 TheDecl: cast<NamedDecl>(Val: D));
3554 }
3555}
3556
3557static bool isValidCodeModelAttr(llvm::Triple &Triple, StringRef Str) {
3558 if (Triple.isLoongArch()) {
3559 return Str == "normal" || Str == "medium" || Str == "extreme";
3560 } else {
3561 assert(Triple.getArch() == llvm::Triple::x86_64 &&
3562 "only loongarch/x86-64 supported");
3563 return Str == "small" || Str == "large";
3564 }
3565}
3566
3567static void handleCodeModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3568 StringRef Str;
3569 SourceLocation LiteralLoc;
3570 auto IsTripleSupported = [](llvm::Triple &Triple) {
3571 return Triple.getArch() == llvm::Triple::ArchType::x86_64 ||
3572 Triple.isLoongArch();
3573 };
3574
3575 // Check that it is a string.
3576 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str, ArgLocation: &LiteralLoc))
3577 return;
3578
3579 SmallVector<llvm::Triple, 2> Triples = {
3580 S.Context.getTargetInfo().getTriple()};
3581 if (auto *aux = S.Context.getAuxTargetInfo()) {
3582 Triples.push_back(Elt: aux->getTriple());
3583 } else if (S.Context.getTargetInfo().getTriple().isNVPTX() ||
3584 S.Context.getTargetInfo().getTriple().isAMDGPU() ||
3585 S.Context.getTargetInfo().getTriple().isSPIRV()) {
3586 // Ignore the attribute for pure GPU device compiles since it only applies
3587 // to host globals.
3588 return;
3589 }
3590
3591 auto SupportedTripleIt = llvm::find_if(Range&: Triples, P: IsTripleSupported);
3592 if (SupportedTripleIt == Triples.end()) {
3593 S.Diag(Loc: LiteralLoc, DiagID: diag::warn_unknown_attribute_ignored) << AL;
3594 return;
3595 }
3596
3597 llvm::CodeModel::Model CM;
3598 if (!CodeModelAttr::ConvertStrToModel(Val: Str, Out&: CM) ||
3599 !isValidCodeModelAttr(Triple&: *SupportedTripleIt, Str)) {
3600 S.Diag(Loc: LiteralLoc, DiagID: diag::err_attr_codemodel_arg) << Str;
3601 return;
3602 }
3603
3604 D->addAttr(A: ::new (S.Context) CodeModelAttr(S.Context, AL, CM));
3605}
3606
3607// This is used for `__declspec(code_seg("segname"))` on a decl.
3608// `#pragma code_seg("segname")` uses checkSectionName() instead.
3609static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc,
3610 StringRef CodeSegName) {
3611 if (llvm::Error E = S.isValidSectionSpecifier(SecName: CodeSegName)) {
3612 S.Diag(Loc: LiteralLoc, DiagID: diag::err_attribute_section_invalid_for_target)
3613 << toString(E: std::move(E)) << 0 /*'code-seg'*/;
3614 return false;
3615 }
3616
3617 return true;
3618}
3619
3620CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3621 StringRef Name) {
3622 // Explicit or partial specializations do not inherit
3623 // the code_seg attribute from the primary template.
3624 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
3625 if (FD->isFunctionTemplateSpecialization())
3626 return nullptr;
3627 }
3628 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3629 if (ExistingAttr->getName() == Name)
3630 return nullptr;
3631 Diag(Loc: ExistingAttr->getLocation(), DiagID: diag::warn_mismatched_section)
3632 << 0 /*codeseg*/;
3633 Diag(Loc: CI.getLoc(), DiagID: diag::note_previous_attribute);
3634 return nullptr;
3635 }
3636 return ::new (Context) CodeSegAttr(Context, CI, Name);
3637}
3638
3639static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3640 StringRef Str;
3641 SourceLocation LiteralLoc;
3642 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str, ArgLocation: &LiteralLoc))
3643 return;
3644 if (!checkCodeSegName(S, LiteralLoc, CodeSegName: Str))
3645 return;
3646 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3647 if (!ExistingAttr->isImplicit()) {
3648 S.Diag(Loc: AL.getLoc(),
3649 DiagID: ExistingAttr->getName() == Str
3650 ? diag::warn_duplicate_codeseg_attribute
3651 : diag::err_conflicting_codeseg_attribute);
3652 return;
3653 }
3654 D->dropAttr<CodeSegAttr>();
3655 }
3656 if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, CI: AL, Name: Str))
3657 D->addAttr(A: CSA);
3658}
3659
3660bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
3661 using namespace DiagAttrParams;
3662
3663 if (AttrStr.contains(Other: "fpmath="))
3664 return Diag(Loc: LiteralLoc, DiagID: diag::warn_unsupported_target_attribute)
3665 << Unsupported << None << "fpmath=" << Target;
3666
3667 // Diagnose use of tune if target doesn't support it.
3668 if (!Context.getTargetInfo().supportsTargetAttributeTune() &&
3669 AttrStr.contains(Other: "tune="))
3670 return Diag(Loc: LiteralLoc, DiagID: diag::warn_unsupported_target_attribute)
3671 << Unsupported << None << "tune=" << Target;
3672
3673 ParsedTargetAttr ParsedAttrs =
3674 Context.getTargetInfo().parseTargetAttr(Str: AttrStr);
3675
3676 if (!ParsedAttrs.CPU.empty() &&
3677 !Context.getTargetInfo().isValidCPUName(Name: ParsedAttrs.CPU))
3678 return Diag(Loc: LiteralLoc, DiagID: diag::warn_unsupported_target_attribute)
3679 << Unknown << CPU << ParsedAttrs.CPU << Target;
3680
3681 if (!ParsedAttrs.Tune.empty() &&
3682 !Context.getTargetInfo().isValidCPUName(Name: ParsedAttrs.Tune))
3683 return Diag(Loc: LiteralLoc, DiagID: diag::warn_unsupported_target_attribute)
3684 << Unknown << Tune << ParsedAttrs.Tune << Target;
3685
3686 if (Context.getTargetInfo().getTriple().isRISCV()) {
3687 if (ParsedAttrs.Duplicate != "")
3688 return Diag(Loc: LiteralLoc, DiagID: diag::err_duplicate_target_attribute)
3689 << Duplicate << None << ParsedAttrs.Duplicate << Target;
3690 for (StringRef CurFeature : ParsedAttrs.Features) {
3691 if (!CurFeature.starts_with(Prefix: '+') && !CurFeature.starts_with(Prefix: '-'))
3692 return Diag(Loc: LiteralLoc, DiagID: diag::warn_unsupported_target_attribute)
3693 << Unsupported << None << AttrStr << Target;
3694 }
3695 }
3696
3697 if (Context.getTargetInfo().getTriple().isLoongArch()) {
3698 for (StringRef CurFeature : ParsedAttrs.Features) {
3699 if (CurFeature.starts_with(Prefix: "!arch=")) {
3700 StringRef ArchValue = CurFeature.split(Separator: "=").second.trim();
3701 return Diag(Loc: LiteralLoc, DiagID: diag::err_attribute_unsupported)
3702 << "target(arch=..)" << ArchValue;
3703 }
3704 }
3705 }
3706
3707 if (ParsedAttrs.Duplicate != "")
3708 return Diag(Loc: LiteralLoc, DiagID: diag::warn_unsupported_target_attribute)
3709 << Duplicate << None << ParsedAttrs.Duplicate << Target;
3710
3711 for (const auto &Feature : ParsedAttrs.Features) {
3712 auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3713 if (!Context.getTargetInfo().isValidFeatureName(Feature: CurFeature))
3714 return Diag(Loc: LiteralLoc, DiagID: diag::warn_unsupported_target_attribute)
3715 << Unsupported << None << CurFeature << Target;
3716 }
3717
3718 if (ParsedAttrs.BranchProtection.empty()) {
3719 if (!ParsedAttrs.SignReturnAddrHardening.empty())
3720 return Diag(Loc: LiteralLoc,
3721 DiagID: diag::warn_attribute_harden_pac_ret_requires_pac_ret);
3722 return false;
3723 }
3724
3725 TargetInfo::BranchProtectionInfo BPI{};
3726 StringRef DiagMsg;
3727
3728 if (!Context.getTargetInfo().validateBranchProtection(
3729 Attr: ParsedAttrs, BPI, LO: Context.getLangOpts(), Err&: DiagMsg)) {
3730 if (DiagMsg.empty())
3731 return Diag(Loc: LiteralLoc, DiagID: diag::warn_unsupported_target_attribute)
3732 << Unsupported << None << "branch-protection" << Target;
3733 return Diag(Loc: LiteralLoc, DiagID: diag::err_invalid_branch_protection_spec)
3734 << DiagMsg;
3735 }
3736 if (!DiagMsg.empty())
3737 Diag(Loc: LiteralLoc, DiagID: diag::warn_unsupported_branch_protection_spec) << DiagMsg;
3738
3739 if (!ParsedAttrs.SignReturnAddrHardening.empty()) {
3740 auto SignReturnAddrHardenOpt =
3741 Context.getTargetInfo().parseSignReturnAddressHardening(
3742 Spec: ParsedAttrs.SignReturnAddrHardening);
3743 if (!SignReturnAddrHardenOpt)
3744 return Diag(Loc: LiteralLoc, DiagID: diag::err_invalid_harden_pac_ret_spec)
3745 << ParsedAttrs.SignReturnAddrHardening;
3746
3747 if (BPI.SignReturnAddr == LangOptions::SignReturnAddressScopeKind::None)
3748 return Diag(Loc: LiteralLoc,
3749 DiagID: diag::warn_attribute_harden_pac_ret_requires_pac_ret);
3750 }
3751
3752 return false;
3753}
3754
3755static void handleTargetVersionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3756 StringRef Param;
3757 SourceLocation Loc;
3758 SmallString<64> NewParam;
3759 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: Param, ArgLocation: &Loc))
3760 return;
3761
3762 if (S.Context.getTargetInfo().getTriple().isAArch64()) {
3763 if (S.ARM().checkTargetVersionAttr(Param, Loc, NewParam))
3764 return;
3765 } else if (S.Context.getTargetInfo().getTriple().isRISCV()) {
3766 if (S.RISCV().checkTargetVersionAttr(Param, Loc, NewParam))
3767 return;
3768 }
3769
3770 TargetVersionAttr *NewAttr =
3771 ::new (S.Context) TargetVersionAttr(S.Context, AL, NewParam);
3772 D->addAttr(A: NewAttr);
3773}
3774
3775static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3776 StringRef Str;
3777 SourceLocation LiteralLoc;
3778 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str, ArgLocation: &LiteralLoc) ||
3779 S.checkTargetAttr(LiteralLoc, AttrStr: Str))
3780 return;
3781
3782 TargetAttr *NewAttr = ::new (S.Context) TargetAttr(S.Context, AL, Str);
3783 D->addAttr(A: NewAttr);
3784}
3785
3786static void handleTargetClonesAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3787 // Ensure we don't combine these with themselves, since that causes some
3788 // confusing behavior.
3789 if (const auto *Other = D->getAttr<TargetClonesAttr>()) {
3790 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_disallowed_duplicate_attribute) << AL;
3791 S.Diag(Loc: Other->getLocation(), DiagID: diag::note_conflicting_attribute);
3792 return;
3793 }
3794 if (checkAttrMutualExclusion<TargetClonesAttr>(S, D, AL))
3795 return;
3796
3797 // FIXME: We could probably figure out how to get this to work for lambdas
3798 // someday.
3799 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
3800 if (MD->getParent()->isLambda()) {
3801 S.Diag(Loc: D->getLocation(), DiagID: diag::err_multiversion_doesnt_support)
3802 << static_cast<unsigned>(MultiVersionKind::TargetClones)
3803 << /*Lambda*/ 9;
3804 return;
3805 }
3806 }
3807
3808 SmallVector<StringRef, 2> Params;
3809 SmallVector<SourceLocation, 2> Locations;
3810 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
3811 StringRef Param;
3812 SourceLocation Loc;
3813 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: I, Str&: Param, ArgLocation: &Loc))
3814 return;
3815 Params.push_back(Elt: Param);
3816 Locations.push_back(Elt: Loc);
3817 }
3818
3819 SmallVector<SmallString<64>, 2> NewParams;
3820 if (S.Context.getTargetInfo().getTriple().isAArch64()) {
3821 if (S.ARM().checkTargetClonesAttr(Params, Locs&: Locations, NewParams))
3822 return;
3823 } else if (S.Context.getTargetInfo().getTriple().isRISCV()) {
3824 if (S.RISCV().checkTargetClonesAttr(Params, Locs: Locations, NewParams,
3825 AttrLoc: AL.getLoc()))
3826 return;
3827 } else if (S.Context.getTargetInfo().getTriple().isX86()) {
3828 if (S.X86().checkTargetClonesAttr(Params, Locs: Locations, NewParams,
3829 AttrLoc: AL.getLoc()))
3830 return;
3831 } else if (S.Context.getTargetInfo().getTriple().isOSAIX()) {
3832 if (S.PPC().checkTargetClonesAttr(Params, Locs: Locations, NewParams,
3833 AttrLoc: AL.getLoc()))
3834 return;
3835 }
3836 Params.clear();
3837 for (auto &SmallStr : NewParams)
3838 Params.push_back(Elt: SmallStr.str());
3839
3840 TargetClonesAttr *NewAttr = ::new (S.Context)
3841 TargetClonesAttr(S.Context, AL, Params.data(), Params.size());
3842 D->addAttr(A: NewAttr);
3843}
3844
3845static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3846 Expr *E = AL.getArgAsExpr(Arg: 0);
3847 uint32_t VecWidth;
3848 if (!S.checkUInt32Argument(AI: AL, Expr: E, Val&: VecWidth)) {
3849 AL.setInvalid();
3850 return;
3851 }
3852
3853 MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
3854 if (Existing && Existing->getVectorWidth() != VecWidth) {
3855 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_duplicate_attribute) << AL;
3856 return;
3857 }
3858
3859 D->addAttr(A: ::new (S.Context) MinVectorWidthAttr(S.Context, AL, VecWidth));
3860}
3861
3862static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3863 Expr *E = AL.getArgAsExpr(Arg: 0);
3864 SourceLocation Loc = E->getExprLoc();
3865 FunctionDecl *FD = nullptr;
3866 DeclarationNameInfo NI;
3867
3868 // gcc only allows for simple identifiers. Since we support more than gcc, we
3869 // will warn the user.
3870 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
3871 if (DRE->hasQualifier())
3872 S.Diag(Loc, DiagID: diag::warn_cleanup_ext);
3873 FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
3874 NI = DRE->getNameInfo();
3875 if (!FD) {
3876 S.Diag(Loc, DiagID: diag::err_attribute_cleanup_arg_not_function) << 1
3877 << NI.getName();
3878 return;
3879 }
3880 } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: E)) {
3881 if (ULE->hasExplicitTemplateArgs())
3882 S.Diag(Loc, DiagID: diag::warn_cleanup_ext);
3883 FD = S.ResolveSingleFunctionTemplateSpecialization(ovl: ULE, Complain: true);
3884 NI = ULE->getNameInfo();
3885 if (!FD) {
3886 S.Diag(Loc, DiagID: diag::err_attribute_cleanup_arg_not_function) << 2
3887 << NI.getName();
3888 if (ULE->getType() == S.Context.OverloadTy)
3889 S.NoteAllOverloadCandidates(E: ULE);
3890 return;
3891 }
3892 } else {
3893 S.Diag(Loc, DiagID: diag::err_attribute_cleanup_arg_not_function) << 0;
3894 return;
3895 }
3896
3897 if (FD->getNumParams() != 1) {
3898 S.Diag(Loc, DiagID: diag::err_attribute_cleanup_func_must_take_one_arg)
3899 << NI.getName();
3900 return;
3901 }
3902
3903 VarDecl *VD = cast<VarDecl>(Val: D);
3904 // Create a reference to the variable declaration. This is a fake/dummy
3905 // reference.
3906 DeclRefExpr *VariableReference = DeclRefExpr::Create(
3907 Context: S.Context, QualifierLoc: NestedNameSpecifierLoc{}, TemplateKWLoc: FD->getLocation(), D: VD, RefersToEnclosingVariableOrCapture: false,
3908 NameInfo: DeclarationNameInfo{VD->getDeclName(), VD->getLocation()}, T: VD->getType(),
3909 VK: VK_LValue);
3910
3911 // Create a unary operator expression that represents taking the address of
3912 // the variable. This is a fake/dummy expression.
3913 Expr *AddressOfVariable = UnaryOperator::Create(
3914 C: S.Context, input: VariableReference, opc: UnaryOperatorKind::UO_AddrOf,
3915 type: S.Context.getPointerType(T: VD->getType()), VK: VK_PRValue, OK: OK_Ordinary, l: Loc,
3916 CanOverflow: +false, FPFeatures: FPOptionsOverride{});
3917
3918 // Create a function call expression. This is a fake/dummy call expression.
3919 CallExpr *FunctionCallExpression =
3920 CallExpr::Create(Ctx: S.Context, Fn: E, Args: ArrayRef{AddressOfVariable},
3921 Ty: S.Context.VoidTy, VK: VK_PRValue, RParenLoc: Loc, FPFeatures: FPOptionsOverride{});
3922
3923 if (S.CheckFunctionCall(FDecl: FD, TheCall: FunctionCallExpression,
3924 Proto: FD->getType()->getAs<FunctionProtoType>())) {
3925 return;
3926 }
3927
3928 // If a declaration contains multiple cleanup attributes, GCC only uses
3929 // the last one.
3930 if (const auto *A = D->getAttr<CleanupAttr>()) {
3931 S.Diag(Loc: A->getLoc(), DiagID: diag::warn_duplicate_cleanup_attr) << A->getRange();
3932 D->dropAttr<CleanupAttr>();
3933 }
3934
3935 auto *attr = ::new (S.Context) CleanupAttr(S.Context, AL, FD);
3936 attr->setArgLoc(E->getExprLoc());
3937 D->addAttr(A: attr);
3938}
3939
3940static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3941 const ParsedAttr &AL) {
3942 if (!AL.isArgIdent(Arg: 0)) {
3943 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_n_type)
3944 << AL << 0 << AANT_ArgumentIdentifier;
3945 return;
3946 }
3947
3948 EnumExtensibilityAttr::Kind ExtensibilityKind;
3949 IdentifierInfo *II = AL.getArgAsIdent(Arg: 0)->getIdentifierInfo();
3950 if (!EnumExtensibilityAttr::ConvertStrToKind(Val: II->getName(),
3951 Out&: ExtensibilityKind)) {
3952 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_type_not_supported) << AL << II;
3953 return;
3954 }
3955
3956 D->addAttr(A: ::new (S.Context)
3957 EnumExtensibilityAttr(S.Context, AL, ExtensibilityKind));
3958}
3959
3960/// Handle __attribute__((format_arg((idx)))) attribute based on
3961/// https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html
3962static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3963 const Expr *IdxExpr = AL.getArgAsExpr(Arg: 0);
3964 ParamIdx Idx;
3965 if (!S.checkFunctionOrMethodParameterIndex(D, AI: AL, AttrArgNum: 1, IdxExpr, Idx))
3966 return;
3967
3968 // Make sure the format string is really a string.
3969 QualType Ty = getFunctionOrMethodParamType(D, Idx: Idx.getASTIndex());
3970
3971 bool NotNSStringTy = !S.ObjC().isNSStringType(T: Ty);
3972 if (NotNSStringTy && !S.ObjC().isCFStringType(T: Ty) &&
3973 (!Ty->isPointerType() ||
3974 !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
3975 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_format_attribute_not)
3976 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, Idx: 0);
3977 return;
3978 }
3979 Ty = getFunctionOrMethodResultType(D);
3980 // replace instancetype with the class type
3981 auto *Instancetype = cast<TypedefType>(Val: S.Context.getTypedefType(
3982 Keyword: ElaboratedTypeKeyword::None, /*Qualifier=*/std::nullopt,
3983 Decl: S.Context.getObjCInstanceTypeDecl()));
3984 if (Ty->getAs<TypedefType>() == Instancetype)
3985 if (auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D))
3986 if (auto *Interface = OMD->getClassInterface())
3987 Ty = S.Context.getObjCObjectPointerType(
3988 OIT: QualType(Interface->getTypeForDecl(), 0));
3989 if (!S.ObjC().isNSStringType(T: Ty, /*AllowNSAttributedString=*/true) &&
3990 !S.ObjC().isCFStringType(T: Ty) &&
3991 (!Ty->isPointerType() ||
3992 !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
3993 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_format_attribute_result_not)
3994 << (NotNSStringTy ? "string type" : "NSString")
3995 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, Idx: 0);
3996 return;
3997 }
3998
3999 D->addAttr(A: ::new (S.Context) FormatArgAttr(S.Context, AL, Idx));
4000}
4001
4002enum FormatAttrKind {
4003 CFStringFormat,
4004 NSStringFormat,
4005 StrftimeFormat,
4006 SupportedFormat,
4007 IgnoredFormat,
4008 InvalidFormat
4009};
4010
4011/// getFormatAttrKind - Map from format attribute names to supported format
4012/// types.
4013static FormatAttrKind getFormatAttrKind(StringRef Format) {
4014 return llvm::StringSwitch<FormatAttrKind>(Format)
4015 // Check for formats that get handled specially.
4016 .Case(S: "NSString", Value: NSStringFormat)
4017 .Case(S: "CFString", Value: CFStringFormat)
4018 .Cases(CaseStrings: {"gnu_strftime", "strftime"}, Value: StrftimeFormat)
4019
4020 // Otherwise, check for supported formats.
4021 .Cases(CaseStrings: {"gnu_scanf", "scanf", "gnu_printf", "printf", "printf0",
4022 "gnu_strfmon", "strfmon"},
4023 Value: SupportedFormat)
4024 .Cases(CaseStrings: {"cmn_err", "vcmn_err", "zcmn_err"}, Value: SupportedFormat)
4025 .Cases(CaseStrings: {"kprintf", "syslog"}, Value: SupportedFormat) // OpenBSD.
4026 .Case(S: "freebsd_kprintf", Value: SupportedFormat) // FreeBSD.
4027 .Case(S: "os_trace", Value: SupportedFormat)
4028 .Case(S: "os_log", Value: SupportedFormat)
4029
4030 .Cases(CaseStrings: {"gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag"},
4031 Value: IgnoredFormat)
4032 .Default(Value: InvalidFormat);
4033}
4034
4035/// Handle __attribute__((init_priority(priority))) attributes based on
4036/// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
4037static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4038 if (!S.getLangOpts().CPlusPlus) {
4039 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_ignored) << AL;
4040 return;
4041 }
4042
4043 if (S.getLangOpts().HLSL) {
4044 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_hlsl_init_priority_unsupported);
4045 return;
4046 }
4047
4048 if (S.getCurFunctionOrMethodDecl()) {
4049 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_init_priority_object_attr);
4050 AL.setInvalid();
4051 return;
4052 }
4053
4054 Expr *E = AL.getArgAsExpr(Arg: 0);
4055 uint32_t prioritynum;
4056 if (!S.checkUInt32Argument(AI: AL, Expr: E, Val&: prioritynum)) {
4057 AL.setInvalid();
4058 return;
4059 }
4060
4061 if (prioritynum > 65535) {
4062 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_out_of_range)
4063 << E->getSourceRange() << AL << 0 << 65535;
4064 AL.setInvalid();
4065 return;
4066 }
4067
4068 // Values <= 100 are reserved for the implementation, and libc++
4069 // benefits from being able to specify values in that range.
4070 if (prioritynum < 101)
4071 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_init_priority_reserved)
4072 << E->getSourceRange() << prioritynum;
4073 D->addAttr(A: ::new (S.Context) InitPriorityAttr(S.Context, AL, prioritynum));
4074}
4075
4076ErrorAttr *Sema::mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
4077 StringRef NewUserDiagnostic) {
4078 if (const auto *EA = D->getAttr<ErrorAttr>()) {
4079 std::string NewAttr = CI.getNormalizedFullName();
4080 assert((NewAttr == "error" || NewAttr == "warning") &&
4081 "unexpected normalized full name");
4082 bool Match = (EA->isError() && NewAttr == "error") ||
4083 (EA->isWarning() && NewAttr == "warning");
4084 if (!Match) {
4085 Diag(Loc: EA->getLocation(), DiagID: diag::err_attributes_are_not_compatible)
4086 << CI << EA
4087 << (CI.isRegularKeywordAttribute() ||
4088 EA->isRegularKeywordAttribute());
4089 Diag(Loc: CI.getLoc(), DiagID: diag::note_conflicting_attribute);
4090 return nullptr;
4091 }
4092 if (EA->getUserDiagnostic() != NewUserDiagnostic) {
4093 Diag(Loc: CI.getLoc(), DiagID: diag::warn_duplicate_attribute) << EA;
4094 Diag(Loc: EA->getLoc(), DiagID: diag::note_previous_attribute);
4095 }
4096 D->dropAttr<ErrorAttr>();
4097 }
4098 return ::new (Context) ErrorAttr(Context, CI, NewUserDiagnostic);
4099}
4100
4101FormatAttr *Sema::mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
4102 const IdentifierInfo *Format, int FormatIdx,
4103 int FirstArg) {
4104 // Check whether we already have an equivalent format attribute.
4105 for (auto *F : D->specific_attrs<FormatAttr>()) {
4106 if (F->getType() == Format &&
4107 F->getFormatIdx() == FormatIdx &&
4108 F->getFirstArg() == FirstArg) {
4109 // If we don't have a valid location for this attribute, adopt the
4110 // location.
4111 if (F->getLocation().isInvalid())
4112 F->setRange(CI.getRange());
4113 return nullptr;
4114 }
4115 }
4116
4117 return ::new (Context) FormatAttr(Context, CI, Format, FormatIdx, FirstArg);
4118}
4119
4120FormatMatchesAttr *Sema::mergeFormatMatchesAttr(Decl *D,
4121 const AttributeCommonInfo &CI,
4122 const IdentifierInfo *Format,
4123 int FormatIdx,
4124 StringLiteral *FormatStr) {
4125 // Check whether we already have an equivalent FormatMatches attribute.
4126 for (auto *F : D->specific_attrs<FormatMatchesAttr>()) {
4127 if (F->getType() == Format && F->getFormatIdx() == FormatIdx) {
4128 if (!CheckFormatStringsCompatible(FST: GetFormatStringType(FormatFlavor: Format->getName()),
4129 AuthoritativeFormatString: F->getFormatString(), TestedFormatString: FormatStr))
4130 return nullptr;
4131
4132 // If we don't have a valid location for this attribute, adopt the
4133 // location.
4134 if (F->getLocation().isInvalid())
4135 F->setRange(CI.getRange());
4136 return nullptr;
4137 }
4138 }
4139
4140 return ::new (Context)
4141 FormatMatchesAttr(Context, CI, Format, FormatIdx, FormatStr);
4142}
4143
4144struct FormatAttrCommon {
4145 FormatAttrKind Kind;
4146 IdentifierInfo *Identifier;
4147 unsigned NumArgs;
4148 unsigned FormatStringIdx;
4149};
4150
4151/// Handle __attribute__((format(type,idx,firstarg))) attributes based on
4152/// https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html
4153static bool handleFormatAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
4154 FormatAttrCommon *Info) {
4155 // Checks the first two arguments of the attribute; this is shared between
4156 // Format and FormatMatches attributes.
4157
4158 if (!AL.isArgIdent(Arg: 0)) {
4159 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_n_type)
4160 << AL << 1 << AANT_ArgumentIdentifier;
4161 return false;
4162 }
4163
4164 // In C++ the implicit 'this' function parameter also counts, and they are
4165 // counted from one.
4166 Info->NumArgs = getFunctionOrMethodNumParams(D, /*IncludeThis=*/true);
4167
4168 Info->Identifier = AL.getArgAsIdent(Arg: 0)->getIdentifierInfo();
4169 StringRef Format = Info->Identifier->getName();
4170
4171 if (normalizeName(AttrName&: Format)) {
4172 // If we've modified the string name, we need a new identifier for it.
4173 Info->Identifier = &S.Context.Idents.get(Name: Format);
4174 }
4175
4176 // Check for supported formats.
4177 Info->Kind = getFormatAttrKind(Format);
4178
4179 if (Info->Kind == IgnoredFormat)
4180 return false;
4181
4182 if (Info->Kind == InvalidFormat) {
4183 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_type_not_supported)
4184 << AL << Info->Identifier->getName();
4185 return false;
4186 }
4187
4188 // checks for the 2nd argument
4189 Expr *IdxExpr = AL.getArgAsExpr(Arg: 1);
4190 if (!S.checkUInt32Argument(AI: AL, Expr: IdxExpr, Val&: Info->FormatStringIdx, Idx: 2))
4191 return false;
4192
4193 if (Info->FormatStringIdx < 1 || Info->FormatStringIdx > Info->NumArgs) {
4194 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_out_of_bounds)
4195 << AL << 2 << IdxExpr->getSourceRange();
4196 return false;
4197 }
4198
4199 // FIXME: Do we need to bounds check?
4200 unsigned ArgIdx = Info->FormatStringIdx - 1;
4201
4202 if (hasImplicitObjectParameter(D)) {
4203 if (ArgIdx == 0) {
4204 S.Diag(Loc: AL.getLoc(),
4205 DiagID: diag::err_format_attribute_implicit_this_format_string)
4206 << IdxExpr->getSourceRange();
4207 return false;
4208 }
4209 ArgIdx--;
4210 }
4211
4212 // make sure the format string is really a string
4213 QualType Ty = getFunctionOrMethodParamType(D, Idx: ArgIdx);
4214
4215 if (!S.ObjC().isNSStringType(T: Ty, AllowNSAttributedString: true) && !S.ObjC().isCFStringType(T: Ty) &&
4216 (!Ty->isPointerType() ||
4217 !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
4218 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_format_attribute_not)
4219 << IdxExpr->getSourceRange()
4220 << getFunctionOrMethodParamRange(D, Idx: ArgIdx);
4221 return false;
4222 }
4223
4224 return true;
4225}
4226
4227static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4228 FormatAttrCommon Info;
4229 if (!handleFormatAttrCommon(S, D, AL, Info: &Info))
4230 return;
4231
4232 // check the 3rd argument
4233 Expr *FirstArgExpr = AL.getArgAsExpr(Arg: 2);
4234 uint32_t FirstArg;
4235 if (!S.checkUInt32Argument(AI: AL, Expr: FirstArgExpr, Val&: FirstArg, Idx: 3))
4236 return;
4237
4238 // FirstArg == 0 is always valid.
4239 if (FirstArg != 0) {
4240 if (Info.Kind == StrftimeFormat) {
4241 // If the kind is strftime, FirstArg must be 0 because strftime does not
4242 // use any variadic arguments.
4243 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_format_strftime_third_parameter)
4244 << FirstArgExpr->getSourceRange()
4245 << FixItHint::CreateReplacement(RemoveRange: FirstArgExpr->getSourceRange(), Code: "0");
4246 return;
4247 } else if (isFunctionOrMethodVariadic(D)) {
4248 // Else, if the function is variadic, then FirstArg must be 0 or the
4249 // "position" of the ... parameter. It's unusual to use 0 with variadic
4250 // functions, so the fixit proposes the latter.
4251 if (FirstArg != Info.NumArgs + 1) {
4252 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_out_of_bounds)
4253 << AL << 3 << FirstArgExpr->getSourceRange()
4254 << FixItHint::CreateReplacement(RemoveRange: FirstArgExpr->getSourceRange(),
4255 Code: std::to_string(val: Info.NumArgs + 1));
4256 return;
4257 }
4258 } else {
4259 // Inescapable GCC compatibility diagnostic.
4260 S.Diag(Loc: D->getLocation(), DiagID: diag::warn_gcc_requires_variadic_function) << AL;
4261 if (FirstArg <= Info.FormatStringIdx) {
4262 // Else, the function is not variadic, and FirstArg must be 0 or any
4263 // parameter after the format parameter. We don't offer a fixit because
4264 // there are too many possible good values.
4265 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_out_of_bounds)
4266 << AL << 3 << FirstArgExpr->getSourceRange();
4267 return;
4268 }
4269 }
4270 }
4271
4272 FormatAttr *NewAttr =
4273 S.mergeFormatAttr(D, CI: AL, Format: Info.Identifier, FormatIdx: Info.FormatStringIdx, FirstArg);
4274 if (NewAttr)
4275 D->addAttr(A: NewAttr);
4276}
4277
4278static void handleFormatMatchesAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4279 FormatAttrCommon Info;
4280 if (!handleFormatAttrCommon(S, D, AL, Info: &Info))
4281 return;
4282
4283 Expr *FormatStrExpr = AL.getArgAsExpr(Arg: 2)->IgnoreParenImpCasts();
4284 if (auto *SL = dyn_cast<StringLiteral>(Val: FormatStrExpr)) {
4285 FormatStringType FST = S.GetFormatStringType(FormatFlavor: Info.Identifier->getName());
4286 if (S.ValidateFormatString(FST, Str: SL))
4287 if (auto *NewAttr = S.mergeFormatMatchesAttr(D, CI: AL, Format: Info.Identifier,
4288 FormatIdx: Info.FormatStringIdx, FormatStr: SL))
4289 D->addAttr(A: NewAttr);
4290 return;
4291 }
4292
4293 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_format_nonliteral)
4294 << FormatStrExpr->getSourceRange();
4295}
4296
4297/// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
4298static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4299 // The index that identifies the callback callee is mandatory.
4300 if (AL.getNumArgs() == 0) {
4301 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_callback_attribute_no_callee)
4302 << AL.getRange();
4303 return;
4304 }
4305
4306 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
4307 int32_t NumArgs = getFunctionOrMethodNumParams(D);
4308
4309 FunctionDecl *FD = D->getAsFunction();
4310 assert(FD && "Expected a function declaration!");
4311
4312 llvm::StringMap<int> NameIdxMapping;
4313 NameIdxMapping["__"] = -1;
4314
4315 NameIdxMapping["this"] = 0;
4316
4317 int Idx = 1;
4318 for (const ParmVarDecl *PVD : FD->parameters())
4319 NameIdxMapping[PVD->getName()] = Idx++;
4320
4321 auto UnknownName = NameIdxMapping.end();
4322
4323 SmallVector<int, 8> EncodingIndices;
4324 for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) {
4325 SourceRange SR;
4326 int32_t ArgIdx;
4327
4328 if (AL.isArgIdent(Arg: I)) {
4329 IdentifierLoc *IdLoc = AL.getArgAsIdent(Arg: I);
4330 auto It = NameIdxMapping.find(Key: IdLoc->getIdentifierInfo()->getName());
4331 if (It == UnknownName) {
4332 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_callback_attribute_argument_unknown)
4333 << IdLoc->getIdentifierInfo() << IdLoc->getLoc();
4334 return;
4335 }
4336
4337 SR = SourceRange(IdLoc->getLoc());
4338 ArgIdx = It->second;
4339 } else if (AL.isArgExpr(Arg: I)) {
4340 Expr *IdxExpr = AL.getArgAsExpr(Arg: I);
4341
4342 // If the expression is not parseable as an int32_t we have a problem.
4343 if (!S.checkUInt32Argument(AI: AL, Expr: IdxExpr, Val&: (uint32_t &)ArgIdx, Idx: I + 1,
4344 StrictlyUnsigned: false)) {
4345 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_out_of_bounds)
4346 << AL << (I + 1) << IdxExpr->getSourceRange();
4347 return;
4348 }
4349
4350 // Check oob, excluding the special values, 0 and -1.
4351 if (ArgIdx < -1 || ArgIdx > NumArgs) {
4352 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_out_of_bounds)
4353 << AL << (I + 1) << IdxExpr->getSourceRange();
4354 return;
4355 }
4356
4357 SR = IdxExpr->getSourceRange();
4358 } else {
4359 llvm_unreachable("Unexpected ParsedAttr argument type!");
4360 }
4361
4362 if (ArgIdx == 0 && !HasImplicitThisParam) {
4363 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_callback_implicit_this_not_available)
4364 << (I + 1) << SR;
4365 return;
4366 }
4367
4368 // Adjust for the case we do not have an implicit "this" parameter. In this
4369 // case we decrease all positive values by 1 to get LLVM argument indices.
4370 if (!HasImplicitThisParam && ArgIdx > 0)
4371 ArgIdx -= 1;
4372
4373 EncodingIndices.push_back(Elt: ArgIdx);
4374 }
4375
4376 int CalleeIdx = EncodingIndices.front();
4377 // Check if the callee index is proper, thus not "this" and not "unknown".
4378 // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam"
4379 // is false and positive if "HasImplicitThisParam" is true.
4380 if (CalleeIdx < (int)HasImplicitThisParam) {
4381 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_callback_attribute_invalid_callee)
4382 << AL.getRange();
4383 return;
4384 }
4385
4386 // Get the callee type, note the index adjustment as the AST doesn't contain
4387 // the this type (which the callee cannot reference anyway!).
4388 const Type *CalleeType =
4389 getFunctionOrMethodParamType(D, Idx: CalleeIdx - HasImplicitThisParam)
4390 .getTypePtr();
4391 if (!CalleeType || !CalleeType->isFunctionPointerType()) {
4392 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_callback_callee_no_function_type)
4393 << AL.getRange();
4394 return;
4395 }
4396
4397 const Type *CalleeFnType =
4398 CalleeType->getPointeeType()->getUnqualifiedDesugaredType();
4399
4400 // TODO: Check the type of the callee arguments.
4401
4402 const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(Val: CalleeFnType);
4403 if (!CalleeFnProtoType) {
4404 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_callback_callee_no_function_type)
4405 << AL.getRange();
4406 return;
4407 }
4408
4409 if (CalleeFnProtoType->getNumParams() != EncodingIndices.size() - 1) {
4410 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_wrong_arg_count_for_func)
4411 << AL << QualType{CalleeFnProtoType, 0}
4412 << CalleeFnProtoType->getNumParams()
4413 << (unsigned)(EncodingIndices.size() - 1);
4414 return;
4415 }
4416
4417 if (CalleeFnProtoType->isVariadic()) {
4418 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_callback_callee_is_variadic) << AL.getRange();
4419 return;
4420 }
4421
4422 // Do not allow multiple callback attributes.
4423 if (D->hasAttr<CallbackAttr>()) {
4424 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_callback_attribute_multiple) << AL.getRange();
4425 return;
4426 }
4427
4428 D->addAttr(A: ::new (S.Context) CallbackAttr(
4429 S.Context, AL, EncodingIndices.data(), EncodingIndices.size()));
4430}
4431
4432LifetimeCaptureByAttr *Sema::ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
4433 StringRef ParamName) {
4434 StringRef AttrName = AL.getAttrName()->getName();
4435 StringRef SpecialEntity;
4436 if (AttrName == "lifetime_capture_by_this")
4437 SpecialEntity = "this";
4438 else if (AttrName == "lifetime_capture_by_global")
4439 SpecialEntity = "global";
4440 else if (AttrName == "lifetime_capture_by_unknown")
4441 SpecialEntity = "unknown";
4442
4443 if (!SpecialEntity.empty() && AL.getNumArgs() != 0) {
4444 Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments) << AL << 0;
4445 return nullptr;
4446 }
4447
4448 // Atleast one capture by is required.
4449 if (SpecialEntity.empty() && AL.getNumArgs() == 0) {
4450 Diag(Loc: AL.getLoc(), DiagID: diag::err_capture_by_attribute_no_entity)
4451 << AL.getRange();
4452 return nullptr;
4453 }
4454 unsigned N = SpecialEntity.empty() ? AL.getNumArgs() : 1;
4455 auto ParamIdents =
4456 MutableArrayRef<IdentifierInfo *>(new (Context) IdentifierInfo *[N], N);
4457 auto ParamLocs =
4458 MutableArrayRef<SourceLocation>(new (Context) SourceLocation[N], N);
4459 if (!SpecialEntity.empty()) {
4460 ParamIdents[0] = &Context.Idents.get(Name: SpecialEntity);
4461 ParamLocs[0] = AL.getRange().getEnd();
4462 int FakeParamIndices[] = {LifetimeCaptureByAttr::Invalid};
4463 auto *CapturedBy =
4464 LifetimeCaptureByAttr::Create(Ctx&: Context, Params: FakeParamIndices, ParamsSize: 1, CommonInfo: AL);
4465 CapturedBy->setArgs(Idents: ParamIdents, Locs: ParamLocs);
4466 return CapturedBy;
4467 }
4468
4469 bool IsValid = true;
4470 for (unsigned I = 0; I < N; ++I) {
4471 if (AL.isArgExpr(Arg: I)) {
4472 Expr *E = AL.getArgAsExpr(Arg: I);
4473 Diag(Loc: E->getExprLoc(), DiagID: diag::err_capture_by_attribute_argument_unknown)
4474 << E << E->getExprLoc();
4475 IsValid = false;
4476 continue;
4477 }
4478 assert(AL.isArgIdent(I));
4479 IdentifierLoc *IdLoc = AL.getArgAsIdent(Arg: I);
4480 StringRef Name = IdLoc->getIdentifierInfo()->getName();
4481 StringRef Replacement;
4482 if (Name == "this")
4483 Replacement = "lifetime_capture_by_this";
4484 else if (Name == "global")
4485 Replacement = "lifetime_capture_by_global";
4486 else if (Name == "unknown")
4487 Replacement = "lifetime_capture_by_unknown";
4488 if (!Replacement.empty())
4489 Diag(Loc: IdLoc->getLoc(), DiagID: diag::warn_deprecated_capture_by_special_entity)
4490 << Name << Replacement << IdLoc->getLoc();
4491 if (IdLoc->getIdentifierInfo()->getName() == ParamName) {
4492 Diag(Loc: IdLoc->getLoc(), DiagID: diag::err_capture_by_references_itself)
4493 << IdLoc->getLoc();
4494 IsValid = false;
4495 continue;
4496 }
4497 ParamIdents[I] = IdLoc->getIdentifierInfo();
4498 ParamLocs[I] = IdLoc->getLoc();
4499 }
4500 if (!IsValid)
4501 return nullptr;
4502 SmallVector<int> FakeParamIndices(N, LifetimeCaptureByAttr::Invalid);
4503 auto *CapturedBy =
4504 LifetimeCaptureByAttr::Create(Ctx&: Context, Params: FakeParamIndices.data(), ParamsSize: N, CommonInfo: AL);
4505 CapturedBy->setArgs(Idents: ParamIdents, Locs: ParamLocs);
4506 return CapturedBy;
4507}
4508
4509static void handleLifetimeCaptureByAttr(Sema &S, Decl *D,
4510 const ParsedAttr &AL) {
4511 auto *PVD = dyn_cast<ParmVarDecl>(Val: D);
4512 assert(PVD);
4513 auto *CaptureByAttr = S.ParseLifetimeCaptureByAttr(AL, ParamName: PVD->getName());
4514 if (!CaptureByAttr)
4515 return;
4516
4517 enum class SpellingKind { ParameterList, This, Global, Unknown };
4518 auto GetSpellingKind = [](const LifetimeCaptureByAttr *A) {
4519 if (A->isThis())
4520 return SpellingKind::This;
4521 if (A->isGlobal())
4522 return SpellingKind::Global;
4523 if (A->isUnknown())
4524 return SpellingKind::Unknown;
4525 return SpellingKind::ParameterList;
4526 };
4527 auto GetSpellingName = [](SpellingKind Kind) -> StringRef {
4528 switch (Kind) {
4529 case SpellingKind::ParameterList:
4530 return "lifetime_capture_by";
4531 case SpellingKind::This:
4532 return "lifetime_capture_by_this";
4533 case SpellingKind::Global:
4534 return "lifetime_capture_by_global";
4535 case SpellingKind::Unknown:
4536 return "lifetime_capture_by_unknown";
4537 }
4538 llvm_unreachable("unknown lifetime_capture_by spelling kind");
4539 };
4540
4541 SpellingKind NewKind = GetSpellingKind(CaptureByAttr);
4542 for (const auto *Existing : D->specific_attrs<LifetimeCaptureByAttr>()) {
4543 if (GetSpellingKind(Existing) == NewKind) {
4544 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_capture_by_attribute_multiple)
4545 << GetSpellingName(NewKind) << AL.getRange();
4546 return;
4547 }
4548 }
4549
4550 D->addAttr(A: CaptureByAttr);
4551}
4552
4553void Sema::LazyProcessLifetimeCaptureByParams(FunctionDecl *FD) {
4554 bool HasImplicitThisParam = hasImplicitObjectParameter(D: FD);
4555 SmallVector<LifetimeCaptureByAttr *, 1> Attrs;
4556 for (ParmVarDecl *PVD : FD->parameters())
4557 for (auto *A : PVD->specific_attrs<LifetimeCaptureByAttr>())
4558 Attrs.push_back(Elt: A);
4559 if (HasImplicitThisParam) {
4560 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4561 if (!TSI)
4562 return;
4563 AttributedTypeLoc ATL;
4564 for (TypeLoc TL = TSI->getTypeLoc();
4565 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4566 TL = ATL.getModifiedLoc()) {
4567 if (auto *A = ATL.getAttrAs<LifetimeCaptureByAttr>())
4568 Attrs.push_back(Elt: const_cast<LifetimeCaptureByAttr *>(A));
4569 }
4570 }
4571 if (Attrs.empty())
4572 return;
4573 llvm::StringMap<int> NameIdxMapping = {
4574 {"global", LifetimeCaptureByAttr::Global},
4575 {"unknown", LifetimeCaptureByAttr::Unknown}};
4576 int Idx = 0;
4577 if (HasImplicitThisParam) {
4578 NameIdxMapping["this"] = 0;
4579 Idx++;
4580 }
4581 for (const ParmVarDecl *PVD : FD->parameters())
4582 NameIdxMapping[PVD->getName()] = Idx++;
4583 auto DisallowReservedParams = [&](StringRef Reserved) {
4584 for (const ParmVarDecl *PVD : FD->parameters())
4585 if (PVD->getName() == Reserved)
4586 Diag(Loc: PVD->getLocation(), DiagID: diag::err_capture_by_param_uses_reserved_name)
4587 << PVD->getName();
4588 };
4589 for (auto *CapturedBy : Attrs) {
4590 const auto &Entities = CapturedBy->getArgIdents();
4591 for (size_t I = 0; I < Entities.size(); ++I) {
4592 StringRef Name = Entities[I]->getName();
4593 auto It = NameIdxMapping.find(Key: Name);
4594 if (It == NameIdxMapping.end()) {
4595 auto Loc = CapturedBy->getArgLocs()[I];
4596 if (!HasImplicitThisParam && Name == "this") {
4597 unsigned DiagID =
4598 CapturedBy->isStandaloneSpecial()
4599 ? diag::err_capture_by_this_attr_without_implicit_this
4600 : diag::err_capture_by_implicit_this_not_available;
4601 Diag(Loc, DiagID) << Loc;
4602 } else
4603 Diag(Loc, DiagID: diag::err_capture_by_attribute_argument_unknown)
4604 << Entities[I] << Loc;
4605 continue;
4606 }
4607 if ((Name == "unknown" || Name == "global") &&
4608 !CapturedBy->isStandaloneSpecial())
4609 DisallowReservedParams(Name);
4610 CapturedBy->setParamIdx(Idx: I, Val: It->second);
4611 }
4612 }
4613}
4614
4615static bool isFunctionLike(const Type &T) {
4616 // Check for explicit function types.
4617 // 'called_once' is only supported in Objective-C and it has
4618 // function pointers and block pointers.
4619 return T.isFunctionPointerType() || T.isBlockPointerType();
4620}
4621
4622/// Handle 'called_once' attribute.
4623static void handleCalledOnceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4624 // 'called_once' only applies to parameters representing functions.
4625 QualType T = cast<ParmVarDecl>(Val: D)->getType();
4626
4627 if (!isFunctionLike(T: *T)) {
4628 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_called_once_attribute_wrong_type);
4629 return;
4630 }
4631
4632 D->addAttr(A: ::new (S.Context) CalledOnceAttr(S.Context, AL));
4633}
4634
4635static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4636 // Try to find the underlying union declaration.
4637 RecordDecl *RD = nullptr;
4638 const auto *TD = dyn_cast<TypedefNameDecl>(Val: D);
4639 if (TD && TD->getUnderlyingType()->isUnionType())
4640 RD = TD->getUnderlyingType()->getAsRecordDecl();
4641 else
4642 RD = dyn_cast<RecordDecl>(Val: D);
4643
4644 if (!RD || !RD->isUnion()) {
4645 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_wrong_decl_type)
4646 << AL << AL.isRegularKeywordAttribute() << ExpectedUnion;
4647 return;
4648 }
4649
4650 if (!RD->isCompleteDefinition()) {
4651 if (!RD->isBeingDefined())
4652 S.Diag(Loc: AL.getLoc(),
4653 DiagID: diag::warn_transparent_union_attribute_not_definition);
4654 return;
4655 }
4656
4657 RecordDecl::field_iterator Field = RD->field_begin(),
4658 FieldEnd = RD->field_end();
4659 if (Field == FieldEnd) {
4660 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_transparent_union_attribute_zero_fields);
4661 return;
4662 }
4663
4664 FieldDecl *FirstField = *Field;
4665 QualType FirstType = FirstField->getType();
4666 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
4667 S.Diag(Loc: FirstField->getLocation(),
4668 DiagID: diag::warn_transparent_union_attribute_floating)
4669 << FirstType->isVectorType() << FirstType;
4670 return;
4671 }
4672
4673 if (FirstType->isIncompleteType())
4674 return;
4675 uint64_t FirstSize = S.Context.getTypeSize(T: FirstType);
4676 uint64_t FirstAlign = S.Context.getTypeAlign(T: FirstType);
4677 for (; Field != FieldEnd; ++Field) {
4678 QualType FieldType = Field->getType();
4679 if (FieldType->isIncompleteType())
4680 return;
4681 // FIXME: this isn't fully correct; we also need to test whether the
4682 // members of the union would all have the same calling convention as the
4683 // first member of the union. Checking just the size and alignment isn't
4684 // sufficient (consider structs passed on the stack instead of in registers
4685 // as an example).
4686 if (S.Context.getTypeSize(T: FieldType) != FirstSize ||
4687 S.Context.getTypeAlign(T: FieldType) > FirstAlign) {
4688 // Warn if we drop the attribute.
4689 bool isSize = S.Context.getTypeSize(T: FieldType) != FirstSize;
4690 unsigned FieldBits = isSize ? S.Context.getTypeSize(T: FieldType)
4691 : S.Context.getTypeAlign(T: FieldType);
4692 S.Diag(Loc: Field->getLocation(),
4693 DiagID: diag::warn_transparent_union_attribute_field_size_align)
4694 << isSize << *Field << FieldBits;
4695 unsigned FirstBits = isSize ? FirstSize : FirstAlign;
4696 S.Diag(Loc: FirstField->getLocation(),
4697 DiagID: diag::note_transparent_union_first_field_size_align)
4698 << isSize << FirstBits;
4699 return;
4700 }
4701 }
4702
4703 RD->addAttr(A: ::new (S.Context) TransparentUnionAttr(S.Context, AL));
4704}
4705
4706static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4707 auto *Attr = S.CreateAnnotationAttr(AL);
4708 if (Attr) {
4709 D->addAttr(A: Attr);
4710 }
4711}
4712
4713static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4714 S.AddAlignValueAttr(D, CI: AL, E: AL.getArgAsExpr(Arg: 0));
4715}
4716
4717void Sema::AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E) {
4718 SourceLocation AttrLoc = CI.getLoc();
4719
4720 QualType T;
4721 if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: D))
4722 T = TD->getUnderlyingType();
4723 else if (const auto *VD = dyn_cast<ValueDecl>(Val: D))
4724 T = VD->getType();
4725 else
4726 llvm_unreachable("Unknown decl type for align_value");
4727
4728 if (!T->isDependentType() && !T->isAnyPointerType() &&
4729 !T->isReferenceType() && !T->isMemberPointerType()) {
4730 Diag(Loc: AttrLoc, DiagID: diag::warn_attribute_pointer_or_reference_only)
4731 << CI << T << D->getSourceRange();
4732 return;
4733 }
4734
4735 if (!E->isValueDependent()) {
4736 llvm::APSInt Alignment;
4737 ExprResult ICE = VerifyIntegerConstantExpression(
4738 E, Result: &Alignment, DiagID: diag::err_align_value_attribute_argument_not_int);
4739 if (ICE.isInvalid())
4740 return;
4741
4742 if (!Alignment.isPowerOf2()) {
4743 Diag(Loc: AttrLoc, DiagID: diag::err_alignment_not_power_of_two)
4744 << E->getSourceRange();
4745 return;
4746 }
4747
4748 D->addAttr(A: ::new (Context) AlignValueAttr(Context, CI, ICE.get()));
4749 return;
4750 }
4751
4752 // Save dependent expressions in the AST to be instantiated.
4753 D->addAttr(A: ::new (Context) AlignValueAttr(Context, CI, E));
4754}
4755
4756static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4757 if (AL.hasParsedType()) {
4758 const ParsedType &TypeArg = AL.getTypeArg();
4759 TypeSourceInfo *TInfo;
4760 (void)S.GetTypeFromParser(
4761 Ty: ParsedType::getFromOpaquePtr(P: TypeArg.getAsOpaquePtr()), TInfo: &TInfo);
4762 if (AL.isPackExpansion() &&
4763 !TInfo->getType()->containsUnexpandedParameterPack()) {
4764 S.Diag(Loc: AL.getEllipsisLoc(),
4765 DiagID: diag::err_pack_expansion_without_parameter_packs);
4766 return;
4767 }
4768
4769 if (!AL.isPackExpansion() &&
4770 S.DiagnoseUnexpandedParameterPack(Loc: TInfo->getTypeLoc().getBeginLoc(),
4771 T: TInfo, UPPC: Sema::UPPC_Expression))
4772 return;
4773
4774 S.AddAlignedAttr(D, CI: AL, T: TInfo, IsPackExpansion: AL.isPackExpansion());
4775 return;
4776 }
4777
4778 // check the attribute arguments.
4779 if (AL.getNumArgs() > 1) {
4780 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments) << AL << 1;
4781 return;
4782 }
4783
4784 if (AL.getNumArgs() == 0) {
4785 D->addAttr(A: ::new (S.Context) AlignedAttr(S.Context, AL, true, nullptr));
4786 return;
4787 }
4788
4789 Expr *E = AL.getArgAsExpr(Arg: 0);
4790 if (AL.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
4791 S.Diag(Loc: AL.getEllipsisLoc(),
4792 DiagID: diag::err_pack_expansion_without_parameter_packs);
4793 return;
4794 }
4795
4796 if (!AL.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
4797 return;
4798
4799 S.AddAlignedAttr(D, CI: AL, E, IsPackExpansion: AL.isPackExpansion());
4800}
4801
4802/// Perform checking of type validity
4803///
4804/// C++11 [dcl.align]p1:
4805/// An alignment-specifier may be applied to a variable or to a class
4806/// data member, but it shall not be applied to a bit-field, a function
4807/// parameter, the formal parameter of a catch clause, or a variable
4808/// declared with the register storage class specifier. An
4809/// alignment-specifier may also be applied to the declaration of a class
4810/// or enumeration type.
4811/// CWG 2354:
4812/// CWG agreed to remove permission for alignas to be applied to
4813/// enumerations.
4814/// C11 6.7.5/2:
4815/// An alignment attribute shall not be specified in a declaration of
4816/// a typedef, or a bit-field, or a function, or a parameter, or an
4817/// object declared with the register storage-class specifier.
4818static bool validateAlignasAppliedType(Sema &S, Decl *D,
4819 const AlignedAttr &Attr,
4820 SourceLocation AttrLoc) {
4821 int DiagKind = -1;
4822 if (isa<ParmVarDecl>(Val: D)) {
4823 DiagKind = 0;
4824 } else if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
4825 if (VD->getStorageClass() == SC_Register)
4826 DiagKind = 1;
4827 if (VD->isExceptionVariable())
4828 DiagKind = 2;
4829 } else if (const auto *FD = dyn_cast<FieldDecl>(Val: D)) {
4830 if (FD->isBitField())
4831 DiagKind = 3;
4832 } else if (const auto *ED = dyn_cast<EnumDecl>(Val: D)) {
4833 if (ED->getLangOpts().CPlusPlus)
4834 DiagKind = 4;
4835 } else if (!isa<TagDecl>(Val: D)) {
4836 return S.Diag(Loc: AttrLoc, DiagID: diag::err_attribute_wrong_decl_type)
4837 << &Attr << Attr.isRegularKeywordAttribute()
4838 << (Attr.isC11() ? ExpectedVariableOrField
4839 : ExpectedVariableFieldOrTag);
4840 }
4841 if (DiagKind != -1) {
4842 return S.Diag(Loc: AttrLoc, DiagID: diag::err_alignas_attribute_wrong_decl_type)
4843 << &Attr << DiagKind;
4844 }
4845 return false;
4846}
4847
4848void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
4849 bool IsPackExpansion) {
4850 AlignedAttr TmpAttr(Context, CI, true, E);
4851 SourceLocation AttrLoc = CI.getLoc();
4852
4853 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
4854 if (TmpAttr.isAlignas() &&
4855 validateAlignasAppliedType(S&: *this, D, Attr: TmpAttr, AttrLoc))
4856 return;
4857
4858 if (E->isValueDependent()) {
4859 // We can't support a dependent alignment on a non-dependent type,
4860 // because we have no way to model that a type is "alignment-dependent"
4861 // but not dependent in any other way.
4862 if (const auto *TND = dyn_cast<TypedefNameDecl>(Val: D)) {
4863 if (!TND->getUnderlyingType()->isDependentType()) {
4864 Diag(Loc: AttrLoc, DiagID: diag::err_alignment_dependent_typedef_name)
4865 << E->getSourceRange();
4866 return;
4867 }
4868 }
4869
4870 // Save dependent expressions in the AST to be instantiated.
4871 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, E);
4872 AA->setPackExpansion(IsPackExpansion);
4873 D->addAttr(A: AA);
4874 return;
4875 }
4876
4877 // FIXME: Cache the number on the AL object?
4878 llvm::APSInt Alignment;
4879 ExprResult ICE = VerifyIntegerConstantExpression(
4880 E, Result: &Alignment, DiagID: diag::err_aligned_attribute_argument_not_int);
4881 if (ICE.isInvalid())
4882 return;
4883
4884 uint64_t MaximumAlignment = Sema::MaximumAlignment;
4885 if (Context.getTargetInfo().getTriple().isOSBinFormatCOFF())
4886 MaximumAlignment = std::min(a: MaximumAlignment, b: uint64_t(8192));
4887 if (Alignment > MaximumAlignment) {
4888 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_aligned_too_great)
4889 << MaximumAlignment << E->getSourceRange();
4890 return;
4891 }
4892
4893 uint64_t AlignVal = Alignment.getZExtValue();
4894 // C++11 [dcl.align]p2:
4895 // -- if the constant expression evaluates to zero, the alignment
4896 // specifier shall have no effect
4897 // C11 6.7.5p6:
4898 // An alignment specification of zero has no effect.
4899 if (!(TmpAttr.isAlignas() && !Alignment)) {
4900 if (!llvm::isPowerOf2_64(Value: AlignVal)) {
4901 Diag(Loc: AttrLoc, DiagID: diag::err_alignment_not_power_of_two)
4902 << E->getSourceRange();
4903 return;
4904 }
4905 }
4906
4907 const auto *VD = dyn_cast<VarDecl>(Val: D);
4908 if (VD) {
4909 unsigned MaxTLSAlign =
4910 Context.toCharUnitsFromBits(BitSize: Context.getTargetInfo().getMaxTLSAlign())
4911 .getQuantity();
4912 if (MaxTLSAlign && AlignVal > MaxTLSAlign &&
4913 VD->getTLSKind() != VarDecl::TLS_None) {
4914 Diag(Loc: VD->getLocation(), DiagID: diag::err_tls_var_aligned_over_maximum)
4915 << (unsigned)AlignVal << VD << MaxTLSAlign;
4916 return;
4917 }
4918 }
4919
4920 // On AIX, an aligned attribute can not decrease the alignment when applied
4921 // to a variable declaration with vector type.
4922 if (VD && Context.getTargetInfo().getTriple().isOSAIX()) {
4923 const Type *Ty = VD->getType().getTypePtr();
4924 if (Ty->isVectorType() && AlignVal < 16) {
4925 Diag(Loc: VD->getLocation(), DiagID: diag::warn_aligned_attr_underaligned)
4926 << VD->getType() << 16;
4927 return;
4928 }
4929 }
4930
4931 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, ICE.get());
4932 AA->setPackExpansion(IsPackExpansion);
4933 AA->setCachedAlignmentValue(
4934 static_cast<unsigned>(AlignVal * Context.getCharWidth()));
4935 D->addAttr(A: AA);
4936}
4937
4938void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI,
4939 TypeSourceInfo *TS, bool IsPackExpansion) {
4940 AlignedAttr TmpAttr(Context, CI, false, TS);
4941 SourceLocation AttrLoc = CI.getLoc();
4942
4943 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
4944 if (TmpAttr.isAlignas() &&
4945 validateAlignasAppliedType(S&: *this, D, Attr: TmpAttr, AttrLoc))
4946 return;
4947
4948 if (TS->getType()->isDependentType()) {
4949 // We can't support a dependent alignment on a non-dependent type,
4950 // because we have no way to model that a type is "type-dependent"
4951 // but not dependent in any other way.
4952 if (const auto *TND = dyn_cast<TypedefNameDecl>(Val: D)) {
4953 if (!TND->getUnderlyingType()->isDependentType()) {
4954 Diag(Loc: AttrLoc, DiagID: diag::err_alignment_dependent_typedef_name)
4955 << TS->getTypeLoc().getSourceRange();
4956 return;
4957 }
4958 }
4959
4960 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
4961 AA->setPackExpansion(IsPackExpansion);
4962 D->addAttr(A: AA);
4963 return;
4964 }
4965
4966 const auto *VD = dyn_cast<VarDecl>(Val: D);
4967 unsigned AlignVal = TmpAttr.getAlignment(Ctx&: Context);
4968 // On AIX, an aligned attribute can not decrease the alignment when applied
4969 // to a variable declaration with vector type.
4970 if (VD && Context.getTargetInfo().getTriple().isOSAIX()) {
4971 const Type *Ty = VD->getType().getTypePtr();
4972 if (Ty->isVectorType() &&
4973 Context.toCharUnitsFromBits(BitSize: AlignVal).getQuantity() < 16) {
4974 Diag(Loc: VD->getLocation(), DiagID: diag::warn_aligned_attr_underaligned)
4975 << VD->getType() << 16;
4976 return;
4977 }
4978 }
4979
4980 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
4981 AA->setPackExpansion(IsPackExpansion);
4982 AA->setCachedAlignmentValue(AlignVal);
4983 D->addAttr(A: AA);
4984}
4985
4986void Sema::CheckAlignasUnderalignment(Decl *D) {
4987 assert(D->hasAttrs() && "no attributes on decl");
4988
4989 QualType UnderlyingTy, DiagTy;
4990 if (const auto *VD = dyn_cast<ValueDecl>(Val: D)) {
4991 UnderlyingTy = DiagTy = VD->getType();
4992 } else {
4993 UnderlyingTy = DiagTy = Context.getCanonicalTagType(TD: cast<TagDecl>(Val: D));
4994 if (const auto *ED = dyn_cast<EnumDecl>(Val: D))
4995 UnderlyingTy = ED->getIntegerType();
4996 }
4997 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
4998 return;
4999
5000 // C++11 [dcl.align]p5, C11 6.7.5/4:
5001 // The combined effect of all alignment attributes in a declaration shall
5002 // not specify an alignment that is less strict than the alignment that
5003 // would otherwise be required for the entity being declared.
5004 AlignedAttr *AlignasAttr = nullptr;
5005 AlignedAttr *LastAlignedAttr = nullptr;
5006 unsigned Align = 0;
5007 for (auto *I : D->specific_attrs<AlignedAttr>()) {
5008 if (I->isAlignmentDependent())
5009 return;
5010 if (I->isAlignas())
5011 AlignasAttr = I;
5012 Align = std::max(a: Align, b: I->getAlignment(Ctx&: Context));
5013 LastAlignedAttr = I;
5014 }
5015
5016 if (Align && DiagTy->isSizelessType()) {
5017 Diag(Loc: LastAlignedAttr->getLocation(), DiagID: diag::err_attribute_sizeless_type)
5018 << LastAlignedAttr << DiagTy;
5019 } else if (AlignasAttr && Align) {
5020 CharUnits RequestedAlign = Context.toCharUnitsFromBits(BitSize: Align);
5021 CharUnits NaturalAlign = Context.getTypeAlignInChars(T: UnderlyingTy);
5022 if (NaturalAlign > RequestedAlign)
5023 Diag(Loc: AlignasAttr->getLocation(), DiagID: diag::err_alignas_underaligned)
5024 << DiagTy << (unsigned)NaturalAlign.getQuantity();
5025 }
5026}
5027
5028bool Sema::checkMSInheritanceAttrOnDefinition(
5029 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
5030 MSInheritanceModel ExplicitModel) {
5031 assert(RD->hasDefinition() && "RD has no definition!");
5032
5033 // We may not have seen base specifiers or any virtual methods yet. We will
5034 // have to wait until the record is defined to catch any mismatches.
5035 if (!RD->getDefinition()->isCompleteDefinition())
5036 return false;
5037
5038 // The unspecified model never matches what a definition could need.
5039 if (ExplicitModel == MSInheritanceModel::Unspecified)
5040 return false;
5041
5042 if (BestCase) {
5043 if (RD->calculateInheritanceModel() == ExplicitModel)
5044 return false;
5045 } else {
5046 if (RD->calculateInheritanceModel() <= ExplicitModel)
5047 return false;
5048 }
5049
5050 Diag(Loc: Range.getBegin(), DiagID: diag::err_mismatched_ms_inheritance)
5051 << 0 /*definition*/;
5052 Diag(Loc: RD->getDefinition()->getLocation(), DiagID: diag::note_defined_here) << RD;
5053 return true;
5054}
5055
5056/// parseModeAttrArg - Parses attribute mode string and returns parsed type
5057/// attribute.
5058static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
5059 bool &IntegerMode, bool &ComplexMode,
5060 FloatModeKind &ExplicitType) {
5061 IntegerMode = true;
5062 ComplexMode = false;
5063 ExplicitType = FloatModeKind::NoFloat;
5064 switch (Str.size()) {
5065 case 2:
5066 switch (Str[0]) {
5067 case 'Q':
5068 DestWidth = 8;
5069 break;
5070 case 'H':
5071 DestWidth = 16;
5072 break;
5073 case 'S':
5074 DestWidth = 32;
5075 break;
5076 case 'D':
5077 DestWidth = 64;
5078 break;
5079 case 'X':
5080 DestWidth = 96;
5081 break;
5082 case 'K': // KFmode - IEEE quad precision (__float128)
5083 ExplicitType = FloatModeKind::Float128;
5084 DestWidth = Str[1] == 'I' ? 0 : 128;
5085 break;
5086 case 'T':
5087 ExplicitType = FloatModeKind::LongDouble;
5088 DestWidth = 128;
5089 break;
5090 case 'I':
5091 ExplicitType = FloatModeKind::Ibm128;
5092 DestWidth = Str[1] == 'I' ? 0 : 128;
5093 break;
5094 }
5095 if (Str[1] == 'F') {
5096 IntegerMode = false;
5097 } else if (Str[1] == 'C') {
5098 IntegerMode = false;
5099 ComplexMode = true;
5100 } else if (Str[1] != 'I') {
5101 DestWidth = 0;
5102 }
5103 break;
5104 case 4:
5105 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
5106 // pointer on PIC16 and other embedded platforms.
5107 if (Str == "word")
5108 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
5109 else if (Str == "byte")
5110 DestWidth = S.Context.getTargetInfo().getCharWidth();
5111 break;
5112 case 7:
5113 if (Str == "pointer")
5114 DestWidth = S.Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default);
5115 break;
5116 case 11:
5117 if (Str == "unwind_word")
5118 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
5119 break;
5120 }
5121}
5122
5123/// handleModeAttr - This attribute modifies the width of a decl with primitive
5124/// type.
5125///
5126/// Despite what would be logical, the mode attribute is a decl attribute, not a
5127/// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
5128/// HImode, not an intermediate pointer.
5129static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5130 // This attribute isn't documented, but glibc uses it. It changes
5131 // the width of an int or unsigned int to the specified size.
5132 if (!AL.isArgIdent(Arg: 0)) {
5133 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_type)
5134 << AL << AANT_ArgumentIdentifier;
5135 return;
5136 }
5137
5138 IdentifierInfo *Name = AL.getArgAsIdent(Arg: 0)->getIdentifierInfo();
5139
5140 S.AddModeAttr(D, CI: AL, Name);
5141}
5142
5143void Sema::AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
5144 const IdentifierInfo *Name, bool InInstantiation) {
5145 StringRef Str = Name->getName();
5146 normalizeName(AttrName&: Str);
5147 SourceLocation AttrLoc = CI.getLoc();
5148
5149 unsigned DestWidth = 0;
5150 bool IntegerMode = true;
5151 bool ComplexMode = false;
5152 FloatModeKind ExplicitType = FloatModeKind::NoFloat;
5153 llvm::APInt VectorSize(64, 0);
5154 if (Str.size() >= 4 && Str[0] == 'V') {
5155 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
5156 size_t StrSize = Str.size();
5157 size_t VectorStringLength = 0;
5158 while ((VectorStringLength + 1) < StrSize &&
5159 isdigit(Str[VectorStringLength + 1]))
5160 ++VectorStringLength;
5161 if (VectorStringLength &&
5162 !Str.substr(Start: 1, N: VectorStringLength).getAsInteger(Radix: 10, Result&: VectorSize) &&
5163 VectorSize.isPowerOf2()) {
5164 parseModeAttrArg(S&: *this, Str: Str.substr(Start: VectorStringLength + 1), DestWidth,
5165 IntegerMode, ComplexMode, ExplicitType);
5166 // Avoid duplicate warning from template instantiation.
5167 if (!InInstantiation)
5168 Diag(Loc: AttrLoc, DiagID: diag::warn_vector_mode_deprecated);
5169 } else {
5170 VectorSize = 0;
5171 }
5172 }
5173
5174 if (!VectorSize)
5175 parseModeAttrArg(S&: *this, Str, DestWidth, IntegerMode, ComplexMode,
5176 ExplicitType);
5177
5178 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
5179 // and friends, at least with glibc.
5180 // FIXME: Make sure floating-point mappings are accurate
5181 // FIXME: Support XF and TF types
5182 if (!DestWidth) {
5183 Diag(Loc: AttrLoc, DiagID: diag::err_machine_mode) << 0 /*Unknown*/ << Name;
5184 return;
5185 }
5186
5187 QualType OldTy;
5188 if (const auto *TD = dyn_cast<TypedefNameDecl>(Val: D))
5189 OldTy = TD->getUnderlyingType();
5190 else if (const auto *ED = dyn_cast<EnumDecl>(Val: D)) {
5191 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
5192 // Try to get type from enum declaration, default to int.
5193 OldTy = ED->getIntegerType();
5194 if (OldTy.isNull())
5195 OldTy = Context.IntTy;
5196 } else
5197 OldTy = cast<ValueDecl>(Val: D)->getType();
5198
5199 if (OldTy->isDependentType()) {
5200 D->addAttr(A: ::new (Context) ModeAttr(Context, CI, Name));
5201 return;
5202 }
5203
5204 // Base type can also be a vector type (see PR17453).
5205 // Distinguish between base type and base element type.
5206 QualType OldElemTy = OldTy;
5207 if (const auto *VT = OldTy->getAs<VectorType>())
5208 OldElemTy = VT->getElementType();
5209
5210 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
5211 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
5212 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
5213 if ((isa<EnumDecl>(Val: D) || OldElemTy->isEnumeralType()) &&
5214 VectorSize.getBoolValue()) {
5215 Diag(Loc: AttrLoc, DiagID: diag::err_enum_mode_vector_type) << Name << CI.getRange();
5216 return;
5217 }
5218 bool IntegralOrAnyEnumType = (OldElemTy->isIntegralOrEnumerationType() &&
5219 !OldElemTy->isBitIntType()) ||
5220 OldElemTy->isEnumeralType();
5221
5222 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
5223 !IntegralOrAnyEnumType)
5224 Diag(Loc: AttrLoc, DiagID: diag::err_mode_not_primitive);
5225 else if (IntegerMode) {
5226 if (!IntegralOrAnyEnumType)
5227 Diag(Loc: AttrLoc, DiagID: diag::err_mode_wrong_type);
5228 } else if (ComplexMode) {
5229 if (!OldElemTy->isComplexType())
5230 Diag(Loc: AttrLoc, DiagID: diag::err_mode_wrong_type);
5231 } else {
5232 if (!OldElemTy->isFloatingType())
5233 Diag(Loc: AttrLoc, DiagID: diag::err_mode_wrong_type);
5234 }
5235
5236 QualType NewElemTy;
5237
5238 if (IntegerMode)
5239 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
5240 Signed: OldElemTy->isSignedIntegerType());
5241 else
5242 NewElemTy = Context.getRealTypeForBitwidth(DestWidth, ExplicitType);
5243
5244 if (NewElemTy.isNull()) {
5245 // FIXME: We need to make sure that the target handles correctly the
5246 // requested mode.
5247 // Only emit diagnostic on host for 128-bit mode attribute
5248 if (!(DestWidth == 128 && getLangOpts().isTargetDevice()))
5249 Diag(Loc: AttrLoc, DiagID: diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
5250 return;
5251 }
5252
5253 if (ComplexMode) {
5254 NewElemTy = Context.getComplexType(T: NewElemTy);
5255 }
5256
5257 QualType NewTy = NewElemTy;
5258 if (VectorSize.getBoolValue()) {
5259 NewTy = Context.getVectorType(VectorType: NewTy, NumElts: VectorSize.getZExtValue(),
5260 VecKind: VectorKind::Generic);
5261 } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
5262 // Complex machine mode does not support base vector types.
5263 if (ComplexMode) {
5264 Diag(Loc: AttrLoc, DiagID: diag::err_complex_mode_vector_type);
5265 return;
5266 }
5267 unsigned NumElements = Context.getTypeSize(T: OldElemTy) *
5268 OldVT->getNumElements() /
5269 Context.getTypeSize(T: NewElemTy);
5270 NewTy =
5271 Context.getVectorType(VectorType: NewElemTy, NumElts: NumElements, VecKind: OldVT->getVectorKind());
5272 }
5273
5274 if (NewTy.isNull()) {
5275 Diag(Loc: AttrLoc, DiagID: diag::err_mode_wrong_type);
5276 return;
5277 }
5278
5279 // Install the new type.
5280 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D))
5281 TD->setModedTypeSourceInfo(unmodedTSI: TD->getTypeSourceInfo(), modedTy: NewTy);
5282 else if (auto *ED = dyn_cast<EnumDecl>(Val: D))
5283 ED->setIntegerType(NewTy);
5284 else
5285 cast<ValueDecl>(Val: D)->setType(NewTy);
5286
5287 D->addAttr(A: ::new (Context) ModeAttr(Context, CI, Name));
5288}
5289
5290static void handleNonStringAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5291 // This only applies to fields and variable declarations which have an array
5292 // type or pointer type, with character elements.
5293 QualType QT = cast<ValueDecl>(Val: D)->getType();
5294 if ((!QT->isArrayType() && !QT->isPointerType()) ||
5295 !QT->getPointeeOrArrayElementType()->isAnyCharacterType()) {
5296 S.Diag(Loc: D->getBeginLoc(), DiagID: diag::warn_attribute_non_character_array)
5297 << AL << AL.isRegularKeywordAttribute() << QT << AL.getRange();
5298 return;
5299 }
5300
5301 D->addAttr(A: ::new (S.Context) NonStringAttr(S.Context, AL));
5302}
5303
5304static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5305 D->addAttr(A: ::new (S.Context) NoDebugAttr(S.Context, AL));
5306}
5307
5308AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D,
5309 const AttributeCommonInfo &CI,
5310 const IdentifierInfo *Ident) {
5311 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
5312 Diag(Loc: CI.getLoc(), DiagID: diag::warn_attribute_ignored) << Ident;
5313 Diag(Loc: Optnone->getLocation(), DiagID: diag::note_conflicting_attribute);
5314 return nullptr;
5315 }
5316
5317 if (D->hasAttr<AlwaysInlineAttr>())
5318 return nullptr;
5319
5320 return ::new (Context) AlwaysInlineAttr(Context, CI);
5321}
5322
5323InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
5324 const ParsedAttr &AL) {
5325 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
5326 // Attribute applies to Var but not any subclass of it (like ParmVar,
5327 // ImplicitParm or VarTemplateSpecialization).
5328 if (VD->getKind() != Decl::Var) {
5329 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_wrong_decl_type)
5330 << AL << AL.isRegularKeywordAttribute()
5331 << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
5332 : ExpectedVariableOrFunction);
5333 return nullptr;
5334 }
5335 // Attribute does not apply to non-static local variables.
5336 if (VD->hasLocalStorage()) {
5337 Diag(Loc: VD->getLocation(), DiagID: diag::warn_internal_linkage_local_storage);
5338 return nullptr;
5339 }
5340 }
5341
5342 return ::new (Context) InternalLinkageAttr(Context, AL);
5343}
5344InternalLinkageAttr *
5345Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
5346 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
5347 // Attribute applies to Var but not any subclass of it (like ParmVar,
5348 // ImplicitParm or VarTemplateSpecialization).
5349 if (VD->getKind() != Decl::Var) {
5350 Diag(Loc: AL.getLocation(), DiagID: diag::warn_attribute_wrong_decl_type)
5351 << &AL << AL.isRegularKeywordAttribute()
5352 << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
5353 : ExpectedVariableOrFunction);
5354 return nullptr;
5355 }
5356 // Attribute does not apply to non-static local variables.
5357 if (VD->hasLocalStorage()) {
5358 Diag(Loc: VD->getLocation(), DiagID: diag::warn_internal_linkage_local_storage);
5359 return nullptr;
5360 }
5361 }
5362
5363 return ::new (Context) InternalLinkageAttr(Context, AL);
5364}
5365
5366MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI) {
5367 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
5368 Diag(Loc: CI.getLoc(), DiagID: diag::warn_attribute_ignored) << "'minsize'";
5369 Diag(Loc: Optnone->getLocation(), DiagID: diag::note_conflicting_attribute);
5370 return nullptr;
5371 }
5372
5373 if (D->hasAttr<MinSizeAttr>())
5374 return nullptr;
5375
5376 return ::new (Context) MinSizeAttr(Context, CI);
5377}
5378
5379OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D,
5380 const AttributeCommonInfo &CI) {
5381 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
5382 Diag(Loc: Inline->getLocation(), DiagID: diag::warn_attribute_ignored) << Inline;
5383 Diag(Loc: CI.getLoc(), DiagID: diag::note_conflicting_attribute);
5384 D->dropAttr<AlwaysInlineAttr>();
5385 }
5386 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
5387 Diag(Loc: MinSize->getLocation(), DiagID: diag::warn_attribute_ignored) << MinSize;
5388 Diag(Loc: CI.getLoc(), DiagID: diag::note_conflicting_attribute);
5389 D->dropAttr<MinSizeAttr>();
5390 }
5391
5392 if (D->hasAttr<OptimizeNoneAttr>())
5393 return nullptr;
5394
5395 return ::new (Context) OptimizeNoneAttr(Context, CI);
5396}
5397
5398static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5399 AlwaysInlineAttr AIA(S.Context, AL);
5400 if (!S.getLangOpts().MicrosoftExt &&
5401 (AIA.isMSVCForceInline() || AIA.isMSVCForceInlineCalls())) {
5402 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_ignored) << AL;
5403 return;
5404 }
5405 if (AIA.isMSVCForceInlineCalls()) {
5406 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_stmt_attribute_ignored_in_function)
5407 << "[[msvc::forceinline]]";
5408 return;
5409 }
5410
5411 if (AlwaysInlineAttr *Inline =
5412 S.mergeAlwaysInlineAttr(D, CI: AL, Ident: AL.getAttrName()))
5413 D->addAttr(A: Inline);
5414}
5415
5416static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5417 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(D, CI: AL))
5418 D->addAttr(A: MinSize);
5419}
5420
5421static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5422 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(D, CI: AL))
5423 D->addAttr(A: Optnone);
5424}
5425
5426static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5427 const auto *VD = cast<VarDecl>(Val: D);
5428 if (VD->hasLocalStorage()) {
5429 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_cuda_nonstatic_constdev);
5430 return;
5431 }
5432 if (!S.CheckVarDeclSizeAddressSpace(VD, AS: LangAS::cuda_constant))
5433 return;
5434 // constexpr variable may already get an implicit constant attr, which should
5435 // be replaced by the explicit constant attr.
5436 if (auto *A = D->getAttr<CUDAConstantAttr>()) {
5437 if (!A->isImplicit())
5438 return;
5439 D->dropAttr<CUDAConstantAttr>();
5440 }
5441 D->addAttr(A: ::new (S.Context) CUDAConstantAttr(S.Context, AL));
5442}
5443
5444static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5445 const auto *VD = cast<VarDecl>(Val: D);
5446 // extern __shared__ is only allowed on arrays with no length (e.g.
5447 // "int x[]").
5448 if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
5449 !isa<IncompleteArrayType>(Val: VD->getType())) {
5450 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_cuda_extern_shared) << VD;
5451 return;
5452 }
5453 if (!S.CheckVarDeclSizeAddressSpace(VD, AS: LangAS::cuda_shared))
5454 return;
5455 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
5456 S.CUDA().DiagIfHostCode(Loc: AL.getLoc(), DiagID: diag::err_cuda_host_shared)
5457 << S.CUDA().CurrentTarget())
5458 return;
5459 D->addAttr(A: ::new (S.Context) CUDASharedAttr(S.Context, AL));
5460}
5461
5462static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5463 const auto *FD = cast<FunctionDecl>(Val: D);
5464 if (!FD->getReturnType()->isVoidType() &&
5465 !FD->getReturnType()->getAs<AutoType>() &&
5466 !FD->getReturnType()->isInstantiationDependentType()) {
5467 SourceRange RTRange = FD->getReturnTypeSourceRange();
5468 S.Diag(Loc: FD->getTypeSpecStartLoc(), DiagID: diag::err_kern_type_not_void_return)
5469 << FD->getType()
5470 << (RTRange.isValid() ? FixItHint::CreateReplacement(RemoveRange: RTRange, Code: "void")
5471 : FixItHint());
5472 return;
5473 }
5474 if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: FD)) {
5475 if (Method->isInstance()) {
5476 S.Diag(Loc: Method->getBeginLoc(), DiagID: diag::err_kern_is_nonstatic_method)
5477 << Method;
5478 return;
5479 }
5480 S.Diag(Loc: Method->getBeginLoc(), DiagID: diag::warn_kern_is_method) << Method;
5481 }
5482 // Only warn for "inline" when compiling for host, to cut down on noise.
5483 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
5484 S.Diag(Loc: FD->getBeginLoc(), DiagID: diag::warn_kern_is_inline) << FD;
5485
5486 switch (AL.getKind()) {
5487 case ParsedAttr::AT_DeviceKernel:
5488 if (!D->hasAttr<DeviceKernelAttr>())
5489 D->addAttr(A: ::new (S.Context) DeviceKernelAttr(S.Context, AL));
5490 break;
5491 case ParsedAttr::AT_CUDAGlobal:
5492 if (!D->hasAttr<CUDAGlobalAttr>())
5493 D->addAttr(A: ::new (S.Context) CUDAGlobalAttr(S.Context, AL));
5494 break;
5495 default:
5496 llvm_unreachable("Unexpected attribute kind");
5497 }
5498 // In host compilation the kernel is emitted as a stub function, which is
5499 // a helper function for launching the kernel. The instructions in the helper
5500 // function has nothing to do with the source code of the kernel. Do not emit
5501 // debug info for the stub function to avoid confusing the debugger.
5502 if (S.LangOpts.HIP && !S.LangOpts.CUDAIsDevice && !D->hasAttr<NoDebugAttr>())
5503 D->addAttr(A: NoDebugAttr::CreateImplicit(Ctx&: S.Context));
5504}
5505
5506static void handleDeviceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5507 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
5508 if (VD->hasLocalStorage()) {
5509 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_cuda_nonstatic_constdev);
5510 return;
5511 }
5512 if (!S.CheckVarDeclSizeAddressSpace(VD, AS: LangAS::cuda_device))
5513 return;
5514 }
5515
5516 if (auto *A = D->getAttr<CUDADeviceAttr>()) {
5517 if (!A->isImplicit())
5518 return;
5519 D->dropAttr<CUDADeviceAttr>();
5520 }
5521 D->addAttr(A: ::new (S.Context) CUDADeviceAttr(S.Context, AL));
5522}
5523
5524static void handleManagedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5525 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
5526 if (VD->hasLocalStorage()) {
5527 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_cuda_nonstatic_constdev);
5528 return;
5529 }
5530 if (!S.CheckVarDeclSizeAddressSpace(VD, AS: LangAS::cuda_device))
5531 return;
5532 }
5533 if (!D->hasAttr<HIPManagedAttr>())
5534 D->addAttr(A: ::new (S.Context) HIPManagedAttr(S.Context, AL));
5535 if (!D->hasAttr<CUDADeviceAttr>())
5536 D->addAttr(A: CUDADeviceAttr::CreateImplicit(Ctx&: S.Context));
5537}
5538
5539static void handleGridConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5540 if (D->isInvalidDecl())
5541 return;
5542 // Whether __grid_constant__ is allowed to be used will be checked in
5543 // Sema::CheckFunctionDeclaration as we need complete function decl to make
5544 // the call.
5545 D->addAttr(A: ::new (S.Context) CUDAGridConstantAttr(S.Context, AL));
5546}
5547
5548static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5549 const auto *Fn = cast<FunctionDecl>(Val: D);
5550 if (!Fn->isInlineSpecified()) {
5551 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_gnu_inline_attribute_requires_inline);
5552 return;
5553 }
5554
5555 if (S.LangOpts.CPlusPlus && Fn->getStorageClass() != SC_Extern)
5556 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_gnu_inline_cplusplus_without_extern);
5557
5558 D->addAttr(A: ::new (S.Context) GNUInlineAttr(S.Context, AL));
5559}
5560
5561static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5562 if (hasDeclarator(D)) return;
5563
5564 // Diagnostic is emitted elsewhere: here we store the (valid) AL
5565 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
5566 CallingConv CC;
5567 if (S.CheckCallingConvAttr(
5568 attr: AL, CC, /*FD*/ nullptr,
5569 CFT: S.CUDA().IdentifyTarget(D: dyn_cast<FunctionDecl>(Val: D))))
5570 return;
5571
5572 if (!isa<ObjCMethodDecl>(Val: D)) {
5573 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_wrong_decl_type)
5574 << AL << AL.isRegularKeywordAttribute() << ExpectedFunctionOrMethod;
5575 return;
5576 }
5577
5578 switch (AL.getKind()) {
5579 case ParsedAttr::AT_FastCall:
5580 D->addAttr(A: ::new (S.Context) FastCallAttr(S.Context, AL));
5581 return;
5582 case ParsedAttr::AT_StdCall:
5583 D->addAttr(A: ::new (S.Context) StdCallAttr(S.Context, AL));
5584 return;
5585 case ParsedAttr::AT_ThisCall:
5586 D->addAttr(A: ::new (S.Context) ThisCallAttr(S.Context, AL));
5587 return;
5588 case ParsedAttr::AT_CDecl:
5589 D->addAttr(A: ::new (S.Context) CDeclAttr(S.Context, AL));
5590 return;
5591 case ParsedAttr::AT_Pascal:
5592 D->addAttr(A: ::new (S.Context) PascalAttr(S.Context, AL));
5593 return;
5594 case ParsedAttr::AT_SwiftCall:
5595 D->addAttr(A: ::new (S.Context) SwiftCallAttr(S.Context, AL));
5596 return;
5597 case ParsedAttr::AT_SwiftAsyncCall:
5598 D->addAttr(A: ::new (S.Context) SwiftAsyncCallAttr(S.Context, AL));
5599 return;
5600 case ParsedAttr::AT_VectorCall:
5601 D->addAttr(A: ::new (S.Context) VectorCallAttr(S.Context, AL));
5602 return;
5603 case ParsedAttr::AT_MSABI:
5604 D->addAttr(A: ::new (S.Context) MSABIAttr(S.Context, AL));
5605 return;
5606 case ParsedAttr::AT_SysVABI:
5607 D->addAttr(A: ::new (S.Context) SysVABIAttr(S.Context, AL));
5608 return;
5609 case ParsedAttr::AT_RegCall:
5610 D->addAttr(A: ::new (S.Context) RegCallAttr(S.Context, AL));
5611 return;
5612 case ParsedAttr::AT_Pcs: {
5613 PcsAttr::PCSType PCS;
5614 switch (CC) {
5615 case CC_AAPCS:
5616 PCS = PcsAttr::AAPCS;
5617 break;
5618 case CC_AAPCS_VFP:
5619 PCS = PcsAttr::AAPCS_VFP;
5620 break;
5621 default:
5622 llvm_unreachable("unexpected calling convention in pcs attribute");
5623 }
5624
5625 D->addAttr(A: ::new (S.Context) PcsAttr(S.Context, AL, PCS));
5626 return;
5627 }
5628 case ParsedAttr::AT_AArch64VectorPcs:
5629 D->addAttr(A: ::new (S.Context) AArch64VectorPcsAttr(S.Context, AL));
5630 return;
5631 case ParsedAttr::AT_AArch64SVEPcs:
5632 D->addAttr(A: ::new (S.Context) AArch64SVEPcsAttr(S.Context, AL));
5633 return;
5634 case ParsedAttr::AT_DeviceKernel: {
5635 // The attribute should already be applied.
5636 assert(D->hasAttr<DeviceKernelAttr>() && "Expected attribute");
5637 return;
5638 }
5639 case ParsedAttr::AT_IntelOclBicc:
5640 D->addAttr(A: ::new (S.Context) IntelOclBiccAttr(S.Context, AL));
5641 return;
5642 case ParsedAttr::AT_PreserveMost:
5643 D->addAttr(A: ::new (S.Context) PreserveMostAttr(S.Context, AL));
5644 return;
5645 case ParsedAttr::AT_PreserveAll:
5646 D->addAttr(A: ::new (S.Context) PreserveAllAttr(S.Context, AL));
5647 return;
5648 case ParsedAttr::AT_M68kRTD:
5649 D->addAttr(A: ::new (S.Context) M68kRTDAttr(S.Context, AL));
5650 return;
5651 case ParsedAttr::AT_PreserveNone:
5652 D->addAttr(A: ::new (S.Context) PreserveNoneAttr(S.Context, AL));
5653 return;
5654 case ParsedAttr::AT_RISCVVectorCC:
5655 D->addAttr(A: ::new (S.Context) RISCVVectorCCAttr(S.Context, AL));
5656 return;
5657 case ParsedAttr::AT_RISCVVLSCC: {
5658 // If the riscv_abi_vlen doesn't have any argument, default ABI_VLEN is 128.
5659 unsigned VectorLength = 128;
5660 if (AL.getNumArgs() &&
5661 !S.checkUInt32Argument(AI: AL, Expr: AL.getArgAsExpr(Arg: 0), Val&: VectorLength))
5662 return;
5663 if (VectorLength < 32 || VectorLength > 65536) {
5664 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_argument_invalid_range)
5665 << VectorLength << 32 << 65536;
5666 return;
5667 }
5668 if (!llvm::isPowerOf2_64(Value: VectorLength)) {
5669 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_argument_not_power_of_2);
5670 return;
5671 }
5672
5673 D->addAttr(A: ::new (S.Context) RISCVVLSCCAttr(S.Context, AL, VectorLength));
5674 return;
5675 }
5676 default:
5677 llvm_unreachable("unexpected attribute kind");
5678 }
5679}
5680
5681static void handleDeviceKernelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5682 const auto *FD = dyn_cast_or_null<FunctionDecl>(Val: D);
5683 bool IsFunctionTemplate = FD && FD->getDescribedFunctionTemplate();
5684 llvm::Triple Triple = S.getASTContext().getTargetInfo().getTriple();
5685 const LangOptions &LangOpts = S.getLangOpts();
5686 // OpenCL has its own error messages.
5687 if (!LangOpts.OpenCL && FD && !FD->isExternallyVisible()) {
5688 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_hidden_device_kernel) << FD;
5689 AL.setInvalid();
5690 return;
5691 }
5692 if (Triple.isNVPTX()) {
5693 handleGlobalAttr(S, D, AL);
5694 } else {
5695 // OpenCL C++ will throw a more specific error.
5696 if (!LangOpts.OpenCLCPlusPlus && (!FD || IsFunctionTemplate)) {
5697 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_wrong_decl_type_str)
5698 << AL << AL.isRegularKeywordAttribute() << "functions";
5699 AL.setInvalid();
5700 return;
5701 }
5702 handleSimpleAttribute<DeviceKernelAttr>(S, D, CI: AL);
5703 }
5704 // TODO: isGPU() should probably return true for SPIR.
5705 bool TargetDeviceEnvironment = Triple.isGPU() || Triple.isSPIR() ||
5706 LangOpts.isTargetDevice() || LangOpts.OpenCL;
5707 if (!TargetDeviceEnvironment) {
5708 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_cconv_unsupported)
5709 << AL << (int)Sema::CallingConventionIgnoredReason::ForThisTarget;
5710 AL.setInvalid();
5711 return;
5712 }
5713
5714 // Make sure we validate the CC with the target
5715 // and warn/error if necessary.
5716 handleCallConvAttr(S, D, AL);
5717}
5718
5719static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5720 if (AL.getAttributeSpellingListIndex() == SuppressAttr::CXX11_gsl_suppress) {
5721 // Suppression attribute with GSL spelling requires at least 1 argument.
5722 if (!AL.checkAtLeastNumArgs(S, Num: 1))
5723 return;
5724 }
5725
5726 std::vector<StringRef> DiagnosticIdentifiers;
5727 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
5728 StringRef RuleName;
5729
5730 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: I, Str&: RuleName, ArgLocation: nullptr))
5731 return;
5732
5733 DiagnosticIdentifiers.push_back(x: RuleName);
5734 }
5735 D->addAttr(A: ::new (S.Context)
5736 SuppressAttr(S.Context, AL, DiagnosticIdentifiers.data(),
5737 DiagnosticIdentifiers.size()));
5738}
5739
5740static void handleLifetimeCategoryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5741 TypeSourceInfo *DerefTypeLoc = nullptr;
5742 QualType ParmType;
5743 if (AL.hasParsedType()) {
5744 ParmType = S.GetTypeFromParser(Ty: AL.getTypeArg(), TInfo: &DerefTypeLoc);
5745
5746 unsigned SelectIdx = ~0U;
5747 if (ParmType->isReferenceType())
5748 SelectIdx = 0;
5749 else if (ParmType->isArrayType())
5750 SelectIdx = 1;
5751
5752 if (SelectIdx != ~0U) {
5753 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_invalid_argument)
5754 << SelectIdx << AL;
5755 return;
5756 }
5757 }
5758
5759 // To check if earlier decl attributes do not conflict the newly parsed ones
5760 // we always add (and check) the attribute to the canonical decl. We need
5761 // to repeat the check for attribute mutual exclusion because we're attaching
5762 // all of the attributes to the canonical declaration rather than the current
5763 // declaration.
5764 D = D->getCanonicalDecl();
5765 if (AL.getKind() == ParsedAttr::AT_Owner) {
5766 if (checkAttrMutualExclusion<PointerAttr>(S, D, AL))
5767 return;
5768 if (const auto *OAttr = D->getAttr<OwnerAttr>()) {
5769 const Type *ExistingDerefType = OAttr->getDerefTypeLoc()
5770 ? OAttr->getDerefType().getTypePtr()
5771 : nullptr;
5772 if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
5773 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attributes_are_not_compatible)
5774 << AL << OAttr
5775 << (AL.isRegularKeywordAttribute() ||
5776 OAttr->isRegularKeywordAttribute());
5777 S.Diag(Loc: OAttr->getLocation(), DiagID: diag::note_conflicting_attribute);
5778 }
5779 return;
5780 }
5781 for (Decl *Redecl : D->redecls()) {
5782 Redecl->addAttr(A: ::new (S.Context) OwnerAttr(S.Context, AL, DerefTypeLoc));
5783 }
5784 } else {
5785 if (checkAttrMutualExclusion<OwnerAttr>(S, D, AL))
5786 return;
5787 if (const auto *PAttr = D->getAttr<PointerAttr>()) {
5788 const Type *ExistingDerefType = PAttr->getDerefTypeLoc()
5789 ? PAttr->getDerefType().getTypePtr()
5790 : nullptr;
5791 if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
5792 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attributes_are_not_compatible)
5793 << AL << PAttr
5794 << (AL.isRegularKeywordAttribute() ||
5795 PAttr->isRegularKeywordAttribute());
5796 S.Diag(Loc: PAttr->getLocation(), DiagID: diag::note_conflicting_attribute);
5797 }
5798 return;
5799 }
5800 for (Decl *Redecl : D->redecls()) {
5801 Redecl->addAttr(A: ::new (S.Context)
5802 PointerAttr(S.Context, AL, DerefTypeLoc));
5803 }
5804 }
5805}
5806
5807static void handleRandomizeLayoutAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5808 if (checkAttrMutualExclusion<NoRandomizeLayoutAttr>(S, D, AL))
5809 return;
5810 if (!D->hasAttr<RandomizeLayoutAttr>())
5811 D->addAttr(A: ::new (S.Context) RandomizeLayoutAttr(S.Context, AL));
5812}
5813
5814static void handleNoRandomizeLayoutAttr(Sema &S, Decl *D,
5815 const ParsedAttr &AL) {
5816 if (checkAttrMutualExclusion<RandomizeLayoutAttr>(S, D, AL))
5817 return;
5818 if (!D->hasAttr<NoRandomizeLayoutAttr>())
5819 D->addAttr(A: ::new (S.Context) NoRandomizeLayoutAttr(S.Context, AL));
5820}
5821
5822bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC,
5823 const FunctionDecl *FD,
5824 CUDAFunctionTarget CFT) {
5825 if (Attrs.isInvalid())
5826 return true;
5827
5828 if (Attrs.hasProcessingCache()) {
5829 CC = (CallingConv) Attrs.getProcessingCache();
5830 return false;
5831 }
5832
5833 if (Attrs.getKind() == ParsedAttr::AT_RISCVVLSCC) {
5834 // riscv_vls_cc only accepts 0 or 1 argument.
5835 if (!Attrs.checkAtLeastNumArgs(S&: *this, Num: 0) ||
5836 !Attrs.checkAtMostNumArgs(S&: *this, Num: 1)) {
5837 Attrs.setInvalid();
5838 return true;
5839 }
5840 } else {
5841 unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
5842 if (!Attrs.checkExactlyNumArgs(S&: *this, Num: ReqArgs)) {
5843 Attrs.setInvalid();
5844 return true;
5845 }
5846 }
5847
5848 bool IsTargetDefaultMSABI =
5849 Context.getTargetInfo().getTriple().isOSWindows() ||
5850 Context.getTargetInfo().getTriple().isUEFI();
5851 // TODO: diagnose uses of these conventions on the wrong target.
5852 switch (Attrs.getKind()) {
5853 case ParsedAttr::AT_CDecl:
5854 CC = CC_C;
5855 break;
5856 case ParsedAttr::AT_FastCall:
5857 CC = CC_X86FastCall;
5858 break;
5859 case ParsedAttr::AT_StdCall:
5860 CC = CC_X86StdCall;
5861 break;
5862 case ParsedAttr::AT_ThisCall:
5863 CC = CC_X86ThisCall;
5864 break;
5865 case ParsedAttr::AT_Pascal:
5866 CC = CC_X86Pascal;
5867 break;
5868 case ParsedAttr::AT_SwiftCall:
5869 CC = CC_Swift;
5870 break;
5871 case ParsedAttr::AT_SwiftAsyncCall:
5872 CC = CC_SwiftAsync;
5873 break;
5874 case ParsedAttr::AT_VectorCall:
5875 CC = CC_X86VectorCall;
5876 break;
5877 case ParsedAttr::AT_AArch64VectorPcs:
5878 CC = CC_AArch64VectorCall;
5879 break;
5880 case ParsedAttr::AT_AArch64SVEPcs:
5881 CC = CC_AArch64SVEPCS;
5882 break;
5883 case ParsedAttr::AT_RegCall:
5884 CC = CC_X86RegCall;
5885 break;
5886 case ParsedAttr::AT_MSABI:
5887 CC = IsTargetDefaultMSABI ? CC_C : CC_Win64;
5888 break;
5889 case ParsedAttr::AT_SysVABI:
5890 CC = IsTargetDefaultMSABI ? CC_X86_64SysV : CC_C;
5891 break;
5892 case ParsedAttr::AT_Pcs: {
5893 StringRef StrRef;
5894 if (!checkStringLiteralArgumentAttr(AL: Attrs, ArgNum: 0, Str&: StrRef)) {
5895 Attrs.setInvalid();
5896 return true;
5897 }
5898 if (StrRef == "aapcs") {
5899 CC = CC_AAPCS;
5900 break;
5901 } else if (StrRef == "aapcs-vfp") {
5902 CC = CC_AAPCS_VFP;
5903 break;
5904 }
5905
5906 Attrs.setInvalid();
5907 Diag(Loc: Attrs.getLoc(), DiagID: diag::err_invalid_pcs);
5908 return true;
5909 }
5910 case ParsedAttr::AT_IntelOclBicc:
5911 CC = CC_IntelOclBicc;
5912 break;
5913 case ParsedAttr::AT_PreserveMost:
5914 CC = CC_PreserveMost;
5915 break;
5916 case ParsedAttr::AT_PreserveAll:
5917 CC = CC_PreserveAll;
5918 break;
5919 case ParsedAttr::AT_M68kRTD:
5920 CC = CC_M68kRTD;
5921 break;
5922 case ParsedAttr::AT_PreserveNone:
5923 CC = CC_PreserveNone;
5924 break;
5925 case ParsedAttr::AT_RISCVVectorCC:
5926 CC = CC_RISCVVectorCall;
5927 break;
5928 case ParsedAttr::AT_RISCVVLSCC: {
5929 // If the riscv_abi_vlen doesn't have any argument, we set set it to default
5930 // value 128.
5931 unsigned ABIVLen = 128;
5932 if (Attrs.getNumArgs() &&
5933 !checkUInt32Argument(AI: Attrs, Expr: Attrs.getArgAsExpr(Arg: 0), Val&: ABIVLen)) {
5934 Attrs.setInvalid();
5935 return true;
5936 }
5937 if (Attrs.getNumArgs() && (ABIVLen < 32 || ABIVLen > 65536)) {
5938 Attrs.setInvalid();
5939 Diag(Loc: Attrs.getLoc(), DiagID: diag::err_argument_invalid_range)
5940 << ABIVLen << 32 << 65536;
5941 return true;
5942 }
5943 if (!llvm::isPowerOf2_64(Value: ABIVLen)) {
5944 Attrs.setInvalid();
5945 Diag(Loc: Attrs.getLoc(), DiagID: diag::err_argument_not_power_of_2);
5946 return true;
5947 }
5948 CC = static_cast<CallingConv>(CallingConv::CC_RISCVVLSCall_32 +
5949 llvm::Log2_64(Value: ABIVLen) - 5);
5950 break;
5951 }
5952 case ParsedAttr::AT_DeviceKernel: {
5953 // Validation was handled in handleDeviceKernelAttr.
5954 CC = CC_DeviceKernel;
5955 break;
5956 }
5957 default: llvm_unreachable("unexpected attribute kind");
5958 }
5959
5960 TargetInfo::CallingConvCheckResult A = TargetInfo::CCCR_OK;
5961 const TargetInfo &TI = Context.getTargetInfo();
5962 auto *Aux = Context.getAuxTargetInfo();
5963 // CUDA functions may have host and/or device attributes which indicate
5964 // their targeted execution environment, therefore the calling convention
5965 // of functions in CUDA should be checked against the target deduced based
5966 // on their host/device attributes.
5967 if (LangOpts.CUDA) {
5968 assert(FD || CFT != CUDAFunctionTarget::InvalidTarget);
5969 auto CudaTarget = FD ? CUDA().IdentifyTarget(D: FD) : CFT;
5970 bool CheckHost = false, CheckDevice = false;
5971 switch (CudaTarget) {
5972 case CUDAFunctionTarget::HostDevice:
5973 CheckHost = true;
5974 CheckDevice = true;
5975 break;
5976 case CUDAFunctionTarget::Host:
5977 CheckHost = true;
5978 break;
5979 case CUDAFunctionTarget::Device:
5980 case CUDAFunctionTarget::Global:
5981 CheckDevice = true;
5982 break;
5983 case CUDAFunctionTarget::InvalidTarget:
5984 llvm_unreachable("unexpected cuda target");
5985 }
5986 auto *HostTI = LangOpts.CUDAIsDevice ? Aux : &TI;
5987 auto *DeviceTI = LangOpts.CUDAIsDevice ? &TI : Aux;
5988 if (CheckHost && HostTI)
5989 A = HostTI->checkCallingConvention(CC);
5990 if (A == TargetInfo::CCCR_OK && CheckDevice && DeviceTI)
5991 A = DeviceTI->checkCallingConvention(CC);
5992 } else if (LangOpts.SYCLIsDevice) {
5993 // During device compilation, calling conventions that are valid for the
5994 // host, for the device, and for both the host and the device may be
5995 // encountered. Diagnostics are desired for cases where the calling
5996 // convention is not supported by either the host or the device. If Aux is
5997 // null (which should rarely be the case), it isn't possible to check
5998 // whether the calling convention is supported by the host, so just assume
5999 // that it is. If the calling convention is supported for the device, there
6000 // is no need to check the host; the device target gets priority since this
6001 // check is only performed during device compilation.
6002 A = TI.checkCallingConvention(CC);
6003 if (Aux && A == TargetInfo::CCCR_Warning) {
6004 // If the calling convention would provoke a warning for the device, check
6005 // the host and preserve the warning only if the calling convention would
6006 // provoke an error for the host. Otherwise, assume this calling
6007 // convention is only used for host only functions.
6008 A = Aux->checkCallingConvention(CC);
6009 if (A == TargetInfo::CCCR_Error)
6010 A = TargetInfo::CCCR_Warning;
6011 } else if (Aux && A == TargetInfo::CCCR_Error) {
6012 // Assume this calling convention is only used for host only functions.
6013 A = Aux->checkCallingConvention(CC);
6014 }
6015 } else {
6016 A = TI.checkCallingConvention(CC);
6017 }
6018
6019 switch (A) {
6020 case TargetInfo::CCCR_OK:
6021 break;
6022
6023 case TargetInfo::CCCR_Ignore:
6024 // Treat an ignored convention as if it was an explicit C calling convention
6025 // attribute. For example, __stdcall on Win x64 functions as __cdecl, so
6026 // that command line flags that change the default convention to
6027 // __vectorcall don't affect declarations marked __stdcall.
6028 CC = CC_C;
6029 break;
6030
6031 case TargetInfo::CCCR_Error:
6032 Diag(Loc: Attrs.getLoc(), DiagID: diag::error_cconv_unsupported)
6033 << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
6034 break;
6035
6036 case TargetInfo::CCCR_Warning: {
6037 Diag(Loc: Attrs.getLoc(), DiagID: diag::warn_cconv_unsupported)
6038 << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
6039
6040 // This convention is not valid for the target. Use the default function or
6041 // method calling convention.
6042 bool IsCXXMethod = false, IsVariadic = false;
6043 if (FD) {
6044 IsCXXMethod = FD->isCXXInstanceMember();
6045 IsVariadic = FD->isVariadic();
6046 }
6047 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
6048 break;
6049 }
6050 }
6051
6052 Attrs.setProcessingCache((unsigned) CC);
6053 return false;
6054}
6055
6056bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) {
6057 if (AL.isInvalid())
6058 return true;
6059
6060 if (!AL.checkExactlyNumArgs(S&: *this, Num: 1)) {
6061 AL.setInvalid();
6062 return true;
6063 }
6064
6065 uint32_t NP;
6066 Expr *NumParamsExpr = AL.getArgAsExpr(Arg: 0);
6067 if (!checkUInt32Argument(AI: AL, Expr: NumParamsExpr, Val&: NP)) {
6068 AL.setInvalid();
6069 return true;
6070 }
6071
6072 if (Context.getTargetInfo().getRegParmMax() == 0) {
6073 Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_regparm_wrong_platform)
6074 << NumParamsExpr->getSourceRange();
6075 AL.setInvalid();
6076 return true;
6077 }
6078
6079 numParams = NP;
6080 if (numParams > Context.getTargetInfo().getRegParmMax()) {
6081 Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_regparm_invalid_number)
6082 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
6083 AL.setInvalid();
6084 return true;
6085 }
6086
6087 return false;
6088}
6089
6090// Helper to get OffloadArch.
6091static OffloadArch getOffloadArch(const TargetInfo &TI) {
6092 if (!TI.getTriple().isNVPTX())
6093 llvm_unreachable("getOffloadArch is only valid for NVPTX triple");
6094 auto &TO = TI.getTargetOpts();
6095 return StringToOffloadArch(S: TO.CPU);
6096}
6097
6098// Checks whether an argument of launch_bounds attribute is
6099// acceptable, performs implicit conversion to Rvalue, and returns
6100// non-nullptr Expr result on success. Otherwise, it returns nullptr
6101// and may output an error.
6102static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
6103 const CUDALaunchBoundsAttr &AL,
6104 const unsigned Idx) {
6105 if (S.DiagnoseUnexpandedParameterPack(E))
6106 return nullptr;
6107
6108 // Accept template arguments for now as they depend on something else.
6109 // We'll get to check them when they eventually get instantiated.
6110 if (E->isValueDependent())
6111 return E;
6112
6113 std::optional<llvm::APSInt> I = llvm::APSInt(64);
6114 if (!(I = E->getIntegerConstantExpr(Ctx: S.Context))) {
6115 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_attribute_argument_n_type)
6116 << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
6117 return nullptr;
6118 }
6119 // Make sure we can fit it in 32 bits.
6120 if (!I->isIntN(N: 32)) {
6121 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_ice_too_large)
6122 << toString(I: *I, Radix: 10, Signed: false) << 32 << /* Unsigned */ 1;
6123 return nullptr;
6124 }
6125 if (*I < 0)
6126 S.Diag(Loc: E->getExprLoc(), DiagID: diag::warn_attribute_argument_n_negative)
6127 << &AL << Idx << E->getSourceRange();
6128
6129 // We may need to perform implicit conversion of the argument.
6130 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6131 Context&: S.Context, Type: S.Context.getConstType(T: S.Context.IntTy), /*consume*/ Consumed: false);
6132 ExprResult ValArg = S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: E);
6133 assert(!ValArg.isInvalid() &&
6134 "Unexpected PerformCopyInitialization() failure.");
6135
6136 return ValArg.getAs<Expr>();
6137}
6138
6139CUDALaunchBoundsAttr *
6140Sema::CreateLaunchBoundsAttr(const AttributeCommonInfo &CI, Expr *MaxThreads,
6141 Expr *MinBlocks, Expr *MaxBlocks,
6142 bool IgnoreArch) {
6143 CUDALaunchBoundsAttr TmpAttr(Context, CI, MaxThreads, MinBlocks, MaxBlocks);
6144 MaxThreads = makeLaunchBoundsArgExpr(S&: *this, E: MaxThreads, AL: TmpAttr, Idx: 0);
6145 if (!MaxThreads)
6146 return nullptr;
6147
6148 if (MinBlocks) {
6149 MinBlocks = makeLaunchBoundsArgExpr(S&: *this, E: MinBlocks, AL: TmpAttr, Idx: 1);
6150 if (!MinBlocks)
6151 return nullptr;
6152 }
6153
6154 if (MaxBlocks) {
6155 // We might want to ignore the nvptx arch check, e.g., when processing the
6156 // launch bounds attribute within ompx_attribute to support other archs.
6157 if (!IgnoreArch) {
6158 const TargetInfo &DeviceTI =
6159 (!Context.getLangOpts().CUDAIsDevice && Context.getAuxTargetInfo())
6160 ? *Context.getAuxTargetInfo()
6161 : Context.getTargetInfo();
6162 if (DeviceTI.getTriple().isNVPTX()) {
6163 // '.maxclusterrank' ptx directive requires .target sm_90 or higher.
6164 OffloadArch SM = getOffloadArch(TI: DeviceTI);
6165 if (SM.isUnknown() || llvm::NVPTX::getSmVersion(Kind: SM.nvptxKind()) < 900) {
6166 Diag(Loc: MaxBlocks->getBeginLoc(), DiagID: diag::warn_cuda_maxclusterrank_sm_90)
6167 << OffloadArchToString(A: SM) << CI << MaxBlocks->getSourceRange();
6168 // Ignore it by setting MaxBlocks to null;
6169 MaxBlocks = nullptr;
6170 }
6171 } else {
6172 // maxclusterrank is only handled for NVPTX; ignore it elsewhere.
6173 // TODO: Interpret this for AMDGPU with the "clusters" subtarget
6174 // feature.
6175 MaxBlocks = nullptr;
6176 }
6177 }
6178
6179 if (MaxBlocks) {
6180 MaxBlocks = makeLaunchBoundsArgExpr(S&: *this, E: MaxBlocks, AL: TmpAttr, Idx: 2);
6181 if (!MaxBlocks)
6182 return nullptr;
6183 }
6184 }
6185
6186 return ::new (Context)
6187 CUDALaunchBoundsAttr(Context, CI, MaxThreads, MinBlocks, MaxBlocks);
6188}
6189
6190void Sema::AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
6191 Expr *MaxThreads, Expr *MinBlocks,
6192 Expr *MaxBlocks) {
6193 if (auto *Attr = CreateLaunchBoundsAttr(CI, MaxThreads, MinBlocks, MaxBlocks))
6194 D->addAttr(A: Attr);
6195}
6196
6197static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6198 if (!AL.checkAtLeastNumArgs(S, Num: 1) || !AL.checkAtMostNumArgs(S, Num: 3))
6199 return;
6200
6201 S.AddLaunchBoundsAttr(D, CI: AL, MaxThreads: AL.getArgAsExpr(Arg: 0),
6202 MinBlocks: AL.getNumArgs() > 1 ? AL.getArgAsExpr(Arg: 1) : nullptr,
6203 MaxBlocks: AL.getNumArgs() > 2 ? AL.getArgAsExpr(Arg: 2) : nullptr);
6204}
6205
6206static std::pair<Expr *, int>
6207makeClusterDimsArgExpr(Sema &S, Expr *E, const CUDAClusterDimsAttr &AL,
6208 const unsigned Idx) {
6209 if (!E)
6210 return {nullptr, 1};
6211
6212 if (S.DiagnoseUnexpandedParameterPack(E))
6213 return {};
6214
6215 // Accept template arguments for now as they depend on something else.
6216 // We'll get to check them when they eventually get instantiated.
6217 if (E->isInstantiationDependent())
6218 return {E, 1};
6219
6220 std::optional<llvm::APSInt> I = E->getIntegerConstantExpr(Ctx: S.Context);
6221 if (!I) {
6222 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_attribute_argument_n_type)
6223 << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
6224 return {};
6225 }
6226 if (*I < 0) {
6227 S.Diag(Loc: E->getExprLoc(), DiagID: diag::warn_attribute_argument_n_negative)
6228 << &AL << Idx << E->getSourceRange();
6229 return {};
6230 }
6231 // Make sure we can fit it in 8 bits, so the product below cannot overflow.
6232 if (!I->isIntN(N: 8)) {
6233 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_ice_too_large)
6234 << toString(I: *I, Radix: 10, Signed: false) << 8 << /*Unsigned=*/1;
6235 return {};
6236 }
6237
6238 ExprResult Result = S.DefaultLvalueConversion(E);
6239 if (!Result.isUsable())
6240 return {};
6241
6242 return {ConstantExpr::Create(Context: S.getASTContext(), E: Result.get(), Result: APValue(*I)),
6243 I->getZExtValue()};
6244}
6245
6246CUDAClusterDimsAttr *Sema::createClusterDimsAttr(const AttributeCommonInfo &CI,
6247 Expr *X, Expr *Y, Expr *Z) {
6248 CUDAClusterDimsAttr TmpAttr(Context, CI, X, Y, Z);
6249
6250 auto [NewX, ValX] = makeClusterDimsArgExpr(S&: *this, E: X, AL: TmpAttr, /*Idx=*/0);
6251 auto [NewY, ValY] = makeClusterDimsArgExpr(S&: *this, E: Y, AL: TmpAttr, /*Idx=*/1);
6252 auto [NewZ, ValZ] = makeClusterDimsArgExpr(S&: *this, E: Z, AL: TmpAttr, /*Idx=*/2);
6253
6254 if (!NewX || (Y && !NewY) || (Z && !NewZ))
6255 return nullptr;
6256
6257 int FlatDim = ValX * ValY * ValZ;
6258 const llvm::Triple TT =
6259 (!Context.getLangOpts().CUDAIsDevice && Context.getAuxTargetInfo())
6260 ? Context.getAuxTargetInfo()->getTriple()
6261 : Context.getTargetInfo().getTriple();
6262 int MaxDim = 1;
6263 if (TT.isNVPTX())
6264 MaxDim = 8;
6265 else if (TT.isAMDGPU())
6266 MaxDim = 16;
6267 else
6268 return nullptr;
6269
6270 // A maximum of 8 thread blocks in a cluster is supported as a portable
6271 // cluster size in CUDA. The number is 16 for AMDGPU.
6272 if (FlatDim > MaxDim) {
6273 Diag(Loc: CI.getLoc(), DiagID: diag::err_cluster_dims_too_large) << MaxDim << FlatDim;
6274 return nullptr;
6275 }
6276
6277 return CUDAClusterDimsAttr::Create(Ctx&: Context, X: NewX, Y: NewY, Z: NewZ, CommonInfo: CI);
6278}
6279
6280void Sema::addClusterDimsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *X,
6281 Expr *Y, Expr *Z) {
6282 if (auto *Attr = createClusterDimsAttr(CI, X, Y, Z))
6283 D->addAttr(A: Attr);
6284}
6285
6286void Sema::addNoClusterAttr(Decl *D, const AttributeCommonInfo &CI) {
6287 D->addAttr(A: CUDANoClusterAttr::Create(Ctx&: Context, CommonInfo: CI));
6288}
6289
6290static void handleClusterDimsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6291 const TargetInfo &TTI = S.Context.getTargetInfo();
6292 OffloadArch Arch = StringToOffloadArch(S: TTI.getTargetOpts().CPU);
6293 if ((TTI.getTriple().isNVPTX() &&
6294 llvm::NVPTX::getSmVersion(Kind: Arch.nvptxKind()) < 900) ||
6295 (TTI.getTriple().isAMDGPU() &&
6296 !TTI.hasFeatureEnabled(Features: TTI.getTargetOpts().FeatureMap, Name: "clusters"))) {
6297 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_cluster_attr_not_supported) << AL;
6298 return;
6299 }
6300
6301 if (!AL.checkAtLeastNumArgs(S, /*Num=*/1) ||
6302 !AL.checkAtMostNumArgs(S, /*Num=*/3))
6303 return;
6304
6305 S.addClusterDimsAttr(D, CI: AL, X: AL.getArgAsExpr(Arg: 0),
6306 Y: AL.getNumArgs() > 1 ? AL.getArgAsExpr(Arg: 1) : nullptr,
6307 Z: AL.getNumArgs() > 2 ? AL.getArgAsExpr(Arg: 2) : nullptr);
6308}
6309
6310static void handleNoClusterAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6311 const TargetInfo &TTI = S.Context.getTargetInfo();
6312 OffloadArch Arch = StringToOffloadArch(S: TTI.getTargetOpts().CPU);
6313 if ((TTI.getTriple().isNVPTX() &&
6314 llvm::NVPTX::getSmVersion(Kind: Arch.nvptxKind()) < 900) ||
6315 (TTI.getTriple().isAMDGPU() &&
6316 !TTI.hasFeatureEnabled(Features: TTI.getTargetOpts().FeatureMap, Name: "clusters"))) {
6317 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_cluster_attr_not_supported) << AL;
6318 return;
6319 }
6320
6321 S.addNoClusterAttr(D, CI: AL);
6322}
6323
6324static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
6325 const ParsedAttr &AL) {
6326 if (!AL.isArgIdent(Arg: 0)) {
6327 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_n_type)
6328 << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier;
6329 return;
6330 }
6331
6332 ParamIdx ArgumentIdx;
6333 if (!S.checkFunctionOrMethodParameterIndex(
6334 D, AI: AL, AttrArgNum: 2, IdxExpr: AL.getArgAsExpr(Arg: 1), Idx&: ArgumentIdx,
6335 /*CanIndexImplicitThis=*/false,
6336 /*CanIndexVariadicArguments=*/true))
6337 return;
6338
6339 ParamIdx TypeTagIdx;
6340 if (!S.checkFunctionOrMethodParameterIndex(
6341 D, AI: AL, AttrArgNum: 3, IdxExpr: AL.getArgAsExpr(Arg: 2), Idx&: TypeTagIdx,
6342 /*CanIndexImplicitThis=*/false,
6343 /*CanIndexVariadicArguments=*/true))
6344 return;
6345
6346 bool IsPointer = AL.getAttrName()->getName() == "pointer_with_type_tag";
6347 if (IsPointer) {
6348 // Ensure that buffer has a pointer type.
6349 unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex();
6350 if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) ||
6351 !getFunctionOrMethodParamType(D, Idx: ArgumentIdxAST)->isPointerType())
6352 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_pointers_only) << AL << 0;
6353 }
6354
6355 D->addAttr(A: ::new (S.Context) ArgumentWithTypeTagAttr(
6356 S.Context, AL, AL.getArgAsIdent(Arg: 0)->getIdentifierInfo(), ArgumentIdx,
6357 TypeTagIdx, IsPointer));
6358}
6359
6360static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
6361 const ParsedAttr &AL) {
6362 if (!AL.isArgIdent(Arg: 0)) {
6363 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_n_type)
6364 << AL << 1 << AANT_ArgumentIdentifier;
6365 return;
6366 }
6367
6368 if (!AL.checkExactlyNumArgs(S, Num: 1))
6369 return;
6370
6371 if (!isa<VarDecl>(Val: D)) {
6372 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_wrong_decl_type)
6373 << AL << AL.isRegularKeywordAttribute() << ExpectedVariable;
6374 return;
6375 }
6376
6377 IdentifierInfo *PointerKind = AL.getArgAsIdent(Arg: 0)->getIdentifierInfo();
6378 TypeSourceInfo *MatchingCTypeLoc = nullptr;
6379 S.GetTypeFromParser(Ty: AL.getMatchingCType(), TInfo: &MatchingCTypeLoc);
6380 assert(MatchingCTypeLoc && "no type source info for attribute argument");
6381
6382 D->addAttr(A: ::new (S.Context) TypeTagForDatatypeAttr(
6383 S.Context, AL, PointerKind, MatchingCTypeLoc, AL.getLayoutCompatible(),
6384 AL.getMustBeNull()));
6385}
6386
6387static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6388 ParamIdx ArgCount;
6389
6390 if (!S.checkFunctionOrMethodParameterIndex(D, AI: AL, AttrArgNum: 1, IdxExpr: AL.getArgAsExpr(Arg: 0),
6391 Idx&: ArgCount,
6392 CanIndexImplicitThis: true /* CanIndexImplicitThis */))
6393 return;
6394
6395 // ArgCount isn't a parameter index [0;n), it's a count [1;n]
6396 D->addAttr(A: ::new (S.Context)
6397 XRayLogArgsAttr(S.Context, AL, ArgCount.getSourceIndex()));
6398}
6399
6400static void handlePatchableFunctionEntryAttr(Sema &S, Decl *D,
6401 const ParsedAttr &AL) {
6402 if (S.Context.getTargetInfo().getTriple().isOSAIX()) {
6403 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_aix_attr_unsupported) << AL;
6404 return;
6405 }
6406 uint32_t Count = 0, Offset = 0;
6407 StringRef Section;
6408 if (!S.checkUInt32Argument(AI: AL, Expr: AL.getArgAsExpr(Arg: 0), Val&: Count, Idx: 0, StrictlyUnsigned: true))
6409 return;
6410 if (AL.getNumArgs() >= 2) {
6411 Expr *Arg = AL.getArgAsExpr(Arg: 1);
6412 if (!S.checkUInt32Argument(AI: AL, Expr: Arg, Val&: Offset, Idx: 1, StrictlyUnsigned: true))
6413 return;
6414 if (Count < Offset) {
6415 S.Diag(Loc: S.getAttrLoc(CI: AL), DiagID: diag::err_attribute_argument_out_of_range)
6416 << &AL << 0 << Count << Arg->getBeginLoc();
6417 return;
6418 }
6419 }
6420 if (AL.getNumArgs() == 3) {
6421 SourceLocation LiteralLoc;
6422 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 2, Str&: Section, ArgLocation: &LiteralLoc))
6423 return;
6424 if (llvm::Error E = S.isValidSectionSpecifier(SecName: Section)) {
6425 S.Diag(Loc: LiteralLoc,
6426 DiagID: diag::err_attribute_patchable_function_entry_invalid_section)
6427 << toString(E: std::move(E));
6428 return;
6429 }
6430 if (Section.empty()) {
6431 S.Diag(Loc: LiteralLoc,
6432 DiagID: diag::err_attribute_patchable_function_entry_invalid_section)
6433 << "section must not be empty";
6434 return;
6435 }
6436 }
6437 D->addAttr(A: ::new (S.Context) PatchableFunctionEntryAttr(S.Context, AL, Count,
6438 Offset, Section));
6439}
6440
6441static void handleBuiltinAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6442 if (!AL.isArgIdent(Arg: 0)) {
6443 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_n_type)
6444 << AL << 1 << AANT_ArgumentIdentifier;
6445 return;
6446 }
6447
6448 IdentifierInfo *Ident = AL.getArgAsIdent(Arg: 0)->getIdentifierInfo();
6449 unsigned BuiltinID = Ident->getBuiltinID();
6450 StringRef AliasName = cast<FunctionDecl>(Val: D)->getIdentifier()->getName();
6451
6452 bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6453 bool IsARM = S.Context.getTargetInfo().getTriple().isARM();
6454 bool IsRISCV = S.Context.getTargetInfo().getTriple().isRISCV();
6455 bool IsSPIRV = S.Context.getTargetInfo().getTriple().isSPIRV();
6456 bool IsHLSL = S.Context.getLangOpts().HLSL;
6457 if ((IsAArch64 && !S.ARM().SveAliasValid(BuiltinID, AliasName)) ||
6458 (IsARM && !S.ARM().MveAliasValid(BuiltinID, AliasName) &&
6459 !S.ARM().CdeAliasValid(BuiltinID, AliasName)) ||
6460 (IsRISCV && !S.RISCV().isAliasValid(BuiltinID, AliasName)) ||
6461 (!IsAArch64 && !IsARM && !IsRISCV && !IsHLSL && !IsSPIRV)) {
6462 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_builtin_alias) << AL;
6463 return;
6464 }
6465
6466 D->addAttr(A: ::new (S.Context) BuiltinAliasAttr(S.Context, AL, Ident));
6467}
6468
6469static void handleNullableTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6470 if (AL.isUsedAsTypeAttr())
6471 return;
6472
6473 if (auto *CRD = dyn_cast<CXXRecordDecl>(Val: D);
6474 !CRD || !(CRD->isClass() || CRD->isStruct())) {
6475 S.Diag(Loc: AL.getRange().getBegin(), DiagID: diag::err_attribute_wrong_decl_type)
6476 << AL << AL.isRegularKeywordAttribute() << ExpectedClass;
6477 return;
6478 }
6479
6480 handleSimpleAttribute<TypeNullableAttr>(S, D, CI: AL);
6481}
6482
6483static void handlePreferredTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6484 if (!AL.hasParsedType()) {
6485 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments) << AL << 1;
6486 return;
6487 }
6488
6489 TypeSourceInfo *ParmTSI = nullptr;
6490 QualType QT = S.GetTypeFromParser(Ty: AL.getTypeArg(), TInfo: &ParmTSI);
6491 assert(ParmTSI && "no type source info for attribute argument");
6492 S.RequireCompleteType(Loc: ParmTSI->getTypeLoc().getBeginLoc(), T: QT,
6493 DiagID: diag::err_incomplete_type);
6494
6495 D->addAttr(A: ::new (S.Context) PreferredTypeAttr(S.Context, AL, ParmTSI));
6496}
6497
6498//===----------------------------------------------------------------------===//
6499// Microsoft specific attribute handlers.
6500//===----------------------------------------------------------------------===//
6501
6502UuidAttr *Sema::mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
6503 StringRef UuidAsWritten, MSGuidDecl *GuidDecl) {
6504 if (const auto *UA = D->getAttr<UuidAttr>()) {
6505 if (declaresSameEntity(D1: UA->getGuidDecl(), D2: GuidDecl))
6506 return nullptr;
6507 if (!UA->getGuid().empty()) {
6508 Diag(Loc: UA->getLocation(), DiagID: diag::err_mismatched_uuid);
6509 Diag(Loc: CI.getLoc(), DiagID: diag::note_previous_uuid);
6510 D->dropAttr<UuidAttr>();
6511 }
6512 }
6513
6514 return ::new (Context) UuidAttr(Context, CI, UuidAsWritten, GuidDecl);
6515}
6516
6517static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6518 if (!S.LangOpts.CPlusPlus) {
6519 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_not_supported_in_lang)
6520 << AL << AttributeLangSupport::C;
6521 return;
6522 }
6523
6524 StringRef OrigStrRef;
6525 SourceLocation LiteralLoc;
6526 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: OrigStrRef, ArgLocation: &LiteralLoc))
6527 return;
6528
6529 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
6530 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
6531 StringRef StrRef = OrigStrRef;
6532 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
6533 StrRef = StrRef.drop_front().drop_back();
6534
6535 // Validate GUID length.
6536 if (StrRef.size() != 36) {
6537 S.Diag(Loc: LiteralLoc, DiagID: diag::err_attribute_uuid_malformed_guid);
6538 return;
6539 }
6540
6541 for (unsigned i = 0; i < 36; ++i) {
6542 if (i == 8 || i == 13 || i == 18 || i == 23) {
6543 if (StrRef[i] != '-') {
6544 S.Diag(Loc: LiteralLoc, DiagID: diag::err_attribute_uuid_malformed_guid);
6545 return;
6546 }
6547 } else if (!isHexDigit(c: StrRef[i])) {
6548 S.Diag(Loc: LiteralLoc, DiagID: diag::err_attribute_uuid_malformed_guid);
6549 return;
6550 }
6551 }
6552
6553 // Convert to our parsed format and canonicalize.
6554 MSGuidDecl::Parts Parsed;
6555 StrRef.substr(Start: 0, N: 8).getAsInteger(Radix: 16, Result&: Parsed.Part1);
6556 StrRef.substr(Start: 9, N: 4).getAsInteger(Radix: 16, Result&: Parsed.Part2);
6557 StrRef.substr(Start: 14, N: 4).getAsInteger(Radix: 16, Result&: Parsed.Part3);
6558 for (unsigned i = 0; i != 8; ++i)
6559 StrRef.substr(Start: 19 + 2 * i + (i >= 2 ? 1 : 0), N: 2)
6560 .getAsInteger(Radix: 16, Result&: Parsed.Part4And5[i]);
6561 MSGuidDecl *Guid = S.Context.getMSGuidDecl(Parts: Parsed);
6562
6563 // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
6564 // the only thing in the [] list, the [] too), and add an insertion of
6565 // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas
6566 // separating attributes nor of the [ and the ] are in the AST.
6567 // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
6568 // on cfe-dev.
6569 if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
6570 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_atl_uuid_deprecated);
6571
6572 UuidAttr *UA = S.mergeUuidAttr(D, CI: AL, UuidAsWritten: OrigStrRef, GuidDecl: Guid);
6573 if (UA)
6574 D->addAttr(A: UA);
6575}
6576
6577static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6578 if (!S.LangOpts.CPlusPlus) {
6579 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_not_supported_in_lang)
6580 << AL << AttributeLangSupport::C;
6581 return;
6582 }
6583 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
6584 D, CI: AL, /*BestCase=*/true, Model: (MSInheritanceModel)AL.getSemanticSpelling());
6585 if (IA) {
6586 D->addAttr(A: IA);
6587 S.Consumer.AssignInheritanceModel(RD: cast<CXXRecordDecl>(Val: D));
6588 }
6589}
6590
6591static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6592 const auto *VD = cast<VarDecl>(Val: D);
6593 if (!S.Context.getTargetInfo().isTLSSupported()) {
6594 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_thread_unsupported);
6595 return;
6596 }
6597 if (VD->getTSCSpec() != TSCS_unspecified) {
6598 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_declspec_thread_on_thread_variable);
6599 return;
6600 }
6601 if (VD->hasLocalStorage()) {
6602 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_thread_non_global) << "__declspec(thread)";
6603 return;
6604 }
6605 D->addAttr(A: ::new (S.Context) ThreadAttr(S.Context, AL));
6606}
6607
6608static void handleMSConstexprAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6609 if (!S.getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2022_3)) {
6610 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_unknown_attribute_ignored)
6611 << AL << AL.getRange();
6612 return;
6613 }
6614 auto *FD = cast<FunctionDecl>(Val: D);
6615 if (FD->isConstexprSpecified() || FD->isConsteval()) {
6616 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_ms_constexpr_cannot_be_applied)
6617 << FD->isConsteval() << FD;
6618 return;
6619 }
6620 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
6621 if (!S.getLangOpts().CPlusPlus20 && MD->isVirtual()) {
6622 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_ms_constexpr_cannot_be_applied)
6623 << /*virtual*/ 2 << MD;
6624 return;
6625 }
6626 }
6627 D->addAttr(A: ::new (S.Context) MSConstexprAttr(S.Context, AL));
6628}
6629
6630static void handleMSStructAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6631 if (const auto *First = D->getAttr<GCCStructAttr>()) {
6632 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attributes_are_not_compatible)
6633 << AL << First << 0;
6634 S.Diag(Loc: First->getLocation(), DiagID: diag::note_conflicting_attribute);
6635 return;
6636 }
6637 if (const auto *Preexisting = D->getAttr<MSStructAttr>()) {
6638 if (Preexisting->isImplicit())
6639 D->dropAttr<MSStructAttr>();
6640 }
6641
6642 D->addAttr(A: ::new (S.Context) MSStructAttr(S.Context, AL));
6643}
6644
6645static void handleGCCStructAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6646 if (const auto *First = D->getAttr<MSStructAttr>()) {
6647 if (First->isImplicit()) {
6648 D->dropAttr<MSStructAttr>();
6649 } else {
6650 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attributes_are_not_compatible)
6651 << AL << First << 0;
6652 S.Diag(Loc: First->getLocation(), DiagID: diag::note_conflicting_attribute);
6653 return;
6654 }
6655 }
6656
6657 D->addAttr(A: ::new (S.Context) GCCStructAttr(S.Context, AL));
6658}
6659
6660static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6661 SmallVector<StringRef, 4> Tags;
6662 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
6663 StringRef Tag;
6664 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: I, Str&: Tag))
6665 return;
6666 Tags.push_back(Elt: Tag);
6667 }
6668
6669 if (const auto *NS = dyn_cast<NamespaceDecl>(Val: D)) {
6670 if (!NS->isInline()) {
6671 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attr_abi_tag_namespace) << 0;
6672 return;
6673 }
6674 if (NS->isAnonymousNamespace()) {
6675 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attr_abi_tag_namespace) << 1;
6676 return;
6677 }
6678 if (AL.getNumArgs() == 0)
6679 Tags.push_back(Elt: NS->getName());
6680 } else if (!AL.checkAtLeastNumArgs(S, Num: 1))
6681 return;
6682
6683 // Store tags sorted and without duplicates.
6684 llvm::sort(C&: Tags);
6685 Tags.erase(CS: llvm::unique(R&: Tags), CE: Tags.end());
6686
6687 D->addAttr(A: ::new (S.Context)
6688 AbiTagAttr(S.Context, AL, Tags.data(), Tags.size()));
6689}
6690
6691static bool hasBTFDeclTagAttr(Decl *D, StringRef Tag) {
6692 for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) {
6693 if (I->getBTFDeclTag() == Tag)
6694 return true;
6695 }
6696 return false;
6697}
6698
6699static void handleBTFDeclTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6700 StringRef Str;
6701 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str))
6702 return;
6703 if (hasBTFDeclTagAttr(D, Tag: Str))
6704 return;
6705
6706 D->addAttr(A: ::new (S.Context) BTFDeclTagAttr(S.Context, AL, Str));
6707}
6708
6709BTFDeclTagAttr *Sema::mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL) {
6710 if (hasBTFDeclTagAttr(D, Tag: AL.getBTFDeclTag()))
6711 return nullptr;
6712 return ::new (Context) BTFDeclTagAttr(Context, AL, AL.getBTFDeclTag());
6713}
6714
6715static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6716 // Dispatch the interrupt attribute based on the current target.
6717 switch (S.Context.getTargetInfo().getTriple().getArch()) {
6718 case llvm::Triple::msp430:
6719 S.MSP430().handleInterruptAttr(D, AL);
6720 break;
6721 case llvm::Triple::mipsel:
6722 case llvm::Triple::mips:
6723 S.MIPS().handleInterruptAttr(D, AL);
6724 break;
6725 case llvm::Triple::m68k:
6726 S.M68k().handleInterruptAttr(D, AL);
6727 break;
6728 case llvm::Triple::x86:
6729 case llvm::Triple::x86_64:
6730 S.X86().handleAnyInterruptAttr(D, AL);
6731 break;
6732 case llvm::Triple::avr:
6733 S.AVR().handleInterruptAttr(D, AL);
6734 break;
6735 case llvm::Triple::riscv32:
6736 case llvm::Triple::riscv64:
6737 case llvm::Triple::riscv32be:
6738 case llvm::Triple::riscv64be:
6739 S.RISCV().handleInterruptAttr(D, AL);
6740 break;
6741 default:
6742 S.ARM().handleInterruptAttr(D, AL);
6743 break;
6744 }
6745}
6746
6747static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) {
6748 uint32_t Version;
6749 Expr *VersionExpr = AL.getArgAsExpr(Arg: 0);
6750 if (!S.checkUInt32Argument(AI: AL, Expr: AL.getArgAsExpr(Arg: 0), Val&: Version))
6751 return;
6752
6753 // TODO: Investigate what happens with the next major version of MSVC.
6754 if (Version != LangOptions::MSVC2015 / 100) {
6755 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_out_of_bounds)
6756 << AL << Version << VersionExpr->getSourceRange();
6757 return;
6758 }
6759
6760 // The attribute expects a "major" version number like 19, but new versions of
6761 // MSVC have moved to updating the "minor", or less significant numbers, so we
6762 // have to multiply by 100 now.
6763 Version *= 100;
6764
6765 D->addAttr(A: ::new (S.Context) LayoutVersionAttr(S.Context, AL, Version));
6766}
6767
6768DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D,
6769 const AttributeCommonInfo &CI) {
6770 if (D->hasAttr<DLLExportAttr>()) {
6771 Diag(Loc: CI.getLoc(), DiagID: diag::warn_attribute_ignored) << "'dllimport'";
6772 return nullptr;
6773 }
6774
6775 if (D->hasAttr<DLLImportAttr>())
6776 return nullptr;
6777
6778 return ::new (Context) DLLImportAttr(Context, CI);
6779}
6780
6781DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D,
6782 const AttributeCommonInfo &CI) {
6783 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
6784 Diag(Loc: Import->getLocation(), DiagID: diag::warn_attribute_ignored) << Import;
6785 D->dropAttr<DLLImportAttr>();
6786 }
6787
6788 if (D->hasAttr<DLLExportAttr>())
6789 return nullptr;
6790
6791 return ::new (Context) DLLExportAttr(Context, CI);
6792}
6793
6794static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) {
6795 if (isa<ClassTemplatePartialSpecializationDecl>(Val: D) &&
6796 (S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) {
6797 S.Diag(Loc: A.getRange().getBegin(), DiagID: diag::warn_attribute_ignored) << A;
6798 return;
6799 }
6800
6801 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
6802 if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport &&
6803 !(S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) {
6804 // MinGW doesn't allow dllimport on inline functions.
6805 S.Diag(Loc: A.getRange().getBegin(), DiagID: diag::warn_attribute_ignored_on_inline)
6806 << A;
6807 return;
6808 }
6809 }
6810
6811 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
6812 if ((S.Context.getTargetInfo().shouldDLLImportComdatSymbols()) &&
6813 MD->getParent()->isLambda()) {
6814 S.Diag(Loc: A.getRange().getBegin(), DiagID: diag::err_attribute_dll_lambda) << A;
6815 return;
6816 }
6817 }
6818
6819 if (auto *EA = D->getAttr<ExcludeFromExplicitInstantiationAttr>()) {
6820 S.Diag(Loc: A.getRange().getBegin(),
6821 DiagID: diag::warn_dllattr_ignored_exclusion_takes_precedence)
6822 << A << EA;
6823 return;
6824 }
6825
6826 Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport
6827 ? (Attr *)S.mergeDLLExportAttr(D, CI: A)
6828 : (Attr *)S.mergeDLLImportAttr(D, CI: A);
6829 if (NewAttr)
6830 D->addAttr(A: NewAttr);
6831}
6832
6833MSInheritanceAttr *
6834Sema::mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI,
6835 bool BestCase,
6836 MSInheritanceModel Model) {
6837 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
6838 if (IA->getInheritanceModel() == Model)
6839 return nullptr;
6840 Diag(Loc: IA->getLocation(), DiagID: diag::err_mismatched_ms_inheritance)
6841 << 1 /*previous declaration*/;
6842 Diag(Loc: CI.getLoc(), DiagID: diag::note_previous_ms_inheritance);
6843 D->dropAttr<MSInheritanceAttr>();
6844 }
6845
6846 auto *RD = cast<CXXRecordDecl>(Val: D);
6847 if (RD->hasDefinition()) {
6848 if (checkMSInheritanceAttrOnDefinition(RD, Range: CI.getRange(), BestCase,
6849 ExplicitModel: Model)) {
6850 return nullptr;
6851 }
6852 } else {
6853 if (isa<ClassTemplatePartialSpecializationDecl>(Val: RD)) {
6854 Diag(Loc: CI.getLoc(), DiagID: diag::warn_ignored_ms_inheritance)
6855 << 1 /*partial specialization*/;
6856 return nullptr;
6857 }
6858 if (RD->getDescribedClassTemplate()) {
6859 Diag(Loc: CI.getLoc(), DiagID: diag::warn_ignored_ms_inheritance)
6860 << 0 /*primary template*/;
6861 return nullptr;
6862 }
6863 }
6864
6865 return ::new (Context) MSInheritanceAttr(Context, CI, BestCase);
6866}
6867
6868static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6869 // The capability attributes take a single string parameter for the name of
6870 // the capability they represent. The lockable attribute does not take any
6871 // parameters. However, semantically, both attributes represent the same
6872 // concept, and so they use the same semantic attribute. Eventually, the
6873 // lockable attribute will be removed.
6874 //
6875 // For backward compatibility, any capability which has no specified string
6876 // literal will be considered a "mutex."
6877 StringRef N("mutex");
6878 SourceLocation LiteralLoc;
6879 if (AL.getKind() == ParsedAttr::AT_Capability &&
6880 !S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: N, ArgLocation: &LiteralLoc))
6881 return;
6882
6883 D->addAttr(A: ::new (S.Context) CapabilityAttr(S.Context, AL, N));
6884}
6885
6886static void handleReentrantCapabilityAttr(Sema &S, Decl *D,
6887 const ParsedAttr &AL) {
6888 // Do not permit 'reentrant_capability' without 'capability(..)'. Note that
6889 // the check here requires 'capability' to be before 'reentrant_capability'.
6890 // This helps enforce a canonical style. Also avoids placing an additional
6891 // branch into ProcessDeclAttributeList().
6892 if (!D->hasAttr<CapabilityAttr>()) {
6893 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_thread_attribute_requires_preceded)
6894 << AL << cast<NamedDecl>(Val: D) << "'capability'";
6895 return;
6896 }
6897
6898 D->addAttr(A: ::new (S.Context) ReentrantCapabilityAttr(S.Context, AL));
6899}
6900
6901static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6902 if (!checkThreadSafetyAttrSubject(S, D, AL))
6903 return;
6904
6905 SmallVector<Expr*, 1> Args;
6906 if (!checkLockFunAttrCommon(S, D, AL, Args))
6907 return;
6908
6909 D->addAttr(A: ::new (S.Context)
6910 AssertCapabilityAttr(S.Context, AL, Args.data(), Args.size()));
6911}
6912
6913static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
6914 const ParsedAttr &AL) {
6915 if (!checkThreadSafetyAttrSubject(S, D, AL, /*CheckParmVar=*/true))
6916 return;
6917
6918 SmallVector<Expr*, 1> Args;
6919 if (!checkLockFunAttrCommon(S, D, AL, Args))
6920 return;
6921
6922 D->addAttr(A: ::new (S.Context) AcquireCapabilityAttr(S.Context, AL, Args.data(),
6923 Args.size()));
6924}
6925
6926static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
6927 const ParsedAttr &AL) {
6928 if (!checkThreadSafetyAttrSubject(S, D, AL))
6929 return;
6930
6931 SmallVector<Expr*, 2> Args;
6932 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
6933 return;
6934
6935 D->addAttr(A: ::new (S.Context) TryAcquireCapabilityAttr(
6936 S.Context, AL, AL.getArgAsExpr(Arg: 0), Args.data(), Args.size()));
6937}
6938
6939static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
6940 const ParsedAttr &AL) {
6941 if (!checkThreadSafetyAttrSubject(S, D, AL, /*CheckParmVar=*/true))
6942 return;
6943
6944 // Check that all arguments are lockable objects.
6945 SmallVector<Expr *, 1> Args;
6946 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, Sidx: 0, ParamIdxOk: true);
6947
6948 D->addAttr(A: ::new (S.Context) ReleaseCapabilityAttr(S.Context, AL, Args.data(),
6949 Args.size()));
6950}
6951
6952static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
6953 const ParsedAttr &AL) {
6954 if (!checkThreadSafetyAttrSubject(S, D, AL, /*CheckParmVar=*/true))
6955 return;
6956
6957 if (!AL.checkAtLeastNumArgs(S, Num: 1))
6958 return;
6959
6960 // check that all arguments are lockable objects
6961 SmallVector<Expr*, 1> Args;
6962 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
6963 if (Args.empty())
6964 return;
6965
6966 RequiresCapabilityAttr *RCA = ::new (S.Context)
6967 RequiresCapabilityAttr(S.Context, AL, Args.data(), Args.size());
6968
6969 D->addAttr(A: RCA);
6970}
6971
6972static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6973 if (const auto *NSD = dyn_cast<NamespaceDecl>(Val: D)) {
6974 if (NSD->isAnonymousNamespace()) {
6975 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_deprecated_anonymous_namespace);
6976 // Do not want to attach the attribute to the namespace because that will
6977 // cause confusing diagnostic reports for uses of declarations within the
6978 // namespace.
6979 return;
6980 }
6981 } else if (isa<UsingDecl, UnresolvedUsingTypenameDecl,
6982 UnresolvedUsingValueDecl>(Val: D)) {
6983 S.Diag(Loc: AL.getRange().getBegin(), DiagID: diag::warn_deprecated_ignored_on_using)
6984 << AL;
6985 return;
6986 }
6987
6988 // Handle the cases where the attribute has a text message.
6989 StringRef Str, Replacement;
6990 if (AL.isArgExpr(Arg: 0) && AL.getArgAsExpr(Arg: 0) &&
6991 !S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str))
6992 return;
6993
6994 // Support a single optional message only for Declspec and [[]] spellings.
6995 if (AL.isDeclspecAttribute() || AL.isStandardAttributeSyntax())
6996 AL.checkAtMostNumArgs(S, Num: 1);
6997 else if (AL.isArgExpr(Arg: 1) && AL.getArgAsExpr(Arg: 1) &&
6998 !S.checkStringLiteralArgumentAttr(AL, ArgNum: 1, Str&: Replacement))
6999 return;
7000
7001 if (!S.getLangOpts().CPlusPlus14 && AL.isCXX11Attribute() && !AL.isGNUScope())
7002 S.Diag(Loc: AL.getLoc(), DiagID: diag::ext_cxx14_attr) << AL;
7003
7004 D->addAttr(A: ::new (S.Context) DeprecatedAttr(S.Context, AL, Str, Replacement));
7005}
7006
7007static bool isGlobalVar(const Decl *D) {
7008 if (const auto *S = dyn_cast<VarDecl>(Val: D))
7009 return S->hasGlobalStorage();
7010 return false;
7011}
7012
7013static bool isSanitizerAttributeAllowedOnGlobals(StringRef Sanitizer) {
7014 return Sanitizer == "address" || Sanitizer == "hwaddress" ||
7015 Sanitizer == "memtag";
7016}
7017
7018static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7019 if (!AL.checkAtLeastNumArgs(S, Num: 1))
7020 return;
7021
7022 std::vector<StringRef> Sanitizers;
7023
7024 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
7025 StringRef SanitizerName;
7026 SourceLocation LiteralLoc;
7027
7028 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: I, Str&: SanitizerName, ArgLocation: &LiteralLoc))
7029 return;
7030
7031 if (parseSanitizerValue(Value: SanitizerName, /*AllowGroups=*/true) ==
7032 SanitizerMask() &&
7033 SanitizerName != "coverage")
7034 S.Diag(Loc: LiteralLoc, DiagID: diag::warn_unknown_sanitizer_ignored) << SanitizerName;
7035 else if (isGlobalVar(D) && !isSanitizerAttributeAllowedOnGlobals(Sanitizer: SanitizerName))
7036 S.Diag(Loc: D->getLocation(), DiagID: diag::warn_attribute_type_not_supported_global)
7037 << AL << SanitizerName;
7038 Sanitizers.push_back(x: SanitizerName);
7039 }
7040
7041 D->addAttr(A: ::new (S.Context) NoSanitizeAttr(S.Context, AL, Sanitizers.data(),
7042 Sanitizers.size()));
7043}
7044
7045static AttributeCommonInfo
7046getNoSanitizeAttrInfo(const ParsedAttr &NoSanitizeSpecificAttr) {
7047 // FIXME: Rather than create a NoSanitizeSpecificAttr, this creates a
7048 // NoSanitizeAttr object; but we need to calculate the correct spelling list
7049 // index rather than incorrectly assume the index for NoSanitizeSpecificAttr
7050 // has the same spellings as the index for NoSanitizeAttr. We don't have a
7051 // general way to "translate" between the two, so this hack attempts to work
7052 // around the issue with hard-coded indices. This is critical for calling
7053 // getSpelling() or prettyPrint() on the resulting semantic attribute object
7054 // without failing assertions.
7055 unsigned TranslatedSpellingIndex = 0;
7056 if (NoSanitizeSpecificAttr.isStandardAttributeSyntax())
7057 TranslatedSpellingIndex = 1;
7058
7059 AttributeCommonInfo Info = NoSanitizeSpecificAttr;
7060 Info.setAttributeSpellingListIndex(TranslatedSpellingIndex);
7061 return Info;
7062}
7063
7064static void handleNoSanitizeAddressAttr(Sema &S, Decl *D,
7065 const ParsedAttr &AL) {
7066 StringRef SanitizerName = "address";
7067 AttributeCommonInfo Info = getNoSanitizeAttrInfo(NoSanitizeSpecificAttr: AL);
7068 D->addAttr(A: ::new (S.Context)
7069 NoSanitizeAttr(S.Context, Info, &SanitizerName, 1));
7070}
7071
7072static void handleNoSanitizeThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7073 StringRef SanitizerName = "thread";
7074 AttributeCommonInfo Info = getNoSanitizeAttrInfo(NoSanitizeSpecificAttr: AL);
7075 D->addAttr(A: ::new (S.Context)
7076 NoSanitizeAttr(S.Context, Info, &SanitizerName, 1));
7077}
7078
7079static void handleNoSanitizeMemoryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7080 StringRef SanitizerName = "memory";
7081 AttributeCommonInfo Info = getNoSanitizeAttrInfo(NoSanitizeSpecificAttr: AL);
7082 D->addAttr(A: ::new (S.Context)
7083 NoSanitizeAttr(S.Context, Info, &SanitizerName, 1));
7084}
7085
7086static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7087 if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, AL))
7088 D->addAttr(A: Internal);
7089}
7090
7091static void handleZeroCallUsedRegsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7092 // Check that the argument is a string literal.
7093 StringRef KindStr;
7094 SourceLocation LiteralLoc;
7095 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: KindStr, ArgLocation: &LiteralLoc))
7096 return;
7097
7098 ZeroCallUsedRegsAttr::ZeroCallUsedRegsKind Kind;
7099 if (!ZeroCallUsedRegsAttr::ConvertStrToZeroCallUsedRegsKind(Val: KindStr, Out&: Kind)) {
7100 S.Diag(Loc: LiteralLoc, DiagID: diag::warn_attribute_type_not_supported)
7101 << AL << KindStr;
7102 return;
7103 }
7104
7105 D->dropAttr<ZeroCallUsedRegsAttr>();
7106 D->addAttr(A: ZeroCallUsedRegsAttr::Create(Ctx&: S.Context, ZeroCallUsedRegs: Kind, CommonInfo: AL));
7107}
7108
7109static void handleNoPFPAttrField(Sema &S, Decl *D, const ParsedAttr &AL) {
7110 D->addAttr(A: NoFieldProtectionAttr::Create(Ctx&: S.Context, CommonInfo: AL));
7111}
7112
7113static void handleCountedByAttrField(Sema &S, Decl *D, const ParsedAttr &AL) {
7114 auto *CountExpr = AL.getArgAsExpr(Arg: 0);
7115 if (!CountExpr)
7116 return;
7117
7118 bool CountInBytes;
7119 bool OrNull;
7120 switch (AL.getKind()) {
7121 case ParsedAttr::AT_CountedBy:
7122 CountInBytes = false;
7123 OrNull = false;
7124 break;
7125 case ParsedAttr::AT_CountedByOrNull:
7126 CountInBytes = false;
7127 OrNull = true;
7128 break;
7129 case ParsedAttr::AT_SizedBy:
7130 CountInBytes = true;
7131 OrNull = false;
7132 break;
7133 case ParsedAttr::AT_SizedByOrNull:
7134 CountInBytes = true;
7135 OrNull = true;
7136 break;
7137 default:
7138 llvm_unreachable("unexpected counted_by family attribute");
7139 }
7140
7141 FieldDecl *FD = cast<FieldDecl>(Val: D);
7142 if (S.CheckCountedByAttrOnField(FD, E: CountExpr, CountInBytes, OrNull))
7143 return;
7144
7145 QualType CAT = S.BuildCountAttributedArrayOrPointerType(
7146 WrappedTy: FD->getType(), CountExpr, CountInBytes, OrNull);
7147 FD->setType(CAT);
7148}
7149
7150static void handleFunctionReturnThunksAttr(Sema &S, Decl *D,
7151 const ParsedAttr &AL) {
7152 StringRef KindStr;
7153 SourceLocation LiteralLoc;
7154 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: KindStr, ArgLocation: &LiteralLoc))
7155 return;
7156
7157 FunctionReturnThunksAttr::Kind Kind;
7158 if (!FunctionReturnThunksAttr::ConvertStrToKind(Val: KindStr, Out&: Kind)) {
7159 S.Diag(Loc: LiteralLoc, DiagID: diag::warn_attribute_type_not_supported)
7160 << AL << KindStr;
7161 return;
7162 }
7163 // FIXME: it would be good to better handle attribute merging rather than
7164 // silently replacing the existing attribute, so long as it does not break
7165 // the expected codegen tests.
7166 D->dropAttr<FunctionReturnThunksAttr>();
7167 D->addAttr(A: FunctionReturnThunksAttr::Create(Ctx&: S.Context, ThunkType: Kind, CommonInfo: AL));
7168}
7169
7170static void handleAvailableOnlyInDefaultEvalMethod(Sema &S, Decl *D,
7171 const ParsedAttr &AL) {
7172 assert(isa<TypedefNameDecl>(D) && "This attribute only applies to a typedef");
7173 handleSimpleAttribute<AvailableOnlyInDefaultEvalMethodAttr>(S, D, CI: AL);
7174}
7175
7176static void handleNoMergeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7177 auto *VDecl = dyn_cast<VarDecl>(Val: D);
7178 if (VDecl && !VDecl->isFunctionPointerType()) {
7179 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_ignored_non_function_pointer)
7180 << AL << VDecl;
7181 return;
7182 }
7183 D->addAttr(A: NoMergeAttr::Create(Ctx&: S.Context, CommonInfo: AL));
7184}
7185
7186static void handleNoUniqueAddressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7187 D->addAttr(A: NoUniqueAddressAttr::Create(Ctx&: S.Context, CommonInfo: AL));
7188}
7189
7190static void handleDestroyAttr(Sema &S, Decl *D, const ParsedAttr &A) {
7191 if (!cast<VarDecl>(Val: D)->hasGlobalStorage()) {
7192 S.Diag(Loc: D->getLocation(), DiagID: diag::err_destroy_attr_on_non_static_var)
7193 << (A.getKind() == ParsedAttr::AT_AlwaysDestroy);
7194 return;
7195 }
7196
7197 if (A.getKind() == ParsedAttr::AT_AlwaysDestroy)
7198 handleSimpleAttribute<AlwaysDestroyAttr>(S, D, CI: A);
7199 else
7200 handleSimpleAttribute<NoDestroyAttr>(S, D, CI: A);
7201}
7202
7203static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7204 assert(cast<VarDecl>(D)->getStorageDuration() == SD_Automatic &&
7205 "uninitialized is only valid on automatic duration variables");
7206 D->addAttr(A: ::new (S.Context) UninitializedAttr(S.Context, AL));
7207}
7208
7209static void handleMIGServerRoutineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7210 // Check that the return type is a `typedef int kern_return_t` or a typedef
7211 // around it, because otherwise MIG convention checks make no sense.
7212 // BlockDecl doesn't store a return type, so it's annoying to check,
7213 // so let's skip it for now.
7214 if (!isa<BlockDecl>(Val: D)) {
7215 QualType T = getFunctionOrMethodResultType(D);
7216 bool IsKernReturnT = false;
7217 while (const auto *TT = T->getAs<TypedefType>()) {
7218 IsKernReturnT = (TT->getDecl()->getName() == "kern_return_t");
7219 T = TT->desugar();
7220 }
7221 if (!IsKernReturnT || T.getCanonicalType() != S.getASTContext().IntTy) {
7222 S.Diag(Loc: D->getBeginLoc(),
7223 DiagID: diag::warn_mig_server_routine_does_not_return_kern_return_t);
7224 return;
7225 }
7226 }
7227
7228 handleSimpleAttribute<MIGServerRoutineAttr>(S, D, CI: AL);
7229}
7230
7231static void handleMSAllocatorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7232 // Warn if the return type is not a pointer or reference type.
7233 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
7234 QualType RetTy = FD->getReturnType();
7235 if (!RetTy->isPointerOrReferenceType()) {
7236 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_declspec_allocator_nonpointer)
7237 << AL.getRange() << RetTy;
7238 return;
7239 }
7240 }
7241
7242 handleSimpleAttribute<MSAllocatorAttr>(S, D, CI: AL);
7243}
7244
7245static void handleAcquireHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7246 if (AL.isUsedAsTypeAttr())
7247 return;
7248 // Warn if the parameter is definitely not an output parameter.
7249 if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: D)) {
7250 if (PVD->getType()->isIntegerType()) {
7251 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_output_parameter)
7252 << AL.getRange();
7253 return;
7254 }
7255 }
7256 StringRef Argument;
7257 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: Argument))
7258 return;
7259 D->addAttr(A: AcquireHandleAttr::Create(Ctx&: S.Context, HandleType: Argument, CommonInfo: AL));
7260}
7261
7262template<typename Attr>
7263static void handleHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7264 StringRef Argument;
7265 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: Argument))
7266 return;
7267 D->addAttr(A: Attr::Create(S.Context, Argument, AL));
7268}
7269
7270static void handleUnsafeBufferUsage(Sema &S, Decl *D, const ParsedAttr &AL) {
7271 StringRef Category;
7272 if (AL.getAttrName()->getName() == "unsafe_buffer_usage_in_container") {
7273 if (!AL.checkExactlyNumArgs(S, Num: 0))
7274 return;
7275 Category = "container";
7276 } else if (AL.getNumArgs() != 0) {
7277 SourceLocation Loc;
7278 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: Category, ArgLocation: &Loc))
7279 return;
7280 if (Category != "container") {
7281 S.Diag(Loc, DiagID: diag::warn_attribute_type_not_supported) << AL << Category;
7282 return;
7283 }
7284 }
7285 D->addAttr(A: UnsafeBufferUsageAttr::Create(Ctx&: S.Context, Category, CommonInfo: AL));
7286}
7287
7288static void handleCFGuardAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7289 // The guard attribute takes a single identifier argument.
7290
7291 if (!AL.isArgIdent(Arg: 0)) {
7292 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_type)
7293 << AL << AANT_ArgumentIdentifier;
7294 return;
7295 }
7296
7297 CFGuardAttr::GuardArg Arg;
7298 IdentifierInfo *II = AL.getArgAsIdent(Arg: 0)->getIdentifierInfo();
7299 if (!CFGuardAttr::ConvertStrToGuardArg(Val: II->getName(), Out&: Arg)) {
7300 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_type_not_supported) << AL << II;
7301 return;
7302 }
7303
7304 D->addAttr(A: ::new (S.Context) CFGuardAttr(S.Context, AL, Arg));
7305}
7306
7307
7308template <typename AttrTy>
7309static const AttrTy *findEnforceTCBAttrByName(Decl *D, StringRef Name) {
7310 auto Attrs = D->specific_attrs<AttrTy>();
7311 auto I = llvm::find_if(Attrs,
7312 [Name](const AttrTy *A) {
7313 return A->getTCBName() == Name;
7314 });
7315 return I == Attrs.end() ? nullptr : *I;
7316}
7317
7318template <typename AttrTy, typename ConflictingAttrTy>
7319static void handleEnforceTCBAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7320 StringRef Argument;
7321 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 0, Str&: Argument))
7322 return;
7323
7324 // A function cannot be have both regular and leaf membership in the same TCB.
7325 if (const ConflictingAttrTy *ConflictingAttr =
7326 findEnforceTCBAttrByName<ConflictingAttrTy>(D, Argument)) {
7327 // We could attach a note to the other attribute but in this case
7328 // there's no need given how the two are very close to each other.
7329 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_tcb_conflicting_attributes)
7330 << AL.getAttrName()->getName() << ConflictingAttr->getAttrName()->getName()
7331 << Argument;
7332
7333 // Error recovery: drop the non-leaf attribute so that to suppress
7334 // all future warnings caused by erroneous attributes. The leaf attribute
7335 // needs to be kept because it can only suppresses warnings, not cause them.
7336 D->dropAttr<EnforceTCBAttr>();
7337 return;
7338 }
7339
7340 D->addAttr(A: AttrTy::Create(S.Context, Argument, AL));
7341}
7342
7343template <typename AttrTy, typename ConflictingAttrTy>
7344static AttrTy *mergeEnforceTCBAttrImpl(Sema &S, Decl *D, const AttrTy &AL) {
7345 // Check if the new redeclaration has different leaf-ness in the same TCB.
7346 StringRef TCBName = AL.getTCBName();
7347 if (const ConflictingAttrTy *ConflictingAttr =
7348 findEnforceTCBAttrByName<ConflictingAttrTy>(D, TCBName)) {
7349 S.Diag(ConflictingAttr->getLoc(), diag::err_tcb_conflicting_attributes)
7350 << ConflictingAttr->getAttrName()->getName()
7351 << AL.getAttrName()->getName() << TCBName;
7352
7353 // Add a note so that the user could easily find the conflicting attribute.
7354 S.Diag(AL.getLoc(), diag::note_conflicting_attribute);
7355
7356 // More error recovery.
7357 D->dropAttr<EnforceTCBAttr>();
7358 return nullptr;
7359 }
7360
7361 ASTContext &Context = S.getASTContext();
7362 return ::new(Context) AttrTy(Context, AL, AL.getTCBName());
7363}
7364
7365EnforceTCBAttr *Sema::mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL) {
7366 return mergeEnforceTCBAttrImpl<EnforceTCBAttr, EnforceTCBLeafAttr>(
7367 S&: *this, D, AL);
7368}
7369
7370EnforceTCBLeafAttr *Sema::mergeEnforceTCBLeafAttr(
7371 Decl *D, const EnforceTCBLeafAttr &AL) {
7372 return mergeEnforceTCBAttrImpl<EnforceTCBLeafAttr, EnforceTCBAttr>(
7373 S&: *this, D, AL);
7374}
7375
7376static void handleVTablePointerAuthentication(Sema &S, Decl *D,
7377 const ParsedAttr &AL) {
7378 CXXRecordDecl *Decl = cast<CXXRecordDecl>(Val: D);
7379 const uint32_t NumArgs = AL.getNumArgs();
7380 if (NumArgs > 4) {
7381 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_too_many_arguments) << AL << 4;
7382 AL.setInvalid();
7383 }
7384
7385 if (NumArgs == 0) {
7386 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_too_few_arguments) << AL;
7387 AL.setInvalid();
7388 return;
7389 }
7390
7391 if (D->getAttr<VTablePointerAuthenticationAttr>()) {
7392 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_duplicated_vtable_pointer_auth) << Decl;
7393 AL.setInvalid();
7394 }
7395
7396 auto KeyType = VTablePointerAuthenticationAttr::VPtrAuthKeyType::DefaultKey;
7397 if (AL.isArgIdent(Arg: 0)) {
7398 IdentifierLoc *IL = AL.getArgAsIdent(Arg: 0);
7399 if (!VTablePointerAuthenticationAttr::ConvertStrToVPtrAuthKeyType(
7400 Val: IL->getIdentifierInfo()->getName(), Out&: KeyType)) {
7401 S.Diag(Loc: IL->getLoc(), DiagID: diag::err_invalid_authentication_key)
7402 << IL->getIdentifierInfo();
7403 AL.setInvalid();
7404 }
7405 if (KeyType == VTablePointerAuthenticationAttr::DefaultKey &&
7406 !S.getLangOpts().PointerAuthCalls) {
7407 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_no_default_vtable_pointer_auth) << 0;
7408 AL.setInvalid();
7409 }
7410 } else {
7411 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_type)
7412 << AL << AANT_ArgumentIdentifier;
7413 return;
7414 }
7415
7416 auto AddressDiversityMode = VTablePointerAuthenticationAttr::
7417 AddressDiscriminationMode::DefaultAddressDiscrimination;
7418 if (AL.getNumArgs() > 1) {
7419 if (AL.isArgIdent(Arg: 1)) {
7420 IdentifierLoc *IL = AL.getArgAsIdent(Arg: 1);
7421 if (!VTablePointerAuthenticationAttr::
7422 ConvertStrToAddressDiscriminationMode(
7423 Val: IL->getIdentifierInfo()->getName(), Out&: AddressDiversityMode)) {
7424 S.Diag(Loc: IL->getLoc(), DiagID: diag::err_invalid_address_discrimination)
7425 << IL->getIdentifierInfo();
7426 AL.setInvalid();
7427 }
7428 if (AddressDiversityMode ==
7429 VTablePointerAuthenticationAttr::DefaultAddressDiscrimination &&
7430 !S.getLangOpts().PointerAuthCalls) {
7431 S.Diag(Loc: IL->getLoc(), DiagID: diag::err_no_default_vtable_pointer_auth) << 1;
7432 AL.setInvalid();
7433 }
7434 } else {
7435 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_type)
7436 << AL << AANT_ArgumentIdentifier;
7437 }
7438 }
7439
7440 auto ED = VTablePointerAuthenticationAttr::ExtraDiscrimination::
7441 DefaultExtraDiscrimination;
7442 if (AL.getNumArgs() > 2) {
7443 if (AL.isArgIdent(Arg: 2)) {
7444 IdentifierLoc *IL = AL.getArgAsIdent(Arg: 2);
7445 if (!VTablePointerAuthenticationAttr::ConvertStrToExtraDiscrimination(
7446 Val: IL->getIdentifierInfo()->getName(), Out&: ED)) {
7447 S.Diag(Loc: IL->getLoc(), DiagID: diag::err_invalid_extra_discrimination)
7448 << IL->getIdentifierInfo();
7449 AL.setInvalid();
7450 }
7451 if (ED == VTablePointerAuthenticationAttr::DefaultExtraDiscrimination &&
7452 !S.getLangOpts().PointerAuthCalls) {
7453 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_no_default_vtable_pointer_auth) << 2;
7454 AL.setInvalid();
7455 }
7456 } else {
7457 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_type)
7458 << AL << AANT_ArgumentIdentifier;
7459 }
7460 }
7461
7462 uint32_t CustomDiscriminationValue = 0;
7463 if (ED == VTablePointerAuthenticationAttr::CustomDiscrimination) {
7464 if (NumArgs < 4) {
7465 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_missing_custom_discrimination) << AL << 4;
7466 AL.setInvalid();
7467 return;
7468 }
7469 if (NumArgs > 4) {
7470 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_too_many_arguments) << AL << 4;
7471 AL.setInvalid();
7472 }
7473
7474 if (!AL.isArgExpr(Arg: 3) || !S.checkUInt32Argument(AI: AL, Expr: AL.getArgAsExpr(Arg: 3),
7475 Val&: CustomDiscriminationValue)) {
7476 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_invalid_custom_discrimination);
7477 AL.setInvalid();
7478 }
7479 } else if (NumArgs > 3) {
7480 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_too_many_arguments) << AL << 3;
7481 AL.setInvalid();
7482 }
7483
7484 Decl->addAttr(A: ::new (S.Context) VTablePointerAuthenticationAttr(
7485 S.Context, AL, KeyType, AddressDiversityMode, ED,
7486 CustomDiscriminationValue));
7487}
7488
7489static bool modularFormatAttrsEquiv(const ModularFormatAttr *Existing,
7490 const IdentifierInfo *ModularImplFn,
7491 StringRef ImplName,
7492 ArrayRef<StringRef> Aspects) {
7493 return Existing->getModularImplFn() == ModularImplFn &&
7494 Existing->getImplName() == ImplName &&
7495 Existing->aspects_size() == Aspects.size() &&
7496 llvm::equal(LRange: Existing->aspects(), RRange&: Aspects);
7497}
7498
7499ModularFormatAttr *Sema::mergeModularFormatAttr(
7500 Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *ModularImplFn,
7501 StringRef ImplName, MutableArrayRef<StringRef> Aspects) {
7502 if (const auto *Existing = D->getAttr<ModularFormatAttr>()) {
7503 if (!modularFormatAttrsEquiv(Existing, ModularImplFn, ImplName, Aspects)) {
7504 Diag(Loc: Existing->getLocation(), DiagID: diag::err_duplicate_attribute) << *Existing;
7505 Diag(Loc: CI.getLoc(), DiagID: diag::note_conflicting_attribute);
7506 }
7507 return nullptr;
7508 }
7509 return ::new (Context) ModularFormatAttr(Context, CI, ModularImplFn, ImplName,
7510 Aspects.data(), Aspects.size());
7511}
7512
7513static void handleModularFormat(Sema &S, Decl *D, const ParsedAttr &AL) {
7514 bool Valid = true;
7515 if (!AL.isArgIdent(Arg: 0)) {
7516 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_argument_n_type)
7517 << AL << 1 << AANT_ArgumentIdentifier;
7518 Valid = false;
7519 }
7520 StringRef ImplName;
7521 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: 1, Str&: ImplName))
7522 Valid = false;
7523 SmallVector<StringRef> Aspects;
7524 llvm::DenseSet<StringRef> SeenAspects;
7525 for (unsigned I = 2, E = AL.getNumArgs(); I != E; ++I) {
7526 StringRef Aspect;
7527 if (!S.checkStringLiteralArgumentAttr(AL, ArgNum: I, Str&: Aspect))
7528 return;
7529 if (!SeenAspects.insert(V: Aspect).second) {
7530 S.Diag(Loc: AL.getArgAsExpr(Arg: I)->getExprLoc(),
7531 DiagID: diag::err_modular_format_duplicate_aspect)
7532 << Aspect;
7533 Valid = false;
7534 continue;
7535 }
7536 Aspects.push_back(Elt: Aspect);
7537 }
7538 if (!Valid)
7539 return;
7540
7541 // Store aspects sorted.
7542 llvm::sort(C&: Aspects);
7543 IdentifierInfo *ModularImplFn = AL.getArgAsIdent(Arg: 0)->getIdentifierInfo();
7544
7545 if (const auto *Existing = D->getAttr<ModularFormatAttr>()) {
7546 if (!modularFormatAttrsEquiv(Existing, ModularImplFn, ImplName, Aspects)) {
7547 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_duplicate_attribute) << *Existing;
7548 S.Diag(Loc: Existing->getLoc(), DiagID: diag::note_conflicting_attribute);
7549 }
7550 // Ignore the later declaration in favor of the earlier one.
7551 return;
7552 }
7553
7554 D->addAttr(A: ::new (S.Context) ModularFormatAttr(
7555 S.Context, AL, ModularImplFn, ImplName, Aspects.data(), Aspects.size()));
7556}
7557
7558//===----------------------------------------------------------------------===//
7559// Top Level Sema Entry Points
7560//===----------------------------------------------------------------------===//
7561
7562// Returns true if the attribute must delay setting its arguments until after
7563// template instantiation, and false otherwise.
7564static bool MustDelayAttributeArguments(const ParsedAttr &AL) {
7565 // Only attributes that accept expression parameter packs can delay arguments.
7566 if (!AL.acceptsExprPack())
7567 return false;
7568
7569 bool AttrHasVariadicArg = AL.hasVariadicArg();
7570 unsigned AttrNumArgs = AL.getNumArgMembers();
7571 for (size_t I = 0; I < std::min(a: AL.getNumArgs(), b: AttrNumArgs); ++I) {
7572 bool IsLastAttrArg = I == (AttrNumArgs - 1);
7573 // If the argument is the last argument and it is variadic it can contain
7574 // any expression.
7575 if (IsLastAttrArg && AttrHasVariadicArg)
7576 return false;
7577 Expr *E = AL.getArgAsExpr(Arg: I);
7578 bool ArgMemberCanHoldExpr = AL.isParamExpr(N: I);
7579 // If the expression is a pack expansion then arguments must be delayed
7580 // unless the argument is an expression and it is the last argument of the
7581 // attribute.
7582 if (isa<PackExpansionExpr>(Val: E))
7583 return !(IsLastAttrArg && ArgMemberCanHoldExpr);
7584 // Last case is if the expression is value dependent then it must delay
7585 // arguments unless the corresponding argument is able to hold the
7586 // expression.
7587 if (E->isValueDependent() && !ArgMemberCanHoldExpr)
7588 return true;
7589 }
7590 return false;
7591}
7592
7593PersonalityAttr *Sema::mergePersonalityAttr(Decl *D, FunctionDecl *Routine,
7594 const AttributeCommonInfo &CI) {
7595 if (PersonalityAttr *PA = D->getAttr<PersonalityAttr>()) {
7596 const FunctionDecl *Personality = PA->getRoutine();
7597 if (Context.isSameEntity(X: Personality, Y: Routine))
7598 return nullptr;
7599 Diag(Loc: PA->getLocation(), DiagID: diag::err_mismatched_personality);
7600 Diag(Loc: CI.getLoc(), DiagID: diag::note_previous_attribute);
7601 D->dropAttr<PersonalityAttr>();
7602 }
7603 return ::new (Context) PersonalityAttr(Context, CI, Routine);
7604}
7605
7606static void handlePersonalityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
7607 Expr *E = AL.getArgAsExpr(Arg: 0);
7608 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
7609 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
7610 if (Attr *A = S.mergePersonalityAttr(D, Routine: FD, CI: AL))
7611 return D->addAttr(A);
7612 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_attribute_personality_arg_not_function)
7613 << AL.getAttrName();
7614}
7615
7616/// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
7617/// the attribute applies to decls. If the attribute is a type attribute, just
7618/// silently ignore it if a GNU attribute.
7619static void
7620ProcessDeclAttribute(Sema &S, Decl *D, const ParsedAttr &AL,
7621 const Sema::ProcessDeclAttributeOptions &Options) {
7622 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
7623 return;
7624
7625 // Ignore C++11 attributes on declarator chunks: they appertain to the type
7626 // instead. Note, isCXX11Attribute() will look at whether the attribute is
7627 // [[]] or alignas, while isC23Attribute() will only look at [[]]. This is
7628 // important for ensuring that alignas in C23 is properly handled on a
7629 // structure member declaration because it is a type-specifier-qualifier in
7630 // C but still applies to the declaration rather than the type.
7631 if ((S.getLangOpts().CPlusPlus ? AL.isCXX11Attribute()
7632 : AL.isC23Attribute()) &&
7633 !Options.IncludeCXX11Attributes)
7634 return;
7635
7636 // Unknown attributes are automatically warned on. Target-specific attributes
7637 // which do not apply to the current target architecture are treated as
7638 // though they were unknown attributes.
7639 if (AL.getKind() == ParsedAttr::UnknownAttribute ||
7640 !AL.existsInTarget(Target: S.Context.getTargetInfo())) {
7641 if (AL.isRegularKeywordAttribute()) {
7642 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_keyword_not_supported_on_target)
7643 << AL.getAttrName() << AL.getRange();
7644 } else if (AL.isDeclspecAttribute()) {
7645 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_unhandled_ms_attribute_ignored)
7646 << AL.getAttrName() << AL.getRange();
7647 } else {
7648 S.DiagnoseUnknownAttribute(AL);
7649 }
7650 return;
7651 }
7652
7653 if (S.getLangOpts().HLSL && isa<FunctionDecl>(Val: D) &&
7654 AL.getKind() == ParsedAttr::AT_NoInline) {
7655 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
7656 for (const ParmVarDecl *PVD : FD->parameters()) {
7657 if (PVD->hasAttr<HLSLGroupSharedAddressSpaceAttr>()) {
7658 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_hlsl_attr_incompatible)
7659 << "'noinline'" << "'groupshared' parameter";
7660 return;
7661 }
7662 }
7663 }
7664 }
7665
7666 // Check if argument population must delayed to after template instantiation.
7667 bool MustDelayArgs = MustDelayAttributeArguments(AL);
7668
7669 // Argument number check must be skipped if arguments are delayed.
7670 if (S.checkCommonAttributeFeatures(D, A: AL, SkipArgCountCheck: MustDelayArgs))
7671 return;
7672
7673 if (MustDelayArgs) {
7674 AL.handleAttrWithDelayedArgs(S, D);
7675 return;
7676 }
7677
7678 switch (AL.getKind()) {
7679 default:
7680 if (AL.getInfo().handleDeclAttribute(S, D, Attr: AL) != ParsedAttrInfo::NotHandled)
7681 break;
7682 if (!AL.isStmtAttr()) {
7683 assert(AL.isTypeAttr() && "Non-type attribute not handled");
7684 }
7685 if (AL.isTypeAttr()) {
7686 if (Options.IgnoreTypeAttributes)
7687 break;
7688 if (!AL.isStandardAttributeSyntax() && !AL.isRegularKeywordAttribute()) {
7689 // Non-[[]] type attributes are handled in processTypeAttrs(); silently
7690 // move on.
7691 break;
7692 }
7693
7694 // According to the C and C++ standards, we should never see a
7695 // [[]] type attribute on a declaration. However, we have in the past
7696 // allowed some type attributes to "slide" to the `DeclSpec`, so we need
7697 // to continue to support this legacy behavior. We only do this, however,
7698 // if
7699 // - we actually have a `DeclSpec`, i.e. if we're looking at a
7700 // `DeclaratorDecl`, or
7701 // - we are looking at an alias-declaration, where historically we have
7702 // allowed type attributes after the identifier to slide to the type.
7703 if (AL.slidesFromDeclToDeclSpecLegacyBehavior() &&
7704 isa<DeclaratorDecl, TypeAliasDecl>(Val: D)) {
7705 // Suggest moving the attribute to the type instead, but only for our
7706 // own vendor attributes; moving other vendors' attributes might hurt
7707 // portability.
7708 if (AL.isClangScope()) {
7709 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_type_attribute_deprecated_on_decl)
7710 << AL << D->getLocation();
7711 }
7712
7713 // Allow this type attribute to be handled in processTypeAttrs();
7714 // silently move on.
7715 break;
7716 }
7717
7718 if (AL.getKind() == ParsedAttr::AT_Regparm) {
7719 // `regparm` is a special case: It's a type attribute but we still want
7720 // to treat it as if it had been written on the declaration because that
7721 // way we'll be able to handle it directly in `processTypeAttr()`.
7722 // If we treated `regparm` it as if it had been written on the
7723 // `DeclSpec`, the logic in `distributeFunctionTypeAttrFromDeclSepc()`
7724 // would try to move it to the declarator, but that doesn't work: We
7725 // can't remove the attribute from the list of declaration attributes
7726 // because it might be needed by other declarators in the same
7727 // declaration.
7728 break;
7729 }
7730
7731 if (AL.getKind() == ParsedAttr::AT_VectorSize) {
7732 // `vector_size` is a special case: It's a type attribute semantically,
7733 // but GCC expects the [[]] syntax to be written on the declaration (and
7734 // warns that the attribute has no effect if it is placed on the
7735 // decl-specifier-seq).
7736 // Silently move on and allow the attribute to be handled in
7737 // processTypeAttr().
7738 break;
7739 }
7740
7741 if (AL.getKind() == ParsedAttr::AT_NoDeref) {
7742 // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
7743 // See https://github.com/llvm/llvm-project/issues/55790 for details.
7744 // We allow processTypeAttrs() to emit a warning and silently move on.
7745 break;
7746 }
7747 }
7748 // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a
7749 // statement attribute is not written on a declaration, but this code is
7750 // needed for type attributes as well as statement attributes in Attr.td
7751 // that do not list any subjects.
7752 S.Diag(Loc: AL.getLoc(), DiagID: diag::err_attribute_invalid_on_decl)
7753 << AL << AL.isRegularKeywordAttribute() << D->getLocation();
7754 break;
7755 case ParsedAttr::AT_Interrupt:
7756 handleInterruptAttr(S, D, AL);
7757 break;
7758 case ParsedAttr::AT_ARMInterruptSaveFP:
7759 S.ARM().handleInterruptSaveFPAttr(D, AL);
7760 break;
7761 case ParsedAttr::AT_X86ForceAlignArgPointer:
7762 S.X86().handleForceAlignArgPointerAttr(D, AL);
7763 break;
7764 case ParsedAttr::AT_ReadOnlyPlacement:
7765 handleSimpleAttribute<ReadOnlyPlacementAttr>(S, D, CI: AL);
7766 break;
7767 case ParsedAttr::AT_DLLExport:
7768 case ParsedAttr::AT_DLLImport:
7769 handleDLLAttr(S, D, A: AL);
7770 break;
7771 case ParsedAttr::AT_AMDGPUFlatWorkGroupSize:
7772 S.AMDGPU().handleAMDGPUFlatWorkGroupSizeAttr(D, AL);
7773 break;
7774 case ParsedAttr::AT_AMDGPUWavesPerEU:
7775 S.AMDGPU().handleAMDGPUWavesPerEUAttr(D, AL);
7776 break;
7777 case ParsedAttr::AT_AMDGPUNumSGPR:
7778 S.AMDGPU().handleAMDGPUNumSGPRAttr(D, AL);
7779 break;
7780 case ParsedAttr::AT_AMDGPUNumVGPR:
7781 S.AMDGPU().handleAMDGPUNumVGPRAttr(D, AL);
7782 break;
7783 case ParsedAttr::AT_AMDGPUMaxNumWorkGroups:
7784 S.AMDGPU().handleAMDGPUMaxNumWorkGroupsAttr(D, AL);
7785 break;
7786 case ParsedAttr::AT_AVRSignal:
7787 S.AVR().handleSignalAttr(D, AL);
7788 break;
7789 case ParsedAttr::AT_BPFPreserveAccessIndex:
7790 S.BPF().handlePreserveAccessIndexAttr(D, AL);
7791 break;
7792 case ParsedAttr::AT_BPFPreserveStaticOffset:
7793 handleSimpleAttribute<BPFPreserveStaticOffsetAttr>(S, D, CI: AL);
7794 break;
7795 case ParsedAttr::AT_BTFDeclTag:
7796 handleBTFDeclTagAttr(S, D, AL);
7797 break;
7798 case ParsedAttr::AT_HexagonHLXVectorStackLimit:
7799 S.Hexagon().handleHLXVectorStackLimitAttr(D, AL);
7800 break;
7801 case ParsedAttr::AT_WebAssemblyExportName:
7802 S.Wasm().handleWebAssemblyExportNameAttr(D, AL);
7803 break;
7804 case ParsedAttr::AT_WebAssemblyImportModule:
7805 S.Wasm().handleWebAssemblyImportModuleAttr(D, AL);
7806 break;
7807 case ParsedAttr::AT_WebAssemblyImportName:
7808 S.Wasm().handleWebAssemblyImportNameAttr(D, AL);
7809 break;
7810 case ParsedAttr::AT_IBOutlet:
7811 S.ObjC().handleIBOutlet(D, AL);
7812 break;
7813 case ParsedAttr::AT_IBOutletCollection:
7814 S.ObjC().handleIBOutletCollection(D, AL);
7815 break;
7816 case ParsedAttr::AT_IFunc:
7817 handleIFuncAttr(S, D, AL);
7818 break;
7819 case ParsedAttr::AT_Alias:
7820 handleAliasAttr(S, D, AL);
7821 break;
7822 case ParsedAttr::AT_Aligned:
7823 handleAlignedAttr(S, D, AL);
7824 break;
7825 case ParsedAttr::AT_AlignValue:
7826 handleAlignValueAttr(S, D, AL);
7827 break;
7828 case ParsedAttr::AT_AllocSize:
7829 handleAllocSizeAttr(S, D, AL);
7830 break;
7831 case ParsedAttr::AT_AlwaysInline:
7832 handleAlwaysInlineAttr(S, D, AL);
7833 break;
7834 case ParsedAttr::AT_AnalyzerNoReturn:
7835 handleAnalyzerNoReturnAttr(S, D, AL);
7836 break;
7837 case ParsedAttr::AT_TLSModel:
7838 handleTLSModelAttr(S, D, AL);
7839 break;
7840 case ParsedAttr::AT_Annotate:
7841 handleAnnotateAttr(S, D, AL);
7842 break;
7843 case ParsedAttr::AT_Availability:
7844 handleAvailabilityAttr(S, D, AL);
7845 break;
7846 case ParsedAttr::AT_CPUDispatch:
7847 case ParsedAttr::AT_CPUSpecific:
7848 handleCPUSpecificAttr(S, D, AL);
7849 break;
7850 case ParsedAttr::AT_Common:
7851 handleCommonAttr(S, D, AL);
7852 break;
7853 case ParsedAttr::AT_CUDAConstant:
7854 handleConstantAttr(S, D, AL);
7855 break;
7856 case ParsedAttr::AT_PassObjectSize:
7857 handlePassObjectSizeAttr(S, D, AL);
7858 break;
7859 case ParsedAttr::AT_Constructor:
7860 handleConstructorAttr(S, D, AL);
7861 break;
7862 case ParsedAttr::AT_Deprecated:
7863 handleDeprecatedAttr(S, D, AL);
7864 break;
7865 case ParsedAttr::AT_Destructor:
7866 handleDestructorAttr(S, D, AL);
7867 break;
7868 case ParsedAttr::AT_EnableIf:
7869 handleEnableIfAttr(S, D, AL);
7870 break;
7871 case ParsedAttr::AT_Error:
7872 handleErrorAttr(S, D, AL);
7873 break;
7874 case ParsedAttr::AT_ExcludeFromExplicitInstantiation:
7875 handleExcludeFromExplicitInstantiationAttr(S, D, AL);
7876 break;
7877 case ParsedAttr::AT_DiagnoseIf:
7878 handleDiagnoseIfAttr(S, D, AL);
7879 break;
7880 case ParsedAttr::AT_DiagnoseAsBuiltin:
7881 handleDiagnoseAsBuiltinAttr(S, D, AL);
7882 break;
7883 case ParsedAttr::AT_NoBuiltin:
7884 handleNoBuiltinAttr(S, D, AL);
7885 break;
7886 case ParsedAttr::AT_CFIUncheckedCallee:
7887 handleCFIUncheckedCalleeAttr(S, D, Attrs: AL);
7888 break;
7889 case ParsedAttr::AT_ExtVectorType:
7890 handleExtVectorTypeAttr(S, D, AL);
7891 break;
7892 case ParsedAttr::AT_ExternalSourceSymbol:
7893 handleExternalSourceSymbolAttr(S, D, AL);
7894 break;
7895 case ParsedAttr::AT_MinSize:
7896 handleMinSizeAttr(S, D, AL);
7897 break;
7898 case ParsedAttr::AT_OptimizeNone:
7899 handleOptimizeNoneAttr(S, D, AL);
7900 break;
7901 case ParsedAttr::AT_EnumExtensibility:
7902 handleEnumExtensibilityAttr(S, D, AL);
7903 break;
7904 case ParsedAttr::AT_SYCLKernel:
7905 S.SYCL().handleKernelAttr(D, AL);
7906 break;
7907 case ParsedAttr::AT_SYCLExternal:
7908 S.SYCL().handleSYCLExternalAttr(D, AL);
7909 break;
7910 case ParsedAttr::AT_SYCLKernelEntryPoint:
7911 S.SYCL().handleKernelEntryPointAttr(D, AL);
7912 break;
7913 case ParsedAttr::AT_SYCLSpecialClass:
7914 handleSimpleAttribute<SYCLSpecialClassAttr>(S, D, CI: AL);
7915 break;
7916 case ParsedAttr::AT_Format:
7917 handleFormatAttr(S, D, AL);
7918 break;
7919 case ParsedAttr::AT_FormatMatches:
7920 handleFormatMatchesAttr(S, D, AL);
7921 break;
7922 case ParsedAttr::AT_FormatArg:
7923 handleFormatArgAttr(S, D, AL);
7924 break;
7925 case ParsedAttr::AT_Callback:
7926 handleCallbackAttr(S, D, AL);
7927 break;
7928 case ParsedAttr::AT_LifetimeCaptureBy:
7929 handleLifetimeCaptureByAttr(S, D, AL);
7930 break;
7931 case ParsedAttr::AT_CalledOnce:
7932 handleCalledOnceAttr(S, D, AL);
7933 break;
7934 case ParsedAttr::AT_CUDAGlobal:
7935 handleGlobalAttr(S, D, AL);
7936 break;
7937 case ParsedAttr::AT_CUDADevice:
7938 handleDeviceAttr(S, D, AL);
7939 break;
7940 case ParsedAttr::AT_CUDAGridConstant:
7941 handleGridConstantAttr(S, D, AL);
7942 break;
7943 case ParsedAttr::AT_HIPManaged:
7944 handleManagedAttr(S, D, AL);
7945 break;
7946 case ParsedAttr::AT_GNUInline:
7947 handleGNUInlineAttr(S, D, AL);
7948 break;
7949 case ParsedAttr::AT_CUDALaunchBounds:
7950 handleLaunchBoundsAttr(S, D, AL);
7951 break;
7952 case ParsedAttr::AT_CUDAClusterDims:
7953 handleClusterDimsAttr(S, D, AL);
7954 break;
7955 case ParsedAttr::AT_CUDANoCluster:
7956 handleNoClusterAttr(S, D, AL);
7957 break;
7958 case ParsedAttr::AT_Restrict:
7959 handleRestrictAttr(S, D, AL);
7960 break;
7961 case ParsedAttr::AT_MallocSpan:
7962 handleMallocSpanAttr(S, D, AL);
7963 break;
7964 case ParsedAttr::AT_Mode:
7965 handleModeAttr(S, D, AL);
7966 break;
7967 case ParsedAttr::AT_NonString:
7968 handleNonStringAttr(S, D, AL);
7969 break;
7970 case ParsedAttr::AT_NonNull:
7971 if (auto *PVD = dyn_cast<ParmVarDecl>(Val: D))
7972 handleNonNullAttrParameter(S, D: PVD, AL);
7973 else
7974 handleNonNullAttr(S, D, AL);
7975 break;
7976 case ParsedAttr::AT_ReturnsNonNull:
7977 handleReturnsNonNullAttr(S, D, AL);
7978 break;
7979 case ParsedAttr::AT_NoEscape:
7980 handleNoEscapeAttr(S, D, AL);
7981 break;
7982 case ParsedAttr::AT_MaybeUndef:
7983 handleSimpleAttribute<MaybeUndefAttr>(S, D, CI: AL);
7984 break;
7985 case ParsedAttr::AT_AssumeAligned:
7986 handleAssumeAlignedAttr(S, D, AL);
7987 break;
7988 case ParsedAttr::AT_AllocAlign:
7989 handleAllocAlignAttr(S, D, AL);
7990 break;
7991 case ParsedAttr::AT_Ownership:
7992 handleOwnershipAttr(S, D, AL);
7993 break;
7994 case ParsedAttr::AT_Naked:
7995 handleNakedAttr(S, D, AL);
7996 break;
7997 case ParsedAttr::AT_NoReturn:
7998 handleNoReturnAttr(S, D, Attrs: AL);
7999 break;
8000 case ParsedAttr::AT_CXX11NoReturn:
8001 handleStandardNoReturnAttr(S, D, A: AL);
8002 break;
8003 case ParsedAttr::AT_AnyX86NoCfCheck:
8004 handleNoCfCheckAttr(S, D, Attrs: AL);
8005 break;
8006 case ParsedAttr::AT_NoThrow:
8007 if (!AL.isUsedAsTypeAttr())
8008 handleSimpleAttribute<NoThrowAttr>(S, D, CI: AL);
8009 break;
8010 case ParsedAttr::AT_CUDAShared:
8011 handleSharedAttr(S, D, AL);
8012 break;
8013 case ParsedAttr::AT_VecReturn:
8014 handleVecReturnAttr(S, D, AL);
8015 break;
8016 case ParsedAttr::AT_ObjCOwnership:
8017 S.ObjC().handleOwnershipAttr(D, AL);
8018 break;
8019 case ParsedAttr::AT_ObjCPreciseLifetime:
8020 S.ObjC().handlePreciseLifetimeAttr(D, AL);
8021 break;
8022 case ParsedAttr::AT_ObjCReturnsInnerPointer:
8023 S.ObjC().handleReturnsInnerPointerAttr(D, Attrs: AL);
8024 break;
8025 case ParsedAttr::AT_ObjCRequiresSuper:
8026 S.ObjC().handleRequiresSuperAttr(D, Attrs: AL);
8027 break;
8028 case ParsedAttr::AT_ObjCBridge:
8029 S.ObjC().handleBridgeAttr(D, AL);
8030 break;
8031 case ParsedAttr::AT_ObjCBridgeMutable:
8032 S.ObjC().handleBridgeMutableAttr(D, AL);
8033 break;
8034 case ParsedAttr::AT_ObjCBridgeRelated:
8035 S.ObjC().handleBridgeRelatedAttr(D, AL);
8036 break;
8037 case ParsedAttr::AT_ObjCDesignatedInitializer:
8038 S.ObjC().handleDesignatedInitializer(D, AL);
8039 break;
8040 case ParsedAttr::AT_ObjCRuntimeName:
8041 S.ObjC().handleRuntimeName(D, AL);
8042 break;
8043 case ParsedAttr::AT_ObjCBoxable:
8044 S.ObjC().handleBoxable(D, AL);
8045 break;
8046 case ParsedAttr::AT_NSErrorDomain:
8047 S.ObjC().handleNSErrorDomain(D, Attr: AL);
8048 break;
8049 case ParsedAttr::AT_CFConsumed:
8050 case ParsedAttr::AT_NSConsumed:
8051 case ParsedAttr::AT_OSConsumed:
8052 S.ObjC().AddXConsumedAttr(D, CI: AL,
8053 K: S.ObjC().parsedAttrToRetainOwnershipKind(AL),
8054 /*IsTemplateInstantiation=*/false);
8055 break;
8056 case ParsedAttr::AT_OSReturnsRetainedOnZero:
8057 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnZeroAttr>(
8058 S, D, CI: AL, PassesCheck: S.ObjC().isValidOSObjectOutParameter(D),
8059 DiagID: diag::warn_ns_attribute_wrong_parameter_type,
8060 /*Extra Args=*/ExtraArgs: AL, /*pointer-to-OSObject-pointer*/ ExtraArgs: 3, ExtraArgs: AL.getRange());
8061 break;
8062 case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
8063 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnNonZeroAttr>(
8064 S, D, CI: AL, PassesCheck: S.ObjC().isValidOSObjectOutParameter(D),
8065 DiagID: diag::warn_ns_attribute_wrong_parameter_type,
8066 /*Extra Args=*/ExtraArgs: AL, /*pointer-to-OSObject-poointer*/ ExtraArgs: 3, ExtraArgs: AL.getRange());
8067 break;
8068 case ParsedAttr::AT_NSReturnsAutoreleased:
8069 case ParsedAttr::AT_NSReturnsNotRetained:
8070 case ParsedAttr::AT_NSReturnsRetained:
8071 case ParsedAttr::AT_CFReturnsNotRetained:
8072 case ParsedAttr::AT_CFReturnsRetained:
8073 case ParsedAttr::AT_OSReturnsNotRetained:
8074 case ParsedAttr::AT_OSReturnsRetained:
8075 S.ObjC().handleXReturnsXRetainedAttr(D, AL);
8076 break;
8077 case ParsedAttr::AT_WorkGroupSizeHint:
8078 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL);
8079 break;
8080 case ParsedAttr::AT_ReqdWorkGroupSize:
8081 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL);
8082 break;
8083 case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize:
8084 S.OpenCL().handleSubGroupSize(D, AL);
8085 break;
8086 case ParsedAttr::AT_VecTypeHint:
8087 handleVecTypeHint(S, D, AL);
8088 break;
8089 case ParsedAttr::AT_InitPriority:
8090 handleInitPriorityAttr(S, D, AL);
8091 break;
8092 case ParsedAttr::AT_Packed:
8093 handlePackedAttr(S, D, AL);
8094 break;
8095 case ParsedAttr::AT_PreferredName:
8096 handlePreferredName(S, D, AL);
8097 break;
8098 case ParsedAttr::AT_NoSpecializations:
8099 handleNoSpecializations(S, D, AL);
8100 break;
8101 case ParsedAttr::AT_Section:
8102 handleSectionAttr(S, D, AL);
8103 break;
8104 case ParsedAttr::AT_CodeModel:
8105 handleCodeModelAttr(S, D, AL);
8106 break;
8107 case ParsedAttr::AT_RandomizeLayout:
8108 handleRandomizeLayoutAttr(S, D, AL);
8109 break;
8110 case ParsedAttr::AT_NoRandomizeLayout:
8111 handleNoRandomizeLayoutAttr(S, D, AL);
8112 break;
8113 case ParsedAttr::AT_CodeSeg:
8114 handleCodeSegAttr(S, D, AL);
8115 break;
8116 case ParsedAttr::AT_Target:
8117 handleTargetAttr(S, D, AL);
8118 break;
8119 case ParsedAttr::AT_TargetVersion:
8120 handleTargetVersionAttr(S, D, AL);
8121 break;
8122 case ParsedAttr::AT_TargetClones:
8123 handleTargetClonesAttr(S, D, AL);
8124 break;
8125 case ParsedAttr::AT_MinVectorWidth:
8126 handleMinVectorWidthAttr(S, D, AL);
8127 break;
8128 case ParsedAttr::AT_Unavailable:
8129 handleAttrWithMessage<UnavailableAttr>(S, D, AL);
8130 break;
8131 case ParsedAttr::AT_OMPAssume:
8132 S.OpenMP().handleOMPAssumeAttr(D, AL);
8133 break;
8134 case ParsedAttr::AT_ObjCDirect:
8135 S.ObjC().handleDirectAttr(D, AL);
8136 break;
8137 case ParsedAttr::AT_ObjCDirectMembers:
8138 S.ObjC().handleDirectMembersAttr(D, AL);
8139 handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, CI: AL);
8140 break;
8141 case ParsedAttr::AT_ObjCExplicitProtocolImpl:
8142 S.ObjC().handleSuppresProtocolAttr(D, AL);
8143 break;
8144 case ParsedAttr::AT_Unused:
8145 handleUnusedAttr(S, D, AL);
8146 break;
8147 case ParsedAttr::AT_Visibility:
8148 handleVisibilityAttr(S, D, AL, isTypeVisibility: false);
8149 break;
8150 case ParsedAttr::AT_TypeVisibility:
8151 handleVisibilityAttr(S, D, AL, isTypeVisibility: true);
8152 break;
8153 case ParsedAttr::AT_WarnUnusedResult:
8154 handleWarnUnusedResult(S, D, AL);
8155 break;
8156 case ParsedAttr::AT_WeakRef:
8157 handleWeakRefAttr(S, D, AL);
8158 break;
8159 case ParsedAttr::AT_WeakImport:
8160 handleWeakImportAttr(S, D, AL);
8161 break;
8162 case ParsedAttr::AT_TransparentUnion:
8163 handleTransparentUnionAttr(S, D, AL);
8164 break;
8165 case ParsedAttr::AT_ObjCMethodFamily:
8166 S.ObjC().handleMethodFamilyAttr(D, AL);
8167 break;
8168 case ParsedAttr::AT_ObjCNSObject:
8169 S.ObjC().handleNSObject(D, AL);
8170 break;
8171 case ParsedAttr::AT_ObjCIndependentClass:
8172 S.ObjC().handleIndependentClass(D, AL);
8173 break;
8174 case ParsedAttr::AT_Blocks:
8175 S.ObjC().handleBlocksAttr(D, AL);
8176 break;
8177 case ParsedAttr::AT_Sentinel:
8178 handleSentinelAttr(S, D, AL);
8179 break;
8180 case ParsedAttr::AT_Cleanup:
8181 handleCleanupAttr(S, D, AL);
8182 break;
8183 case ParsedAttr::AT_NoDebug:
8184 handleNoDebugAttr(S, D, AL);
8185 break;
8186 case ParsedAttr::AT_CmseNSEntry:
8187 S.ARM().handleCmseNSEntryAttr(D, AL);
8188 break;
8189 case ParsedAttr::AT_StdCall:
8190 case ParsedAttr::AT_CDecl:
8191 case ParsedAttr::AT_FastCall:
8192 case ParsedAttr::AT_ThisCall:
8193 case ParsedAttr::AT_Pascal:
8194 case ParsedAttr::AT_RegCall:
8195 case ParsedAttr::AT_SwiftCall:
8196 case ParsedAttr::AT_SwiftAsyncCall:
8197 case ParsedAttr::AT_VectorCall:
8198 case ParsedAttr::AT_MSABI:
8199 case ParsedAttr::AT_SysVABI:
8200 case ParsedAttr::AT_Pcs:
8201 case ParsedAttr::AT_IntelOclBicc:
8202 case ParsedAttr::AT_PreserveMost:
8203 case ParsedAttr::AT_PreserveAll:
8204 case ParsedAttr::AT_AArch64VectorPcs:
8205 case ParsedAttr::AT_AArch64SVEPcs:
8206 case ParsedAttr::AT_M68kRTD:
8207 case ParsedAttr::AT_PreserveNone:
8208 case ParsedAttr::AT_RISCVVectorCC:
8209 case ParsedAttr::AT_RISCVVLSCC:
8210 handleCallConvAttr(S, D, AL);
8211 break;
8212 case ParsedAttr::AT_DeviceKernel:
8213 handleDeviceKernelAttr(S, D, AL);
8214 break;
8215 case ParsedAttr::AT_Suppress:
8216 handleSuppressAttr(S, D, AL);
8217 break;
8218 case ParsedAttr::AT_Owner:
8219 case ParsedAttr::AT_Pointer:
8220 handleLifetimeCategoryAttr(S, D, AL);
8221 break;
8222 case ParsedAttr::AT_OpenCLAccess:
8223 S.OpenCL().handleAccessAttr(D, AL);
8224 break;
8225 case ParsedAttr::AT_OpenCLNoSVM:
8226 S.OpenCL().handleNoSVMAttr(D, AL);
8227 break;
8228 case ParsedAttr::AT_SwiftContext:
8229 S.Swift().AddParameterABIAttr(D, CI: AL, abi: ParameterABI::SwiftContext);
8230 break;
8231 case ParsedAttr::AT_SwiftAsyncContext:
8232 S.Swift().AddParameterABIAttr(D, CI: AL, abi: ParameterABI::SwiftAsyncContext);
8233 break;
8234 case ParsedAttr::AT_SwiftErrorResult:
8235 S.Swift().AddParameterABIAttr(D, CI: AL, abi: ParameterABI::SwiftErrorResult);
8236 break;
8237 case ParsedAttr::AT_SwiftIndirectResult:
8238 S.Swift().AddParameterABIAttr(D, CI: AL, abi: ParameterABI::SwiftIndirectResult);
8239 break;
8240 case ParsedAttr::AT_InternalLinkage:
8241 handleInternalLinkageAttr(S, D, AL);
8242 break;
8243 case ParsedAttr::AT_ZeroCallUsedRegs:
8244 handleZeroCallUsedRegsAttr(S, D, AL);
8245 break;
8246 case ParsedAttr::AT_FunctionReturnThunks:
8247 handleFunctionReturnThunksAttr(S, D, AL);
8248 break;
8249 case ParsedAttr::AT_NoMerge:
8250 handleNoMergeAttr(S, D, AL);
8251 break;
8252 case ParsedAttr::AT_NoUniqueAddress:
8253 handleNoUniqueAddressAttr(S, D, AL);
8254 break;
8255
8256 case ParsedAttr::AT_AvailableOnlyInDefaultEvalMethod:
8257 handleAvailableOnlyInDefaultEvalMethod(S, D, AL);
8258 break;
8259
8260 case ParsedAttr::AT_CountedBy:
8261 case ParsedAttr::AT_CountedByOrNull:
8262 case ParsedAttr::AT_SizedBy:
8263 case ParsedAttr::AT_SizedByOrNull:
8264 handleCountedByAttrField(S, D, AL);
8265 break;
8266
8267 case ParsedAttr::AT_NoFieldProtection:
8268 handleNoPFPAttrField(S, D, AL);
8269 break;
8270
8271 case ParsedAttr::AT_Personality:
8272 handlePersonalityAttr(S, D, AL);
8273 break;
8274
8275 // Microsoft attributes:
8276 case ParsedAttr::AT_LayoutVersion:
8277 handleLayoutVersion(S, D, AL);
8278 break;
8279 case ParsedAttr::AT_Uuid:
8280 handleUuidAttr(S, D, AL);
8281 break;
8282 case ParsedAttr::AT_MSInheritance:
8283 handleMSInheritanceAttr(S, D, AL);
8284 break;
8285 case ParsedAttr::AT_Thread:
8286 handleDeclspecThreadAttr(S, D, AL);
8287 break;
8288 case ParsedAttr::AT_MSConstexpr:
8289 handleMSConstexprAttr(S, D, AL);
8290 break;
8291 case ParsedAttr::AT_HybridPatchable:
8292 handleSimpleAttribute<HybridPatchableAttr>(S, D, CI: AL);
8293 break;
8294
8295 // HLSL attributes:
8296 case ParsedAttr::AT_RootSignature:
8297 S.HLSL().handleRootSignatureAttr(D, AL);
8298 break;
8299 case ParsedAttr::AT_HLSLNumThreads:
8300 S.HLSL().handleNumThreadsAttr(D, AL);
8301 break;
8302 case ParsedAttr::AT_HLSLWaveSize:
8303 S.HLSL().handleWaveSizeAttr(D, AL);
8304 break;
8305 case ParsedAttr::AT_HLSLVkExtBuiltinInput:
8306 S.HLSL().handleVkExtBuiltinInputAttr(D, AL);
8307 break;
8308 case ParsedAttr::AT_HLSLVkExtBuiltinOutput:
8309 S.HLSL().handleVkExtBuiltinOutputAttr(D, AL);
8310 break;
8311 case ParsedAttr::AT_HLSLVkBuiltIn:
8312 S.HLSL().handleVkBuiltInAttr(D, AL);
8313 break;
8314 case ParsedAttr::AT_HLSLVkPushConstant:
8315 S.HLSL().handleVkPushConstantAttr(D, AL);
8316 break;
8317 case ParsedAttr::AT_HLSLVkConstantId:
8318 S.HLSL().handleVkConstantIdAttr(D, AL);
8319 break;
8320 case ParsedAttr::AT_HLSLVkBinding:
8321 S.HLSL().handleVkBindingAttr(D, AL);
8322 break;
8323 case ParsedAttr::AT_HLSLGroupSharedAddressSpace:
8324 handleSimpleAttribute<HLSLGroupSharedAddressSpaceAttr>(S, D, CI: AL);
8325 break;
8326 case ParsedAttr::AT_HLSLPackOffset:
8327 S.HLSL().handlePackOffsetAttr(D, AL);
8328 break;
8329 case ParsedAttr::AT_HLSLShader:
8330 S.HLSL().handleShaderAttr(D, AL);
8331 break;
8332 case ParsedAttr::AT_HLSLResourceBinding:
8333 S.HLSL().handleResourceBindingAttr(D, AL);
8334 break;
8335 case ParsedAttr::AT_HLSLInterpolationModifier:
8336 S.HLSL().handleInterpolationModifierAttr(D, AL);
8337 break;
8338 case ParsedAttr::AT_HLSLParamModifier:
8339 S.HLSL().handleParamModifierAttr(D, AL);
8340 break;
8341 case ParsedAttr::AT_HLSLUnparsedSemantic:
8342 S.HLSL().handleSemanticAttr(D, AL);
8343 break;
8344 case ParsedAttr::AT_HLSLVkLocation:
8345 S.HLSL().handleVkLocationAttr(D, AL);
8346 break;
8347
8348 case ParsedAttr::AT_AbiTag:
8349 handleAbiTagAttr(S, D, AL);
8350 break;
8351 case ParsedAttr::AT_CFGuard:
8352 handleCFGuardAttr(S, D, AL);
8353 break;
8354
8355 // Thread safety attributes:
8356 case ParsedAttr::AT_PtGuardedVar:
8357 handlePtGuardedVarAttr(S, D, AL);
8358 break;
8359 case ParsedAttr::AT_NoSanitize:
8360 handleNoSanitizeAttr(S, D, AL);
8361 break;
8362 case ParsedAttr::AT_NoSanitizeAddress:
8363 handleNoSanitizeAddressAttr(S, D, AL);
8364 break;
8365 case ParsedAttr::AT_NoSanitizeThread:
8366 handleNoSanitizeThreadAttr(S, D, AL);
8367 break;
8368 case ParsedAttr::AT_NoSanitizeMemory:
8369 handleNoSanitizeMemoryAttr(S, D, AL);
8370 break;
8371 case ParsedAttr::AT_GuardedBy:
8372 handleGuardedByAttr(S, D, AL);
8373 break;
8374 case ParsedAttr::AT_PtGuardedBy:
8375 handlePtGuardedByAttr(S, D, AL);
8376 break;
8377 case ParsedAttr::AT_LockReturned:
8378 handleLockReturnedAttr(S, D, AL);
8379 break;
8380 case ParsedAttr::AT_LocksExcluded:
8381 handleLocksExcludedAttr(S, D, AL);
8382 break;
8383 case ParsedAttr::AT_AcquiredBefore:
8384 handleAcquiredBeforeAttr(S, D, AL);
8385 break;
8386 case ParsedAttr::AT_AcquiredAfter:
8387 handleAcquiredAfterAttr(S, D, AL);
8388 break;
8389
8390 // Capability analysis attributes.
8391 case ParsedAttr::AT_Capability:
8392 case ParsedAttr::AT_Lockable:
8393 handleCapabilityAttr(S, D, AL);
8394 break;
8395 case ParsedAttr::AT_ReentrantCapability:
8396 handleReentrantCapabilityAttr(S, D, AL);
8397 break;
8398 case ParsedAttr::AT_RequiresCapability:
8399 handleRequiresCapabilityAttr(S, D, AL);
8400 break;
8401
8402 case ParsedAttr::AT_AssertCapability:
8403 handleAssertCapabilityAttr(S, D, AL);
8404 break;
8405 case ParsedAttr::AT_AcquireCapability:
8406 handleAcquireCapabilityAttr(S, D, AL);
8407 break;
8408 case ParsedAttr::AT_ReleaseCapability:
8409 handleReleaseCapabilityAttr(S, D, AL);
8410 break;
8411 case ParsedAttr::AT_TryAcquireCapability:
8412 handleTryAcquireCapabilityAttr(S, D, AL);
8413 break;
8414
8415 // Consumed analysis attributes.
8416 case ParsedAttr::AT_Consumable:
8417 handleConsumableAttr(S, D, AL);
8418 break;
8419 case ParsedAttr::AT_CallableWhen:
8420 handleCallableWhenAttr(S, D, AL);
8421 break;
8422 case ParsedAttr::AT_ParamTypestate:
8423 handleParamTypestateAttr(S, D, AL);
8424 break;
8425 case ParsedAttr::AT_ReturnTypestate:
8426 handleReturnTypestateAttr(S, D, AL);
8427 break;
8428 case ParsedAttr::AT_SetTypestate:
8429 handleSetTypestateAttr(S, D, AL);
8430 break;
8431 case ParsedAttr::AT_TestTypestate:
8432 handleTestTypestateAttr(S, D, AL);
8433 break;
8434
8435 // Type safety attributes.
8436 case ParsedAttr::AT_ArgumentWithTypeTag:
8437 handleArgumentWithTypeTagAttr(S, D, AL);
8438 break;
8439 case ParsedAttr::AT_TypeTagForDatatype:
8440 handleTypeTagForDatatypeAttr(S, D, AL);
8441 break;
8442
8443 // Swift attributes.
8444 case ParsedAttr::AT_SwiftAsyncName:
8445 S.Swift().handleAsyncName(D, AL);
8446 break;
8447 case ParsedAttr::AT_SwiftAttr:
8448 S.Swift().handleAttrAttr(D, AL);
8449 break;
8450 case ParsedAttr::AT_SwiftBridge:
8451 S.Swift().handleBridge(D, AL);
8452 break;
8453 case ParsedAttr::AT_SwiftError:
8454 S.Swift().handleError(D, AL);
8455 break;
8456 case ParsedAttr::AT_SwiftName:
8457 S.Swift().handleName(D, AL);
8458 break;
8459 case ParsedAttr::AT_SwiftNewType:
8460 S.Swift().handleNewType(D, AL);
8461 break;
8462 case ParsedAttr::AT_SwiftAsync:
8463 S.Swift().handleAsyncAttr(D, AL);
8464 break;
8465 case ParsedAttr::AT_SwiftAsyncError:
8466 S.Swift().handleAsyncError(D, AL);
8467 break;
8468
8469 // XRay attributes.
8470 case ParsedAttr::AT_XRayLogArgs:
8471 handleXRayLogArgsAttr(S, D, AL);
8472 break;
8473
8474 case ParsedAttr::AT_PatchableFunctionEntry:
8475 handlePatchableFunctionEntryAttr(S, D, AL);
8476 break;
8477
8478 case ParsedAttr::AT_AlwaysDestroy:
8479 case ParsedAttr::AT_NoDestroy:
8480 handleDestroyAttr(S, D, A: AL);
8481 break;
8482
8483 case ParsedAttr::AT_Uninitialized:
8484 handleUninitializedAttr(S, D, AL);
8485 break;
8486
8487 case ParsedAttr::AT_ObjCExternallyRetained:
8488 S.ObjC().handleExternallyRetainedAttr(D, AL);
8489 break;
8490
8491 case ParsedAttr::AT_MIGServerRoutine:
8492 handleMIGServerRoutineAttr(S, D, AL);
8493 break;
8494
8495 case ParsedAttr::AT_MSAllocator:
8496 handleMSAllocatorAttr(S, D, AL);
8497 break;
8498
8499 case ParsedAttr::AT_ArmBuiltinAlias:
8500 S.ARM().handleBuiltinAliasAttr(D, AL);
8501 break;
8502
8503 case ParsedAttr::AT_ArmLocallyStreaming:
8504 handleSimpleAttribute<ArmLocallyStreamingAttr>(S, D, CI: AL);
8505 break;
8506
8507 case ParsedAttr::AT_ArmNew:
8508 S.ARM().handleNewAttr(D, AL);
8509 break;
8510
8511 case ParsedAttr::AT_AcquireHandle:
8512 handleAcquireHandleAttr(S, D, AL);
8513 break;
8514
8515 case ParsedAttr::AT_ReleaseHandle:
8516 handleHandleAttr<ReleaseHandleAttr>(S, D, AL);
8517 break;
8518
8519 case ParsedAttr::AT_UnsafeBufferUsage:
8520 handleUnsafeBufferUsage(S, D, AL);
8521 break;
8522
8523 case ParsedAttr::AT_UseHandle:
8524 handleHandleAttr<UseHandleAttr>(S, D, AL);
8525 break;
8526
8527 case ParsedAttr::AT_EnforceTCB:
8528 handleEnforceTCBAttr<EnforceTCBAttr, EnforceTCBLeafAttr>(S, D, AL);
8529 break;
8530
8531 case ParsedAttr::AT_EnforceTCBLeaf:
8532 handleEnforceTCBAttr<EnforceTCBLeafAttr, EnforceTCBAttr>(S, D, AL);
8533 break;
8534
8535 case ParsedAttr::AT_BuiltinAlias:
8536 handleBuiltinAliasAttr(S, D, AL);
8537 break;
8538
8539 case ParsedAttr::AT_PreferredType:
8540 handlePreferredTypeAttr(S, D, AL);
8541 break;
8542
8543 case ParsedAttr::AT_UsingIfExists:
8544 handleSimpleAttribute<UsingIfExistsAttr>(S, D, CI: AL);
8545 break;
8546
8547 case ParsedAttr::AT_TypeNullable:
8548 handleNullableTypeAttr(S, D, AL);
8549 break;
8550
8551 case ParsedAttr::AT_VTablePointerAuthentication:
8552 handleVTablePointerAuthentication(S, D, AL);
8553 break;
8554
8555 case ParsedAttr::AT_ModularFormat:
8556 handleModularFormat(S, D, AL);
8557 break;
8558
8559 case ParsedAttr::AT_MSStruct:
8560 handleMSStructAttr(S, D, AL);
8561 break;
8562
8563 case ParsedAttr::AT_GCCStruct:
8564 handleGCCStructAttr(S, D, AL);
8565 break;
8566
8567 case ParsedAttr::AT_PointerFieldProtection:
8568 if (!S.getLangOpts().PointerFieldProtectionAttr)
8569 S.Diag(Loc: AL.getLoc(),
8570 DiagID: diag::err_attribute_pointer_field_protection_experimental)
8571 << AL << AL.isRegularKeywordAttribute() << D->getLocation();
8572 handleSimpleAttribute<PointerFieldProtectionAttr>(S, D, CI: AL);
8573 break;
8574 }
8575}
8576
8577static bool isKernelDecl(Decl *D) {
8578 const FunctionType *FnTy = D->getFunctionType();
8579 return D->hasAttr<DeviceKernelAttr>() ||
8580 (FnTy && FnTy->getCallConv() == CallingConv::CC_DeviceKernel) ||
8581 D->hasAttr<CUDAGlobalAttr>();
8582}
8583
8584static void checkAMDGPUReqdWorkGroupSize(Sema &S, Decl *D) {
8585 if (!S.Context.getTargetInfo().getTriple().isAMDGPU())
8586 return;
8587
8588 const auto *Flat = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
8589 const auto *Reqd = D->getAttr<ReqdWorkGroupSizeAttr>();
8590 if (!Flat || !Reqd)
8591 return;
8592
8593 auto Eval = [&](Expr *E) -> std::optional<uint64_t> {
8594 if (E->isValueDependent())
8595 return std::nullopt;
8596 std::optional<llvm::APSInt> V = E->getIntegerConstantExpr(Ctx: S.Context);
8597 if (!V)
8598 return std::nullopt;
8599 return V->getZExtValue();
8600 };
8601
8602 std::optional<uint64_t> X = Eval(Reqd->getXDim());
8603 std::optional<uint64_t> Y = Eval(Reqd->getYDim());
8604 std::optional<uint64_t> Z = Eval(Reqd->getZDim());
8605 std::optional<uint64_t> Min = Eval(Flat->getMin());
8606 std::optional<uint64_t> Max = Eval(Flat->getMax());
8607 if (!X || !Y || !Z || !Min || !Max)
8608 return;
8609
8610 uint64_t Product = *X * *Y * *Z;
8611 if (*Min != Product || *Max != Product) {
8612 S.Diag(Loc: Flat->getLocation(),
8613 DiagID: diag::err_attribute_amdgpu_flat_work_group_size_mismatch);
8614 D->setInvalidDecl();
8615 }
8616}
8617
8618void Sema::ProcessDeclAttributeList(
8619 Scope *S, Decl *D, const ParsedAttributesView &AttrList,
8620 const ProcessDeclAttributeOptions &Options) {
8621 if (AttrList.empty())
8622 return;
8623
8624 for (const ParsedAttr &AL : AttrList)
8625 ProcessDeclAttribute(S&: *this, D, AL, Options);
8626
8627 // FIXME: We should be able to handle these cases in TableGen.
8628 // GCC accepts
8629 // static int a9 __attribute__((weakref));
8630 // but that looks really pointless. We reject it.
8631 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
8632 Diag(Loc: AttrList.begin()->getLoc(), DiagID: diag::err_attribute_weakref_without_alias)
8633 << cast<NamedDecl>(Val: D);
8634 D->dropAttr<WeakRefAttr>();
8635 return;
8636 }
8637
8638 // FIXME: We should be able to handle this in TableGen as well. It would be
8639 // good to have a way to specify "these attributes must appear as a group",
8640 // for these. Additionally, it would be good to have a way to specify "these
8641 // attribute must never appear as a group" for attributes like cold and hot.
8642 if (!(D->hasAttr<DeviceKernelAttr>() ||
8643 (D->hasAttr<CUDAGlobalAttr>() &&
8644 Context.getTargetInfo().getTriple().isSPIRV()))) {
8645 // These attributes cannot be applied to a non-kernel function.
8646 if (const auto *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
8647 // FIXME: This emits a different error message than
8648 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
8649 Diag(Loc: D->getLocation(), DiagID: diag::err_opencl_kernel_attr) << A;
8650 D->setInvalidDecl();
8651 } else if (const auto *A = D->getAttr<WorkGroupSizeHintAttr>()) {
8652 Diag(Loc: D->getLocation(), DiagID: diag::err_opencl_kernel_attr) << A;
8653 D->setInvalidDecl();
8654 } else if (const auto *A = D->getAttr<VecTypeHintAttr>()) {
8655 Diag(Loc: D->getLocation(), DiagID: diag::err_opencl_kernel_attr) << A;
8656 D->setInvalidDecl();
8657 } else if (const auto *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
8658 Diag(Loc: D->getLocation(), DiagID: diag::err_opencl_kernel_attr) << A;
8659 D->setInvalidDecl();
8660 }
8661 }
8662 if (!isKernelDecl(D)) {
8663 if (const auto *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
8664 Diag(Loc: D->getLocation(), DiagID: diag::err_attribute_wrong_decl_type)
8665 << A << A->isRegularKeywordAttribute() << ExpectedKernelFunction;
8666 D->setInvalidDecl();
8667 } else if (const auto *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
8668 Diag(Loc: D->getLocation(), DiagID: diag::err_attribute_wrong_decl_type)
8669 << A << A->isRegularKeywordAttribute() << ExpectedKernelFunction;
8670 D->setInvalidDecl();
8671 } else if (const auto *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
8672 Diag(Loc: D->getLocation(), DiagID: diag::err_attribute_wrong_decl_type)
8673 << A << A->isRegularKeywordAttribute() << ExpectedKernelFunction;
8674 D->setInvalidDecl();
8675 } else if (const auto *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
8676 Diag(Loc: D->getLocation(), DiagID: diag::err_attribute_wrong_decl_type)
8677 << A << A->isRegularKeywordAttribute() << ExpectedKernelFunction;
8678 D->setInvalidDecl();
8679 }
8680 }
8681 checkAMDGPUReqdWorkGroupSize(S&: *this, D);
8682
8683 // CUDA/HIP: restrict explicit CUDA target attributes on deduction guides.
8684 //
8685 // Deduction guides are not callable functions and never participate in
8686 // codegen; they are always treated as host+device for CUDA/HIP semantic
8687 // checks. We therefore allow either no CUDA target attributes or an explicit
8688 // '__host__ __device__' annotation, but reject guides that are host-only,
8689 // device-only, or marked '__global__'. The use of explicit CUDA/HIP target
8690 // attributes on deduction guides is deprecated and will be rejected in a
8691 // future Clang version.
8692 if (getLangOpts().CUDA)
8693 if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: D)) {
8694 bool HasHost = Guide->hasAttr<CUDAHostAttr>();
8695 bool HasDevice = Guide->hasAttr<CUDADeviceAttr>();
8696 bool HasGlobal = Guide->hasAttr<CUDAGlobalAttr>();
8697
8698 if (HasGlobal || HasHost != HasDevice) {
8699 Diag(Loc: Guide->getLocation(), DiagID: diag::err_deduction_guide_target_attr);
8700 Guide->setInvalidDecl();
8701 } else if (HasHost && HasDevice) {
8702 Diag(Loc: Guide->getLocation(),
8703 DiagID: diag::warn_deduction_guide_target_attr_deprecated);
8704 }
8705 }
8706
8707 // Do not permit 'constructor' or 'destructor' attributes on __device__ code.
8708 if (getLangOpts().CUDAIsDevice && D->hasAttr<CUDADeviceAttr>() &&
8709 (D->hasAttr<ConstructorAttr>() || D->hasAttr<DestructorAttr>()) &&
8710 !getLangOpts().GPUAllowDeviceInit) {
8711 Diag(Loc: D->getLocation(), DiagID: diag::err_cuda_ctor_dtor_attrs)
8712 << (D->hasAttr<ConstructorAttr>() ? "constructors" : "destructors");
8713 D->setInvalidDecl();
8714 }
8715
8716 // Do this check after processing D's attributes because the attribute
8717 // objc_method_family can change whether the given method is in the init
8718 // family, and it can be applied after objc_designated_initializer. This is a
8719 // bit of a hack, but we need it to be compatible with versions of clang that
8720 // processed the attribute list in the wrong order.
8721 if (D->hasAttr<ObjCDesignatedInitializerAttr>() &&
8722 cast<ObjCMethodDecl>(Val: D)->getMethodFamily() != OMF_init) {
8723 Diag(Loc: D->getLocation(), DiagID: diag::err_designated_init_attr_non_init);
8724 D->dropAttr<ObjCDesignatedInitializerAttr>();
8725 }
8726}
8727
8728void Sema::ProcessDeclAttributeDelayed(Decl *D,
8729 const ParsedAttributesView &AttrList) {
8730 for (const ParsedAttr &AL : AttrList)
8731 if (AL.getKind() == ParsedAttr::AT_TransparentUnion) {
8732 handleTransparentUnionAttr(S&: *this, D, AL);
8733 break;
8734 }
8735
8736 // For BPFPreserveAccessIndexAttr, we want to populate the attributes
8737 // to fields and inner records as well.
8738 if (D && D->hasAttr<BPFPreserveAccessIndexAttr>())
8739 BPF().handlePreserveAIRecord(RD: cast<RecordDecl>(Val: D));
8740}
8741
8742bool Sema::ProcessAccessDeclAttributeList(
8743 AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList) {
8744 for (const ParsedAttr &AL : AttrList) {
8745 if (AL.getKind() == ParsedAttr::AT_Annotate) {
8746 ProcessDeclAttribute(S&: *this, D: ASDecl, AL, Options: ProcessDeclAttributeOptions());
8747 } else {
8748 Diag(Loc: AL.getLoc(), DiagID: diag::err_only_annotate_after_access_spec);
8749 return true;
8750 }
8751 }
8752 return false;
8753}
8754
8755/// checkUnusedDeclAttributes - Check a list of attributes to see if it
8756/// contains any decl attributes that we should warn about.
8757static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A) {
8758 for (const ParsedAttr &AL : A) {
8759 // Only warn if the attribute is an unignored, non-type attribute.
8760 if (AL.isUsedAsTypeAttr() || AL.isInvalid())
8761 continue;
8762 if (AL.getKind() == ParsedAttr::IgnoredAttribute)
8763 continue;
8764
8765 if (AL.getKind() == ParsedAttr::UnknownAttribute) {
8766 S.DiagnoseUnknownAttribute(AL);
8767 } else {
8768 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_not_on_decl) << AL
8769 << AL.getRange();
8770 }
8771 }
8772}
8773
8774void Sema::checkUnusedDeclAttributes(Declarator &D) {
8775 ::checkUnusedDeclAttributes(S&: *this, A: D.getDeclarationAttributes());
8776 ::checkUnusedDeclAttributes(S&: *this, A: D.getDeclSpec().getAttributes());
8777 ::checkUnusedDeclAttributes(S&: *this, A: D.getAttributes());
8778 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
8779 ::checkUnusedDeclAttributes(S&: *this, A: D.getTypeObject(i).getAttrs());
8780}
8781
8782void Sema::DiagnoseUnknownAttribute(const ParsedAttr &AL) {
8783 SourceRange NR = AL.getNormalizedRange();
8784 // Skip the expensive spelling-list typo-correction scan when the
8785 // diagnostics it feeds are disabled at this location.
8786 if (Diags.isIgnored(DiagID: diag::warn_unknown_attribute_ignored, Loc: NR.getBegin()) &&
8787 Diags.isIgnored(DiagID: diag::warn_unknown_attribute_ignored_suggestion,
8788 Loc: NR.getBegin()))
8789 return;
8790 StringRef ScopeName = AL.getNormalizedScopeName();
8791 std::optional<StringRef> CorrectedScopeName =
8792 AL.tryGetCorrectedScopeName(ScopeName);
8793 if (CorrectedScopeName) {
8794 ScopeName = *CorrectedScopeName;
8795 }
8796
8797 StringRef AttrName = AL.getNormalizedAttrName(ScopeName);
8798 std::optional<StringRef> CorrectedAttrName = AL.tryGetCorrectedAttrName(
8799 ScopeName, AttrName, Target: Context.getTargetInfo(), LangOpts: getLangOpts());
8800 if (CorrectedAttrName) {
8801 AttrName = *CorrectedAttrName;
8802 }
8803
8804 if (CorrectedScopeName || CorrectedAttrName) {
8805 std::string CorrectedFullName =
8806 AL.getNormalizedFullName(ScopeName, AttrName);
8807 SemaDiagnosticBuilder D =
8808 Diag(Loc: CorrectedScopeName ? NR.getBegin() : AL.getRange().getBegin(),
8809 DiagID: diag::warn_unknown_attribute_ignored_suggestion);
8810
8811 D << AL << CorrectedFullName;
8812
8813 if (AL.isExplicitScope()) {
8814 D << FixItHint::CreateReplacement(RemoveRange: NR, Code: CorrectedFullName) << NR;
8815 } else {
8816 if (CorrectedScopeName) {
8817 D << FixItHint::CreateReplacement(RemoveRange: SourceRange(AL.getScopeLoc()),
8818 Code: ScopeName);
8819 }
8820 if (CorrectedAttrName) {
8821 D << FixItHint::CreateReplacement(RemoveRange: AL.getRange(), Code: AttrName);
8822 }
8823 }
8824 } else {
8825 Diag(Loc: NR.getBegin(), DiagID: diag::warn_unknown_attribute_ignored) << AL << NR;
8826 }
8827}
8828
8829NamedDecl *Sema::DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II,
8830 SourceLocation Loc) {
8831 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND));
8832 NamedDecl *NewD = nullptr;
8833 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND)) {
8834 FunctionDecl *NewFD;
8835 // FIXME: Missing call to CheckFunctionDeclaration().
8836 // FIXME: Mangling?
8837 // FIXME: Is the qualifier info correct?
8838 // FIXME: Is the DeclContext correct?
8839 NewFD = FunctionDecl::Create(
8840 C&: FD->getASTContext(), DC: FD->getDeclContext(), StartLoc: Loc, NLoc: Loc,
8841 N: DeclarationName(II), T: FD->getType(), TInfo: FD->getTypeSourceInfo(), SC: SC_None,
8842 UsesFPIntrin: getCurFPFeatures().isFPConstrained(), isInlineSpecified: false /*isInlineSpecified*/,
8843 hasWrittenPrototype: FD->hasPrototype(), ConstexprKind: ConstexprSpecKind::Unspecified,
8844 TrailingRequiresClause: FD->getTrailingRequiresClause());
8845 NewD = NewFD;
8846
8847 if (FD->getQualifier())
8848 NewFD->setQualifierInfo(FD->getQualifierLoc());
8849
8850 // Fake up parameter variables; they are declared as if this were
8851 // a typedef.
8852 QualType FDTy = FD->getType();
8853 if (const auto *FT = FDTy->getAs<FunctionProtoType>()) {
8854 SmallVector<ParmVarDecl*, 16> Params;
8855 for (const auto &AI : FT->param_types()) {
8856 ParmVarDecl *Param = BuildParmVarDeclForTypedef(DC: NewFD, Loc, T: AI);
8857 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
8858 Params.push_back(Elt: Param);
8859 }
8860 NewFD->setParams(Params);
8861 }
8862 } else if (auto *VD = dyn_cast<VarDecl>(Val: ND)) {
8863 NewD = VarDecl::Create(C&: VD->getASTContext(), DC: VD->getDeclContext(),
8864 StartLoc: VD->getInnerLocStart(), IdLoc: VD->getLocation(), Id: II,
8865 T: VD->getType(), TInfo: VD->getTypeSourceInfo(),
8866 S: VD->getStorageClass());
8867 if (VD->getQualifier())
8868 cast<VarDecl>(Val: NewD)->setQualifierInfo(VD->getQualifierLoc());
8869 }
8870 return NewD;
8871}
8872
8873void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W) {
8874 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
8875 IdentifierInfo *NDId = ND->getIdentifier();
8876 NamedDecl *NewD = DeclClonePragmaWeak(ND, II: W.getAlias(), Loc: W.getLocation());
8877 NewD->addAttr(
8878 A: AliasAttr::CreateImplicit(Ctx&: Context, Aliasee: NDId->getName(), Range: W.getLocation()));
8879 NewD->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context, Range: W.getLocation()));
8880 WeakTopLevelDecl.push_back(Elt: NewD);
8881 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
8882 // to insert Decl at TU scope, sorry.
8883 DeclContext *SavedContext = CurContext;
8884 CurContext = Context.getTranslationUnitDecl();
8885 NewD->setDeclContext(CurContext);
8886 NewD->setLexicalDeclContext(CurContext);
8887 PushOnScopeChains(D: NewD, S);
8888 CurContext = SavedContext;
8889 } else { // just add weak to existing
8890 ND->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context, Range: W.getLocation()));
8891 }
8892}
8893
8894void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
8895 // It's valid to "forward-declare" #pragma weak, in which case we
8896 // have to do this.
8897 LoadExternalWeakUndeclaredIdentifiers();
8898 if (WeakUndeclaredIdentifiers.empty())
8899 return;
8900 NamedDecl *ND = nullptr;
8901 if (auto *VD = dyn_cast<VarDecl>(Val: D))
8902 if (VD->isExternC())
8903 ND = VD;
8904 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
8905 if (FD->isExternC())
8906 ND = FD;
8907 if (!ND)
8908 return;
8909 if (IdentifierInfo *Id = ND->getIdentifier()) {
8910 auto I = WeakUndeclaredIdentifiers.find(Key: Id);
8911 if (I != WeakUndeclaredIdentifiers.end()) {
8912 auto &WeakInfos = I->second;
8913 for (const auto &W : WeakInfos)
8914 DeclApplyPragmaWeak(S, ND, W);
8915 std::remove_reference_t<decltype(WeakInfos)> EmptyWeakInfos;
8916 WeakInfos.swap(RHS&: EmptyWeakInfos);
8917 }
8918 }
8919}
8920
8921/// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
8922/// it, apply them to D. This is a bit tricky because PD can have attributes
8923/// specified in many different places, and we need to find and apply them all.
8924void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
8925 // Ordering of attributes can be important, so we take care to process
8926 // attributes in the order in which they appeared in the source code.
8927
8928 auto ProcessAttributesWithSliding =
8929 [&](const ParsedAttributesView &Src,
8930 const ProcessDeclAttributeOptions &Options) {
8931 ParsedAttributesView NonSlidingAttrs;
8932 for (ParsedAttr &AL : Src) {
8933 // FIXME: this sliding is specific to standard attributes and should
8934 // eventually be deprecated and removed as those are not intended to
8935 // slide to anything.
8936 if ((AL.isStandardAttributeSyntax() || AL.isAlignas()) &&
8937 AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
8938 // Skip processing the attribute, but do check if it appertains to
8939 // the declaration. This is needed for the `MatrixType` attribute,
8940 // which, despite being a type attribute, defines a `SubjectList`
8941 // that only allows it to be used on typedef declarations.
8942 AL.diagnoseAppertainsTo(S&: *this, D);
8943 } else {
8944 NonSlidingAttrs.addAtEnd(newAttr: &AL);
8945 }
8946 }
8947 ProcessDeclAttributeList(S, D, AttrList: NonSlidingAttrs, Options);
8948 };
8949
8950 // First, process attributes that appeared on the declaration itself (but
8951 // only if they don't have the legacy behavior of "sliding" to the DeclSepc).
8952 ProcessAttributesWithSliding(PD.getDeclarationAttributes(), {});
8953
8954 // Apply decl attributes from the DeclSpec if present.
8955 ProcessAttributesWithSliding(PD.getDeclSpec().getAttributes(),
8956 ProcessDeclAttributeOptions()
8957 .WithIncludeCXX11Attributes(Val: false)
8958 .WithIgnoreTypeAttributes(Val: true));
8959
8960 // Walk the declarator structure, applying decl attributes that were in a type
8961 // position to the decl itself. This handles cases like:
8962 // int *__attr__(x)** D;
8963 // when X is a decl attribute.
8964 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i) {
8965 ProcessDeclAttributeList(S, D, AttrList: PD.getTypeObject(i).getAttrs(),
8966 Options: ProcessDeclAttributeOptions()
8967 .WithIncludeCXX11Attributes(Val: false)
8968 .WithIgnoreTypeAttributes(Val: true));
8969 }
8970
8971 // Finally, apply any attributes on the decl itself.
8972 ProcessDeclAttributeList(S, D, AttrList: PD.getAttributes());
8973
8974 // Apply additional attributes specified by '#pragma clang attribute'.
8975 AddPragmaAttributes(S, D);
8976
8977 // Look for API notes that map to attributes.
8978 ProcessAPINotes(D);
8979}
8980
8981/// Is the given declaration allowed to use a forbidden type?
8982/// If so, it'll still be annotated with an attribute that makes it
8983/// illegal to actually use.
8984static bool isForbiddenTypeAllowed(Sema &S, Decl *D,
8985 const DelayedDiagnostic &diag,
8986 UnavailableAttr::ImplicitReason &reason) {
8987 // Private ivars are always okay. Unfortunately, people don't
8988 // always properly make their ivars private, even in system headers.
8989 // Plus we need to make fields okay, too.
8990 if (!isa<FieldDecl>(Val: D) && !isa<ObjCPropertyDecl>(Val: D) &&
8991 !isa<FunctionDecl>(Val: D))
8992 return false;
8993
8994 // Silently accept unsupported uses of __weak in both user and system
8995 // declarations when it's been disabled, for ease of integration with
8996 // -fno-objc-arc files. We do have to take some care against attempts
8997 // to define such things; for now, we've only done that for ivars
8998 // and properties.
8999 if ((isa<ObjCIvarDecl>(Val: D) || isa<ObjCPropertyDecl>(Val: D))) {
9000 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
9001 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
9002 reason = UnavailableAttr::IR_ForbiddenWeak;
9003 return true;
9004 }
9005 }
9006
9007 // Allow all sorts of things in system headers.
9008 if (S.Context.getSourceManager().isInSystemHeader(Loc: D->getLocation())) {
9009 // Currently, all the failures dealt with this way are due to ARC
9010 // restrictions.
9011 reason = UnavailableAttr::IR_ARCForbiddenType;
9012 return true;
9013 }
9014
9015 return false;
9016}
9017
9018/// Handle a delayed forbidden-type diagnostic.
9019static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD,
9020 Decl *D) {
9021 auto Reason = UnavailableAttr::IR_None;
9022 if (D && isForbiddenTypeAllowed(S, D, diag: DD, reason&: Reason)) {
9023 assert(Reason && "didn't set reason?");
9024 D->addAttr(A: UnavailableAttr::CreateImplicit(Ctx&: S.Context, Message: "", ImplicitReason: Reason, Range: DD.Loc));
9025 return;
9026 }
9027 if (S.getLangOpts().ObjCAutoRefCount)
9028 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
9029 // FIXME: we may want to suppress diagnostics for all
9030 // kind of forbidden type messages on unavailable functions.
9031 if (FD->hasAttr<UnavailableAttr>() &&
9032 DD.getForbiddenTypeDiagnostic() ==
9033 diag::err_arc_array_param_no_ownership) {
9034 DD.Triggered = true;
9035 return;
9036 }
9037 }
9038
9039 S.Diag(Loc: DD.Loc, DiagID: DD.getForbiddenTypeDiagnostic())
9040 << DD.getForbiddenTypeOperand() << DD.getForbiddenTypeArgument();
9041 DD.Triggered = true;
9042}
9043
9044
9045void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
9046 assert(DelayedDiagnostics.getCurrentPool());
9047 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
9048 DelayedDiagnostics.popWithoutEmitting(state);
9049
9050 // When delaying diagnostics to run in the context of a parsed
9051 // declaration, we only want to actually emit anything if parsing
9052 // succeeds.
9053 if (!decl) return;
9054
9055 // We emit all the active diagnostics in this pool or any of its
9056 // parents. In general, we'll get one pool for the decl spec
9057 // and a child pool for each declarator; in a decl group like:
9058 // deprecated_typedef foo, *bar, baz();
9059 // only the declarator pops will be passed decls. This is correct;
9060 // we really do need to consider delayed diagnostics from the decl spec
9061 // for each of the different declarations.
9062 const DelayedDiagnosticPool *pool = &poppedPool;
9063 do {
9064 bool AnyAccessFailures = false;
9065 for (DelayedDiagnosticPool::pool_iterator
9066 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
9067 // This const_cast is a bit lame. Really, Triggered should be mutable.
9068 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
9069 if (diag.Triggered)
9070 continue;
9071
9072 switch (diag.Kind) {
9073 case DelayedDiagnostic::Availability:
9074 // Don't bother giving deprecation/unavailable diagnostics if
9075 // the decl is invalid.
9076 if (!decl->isInvalidDecl())
9077 handleDelayedAvailabilityCheck(DD&: diag, Ctx: decl);
9078 break;
9079
9080 case DelayedDiagnostic::Access:
9081 // Only produce one access control diagnostic for a structured binding
9082 // declaration: we don't need to tell the user that all the fields are
9083 // inaccessible one at a time.
9084 if (AnyAccessFailures && isa<DecompositionDecl>(Val: decl))
9085 continue;
9086 HandleDelayedAccessCheck(DD&: diag, Ctx: decl);
9087 if (diag.Triggered)
9088 AnyAccessFailures = true;
9089 break;
9090
9091 case DelayedDiagnostic::ForbiddenType:
9092 handleDelayedForbiddenType(S&: *this, DD&: diag, D: decl);
9093 break;
9094 }
9095 }
9096 } while ((pool = pool->getParent()));
9097}
9098
9099void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
9100 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
9101 assert(curPool && "re-emitting in undelayed context not supported");
9102 curPool->steal(pool);
9103}
9104
9105void Sema::ActOnCleanupAttr(Decl *D, const Attr *A) {
9106 VarDecl *VD = cast<VarDecl>(Val: D);
9107 if (VD->isInvalidDecl() || VD->getType()->isDependentType())
9108 return;
9109
9110 // Obtains the FunctionDecl that was found when handling the attribute
9111 // earlier.
9112 CleanupAttr *Attr = D->getAttr<CleanupAttr>();
9113 FunctionDecl *FD = Attr->getFunctionDecl();
9114 DeclarationNameInfo NI = FD->getNameInfo();
9115
9116 // We're currently more strict than GCC about what function types we accept.
9117 // If this ever proves to be a problem it should be easy to fix.
9118 QualType Ty = this->Context.getPointerType(T: VD->getType());
9119 QualType ParamTy = FD->getParamDecl(i: 0)->getType();
9120 if (QualType ConvertedTy;
9121 !this->IsAssignConvertCompatible(ConvTy: this->CheckAssignmentConstraints(
9122 Loc: FD->getParamDecl(i: 0)->getLocation(), LHSType: ParamTy, RHSType: Ty)) &&
9123 !ObjC().isObjCWritebackConversion(FromType: Ty, ToType: ParamTy, ConvertedType&: ConvertedTy)) {
9124 this->Diag(Loc: Attr->getArgLoc(),
9125 DiagID: diag::err_attribute_cleanup_func_arg_incompatible_type)
9126 << NI.getName() << ParamTy << Ty;
9127 D->dropAttr<CleanupAttr>();
9128 return;
9129 }
9130}
9131
9132void Sema::ActOnInitPriorityAttr(Decl *D, const Attr *A) {
9133 QualType T = cast<VarDecl>(Val: D)->getType();
9134 if (this->Context.getAsArrayType(T))
9135 T = this->Context.getBaseElementType(QT: T);
9136 if (!T->isRecordType()) {
9137 this->Diag(Loc: A->getLoc(), DiagID: diag::err_init_priority_object_attr);
9138 D->dropAttr<InitPriorityAttr>();
9139 }
9140}
9141