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