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