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