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