clang 20.0.0git
SemaDeclAttr.cpp
Go to the documentation of this file.
1//===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements decl-related attribute processing.
10//
11//===----------------------------------------------------------------------===//
12
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/Mangle.h"
24#include "clang/AST/Type.h"
26#include "clang/Basic/Cuda.h"
36#include "clang/Sema/Attr.h"
37#include "clang/Sema/DeclSpec.h"
40#include "clang/Sema/Lookup.h"
42#include "clang/Sema/Scope.h"
45#include "clang/Sema/SemaARM.h"
46#include "clang/Sema/SemaAVR.h"
47#include "clang/Sema/SemaBPF.h"
48#include "clang/Sema/SemaCUDA.h"
49#include "clang/Sema/SemaHLSL.h"
51#include "clang/Sema/SemaM68k.h"
52#include "clang/Sema/SemaMIPS.h"
54#include "clang/Sema/SemaObjC.h"
58#include "clang/Sema/SemaSYCL.h"
60#include "clang/Sema/SemaWasm.h"
61#include "clang/Sema/SemaX86.h"
62#include "llvm/ADT/STLExtras.h"
63#include "llvm/ADT/STLForwardCompat.h"
64#include "llvm/ADT/StringExtras.h"
65#include "llvm/Demangle/Demangle.h"
66#include "llvm/IR/Assumptions.h"
67#include "llvm/MC/MCSectionMachO.h"
68#include "llvm/Support/Error.h"
69#include "llvm/Support/MathExtras.h"
70#include "llvm/Support/raw_ostream.h"
71#include "llvm/TargetParser/Triple.h"
72#include <optional>
73
74using namespace clang;
75using namespace sema;
76
78 enum LANG {
81 ObjC
82 };
83} // end namespace AttributeLangSupport
84
85static unsigned getNumAttributeArgs(const ParsedAttr &AL) {
86 // FIXME: Include the type in the argument list.
87 return AL.getNumArgs() + AL.hasParsedType();
88}
89
91
92/// Wrapper around checkUInt32Argument, with an extra check to be sure
93/// that the result will fit into a regular (signed) int. All args have the same
94/// purpose as they do in checkUInt32Argument.
95template <typename AttrInfo>
96static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr,
97 int &Val, unsigned Idx = UINT_MAX) {
98 uint32_t UVal;
99 if (!S.checkUInt32Argument(AI, Expr, UVal, Idx))
100 return false;
101
102 if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
103 llvm::APSInt I(32); // for toString
104 I = UVal;
105 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
106 << toString(I, 10, false) << 32 << /* Unsigned */ 0;
107 return false;
108 }
109
110 Val = UVal;
111 return true;
112}
113
115 const Expr *E, StringRef &Str,
116 SourceLocation *ArgLocation) {
117 const auto *Literal = dyn_cast<StringLiteral>(E->IgnoreParenCasts());
118 if (ArgLocation)
119 *ArgLocation = E->getBeginLoc();
120
121 if (!Literal || (!Literal->isUnevaluated() && !Literal->isOrdinary())) {
122 Diag(E->getBeginLoc(), diag::err_attribute_argument_type)
123 << CI << AANT_ArgumentString;
124 return false;
125 }
126
127 Str = Literal->getString();
128 return true;
129}
130
131bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum,
132 StringRef &Str,
133 SourceLocation *ArgLocation) {
134 // Look for identifiers. If we have one emit a hint to fix it to a literal.
135 if (AL.isArgIdent(ArgNum)) {
136 IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum);
137 Diag(Loc->Loc, diag::err_attribute_argument_type)
138 << AL << AANT_ArgumentString
139 << FixItHint::CreateInsertion(Loc->Loc, "\"")
141 Str = Loc->Ident->getName();
142 if (ArgLocation)
143 *ArgLocation = Loc->Loc;
144 return true;
145 }
146
147 // Now check for an actual string literal.
148 Expr *ArgExpr = AL.getArgAsExpr(ArgNum);
149 const auto *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
150 if (ArgLocation)
151 *ArgLocation = ArgExpr->getBeginLoc();
152
153 if (!Literal || (!Literal->isUnevaluated() && !Literal->isOrdinary())) {
154 Diag(ArgExpr->getBeginLoc(), diag::err_attribute_argument_type)
155 << AL << AANT_ArgumentString;
156 return false;
157 }
158 Str = Literal->getString();
159 return checkStringLiteralArgumentAttr(AL, ArgExpr, Str, ArgLocation);
160}
161
162/// Check if the passed-in expression is of type int or bool.
163static bool isIntOrBool(Expr *Exp) {
164 QualType QT = Exp->getType();
165 return QT->isBooleanType() || QT->isIntegerType();
166}
167
168
169// Check to see if the type is a smart pointer of some kind. We assume
170// it's a smart pointer if it defines both operator-> and operator*.
172 auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record,
176 return !Result.empty();
177 };
178
179 const RecordDecl *Record = RT->getDecl();
180 bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star);
181 bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow);
182 if (foundStarOperator && foundArrowOperator)
183 return true;
184
185 const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record);
186 if (!CXXRecord)
187 return false;
188
189 for (const auto &BaseSpecifier : CXXRecord->bases()) {
190 if (!foundStarOperator)
191 foundStarOperator = IsOverloadedOperatorPresent(
192 BaseSpecifier.getType()->getAsRecordDecl(), OO_Star);
193 if (!foundArrowOperator)
194 foundArrowOperator = IsOverloadedOperatorPresent(
195 BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow);
196 }
197
198 if (foundStarOperator && foundArrowOperator)
199 return true;
200
201 return false;
202}
203
204/// Check if passed in Decl is a pointer type.
205/// Note that this function may produce an error message.
206/// \return true if the Decl is a pointer type; false otherwise
207static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
208 const ParsedAttr &AL) {
209 const auto *VD = cast<ValueDecl>(D);
210 QualType QT = VD->getType();
211 if (QT->isAnyPointerType())
212 return true;
213
214 if (const auto *RT = QT->getAs<RecordType>()) {
215 // If it's an incomplete type, it could be a smart pointer; skip it.
216 // (We don't want to force template instantiation if we can avoid it,
217 // since that would alter the order in which templates are instantiated.)
218 if (RT->isIncompleteType())
219 return true;
220
222 return true;
223 }
224
225 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << AL << QT;
226 return false;
227}
228
229/// Checks that the passed in QualType either is of RecordType or points
230/// to RecordType. Returns the relevant RecordType, null if it does not exit.
232 if (const auto *RT = QT->getAs<RecordType>())
233 return RT;
234
235 // Now check if we point to record type.
236 if (const auto *PT = QT->getAs<PointerType>())
237 return PT->getPointeeType()->getAs<RecordType>();
238
239 return nullptr;
240}
241
242template <typename AttrType>
243static bool checkRecordDeclForAttr(const RecordDecl *RD) {
244 // Check if the record itself has the attribute.
245 if (RD->hasAttr<AttrType>())
246 return true;
247
248 // Else check if any base classes have the attribute.
249 if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
250 if (!CRD->forallBases([](const CXXRecordDecl *Base) {
251 return !Base->hasAttr<AttrType>();
252 }))
253 return true;
254 }
255 return false;
256}
257
259 const RecordType *RT = getRecordType(Ty);
260
261 if (!RT)
262 return false;
263
264 // Don't check for the capability if the class hasn't been defined yet.
265 if (RT->isIncompleteType())
266 return true;
267
268 // Allow smart pointers to be used as capability objects.
269 // FIXME -- Check the type that the smart pointer points to.
271 return true;
272
273 return checkRecordDeclForAttr<CapabilityAttr>(RT->getDecl());
274}
275
277 const auto *TD = Ty->getAs<TypedefType>();
278 if (!TD)
279 return false;
280
281 TypedefNameDecl *TN = TD->getDecl();
282 if (!TN)
283 return false;
284
285 return TN->hasAttr<CapabilityAttr>();
286}
287
288static bool typeHasCapability(Sema &S, QualType Ty) {
290 return true;
291
293 return true;
294
295 return false;
296}
297
298static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
299 // Capability expressions are simple expressions involving the boolean logic
300 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
301 // a DeclRefExpr is found, its type should be checked to determine whether it
302 // is a capability or not.
303
304 if (const auto *E = dyn_cast<CastExpr>(Ex))
305 return isCapabilityExpr(S, E->getSubExpr());
306 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
307 return isCapabilityExpr(S, E->getSubExpr());
308 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
309 if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
310 E->getOpcode() == UO_Deref)
311 return isCapabilityExpr(S, E->getSubExpr());
312 return false;
313 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
314 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
315 return isCapabilityExpr(S, E->getLHS()) &&
316 isCapabilityExpr(S, E->getRHS());
317 return false;
318 }
319
320 return typeHasCapability(S, Ex->getType());
321}
322
323/// Checks that all attribute arguments, starting from Sidx, resolve to
324/// a capability object.
325/// \param Sidx The attribute argument index to start checking with.
326/// \param ParamIdxOk Whether an argument can be indexing into a function
327/// parameter list.
329 const ParsedAttr &AL,
331 unsigned Sidx = 0,
332 bool ParamIdxOk = false) {
333 if (Sidx == AL.getNumArgs()) {
334 // If we don't have any capability arguments, the attribute implicitly
335 // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're
336 // a non-static method, and that the class is a (scoped) capability.
337 const auto *MD = dyn_cast<const CXXMethodDecl>(D);
338 if (MD && !MD->isStatic()) {
339 const CXXRecordDecl *RD = MD->getParent();
340 // FIXME -- need to check this again on template instantiation
341 if (!checkRecordDeclForAttr<CapabilityAttr>(RD) &&
342 !checkRecordDeclForAttr<ScopedLockableAttr>(RD))
343 S.Diag(AL.getLoc(),
344 diag::warn_thread_attribute_not_on_capability_member)
345 << AL << MD->getParent();
346 } else {
347 S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member)
348 << AL;
349 }
350 }
351
352 for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) {
353 Expr *ArgExp = AL.getArgAsExpr(Idx);
354
355 if (ArgExp->isTypeDependent()) {
356 // FIXME -- need to check this again on template instantiation
357 Args.push_back(ArgExp);
358 continue;
359 }
360
361 if (const auto *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
362 if (StrLit->getLength() == 0 ||
363 (StrLit->isOrdinary() && StrLit->getString() == "*")) {
364 // Pass empty strings to the analyzer without warnings.
365 // Treat "*" as the universal lock.
366 Args.push_back(ArgExp);
367 continue;
368 }
369
370 // We allow constant strings to be used as a placeholder for expressions
371 // that are not valid C++ syntax, but warn that they are ignored.
372 S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL;
373 Args.push_back(ArgExp);
374 continue;
375 }
376
377 QualType ArgTy = ArgExp->getType();
378
379 // A pointer to member expression of the form &MyClass::mu is treated
380 // specially -- we need to look at the type of the member.
381 if (const auto *UOp = dyn_cast<UnaryOperator>(ArgExp))
382 if (UOp->getOpcode() == UO_AddrOf)
383 if (const auto *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
384 if (DRE->getDecl()->isCXXInstanceMember())
385 ArgTy = DRE->getDecl()->getType();
386
387 // First see if we can just cast to record type, or pointer to record type.
388 const RecordType *RT = getRecordType(ArgTy);
389
390 // Now check if we index into a record type function param.
391 if(!RT && ParamIdxOk) {
392 const auto *FD = dyn_cast<FunctionDecl>(D);
393 const auto *IL = dyn_cast<IntegerLiteral>(ArgExp);
394 if(FD && IL) {
395 unsigned int NumParams = FD->getNumParams();
396 llvm::APInt ArgValue = IL->getValue();
397 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
398 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
399 if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
400 S.Diag(AL.getLoc(),
401 diag::err_attribute_argument_out_of_bounds_extra_info)
402 << AL << Idx + 1 << NumParams;
403 continue;
404 }
405 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
406 }
407 }
408
409 // If the type does not have a capability, see if the components of the
410 // expression have capabilities. This allows for writing C code where the
411 // capability may be on the type, and the expression is a capability
412 // boolean logic expression. Eg) requires_capability(A || B && !C)
413 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
414 S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
415 << AL << ArgTy;
416
417 Args.push_back(ArgExp);
418 }
419}
420
421//===----------------------------------------------------------------------===//
422// Attribute Implementations
423//===----------------------------------------------------------------------===//
424
425static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
426 if (!threadSafetyCheckIsPointer(S, D, AL))
427 return;
428
429 D->addAttr(::new (S.Context) PtGuardedVarAttr(S.Context, AL));
430}
431
432static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
433 Expr *&Arg) {
435 // check that all arguments are lockable objects
436 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
437 unsigned Size = Args.size();
438 if (Size != 1)
439 return false;
440
441 Arg = Args[0];
442
443 return true;
444}
445
446static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
447 Expr *Arg = nullptr;
448 if (!checkGuardedByAttrCommon(S, D, AL, Arg))
449 return;
450
451 D->addAttr(::new (S.Context) GuardedByAttr(S.Context, AL, Arg));
452}
453
454static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
455 Expr *Arg = nullptr;
456 if (!checkGuardedByAttrCommon(S, D, AL, Arg))
457 return;
458
459 if (!threadSafetyCheckIsPointer(S, D, AL))
460 return;
461
462 D->addAttr(::new (S.Context) PtGuardedByAttr(S.Context, AL, Arg));
463}
464
467 if (!AL.checkAtLeastNumArgs(S, 1))
468 return false;
469
470 // Check that this attribute only applies to lockable types.
471 QualType QT = cast<ValueDecl>(D)->getType();
472 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
473 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable) << AL;
474 return false;
475 }
476
477 // Check that all arguments are lockable objects.
478 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
479 if (Args.empty())
480 return false;
481
482 return true;
483}
484
485static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
487 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
488 return;
489
490 Expr **StartArg = &Args[0];
491 D->addAttr(::new (S.Context)
492 AcquiredAfterAttr(S.Context, AL, StartArg, Args.size()));
493}
494
495static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
497 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
498 return;
499
500 Expr **StartArg = &Args[0];
501 D->addAttr(::new (S.Context)
502 AcquiredBeforeAttr(S.Context, AL, StartArg, Args.size()));
503}
504
505static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
507 // zero or more arguments ok
508 // check that all arguments are lockable objects
509 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, /*ParamIdxOk=*/true);
510
511 return true;
512}
513
514static void handleAssertSharedLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
516 if (!checkLockFunAttrCommon(S, D, AL, Args))
517 return;
518
519 unsigned Size = Args.size();
520 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
521 D->addAttr(::new (S.Context)
522 AssertSharedLockAttr(S.Context, AL, StartArg, Size));
523}
524
526 const ParsedAttr &AL) {
528 if (!checkLockFunAttrCommon(S, D, AL, Args))
529 return;
530
531 unsigned Size = Args.size();
532 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
533 D->addAttr(::new (S.Context)
534 AssertExclusiveLockAttr(S.Context, AL, StartArg, Size));
535}
536
537/// Checks to be sure that the given parameter number is in bounds, and
538/// is an integral type. Will emit appropriate diagnostics if this returns
539/// false.
540///
541/// AttrArgNo is used to actually retrieve the argument, so it's base-0.
542template <typename AttrInfo>
543static bool checkParamIsIntegerType(Sema &S, const Decl *D, const AttrInfo &AI,
544 unsigned AttrArgNo) {
545 assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument");
546 Expr *AttrArg = AI.getArgAsExpr(AttrArgNo);
547 ParamIdx Idx;
548 if (!S.checkFunctionOrMethodParameterIndex(D, AI, AttrArgNo + 1, AttrArg,
549 Idx))
550 return false;
551
553 if (!ParamTy->isIntegerType() && !ParamTy->isCharType()) {
554 SourceLocation SrcLoc = AttrArg->getBeginLoc();
555 S.Diag(SrcLoc, diag::err_attribute_integers_only)
557 return false;
558 }
559 return true;
560}
561
562static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
563 if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2))
564 return;
565
567
569 if (!RetTy->isPointerType()) {
570 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL;
571 return;
572 }
573
574 const Expr *SizeExpr = AL.getArgAsExpr(0);
575 int SizeArgNoVal;
576 // Parameter indices are 1-indexed, hence Index=1
577 if (!checkPositiveIntArgument(S, AL, SizeExpr, SizeArgNoVal, /*Idx=*/1))
578 return;
579 if (!checkParamIsIntegerType(S, D, AL, /*AttrArgNo=*/0))
580 return;
581 ParamIdx SizeArgNo(SizeArgNoVal, D);
582
583 ParamIdx NumberArgNo;
584 if (AL.getNumArgs() == 2) {
585 const Expr *NumberExpr = AL.getArgAsExpr(1);
586 int Val;
587 // Parameter indices are 1-based, hence Index=2
588 if (!checkPositiveIntArgument(S, AL, NumberExpr, Val, /*Idx=*/2))
589 return;
590 if (!checkParamIsIntegerType(S, D, AL, /*AttrArgNo=*/1))
591 return;
592 NumberArgNo = ParamIdx(Val, D);
593 }
594
595 D->addAttr(::new (S.Context)
596 AllocSizeAttr(S.Context, AL, SizeArgNo, NumberArgNo));
597}
598
599static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
601 if (!AL.checkAtLeastNumArgs(S, 1))
602 return false;
603
604 if (!isIntOrBool(AL.getArgAsExpr(0))) {
605 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
606 << AL << 1 << AANT_ArgumentIntOrBool;
607 return false;
608 }
609
610 // check that all arguments are lockable objects
611 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 1);
612
613 return true;
614}
615
617 const ParsedAttr &AL) {
619 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
620 return;
621
622 D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(
623 S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
624}
625
627 const ParsedAttr &AL) {
629 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
630 return;
631
632 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
633 S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
634}
635
636static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
637 // check that the argument is lockable object
639 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
640 unsigned Size = Args.size();
641 if (Size == 0)
642 return;
643
644 D->addAttr(::new (S.Context) LockReturnedAttr(S.Context, AL, Args[0]));
645}
646
647static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
648 if (!AL.checkAtLeastNumArgs(S, 1))
649 return;
650
651 // check that all arguments are lockable objects
653 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
654 unsigned Size = Args.size();
655 if (Size == 0)
656 return;
657 Expr **StartArg = &Args[0];
658
659 D->addAttr(::new (S.Context)
660 LocksExcludedAttr(S.Context, AL, StartArg, Size));
661}
662
663static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL,
664 Expr *&Cond, StringRef &Msg) {
665 Cond = AL.getArgAsExpr(0);
666 if (!Cond->isTypeDependent()) {
668 if (Converted.isInvalid())
669 return false;
670 Cond = Converted.get();
671 }
672
673 if (!S.checkStringLiteralArgumentAttr(AL, 1, Msg))
674 return false;
675
676 if (Msg.empty())
677 Msg = "<no message provided>";
678
680 if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
681 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
682 Diags)) {
683 S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr) << AL;
684 for (const PartialDiagnosticAt &PDiag : Diags)
685 S.Diag(PDiag.first, PDiag.second);
686 return false;
687 }
688 return true;
689}
690
691static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
692 S.Diag(AL.getLoc(), diag::ext_clang_enable_if);
693
694 Expr *Cond;
695 StringRef Msg;
696 if (checkFunctionConditionAttr(S, D, AL, Cond, Msg))
697 D->addAttr(::new (S.Context) EnableIfAttr(S.Context, AL, Cond, Msg));
698}
699
700static void handleErrorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
701 StringRef NewUserDiagnostic;
702 if (!S.checkStringLiteralArgumentAttr(AL, 0, NewUserDiagnostic))
703 return;
704 if (ErrorAttr *EA = S.mergeErrorAttr(D, AL, NewUserDiagnostic))
705 D->addAttr(EA);
706}
707
709 const ParsedAttr &AL) {
710 const auto *PD = isa<CXXRecordDecl>(D)
711 ? cast<DeclContext>(D)
713 if (const auto *RD = dyn_cast<CXXRecordDecl>(PD); RD && RD->isLocalClass()) {
714 S.Diag(AL.getLoc(),
715 diag::warn_attribute_exclude_from_explicit_instantiation_local_class)
716 << AL << /*IsMember=*/!isa<CXXRecordDecl>(D);
717 return;
718 }
719 D->addAttr(::new (S.Context)
720 ExcludeFromExplicitInstantiationAttr(S.Context, AL));
721}
722
723namespace {
724/// Determines if a given Expr references any of the given function's
725/// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
726class ArgumentDependenceChecker
727 : public RecursiveASTVisitor<ArgumentDependenceChecker> {
728#ifndef NDEBUG
729 const CXXRecordDecl *ClassType;
730#endif
732 bool Result;
733
734public:
735 ArgumentDependenceChecker(const FunctionDecl *FD) {
736#ifndef NDEBUG
737 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
738 ClassType = MD->getParent();
739 else
740 ClassType = nullptr;
741#endif
742 Parms.insert(FD->param_begin(), FD->param_end());
743 }
744
745 bool referencesArgs(Expr *E) {
746 Result = false;
747 TraverseStmt(E);
748 return Result;
749 }
750
751 bool VisitCXXThisExpr(CXXThisExpr *E) {
752 assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
753 "`this` doesn't refer to the enclosing class?");
754 Result = true;
755 return false;
756 }
757
758 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
759 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
760 if (Parms.count(PVD)) {
761 Result = true;
762 return false;
763 }
764 return true;
765 }
766};
767}
768
770 const ParsedAttr &AL) {
771 const auto *DeclFD = cast<FunctionDecl>(D);
772
773 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(DeclFD))
774 if (!MethodDecl->isStatic()) {
775 S.Diag(AL.getLoc(), diag::err_attribute_no_member_function) << AL;
776 return;
777 }
778
779 auto DiagnoseType = [&](unsigned Index, AttributeArgumentNType T) {
780 SourceLocation Loc = [&]() {
781 auto Union = AL.getArg(Index - 1);
782 if (Union.is<Expr *>())
783 return Union.get<Expr *>()->getBeginLoc();
784 return Union.get<IdentifierLoc *>()->Loc;
785 }();
786
787 S.Diag(Loc, diag::err_attribute_argument_n_type) << AL << Index << T;
788 };
789
790 FunctionDecl *AttrFD = [&]() -> FunctionDecl * {
791 if (!AL.isArgExpr(0))
792 return nullptr;
793 auto *F = dyn_cast_if_present<DeclRefExpr>(AL.getArgAsExpr(0));
794 if (!F)
795 return nullptr;
796 return dyn_cast_if_present<FunctionDecl>(F->getFoundDecl());
797 }();
798
799 if (!AttrFD || !AttrFD->getBuiltinID(true)) {
800 DiagnoseType(1, AANT_ArgumentBuiltinFunction);
801 return;
802 }
803
804 if (AttrFD->getNumParams() != AL.getNumArgs() - 1) {
805 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments_for)
806 << AL << AttrFD << AttrFD->getNumParams();
807 return;
808 }
809
811
812 for (unsigned I = 1; I < AL.getNumArgs(); ++I) {
813 if (!AL.isArgExpr(I)) {
814 DiagnoseType(I + 1, AANT_ArgumentIntegerConstant);
815 return;
816 }
817
818 const Expr *IndexExpr = AL.getArgAsExpr(I);
819 uint32_t Index;
820
821 if (!S.checkUInt32Argument(AL, IndexExpr, Index, I + 1, false))
822 return;
823
824 if (Index > DeclFD->getNumParams()) {
825 S.Diag(AL.getLoc(), diag::err_attribute_bounds_for_function)
826 << AL << Index << DeclFD << DeclFD->getNumParams();
827 return;
828 }
829
830 QualType T1 = AttrFD->getParamDecl(I - 1)->getType();
831 QualType T2 = DeclFD->getParamDecl(Index - 1)->getType();
832
835 S.Diag(IndexExpr->getBeginLoc(), diag::err_attribute_parameter_types)
836 << AL << Index << DeclFD << T2 << I << AttrFD << T1;
837 return;
838 }
839
840 Indices.push_back(Index - 1);
841 }
842
843 D->addAttr(::new (S.Context) DiagnoseAsBuiltinAttr(
844 S.Context, AL, AttrFD, Indices.data(), Indices.size()));
845}
846
847static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
848 S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if);
849
850 Expr *Cond;
851 StringRef Msg;
852 if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg))
853 return;
854
855 StringRef DiagTypeStr;
856 if (!S.checkStringLiteralArgumentAttr(AL, 2, DiagTypeStr))
857 return;
858
859 DiagnoseIfAttr::DiagnosticType DiagType;
860 if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
861 S.Diag(AL.getArgAsExpr(2)->getBeginLoc(),
862 diag::err_diagnose_if_invalid_diagnostic_type);
863 return;
864 }
865
866 bool ArgDependent = false;
867 if (const auto *FD = dyn_cast<FunctionDecl>(D))
868 ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
869 D->addAttr(::new (S.Context) DiagnoseIfAttr(
870 S.Context, AL, Cond, Msg, DiagType, ArgDependent, cast<NamedDecl>(D)));
871}
872
873static void handleNoBuiltinAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
874 static constexpr const StringRef kWildcard = "*";
875
877 bool HasWildcard = false;
878
879 const auto AddBuiltinName = [&Names, &HasWildcard](StringRef Name) {
880 if (Name == kWildcard)
881 HasWildcard = true;
882 Names.push_back(Name);
883 };
884
885 // Add previously defined attributes.
886 if (const auto *NBA = D->getAttr<NoBuiltinAttr>())
887 for (StringRef BuiltinName : NBA->builtinNames())
888 AddBuiltinName(BuiltinName);
889
890 // Add current attributes.
891 if (AL.getNumArgs() == 0)
892 AddBuiltinName(kWildcard);
893 else
894 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
895 StringRef BuiltinName;
896 SourceLocation LiteralLoc;
897 if (!S.checkStringLiteralArgumentAttr(AL, I, BuiltinName, &LiteralLoc))
898 return;
899
900 if (Builtin::Context::isBuiltinFunc(BuiltinName))
901 AddBuiltinName(BuiltinName);
902 else
903 S.Diag(LiteralLoc, diag::warn_attribute_no_builtin_invalid_builtin_name)
904 << BuiltinName << AL;
905 }
906
907 // Repeating the same attribute is fine.
908 llvm::sort(Names);
909 Names.erase(std::unique(Names.begin(), Names.end()), Names.end());
910
911 // Empty no_builtin must be on its own.
912 if (HasWildcard && Names.size() > 1)
913 S.Diag(D->getLocation(),
914 diag::err_attribute_no_builtin_wildcard_or_builtin_name)
915 << AL;
916
917 if (D->hasAttr<NoBuiltinAttr>())
918 D->dropAttr<NoBuiltinAttr>();
919 D->addAttr(::new (S.Context)
920 NoBuiltinAttr(S.Context, AL, Names.data(), Names.size()));
921}
922
923static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
924 if (D->hasAttr<PassObjectSizeAttr>()) {
925 S.Diag(D->getBeginLoc(), diag::err_attribute_only_once_per_parameter) << AL;
926 return;
927 }
928
929 Expr *E = AL.getArgAsExpr(0);
930 uint32_t Type;
931 if (!S.checkUInt32Argument(AL, E, Type, /*Idx=*/1))
932 return;
933
934 // pass_object_size's argument is passed in as the second argument of
935 // __builtin_object_size. So, it has the same constraints as that second
936 // argument; namely, it must be in the range [0, 3].
937 if (Type > 3) {
938 S.Diag(E->getBeginLoc(), diag::err_attribute_argument_out_of_range)
939 << AL << 0 << 3 << E->getSourceRange();
940 return;
941 }
942
943 // pass_object_size is only supported on constant pointer parameters; as a
944 // kindness to users, we allow the parameter to be non-const for declarations.
945 // At this point, we have no clue if `D` belongs to a function declaration or
946 // definition, so we defer the constness check until later.
947 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
948 S.Diag(D->getBeginLoc(), diag::err_attribute_pointers_only) << AL << 1;
949 return;
950 }
951
952 D->addAttr(::new (S.Context) PassObjectSizeAttr(S.Context, AL, (int)Type));
953}
954
955static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
956 ConsumableAttr::ConsumedState DefaultState;
957
958 if (AL.isArgIdent(0)) {
959 IdentifierLoc *IL = AL.getArgAsIdent(0);
960 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
961 DefaultState)) {
962 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
963 << IL->Ident;
964 return;
965 }
966 } else {
967 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
969 return;
970 }
971
972 D->addAttr(::new (S.Context) ConsumableAttr(S.Context, AL, DefaultState));
973}
974
976 const ParsedAttr &AL) {
978
979 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
980 if (!RD->hasAttr<ConsumableAttr>()) {
981 S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) << RD;
982
983 return false;
984 }
985 }
986
987 return true;
988}
989
990static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
991 if (!AL.checkAtLeastNumArgs(S, 1))
992 return;
993
994 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
995 return;
996
998 for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
999 CallableWhenAttr::ConsumedState CallableState;
1000
1001 StringRef StateString;
1003 if (AL.isArgIdent(ArgIndex)) {
1004 IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
1005 StateString = Ident->Ident->getName();
1006 Loc = Ident->Loc;
1007 } else {
1008 if (!S.checkStringLiteralArgumentAttr(AL, ArgIndex, StateString, &Loc))
1009 return;
1010 }
1011
1012 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1013 CallableState)) {
1014 S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << StateString;
1015 return;
1016 }
1017
1018 States.push_back(CallableState);
1019 }
1020
1021 D->addAttr(::new (S.Context)
1022 CallableWhenAttr(S.Context, AL, States.data(), States.size()));
1023}
1024
1025static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1026 ParamTypestateAttr::ConsumedState ParamState;
1027
1028 if (AL.isArgIdent(0)) {
1029 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1030 StringRef StateString = Ident->Ident->getName();
1031
1032 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1033 ParamState)) {
1034 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1035 << AL << StateString;
1036 return;
1037 }
1038 } else {
1039 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1040 << AL << AANT_ArgumentIdentifier;
1041 return;
1042 }
1043
1044 // FIXME: This check is currently being done in the analysis. It can be
1045 // enabled here only after the parser propagates attributes at
1046 // template specialization definition, not declaration.
1047 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1048 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1049 //
1050 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1051 // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1052 // ReturnType.getAsString();
1053 // return;
1054 //}
1055
1056 D->addAttr(::new (S.Context) ParamTypestateAttr(S.Context, AL, ParamState));
1057}
1058
1059static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1060 ReturnTypestateAttr::ConsumedState ReturnState;
1061
1062 if (AL.isArgIdent(0)) {
1063 IdentifierLoc *IL = AL.getArgAsIdent(0);
1064 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1065 ReturnState)) {
1066 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1067 << IL->Ident;
1068 return;
1069 }
1070 } else {
1071 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1072 << AL << AANT_ArgumentIdentifier;
1073 return;
1074 }
1075
1076 // FIXME: This check is currently being done in the analysis. It can be
1077 // enabled here only after the parser propagates attributes at
1078 // template specialization definition, not declaration.
1079 // QualType ReturnType;
1080 //
1081 // if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1082 // ReturnType = Param->getType();
1083 //
1084 //} else if (const CXXConstructorDecl *Constructor =
1085 // dyn_cast<CXXConstructorDecl>(D)) {
1086 // ReturnType = Constructor->getFunctionObjectParameterType();
1087 //
1088 //} else {
1089 //
1090 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1091 //}
1092 //
1093 // const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1094 //
1095 // if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1096 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1097 // ReturnType.getAsString();
1098 // return;
1099 //}
1100
1101 D->addAttr(::new (S.Context) ReturnTypestateAttr(S.Context, AL, ReturnState));
1102}
1103
1104static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1105 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1106 return;
1107
1108 SetTypestateAttr::ConsumedState NewState;
1109 if (AL.isArgIdent(0)) {
1110 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1111 StringRef Param = Ident->Ident->getName();
1112 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1113 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1114 << Param;
1115 return;
1116 }
1117 } else {
1118 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1119 << AL << AANT_ArgumentIdentifier;
1120 return;
1121 }
1122
1123 D->addAttr(::new (S.Context) SetTypestateAttr(S.Context, AL, NewState));
1124}
1125
1126static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1127 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1128 return;
1129
1130 TestTypestateAttr::ConsumedState TestState;
1131 if (AL.isArgIdent(0)) {
1132 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1133 StringRef Param = Ident->Ident->getName();
1134 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1135 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1136 << Param;
1137 return;
1138 }
1139 } else {
1140 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1141 << AL << AANT_ArgumentIdentifier;
1142 return;
1143 }
1144
1145 D->addAttr(::new (S.Context) TestTypestateAttr(S.Context, AL, TestState));
1146}
1147
1148static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1149 // Remember this typedef decl, we will need it later for diagnostics.
1150 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1151}
1152
1153static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1154 if (auto *TD = dyn_cast<TagDecl>(D))
1155 TD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1156 else if (auto *FD = dyn_cast<FieldDecl>(D)) {
1157 bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
1158 !FD->getType()->isIncompleteType() &&
1159 FD->isBitField() &&
1160 S.Context.getTypeAlign(FD->getType()) <= 8);
1161
1162 if (S.getASTContext().getTargetInfo().getTriple().isPS()) {
1163 if (BitfieldByteAligned)
1164 // The PS4/PS5 targets need to maintain ABI backwards compatibility.
1165 S.Diag(AL.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1166 << AL << FD->getType();
1167 else
1168 FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1169 } else {
1170 // Report warning about changed offset in the newer compiler versions.
1171 if (BitfieldByteAligned)
1172 S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield);
1173
1174 FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1175 }
1176
1177 } else
1178 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
1179}
1180
1181static void handlePreferredName(Sema &S, Decl *D, const ParsedAttr &AL) {
1182 auto *RD = cast<CXXRecordDecl>(D);
1183 ClassTemplateDecl *CTD = RD->getDescribedClassTemplate();
1184 assert(CTD && "attribute does not appertain to this declaration");
1185
1186 ParsedType PT = AL.getTypeArg();
1187 TypeSourceInfo *TSI = nullptr;
1188 QualType T = S.GetTypeFromParser(PT, &TSI);
1189 if (!TSI)
1191
1192 if (!T.hasQualifiers() && T->isTypedefNameType()) {
1193 // Find the template name, if this type names a template specialization.
1194 const TemplateDecl *Template = nullptr;
1195 if (const auto *CTSD = dyn_cast_if_present<ClassTemplateSpecializationDecl>(
1196 T->getAsCXXRecordDecl())) {
1197 Template = CTSD->getSpecializedTemplate();
1198 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
1199 while (TST && TST->isTypeAlias())
1200 TST = TST->getAliasedType()->getAs<TemplateSpecializationType>();
1201 if (TST)
1202 Template = TST->getTemplateName().getAsTemplateDecl();
1203 }
1204
1205 if (Template && declaresSameEntity(Template, CTD)) {
1206 D->addAttr(::new (S.Context) PreferredNameAttr(S.Context, AL, TSI));
1207 return;
1208 }
1209 }
1210
1211 S.Diag(AL.getLoc(), diag::err_attribute_preferred_name_arg_invalid)
1212 << T << CTD;
1213 if (const auto *TT = T->getAs<TypedefType>())
1214 S.Diag(TT->getDecl()->getLocation(), diag::note_entity_declared_at)
1215 << TT->getDecl();
1216}
1217
1219 if (RefOkay) {
1220 if (T->isReferenceType())
1221 return true;
1222 } else {
1223 T = T.getNonReferenceType();
1224 }
1225
1226 // The nonnull attribute, and other similar attributes, can be applied to a
1227 // transparent union that contains a pointer type.
1228 if (const RecordType *UT = T->getAsUnionType()) {
1229 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1230 RecordDecl *UD = UT->getDecl();
1231 for (const auto *I : UD->fields()) {
1232 QualType QT = I->getType();
1233 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1234 return true;
1235 }
1236 }
1237 }
1238
1239 return T->isAnyPointerType() || T->isBlockPointerType();
1240}
1241
1242static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL,
1243 SourceRange AttrParmRange,
1244 SourceRange TypeRange,
1245 bool isReturnValue = false) {
1246 if (!S.isValidPointerAttrType(T)) {
1247 if (isReturnValue)
1248 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1249 << AL << AttrParmRange << TypeRange;
1250 else
1251 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1252 << AL << AttrParmRange << TypeRange << 0;
1253 return false;
1254 }
1255 return true;
1256}
1257
1258static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1259 SmallVector<ParamIdx, 8> NonNullArgs;
1260 for (unsigned I = 0; I < AL.getNumArgs(); ++I) {
1261 Expr *Ex = AL.getArgAsExpr(I);
1262 ParamIdx Idx;
1263 if (!S.checkFunctionOrMethodParameterIndex(D, AL, I + 1, Ex, Idx))
1264 return;
1265
1266 // Is the function argument a pointer type?
1270 Ex->getSourceRange(),
1272 continue;
1273
1274 NonNullArgs.push_back(Idx);
1275 }
1276
1277 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1278 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1279 // check if the attribute came from a macro expansion or a template
1280 // instantiation.
1281 if (NonNullArgs.empty() && AL.getLoc().isFileID() &&
1283 bool AnyPointers = isFunctionOrMethodVariadic(D);
1284 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1285 I != E && !AnyPointers; ++I) {
1288 AnyPointers = true;
1289 }
1290
1291 if (!AnyPointers)
1292 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1293 }
1294
1295 ParamIdx *Start = NonNullArgs.data();
1296 unsigned Size = NonNullArgs.size();
1297 llvm::array_pod_sort(Start, Start + Size);
1298 D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, Start, Size));
1299}
1300
1302 const ParsedAttr &AL) {
1303 if (AL.getNumArgs() > 0) {
1304 if (D->getFunctionType()) {
1305 handleNonNullAttr(S, D, AL);
1306 } else {
1307 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1308 << D->getSourceRange();
1309 }
1310 return;
1311 }
1312
1313 // Is the argument a pointer type?
1314 if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(),
1315 D->getSourceRange()))
1316 return;
1317
1318 D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, nullptr, 0));
1319}
1320
1321static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1324 if (!attrNonNullArgCheck(S, ResultType, AL, SourceRange(), SR,
1325 /* isReturnValue */ true))
1326 return;
1327
1328 D->addAttr(::new (S.Context) ReturnsNonNullAttr(S.Context, AL));
1329}
1330
1331static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1332 if (D->isInvalidDecl())
1333 return;
1334
1335 // noescape only applies to pointer types.
1336 QualType T = cast<ParmVarDecl>(D)->getType();
1337 if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
1338 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1339 << AL << AL.getRange() << 0;
1340 return;
1341 }
1342
1343 D->addAttr(::new (S.Context) NoEscapeAttr(S.Context, AL));
1344}
1345
1346static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1347 Expr *E = AL.getArgAsExpr(0),
1348 *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr;
1349 S.AddAssumeAlignedAttr(D, AL, E, OE);
1350}
1351
1352static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1353 S.AddAllocAlignAttr(D, AL, AL.getArgAsExpr(0));
1354}
1355
1357 Expr *OE) {
1360
1361 AssumeAlignedAttr TmpAttr(Context, CI, E, OE);
1362 SourceLocation AttrLoc = TmpAttr.getLocation();
1363
1364 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1365 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1366 << &TmpAttr << TmpAttr.getRange() << SR;
1367 return;
1368 }
1369
1370 if (!E->isValueDependent()) {
1371 std::optional<llvm::APSInt> I = llvm::APSInt(64);
1372 if (!(I = E->getIntegerConstantExpr(Context))) {
1373 if (OE)
1374 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1375 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1376 << E->getSourceRange();
1377 else
1378 Diag(AttrLoc, diag::err_attribute_argument_type)
1379 << &TmpAttr << AANT_ArgumentIntegerConstant
1380 << E->getSourceRange();
1381 return;
1382 }
1383
1384 if (!I->isPowerOf2()) {
1385 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1386 << E->getSourceRange();
1387 return;
1388 }
1389
1390 if (*I > Sema::MaximumAlignment)
1391 Diag(CI.getLoc(), diag::warn_assume_aligned_too_great)
1393 }
1394
1395 if (OE && !OE->isValueDependent() && !OE->isIntegerConstantExpr(Context)) {
1396 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1397 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1398 << OE->getSourceRange();
1399 return;
1400 }
1401
1402 D->addAttr(::new (Context) AssumeAlignedAttr(Context, CI, E, OE));
1403}
1404
1406 Expr *ParamExpr) {
1408
1409 AllocAlignAttr TmpAttr(Context, CI, ParamIdx());
1410 SourceLocation AttrLoc = CI.getLoc();
1411
1412 if (!ResultType->isDependentType() &&
1413 !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1414 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1415 << &TmpAttr << CI.getRange() << getFunctionOrMethodResultSourceRange(D);
1416 return;
1417 }
1418
1419 ParamIdx Idx;
1420 const auto *FuncDecl = cast<FunctionDecl>(D);
1421 if (!checkFunctionOrMethodParameterIndex(FuncDecl, TmpAttr,
1422 /*AttrArgNum=*/1, ParamExpr, Idx))
1423 return;
1424
1426 if (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
1427 !Ty->isAlignValT()) {
1428 Diag(ParamExpr->getBeginLoc(), diag::err_attribute_integers_only)
1429 << &TmpAttr
1430 << FuncDecl->getParamDecl(Idx.getASTIndex())->getSourceRange();
1431 return;
1432 }
1433
1434 D->addAttr(::new (Context) AllocAlignAttr(Context, CI, Idx));
1435}
1436
1437/// Normalize the attribute, __foo__ becomes foo.
1438/// Returns true if normalization was applied.
1439static bool normalizeName(StringRef &AttrName) {
1440 if (AttrName.size() > 4 && AttrName.starts_with("__") &&
1441 AttrName.ends_with("__")) {
1442 AttrName = AttrName.drop_front(2).drop_back(2);
1443 return true;
1444 }
1445 return false;
1446}
1447
1448static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1449 // This attribute must be applied to a function declaration. The first
1450 // argument to the attribute must be an identifier, the name of the resource,
1451 // for example: malloc. The following arguments must be argument indexes, the
1452 // arguments must be of integer type for Returns, otherwise of pointer type.
1453 // The difference between Holds and Takes is that a pointer may still be used
1454 // after being held. free() should be __attribute((ownership_takes)), whereas
1455 // a list append function may well be __attribute((ownership_holds)).
1456
1457 if (!AL.isArgIdent(0)) {
1458 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1459 << AL << 1 << AANT_ArgumentIdentifier;
1460 return;
1461 }
1462
1463 // Figure out our Kind.
1464 OwnershipAttr::OwnershipKind K =
1465 OwnershipAttr(S.Context, AL, nullptr, nullptr, 0).getOwnKind();
1466
1467 // Check arguments.
1468 switch (K) {
1469 case OwnershipAttr::Takes:
1470 case OwnershipAttr::Holds:
1471 if (AL.getNumArgs() < 2) {
1472 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << AL << 2;
1473 return;
1474 }
1475 break;
1476 case OwnershipAttr::Returns:
1477 if (AL.getNumArgs() > 2) {
1478 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
1479 return;
1480 }
1481 break;
1482 }
1483
1484 // Allow only pointers to be return type for functions with ownership_returns
1485 // attribute. This matches with current OwnershipAttr::Takes semantics
1486 if (K == OwnershipAttr::Returns &&
1487 !getFunctionOrMethodResultType(D)->isPointerType()) {
1488 S.Diag(AL.getLoc(), diag::err_ownership_takes_return_type) << AL;
1489 return;
1490 }
1491
1493
1494 StringRef ModuleName = Module->getName();
1495 if (normalizeName(ModuleName)) {
1496 Module = &S.PP.getIdentifierTable().get(ModuleName);
1497 }
1498
1499 SmallVector<ParamIdx, 8> OwnershipArgs;
1500 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1501 Expr *Ex = AL.getArgAsExpr(i);
1502 ParamIdx Idx;
1503 if (!S.checkFunctionOrMethodParameterIndex(D, AL, i, Ex, Idx))
1504 return;
1505
1506 // Is the function argument a pointer type?
1508 int Err = -1; // No error
1509 switch (K) {
1510 case OwnershipAttr::Takes:
1511 case OwnershipAttr::Holds:
1512 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1513 Err = 0;
1514 break;
1515 case OwnershipAttr::Returns:
1516 if (!T->isIntegerType())
1517 Err = 1;
1518 break;
1519 }
1520 if (-1 != Err) {
1521 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL << Err
1522 << Ex->getSourceRange();
1523 return;
1524 }
1525
1526 // Check we don't have a conflict with another ownership attribute.
1527 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1528 // Cannot have two ownership attributes of different kinds for the same
1529 // index.
1530 if (I->getOwnKind() != K && llvm::is_contained(I->args(), Idx)) {
1531 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1532 << AL << I
1533 << (AL.isRegularKeywordAttribute() ||
1534 I->isRegularKeywordAttribute());
1535 return;
1536 } else if (K == OwnershipAttr::Returns &&
1537 I->getOwnKind() == OwnershipAttr::Returns) {
1538 // A returns attribute conflicts with any other returns attribute using
1539 // a different index.
1540 if (!llvm::is_contained(I->args(), Idx)) {
1541 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1542 << I->args_begin()->getSourceIndex();
1543 if (I->args_size())
1544 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1545 << Idx.getSourceIndex() << Ex->getSourceRange();
1546 return;
1547 }
1548 } else if (K == OwnershipAttr::Takes &&
1549 I->getOwnKind() == OwnershipAttr::Takes) {
1550 if (I->getModule()->getName() != ModuleName) {
1551 S.Diag(I->getLocation(), diag::err_ownership_takes_class_mismatch)
1552 << I->getModule()->getName();
1553 S.Diag(AL.getLoc(), diag::note_ownership_takes_class_mismatch)
1554 << ModuleName << Ex->getSourceRange();
1555
1556 return;
1557 }
1558 }
1559 }
1560 OwnershipArgs.push_back(Idx);
1561 }
1562
1563 ParamIdx *Start = OwnershipArgs.data();
1564 unsigned Size = OwnershipArgs.size();
1565 llvm::array_pod_sort(Start, Start + Size);
1566 D->addAttr(::new (S.Context)
1567 OwnershipAttr(S.Context, AL, Module, Start, Size));
1568}
1569
1570static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1571 // Check the attribute arguments.
1572 if (AL.getNumArgs() > 1) {
1573 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1574 return;
1575 }
1576
1577 // gcc rejects
1578 // class c {
1579 // static int a __attribute__((weakref ("v2")));
1580 // static int b() __attribute__((weakref ("f3")));
1581 // };
1582 // and ignores the attributes of
1583 // void f(void) {
1584 // static int a __attribute__((weakref ("v2")));
1585 // }
1586 // we reject them
1587 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1588 if (!Ctx->isFileContext()) {
1589 S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context)
1590 << cast<NamedDecl>(D);
1591 return;
1592 }
1593
1594 // The GCC manual says
1595 //
1596 // At present, a declaration to which `weakref' is attached can only
1597 // be `static'.
1598 //
1599 // It also says
1600 //
1601 // Without a TARGET,
1602 // given as an argument to `weakref' or to `alias', `weakref' is
1603 // equivalent to `weak'.
1604 //
1605 // gcc 4.4.1 will accept
1606 // int a7 __attribute__((weakref));
1607 // as
1608 // int a7 __attribute__((weak));
1609 // This looks like a bug in gcc. We reject that for now. We should revisit
1610 // it if this behaviour is actually used.
1611
1612 // GCC rejects
1613 // static ((alias ("y"), weakref)).
1614 // Should we? How to check that weakref is before or after alias?
1615
1616 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1617 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1618 // StringRef parameter it was given anyway.
1619 StringRef Str;
1620 if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, 0, Str))
1621 // GCC will accept anything as the argument of weakref. Should we
1622 // check for an existing decl?
1623 D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
1624
1625 D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
1626}
1627
1628// Mark alias/ifunc target as used. Due to name mangling, we look up the
1629// demangled name ignoring parameters (not supported by microsoftDemangle
1630// https://github.com/llvm/llvm-project/issues/88825). This should handle the
1631// majority of use cases while leaving namespace scope names unmarked.
1632static void markUsedForAliasOrIfunc(Sema &S, Decl *D, const ParsedAttr &AL,
1633 StringRef Str) {
1634 std::unique_ptr<char, llvm::FreeDeleter> Demangled;
1635 if (S.getASTContext().getCXXABIKind() != TargetCXXABI::Microsoft)
1636 Demangled.reset(llvm::itaniumDemangle(Str, /*ParseParams=*/false));
1637 std::unique_ptr<MangleContext> MC(S.Context.createMangleContext());
1638 SmallString<256> Name;
1639
1641 &S.Context.Idents.get(Demangled ? Demangled.get() : Str), AL.getLoc());
1643 if (S.LookupName(LR, S.TUScope)) {
1644 for (NamedDecl *ND : LR) {
1645 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND))
1646 continue;
1647 if (MC->shouldMangleDeclName(ND)) {
1648 llvm::raw_svector_ostream Out(Name);
1649 Name.clear();
1650 MC->mangleName(GlobalDecl(ND), Out);
1651 } else {
1652 Name = ND->getIdentifier()->getName();
1653 }
1654 if (Name == Str)
1655 ND->markUsed(S.Context);
1656 }
1657 }
1658}
1659
1660static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1661 StringRef Str;
1662 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1663 return;
1664
1665 // Aliases should be on declarations, not definitions.
1666 const auto *FD = cast<FunctionDecl>(D);
1667 if (FD->isThisDeclarationADefinition()) {
1668 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1;
1669 return;
1670 }
1671
1672 markUsedForAliasOrIfunc(S, D, AL, Str);
1673 D->addAttr(::new (S.Context) IFuncAttr(S.Context, AL, Str));
1674}
1675
1676static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1677 StringRef Str;
1678 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1679 return;
1680
1681 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1682 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin);
1683 return;
1684 }
1685
1686 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1687 CudaVersion Version =
1689 if (Version != CudaVersion::UNKNOWN && Version < CudaVersion::CUDA_100)
1690 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx);
1691 }
1692
1693 // Aliases should be on declarations, not definitions.
1694 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1695 if (FD->isThisDeclarationADefinition()) {
1696 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0;
1697 return;
1698 }
1699 } else {
1700 const auto *VD = cast<VarDecl>(D);
1701 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1702 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0;
1703 return;
1704 }
1705 }
1706
1707 markUsedForAliasOrIfunc(S, D, AL, Str);
1708 D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
1709}
1710
1711static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1712 StringRef Model;
1713 SourceLocation LiteralLoc;
1714 // Check that it is a string.
1715 if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc))
1716 return;
1717
1718 // Check that the value.
1719 if (Model != "global-dynamic" && Model != "local-dynamic"
1720 && Model != "initial-exec" && Model != "local-exec") {
1721 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1722 return;
1723 }
1724
1725 D->addAttr(::new (S.Context) TLSModelAttr(S.Context, AL, Model));
1726}
1727
1728static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1730 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1731 D->addAttr(::new (S.Context) RestrictAttr(S.Context, AL));
1732 return;
1733 }
1734
1735 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1737}
1738
1739static void handleCPUSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1740 // Ensure we don't combine these with themselves, since that causes some
1741 // confusing behavior.
1742 if (AL.getParsedKind() == ParsedAttr::AT_CPUDispatch) {
1743 if (checkAttrMutualExclusion<CPUSpecificAttr>(S, D, AL))
1744 return;
1745
1746 if (const auto *Other = D->getAttr<CPUDispatchAttr>()) {
1747 S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
1748 S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
1749 return;
1750 }
1751 } else if (AL.getParsedKind() == ParsedAttr::AT_CPUSpecific) {
1752 if (checkAttrMutualExclusion<CPUDispatchAttr>(S, D, AL))
1753 return;
1754
1755 if (const auto *Other = D->getAttr<CPUSpecificAttr>()) {
1756 S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
1757 S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
1758 return;
1759 }
1760 }
1761
1762 FunctionDecl *FD = cast<FunctionDecl>(D);
1763
1764 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
1765 if (MD->getParent()->isLambda()) {
1766 S.Diag(AL.getLoc(), diag::err_attribute_dll_lambda) << AL;
1767 return;
1768 }
1769 }
1770
1771 if (!AL.checkAtLeastNumArgs(S, 1))
1772 return;
1773
1775 for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); ++ArgNo) {
1776 if (!AL.isArgIdent(ArgNo)) {
1777 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1778 << AL << AANT_ArgumentIdentifier;
1779 return;
1780 }
1781
1782 IdentifierLoc *CPUArg = AL.getArgAsIdent(ArgNo);
1783 StringRef CPUName = CPUArg->Ident->getName().trim();
1784
1786 S.Diag(CPUArg->Loc, diag::err_invalid_cpu_specific_dispatch_value)
1787 << CPUName << (AL.getKind() == ParsedAttr::AT_CPUDispatch);
1788 return;
1789 }
1790
1792 if (llvm::any_of(CPUs, [CPUName, &Target](const IdentifierInfo *Cur) {
1793 return Target.CPUSpecificManglingCharacter(CPUName) ==
1794 Target.CPUSpecificManglingCharacter(Cur->getName());
1795 })) {
1796 S.Diag(AL.getLoc(), diag::warn_multiversion_duplicate_entries);
1797 return;
1798 }
1799 CPUs.push_back(CPUArg->Ident);
1800 }
1801
1802 FD->setIsMultiVersion(true);
1803 if (AL.getKind() == ParsedAttr::AT_CPUSpecific)
1804 D->addAttr(::new (S.Context)
1805 CPUSpecificAttr(S.Context, AL, CPUs.data(), CPUs.size()));
1806 else
1807 D->addAttr(::new (S.Context)
1808 CPUDispatchAttr(S.Context, AL, CPUs.data(), CPUs.size()));
1809}
1810
1811static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1812 if (S.LangOpts.CPlusPlus) {
1813 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
1815 return;
1816 }
1817
1818 D->addAttr(::new (S.Context) CommonAttr(S.Context, AL));
1819}
1820
1821static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1822 if (AL.isDeclspecAttribute()) {
1823 const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
1824 const auto &Arch = Triple.getArch();
1825 if (Arch != llvm::Triple::x86 &&
1826 (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
1827 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch)
1828 << AL << Triple.getArchName();
1829 return;
1830 }
1831
1832 // This form is not allowed to be written on a member function (static or
1833 // nonstatic) when in Microsoft compatibility mode.
1834 if (S.getLangOpts().MSVCCompat && isa<CXXMethodDecl>(D)) {
1835 S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type_str)
1836 << AL << AL.isRegularKeywordAttribute() << "non-member functions";
1837 return;
1838 }
1839 }
1840
1841 D->addAttr(::new (S.Context) NakedAttr(S.Context, AL));
1842}
1843
1844static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
1845 if (hasDeclarator(D)) return;
1846
1847 if (!isa<ObjCMethodDecl>(D)) {
1848 S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
1849 << Attrs << Attrs.isRegularKeywordAttribute()
1851 return;
1852 }
1853
1854 D->addAttr(::new (S.Context) NoReturnAttr(S.Context, Attrs));
1855}
1856
1857static void handleStandardNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &A) {
1858 // The [[_Noreturn]] spelling is deprecated in C23, so if that was used,
1859 // issue an appropriate diagnostic. However, don't issue a diagnostic if the
1860 // attribute name comes from a macro expansion. We don't want to punish users
1861 // who write [[noreturn]] after including <stdnoreturn.h> (where 'noreturn'
1862 // is defined as a macro which expands to '_Noreturn').
1863 if (!S.getLangOpts().CPlusPlus &&
1864 A.getSemanticSpelling() == CXX11NoReturnAttr::C23_Noreturn &&
1865 !(A.getLoc().isMacroID() &&
1867 S.Diag(A.getLoc(), diag::warn_deprecated_noreturn_spelling) << A.getRange();
1868
1869 D->addAttr(::new (S.Context) CXX11NoReturnAttr(S.Context, A));
1870}
1871
1872static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
1873 if (!S.getLangOpts().CFProtectionBranch)
1874 S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored);
1875 else
1876 handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs);
1877}
1878
1880 if (!Attrs.checkExactlyNumArgs(*this, 0)) {
1881 Attrs.setInvalid();
1882 return true;
1883 }
1884
1885 return false;
1886}
1887
1889 // Check whether the attribute is valid on the current target.
1892 ? diag::err_keyword_not_supported_on_target
1893 : diag::warn_unknown_attribute_ignored)
1894 << AL << AL.getRange();
1895 AL.setInvalid();
1896 return true;
1897 }
1898
1899 return false;
1900}
1901
1902static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1903
1904 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1905 // because 'analyzer_noreturn' does not impact the type.
1907 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1908 if (!VD || (!VD->getType()->isBlockPointerType() &&
1909 !VD->getType()->isFunctionPointerType())) {
1911 ? diag::err_attribute_wrong_decl_type
1912 : diag::warn_attribute_wrong_decl_type)
1913 << AL << AL.isRegularKeywordAttribute()
1915 return;
1916 }
1917 }
1918
1919 D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(S.Context, AL));
1920}
1921
1922// PS3 PPU-specific.
1923static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1924 /*
1925 Returning a Vector Class in Registers
1926
1927 According to the PPU ABI specifications, a class with a single member of
1928 vector type is returned in memory when used as the return value of a
1929 function.
1930 This results in inefficient code when implementing vector classes. To return
1931 the value in a single vector register, add the vecreturn attribute to the
1932 class definition. This attribute is also applicable to struct types.
1933
1934 Example:
1935
1936 struct Vector
1937 {
1938 __vector float xyzw;
1939 } __attribute__((vecreturn));
1940
1941 Vector Add(Vector lhs, Vector rhs)
1942 {
1943 Vector result;
1944 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1945 return result; // This will be returned in a register
1946 }
1947 */
1948 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
1949 S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A;
1950 return;
1951 }
1952
1953 const auto *R = cast<RecordDecl>(D);
1954 int count = 0;
1955
1956 if (!isa<CXXRecordDecl>(R)) {
1957 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1958 return;
1959 }
1960
1961 if (!cast<CXXRecordDecl>(R)->isPOD()) {
1962 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1963 return;
1964 }
1965
1966 for (const auto *I : R->fields()) {
1967 if ((count == 1) || !I->getType()->isVectorType()) {
1968 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1969 return;
1970 }
1971 count++;
1972 }
1973
1974 D->addAttr(::new (S.Context) VecReturnAttr(S.Context, AL));
1975}
1976
1978 const ParsedAttr &AL) {
1979 if (isa<ParmVarDecl>(D)) {
1980 // [[carries_dependency]] can only be applied to a parameter if it is a
1981 // parameter of a function declaration or lambda.
1983 S.Diag(AL.getLoc(),
1984 diag::err_carries_dependency_param_not_function_decl);
1985 return;
1986 }
1987 }
1988
1989 D->addAttr(::new (S.Context) CarriesDependencyAttr(S.Context, AL));
1990}
1991
1992static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1993 bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName();
1994
1995 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
1996 // about using it as an extension.
1997 if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
1998 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
1999
2000 D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL));
2001}
2002
2003static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2004 uint32_t priority = ConstructorAttr::DefaultPriority;
2005 if (S.getLangOpts().HLSL && AL.getNumArgs()) {
2006 S.Diag(AL.getLoc(), diag::err_hlsl_init_priority_unsupported);
2007 return;
2008 }
2009 if (AL.getNumArgs() &&
2010 !S.checkUInt32Argument(AL, AL.getArgAsExpr(0), priority))
2011 return;
2012
2013 D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority));
2014}
2015
2016static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2017 uint32_t priority = DestructorAttr::DefaultPriority;
2018 if (AL.getNumArgs() &&
2019 !S.checkUInt32Argument(AL, AL.getArgAsExpr(0), priority))
2020 return;
2021
2022 D->addAttr(::new (S.Context) DestructorAttr(S.Context, AL, priority));
2023}
2024
2025template <typename AttrTy>
2026static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) {
2027 // Handle the case where the attribute has a text message.
2028 StringRef Str;
2029 if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str))
2030 return;
2031
2032 D->addAttr(::new (S.Context) AttrTy(S.Context, AL, Str));
2033}
2034
2036 IdentifierInfo *Platform,
2037 VersionTuple Introduced,
2038 VersionTuple Deprecated,
2039 VersionTuple Obsoleted) {
2040 StringRef PlatformName
2041 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2042 if (PlatformName.empty())
2043 PlatformName = Platform->getName();
2044
2045 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2046 // of these steps are needed).
2047 if (!Introduced.empty() && !Deprecated.empty() &&
2048 !(Introduced <= Deprecated)) {
2049 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2050 << 1 << PlatformName << Deprecated.getAsString()
2051 << 0 << Introduced.getAsString();
2052 return true;
2053 }
2054
2055 if (!Introduced.empty() && !Obsoleted.empty() &&
2056 !(Introduced <= Obsoleted)) {
2057 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2058 << 2 << PlatformName << Obsoleted.getAsString()
2059 << 0 << Introduced.getAsString();
2060 return true;
2061 }
2062
2063 if (!Deprecated.empty() && !Obsoleted.empty() &&
2064 !(Deprecated <= Obsoleted)) {
2065 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2066 << 2 << PlatformName << Obsoleted.getAsString()
2067 << 1 << Deprecated.getAsString();
2068 return true;
2069 }
2070
2071 return false;
2072}
2073
2074/// Check whether the two versions match.
2075///
2076/// If either version tuple is empty, then they are assumed to match. If
2077/// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2078static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2079 bool BeforeIsOkay) {
2080 if (X.empty() || Y.empty())
2081 return true;
2082
2083 if (X == Y)
2084 return true;
2085
2086 if (BeforeIsOkay && X < Y)
2087 return true;
2088
2089 return false;
2090}
2091
2093 NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform,
2094 bool Implicit, VersionTuple Introduced, VersionTuple Deprecated,
2095 VersionTuple Obsoleted, bool IsUnavailable, StringRef Message,
2096 bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK,
2097 int Priority, IdentifierInfo *Environment) {
2098 VersionTuple MergedIntroduced = Introduced;
2099 VersionTuple MergedDeprecated = Deprecated;
2100 VersionTuple MergedObsoleted = Obsoleted;
2101 bool FoundAny = false;
2102 bool OverrideOrImpl = false;
2103 switch (AMK) {
2104 case AMK_None:
2105 case AMK_Redeclaration:
2106 OverrideOrImpl = false;
2107 break;
2108
2109 case AMK_Override:
2112 OverrideOrImpl = true;
2113 break;
2114 }
2115
2116 if (D->hasAttrs()) {
2117 AttrVec &Attrs = D->getAttrs();
2118 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2119 const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2120 if (!OldAA) {
2121 ++i;
2122 continue;
2123 }
2124
2125 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2126 if (OldPlatform != Platform) {
2127 ++i;
2128 continue;
2129 }
2130
2131 IdentifierInfo *OldEnvironment = OldAA->getEnvironment();
2132 if (OldEnvironment != Environment) {
2133 ++i;
2134 continue;
2135 }
2136
2137 // If there is an existing availability attribute for this platform that
2138 // has a lower priority use the existing one and discard the new
2139 // attribute.
2140 if (OldAA->getPriority() < Priority)
2141 return nullptr;
2142
2143 // If there is an existing attribute for this platform that has a higher
2144 // priority than the new attribute then erase the old one and continue
2145 // processing the attributes.
2146 if (OldAA->getPriority() > Priority) {
2147 Attrs.erase(Attrs.begin() + i);
2148 --e;
2149 continue;
2150 }
2151
2152 FoundAny = true;
2153 VersionTuple OldIntroduced = OldAA->getIntroduced();
2154 VersionTuple OldDeprecated = OldAA->getDeprecated();
2155 VersionTuple OldObsoleted = OldAA->getObsoleted();
2156 bool OldIsUnavailable = OldAA->getUnavailable();
2157
2158 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2159 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2160 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2161 !(OldIsUnavailable == IsUnavailable ||
2162 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2163 if (OverrideOrImpl) {
2164 int Which = -1;
2165 VersionTuple FirstVersion;
2166 VersionTuple SecondVersion;
2167 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2168 Which = 0;
2169 FirstVersion = OldIntroduced;
2170 SecondVersion = Introduced;
2171 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2172 Which = 1;
2173 FirstVersion = Deprecated;
2174 SecondVersion = OldDeprecated;
2175 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2176 Which = 2;
2177 FirstVersion = Obsoleted;
2178 SecondVersion = OldObsoleted;
2179 }
2180
2181 if (Which == -1) {
2182 Diag(OldAA->getLocation(),
2183 diag::warn_mismatched_availability_override_unavail)
2184 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2185 << (AMK == AMK_Override);
2186 } else if (Which != 1 && AMK == AMK_OptionalProtocolImplementation) {
2187 // Allow different 'introduced' / 'obsoleted' availability versions
2188 // on a method that implements an optional protocol requirement. It
2189 // makes less sense to allow this for 'deprecated' as the user can't
2190 // see if the method is 'deprecated' as 'respondsToSelector' will
2191 // still return true when the method is deprecated.
2192 ++i;
2193 continue;
2194 } else {
2195 Diag(OldAA->getLocation(),
2196 diag::warn_mismatched_availability_override)
2197 << Which
2198 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2199 << FirstVersion.getAsString() << SecondVersion.getAsString()
2200 << (AMK == AMK_Override);
2201 }
2202 if (AMK == AMK_Override)
2203 Diag(CI.getLoc(), diag::note_overridden_method);
2204 else
2205 Diag(CI.getLoc(), diag::note_protocol_method);
2206 } else {
2207 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2208 Diag(CI.getLoc(), diag::note_previous_attribute);
2209 }
2210
2211 Attrs.erase(Attrs.begin() + i);
2212 --e;
2213 continue;
2214 }
2215
2216 VersionTuple MergedIntroduced2 = MergedIntroduced;
2217 VersionTuple MergedDeprecated2 = MergedDeprecated;
2218 VersionTuple MergedObsoleted2 = MergedObsoleted;
2219
2220 if (MergedIntroduced2.empty())
2221 MergedIntroduced2 = OldIntroduced;
2222 if (MergedDeprecated2.empty())
2223 MergedDeprecated2 = OldDeprecated;
2224 if (MergedObsoleted2.empty())
2225 MergedObsoleted2 = OldObsoleted;
2226
2227 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2228 MergedIntroduced2, MergedDeprecated2,
2229 MergedObsoleted2)) {
2230 Attrs.erase(Attrs.begin() + i);
2231 --e;
2232 continue;
2233 }
2234
2235 MergedIntroduced = MergedIntroduced2;
2236 MergedDeprecated = MergedDeprecated2;
2237 MergedObsoleted = MergedObsoleted2;
2238 ++i;
2239 }
2240 }
2241
2242 if (FoundAny &&
2243 MergedIntroduced == Introduced &&
2244 MergedDeprecated == Deprecated &&
2245 MergedObsoleted == Obsoleted)
2246 return nullptr;
2247
2248 // Only create a new attribute if !OverrideOrImpl, but we want to do
2249 // the checking.
2250 if (!checkAvailabilityAttr(*this, CI.getRange(), Platform, MergedIntroduced,
2251 MergedDeprecated, MergedObsoleted) &&
2252 !OverrideOrImpl) {
2253 auto *Avail = ::new (Context) AvailabilityAttr(
2254 Context, CI, Platform, Introduced, Deprecated, Obsoleted, IsUnavailable,
2255 Message, IsStrict, Replacement, Priority, Environment);
2256 Avail->setImplicit(Implicit);
2257 return Avail;
2258 }
2259 return nullptr;
2260}
2261
2262static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2263 if (isa<UsingDecl, UnresolvedUsingTypenameDecl, UnresolvedUsingValueDecl>(
2264 D)) {
2265 S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using)
2266 << AL;
2267 return;
2268 }
2269
2270 if (!AL.checkExactlyNumArgs(S, 1))
2271 return;
2272 IdentifierLoc *Platform = AL.getArgAsIdent(0);
2273
2274 IdentifierInfo *II = Platform->Ident;
2275 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2276 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2277 << Platform->Ident;
2278
2279 auto *ND = dyn_cast<NamedDecl>(D);
2280 if (!ND) // We warned about this already, so just return.
2281 return;
2282
2286 bool IsUnavailable = AL.getUnavailableLoc().isValid();
2287 bool IsStrict = AL.getStrictLoc().isValid();
2288 StringRef Str;
2289 if (const auto *SE = dyn_cast_if_present<StringLiteral>(AL.getMessageExpr()))
2290 Str = SE->getString();
2291 StringRef Replacement;
2292 if (const auto *SE =
2293 dyn_cast_if_present<StringLiteral>(AL.getReplacementExpr()))
2294 Replacement = SE->getString();
2295
2296 if (II->isStr("swift")) {
2297 if (Introduced.isValid() || Obsoleted.isValid() ||
2298 (!IsUnavailable && !Deprecated.isValid())) {
2299 S.Diag(AL.getLoc(),
2300 diag::warn_availability_swift_unavailable_deprecated_only);
2301 return;
2302 }
2303 }
2304
2305 if (II->isStr("fuchsia")) {
2306 std::optional<unsigned> Min, Sub;
2307 if ((Min = Introduced.Version.getMinor()) ||
2308 (Sub = Introduced.Version.getSubminor())) {
2309 S.Diag(AL.getLoc(), diag::warn_availability_fuchsia_unavailable_minor);
2310 return;
2311 }
2312 }
2313
2314 if (S.getLangOpts().HLSL && IsStrict)
2315 S.Diag(AL.getStrictLoc(), diag::err_availability_unexpected_parameter)
2316 << "strict" << /* HLSL */ 0;
2317
2318 int PriorityModifier = AL.isPragmaClangAttribute()
2321
2322 const IdentifierLoc *EnvironmentLoc = AL.getEnvironment();
2323 IdentifierInfo *IIEnvironment = nullptr;
2324 if (EnvironmentLoc) {
2325 if (S.getLangOpts().HLSL) {
2326 IIEnvironment = EnvironmentLoc->Ident;
2327 if (AvailabilityAttr::getEnvironmentType(
2328 EnvironmentLoc->Ident->getName()) ==
2329 llvm::Triple::EnvironmentType::UnknownEnvironment)
2330 S.Diag(EnvironmentLoc->Loc, diag::warn_availability_unknown_environment)
2331 << EnvironmentLoc->Ident;
2332 } else {
2333 S.Diag(EnvironmentLoc->Loc, diag::err_availability_unexpected_parameter)
2334 << "environment" << /* C/C++ */ 1;
2335 }
2336 }
2337
2338 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2339 ND, AL, II, false /*Implicit*/, Introduced.Version, Deprecated.Version,
2340 Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement,
2341 Sema::AMK_None, PriorityModifier, IIEnvironment);
2342 if (NewAttr)
2343 D->addAttr(NewAttr);
2344
2345 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2346 // matches before the start of the watchOS platform.
2347 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2348 IdentifierInfo *NewII = nullptr;
2349 if (II->getName() == "ios")
2350 NewII = &S.Context.Idents.get("watchos");
2351 else if (II->getName() == "ios_app_extension")
2352 NewII = &S.Context.Idents.get("watchos_app_extension");
2353
2354 if (NewII) {
2355 const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking();
2356 const auto *IOSToWatchOSMapping =
2357 SDKInfo ? SDKInfo->getVersionMapping(
2359 : nullptr;
2360
2361 auto adjustWatchOSVersion =
2362 [IOSToWatchOSMapping](VersionTuple Version) -> VersionTuple {
2363 if (Version.empty())
2364 return Version;
2365 auto MinimumWatchOSVersion = VersionTuple(2, 0);
2366
2367 if (IOSToWatchOSMapping) {
2368 if (auto MappedVersion = IOSToWatchOSMapping->map(
2369 Version, MinimumWatchOSVersion, std::nullopt)) {
2370 return *MappedVersion;
2371 }
2372 }
2373
2374 auto Major = Version.getMajor();
2375 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2376 if (NewMajor >= 2) {
2377 if (Version.getMinor()) {
2378 if (Version.getSubminor())
2379 return VersionTuple(NewMajor, *Version.getMinor(),
2380 *Version.getSubminor());
2381 else
2382 return VersionTuple(NewMajor, *Version.getMinor());
2383 }
2384 return VersionTuple(NewMajor);
2385 }
2386
2387 return MinimumWatchOSVersion;
2388 };
2389
2390 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2391 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2392 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2393
2394 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2395 ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
2396 NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
2398 IIEnvironment);
2399 if (NewAttr)
2400 D->addAttr(NewAttr);
2401 }
2402 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2403 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2404 // matches before the start of the tvOS platform.
2405 IdentifierInfo *NewII = nullptr;
2406 if (II->getName() == "ios")
2407 NewII = &S.Context.Idents.get("tvos");
2408 else if (II->getName() == "ios_app_extension")
2409 NewII = &S.Context.Idents.get("tvos_app_extension");
2410
2411 if (NewII) {
2412 const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking();
2413 const auto *IOSToTvOSMapping =
2414 SDKInfo ? SDKInfo->getVersionMapping(
2416 : nullptr;
2417
2418 auto AdjustTvOSVersion =
2419 [IOSToTvOSMapping](VersionTuple Version) -> VersionTuple {
2420 if (Version.empty())
2421 return Version;
2422
2423 if (IOSToTvOSMapping) {
2424 if (auto MappedVersion = IOSToTvOSMapping->map(
2425 Version, VersionTuple(0, 0), std::nullopt)) {
2426 return *MappedVersion;
2427 }
2428 }
2429 return Version;
2430 };
2431
2432 auto NewIntroduced = AdjustTvOSVersion(Introduced.Version);
2433 auto NewDeprecated = AdjustTvOSVersion(Deprecated.Version);
2434 auto NewObsoleted = AdjustTvOSVersion(Obsoleted.Version);
2435
2436 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2437 ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
2438 NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
2440 IIEnvironment);
2441 if (NewAttr)
2442 D->addAttr(NewAttr);
2443 }
2444 } else if (S.Context.getTargetInfo().getTriple().getOS() ==
2445 llvm::Triple::IOS &&
2446 S.Context.getTargetInfo().getTriple().isMacCatalystEnvironment()) {
2447 auto GetSDKInfo = [&]() {
2449 "macOS");
2450 };
2451
2452 // Transcribe "ios" to "maccatalyst" (and add a new attribute).
2453 IdentifierInfo *NewII = nullptr;
2454 if (II->getName() == "ios")
2455 NewII = &S.Context.Idents.get("maccatalyst");
2456 else if (II->getName() == "ios_app_extension")
2457 NewII = &S.Context.Idents.get("maccatalyst_app_extension");
2458 if (NewII) {
2459 auto MinMacCatalystVersion = [](const VersionTuple &V) {
2460 if (V.empty())
2461 return V;
2462 if (V.getMajor() < 13 ||
2463 (V.getMajor() == 13 && V.getMinor() && *V.getMinor() < 1))
2464 return VersionTuple(13, 1); // The min Mac Catalyst version is 13.1.
2465 return V;
2466 };
2467 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2468 ND, AL, NewII, true /*Implicit*/,
2469 MinMacCatalystVersion(Introduced.Version),
2470 MinMacCatalystVersion(Deprecated.Version),
2471 MinMacCatalystVersion(Obsoleted.Version), IsUnavailable, Str,
2472 IsStrict, Replacement, Sema::AMK_None,
2473 PriorityModifier + Sema::AP_InferredFromOtherPlatform, IIEnvironment);
2474 if (NewAttr)
2475 D->addAttr(NewAttr);
2476 } else if (II->getName() == "macos" && GetSDKInfo() &&
2477 (!Introduced.Version.empty() || !Deprecated.Version.empty() ||
2478 !Obsoleted.Version.empty())) {
2479 if (const auto *MacOStoMacCatalystMapping =
2480 GetSDKInfo()->getVersionMapping(
2482 // Infer Mac Catalyst availability from the macOS availability attribute
2483 // if it has versioned availability. Don't infer 'unavailable'. This
2484 // inferred availability has lower priority than the other availability
2485 // attributes that are inferred from 'ios'.
2486 NewII = &S.Context.Idents.get("maccatalyst");
2487 auto RemapMacOSVersion =
2488 [&](const VersionTuple &V) -> std::optional<VersionTuple> {
2489 if (V.empty())
2490 return std::nullopt;
2491 // API_TO_BE_DEPRECATED is 100000.
2492 if (V.getMajor() == 100000)
2493 return VersionTuple(100000);
2494 // The minimum iosmac version is 13.1
2495 return MacOStoMacCatalystMapping->map(V, VersionTuple(13, 1),
2496 std::nullopt);
2497 };
2498 std::optional<VersionTuple> NewIntroduced =
2499 RemapMacOSVersion(Introduced.Version),
2500 NewDeprecated =
2501 RemapMacOSVersion(Deprecated.Version),
2502 NewObsoleted =
2503 RemapMacOSVersion(Obsoleted.Version);
2504 if (NewIntroduced || NewDeprecated || NewObsoleted) {
2505 auto VersionOrEmptyVersion =
2506 [](const std::optional<VersionTuple> &V) -> VersionTuple {
2507 return V ? *V : VersionTuple();
2508 };
2509 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2510 ND, AL, NewII, true /*Implicit*/,
2511 VersionOrEmptyVersion(NewIntroduced),
2512 VersionOrEmptyVersion(NewDeprecated),
2513 VersionOrEmptyVersion(NewObsoleted), /*IsUnavailable=*/false, Str,
2514 IsStrict, Replacement, Sema::AMK_None,
2515 PriorityModifier + Sema::AP_InferredFromOtherPlatform +
2517 IIEnvironment);
2518 if (NewAttr)
2519 D->addAttr(NewAttr);
2520 }
2521 }
2522 }
2523 }
2524}
2525
2527 const ParsedAttr &AL) {
2528 if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 4))
2529 return;
2530
2531 StringRef Language;
2532 if (const auto *SE = dyn_cast_if_present<StringLiteral>(AL.getArgAsExpr(0)))
2533 Language = SE->getString();
2534 StringRef DefinedIn;
2535 if (const auto *SE = dyn_cast_if_present<StringLiteral>(AL.getArgAsExpr(1)))
2536 DefinedIn = SE->getString();
2537 bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
2538 StringRef USR;
2539 if (const auto *SE = dyn_cast_if_present<StringLiteral>(AL.getArgAsExpr(3)))
2540 USR = SE->getString();
2541
2542 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2543 S.Context, AL, Language, DefinedIn, IsGeneratedDeclaration, USR));
2544}
2545
2546template <class T>
2548 typename T::VisibilityType value) {
2549 T *existingAttr = D->getAttr<T>();
2550 if (existingAttr) {
2551 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2552 if (existingValue == value)
2553 return nullptr;
2554 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2555 S.Diag(CI.getLoc(), diag::note_previous_attribute);
2556 D->dropAttr<T>();
2557 }
2558 return ::new (S.Context) T(S.Context, CI, value);
2559}
2560
2562 const AttributeCommonInfo &CI,
2563 VisibilityAttr::VisibilityType Vis) {
2564 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, CI, Vis);
2565}
2566
2567TypeVisibilityAttr *
2569 TypeVisibilityAttr::VisibilityType Vis) {
2570 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, CI, Vis);
2571}
2572
2573static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
2574 bool isTypeVisibility) {
2575 // Visibility attributes don't mean anything on a typedef.
2576 if (isa<TypedefNameDecl>(D)) {
2577 S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
2578 return;
2579 }
2580
2581 // 'type_visibility' can only go on a type or namespace.
2582 if (isTypeVisibility && !(isa<TagDecl>(D) || isa<ObjCInterfaceDecl>(D) ||
2583 isa<NamespaceDecl>(D))) {
2584 S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2586 return;
2587 }
2588
2589 // Check that the argument is a string literal.
2590 StringRef TypeStr;
2591 SourceLocation LiteralLoc;
2592 if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc))
2593 return;
2594
2595 VisibilityAttr::VisibilityType type;
2596 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2597 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL
2598 << TypeStr;
2599 return;
2600 }
2601
2602 // Complain about attempts to use protected visibility on targets
2603 // (like Darwin) that don't support it.
2604 if (type == VisibilityAttr::Protected &&
2606 S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
2607 type = VisibilityAttr::Default;
2608 }
2609
2610 Attr *newAttr;
2611 if (isTypeVisibility) {
2612 newAttr = S.mergeTypeVisibilityAttr(
2613 D, AL, (TypeVisibilityAttr::VisibilityType)type);
2614 } else {
2615 newAttr = S.mergeVisibilityAttr(D, AL, type);
2616 }
2617 if (newAttr)
2618 D->addAttr(newAttr);
2619}
2620
2621static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2622 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2623 if (AL.getNumArgs() > 0) {
2624 Expr *E = AL.getArgAsExpr(0);
2625 std::optional<llvm::APSInt> Idx = llvm::APSInt(32);
2626 if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) {
2627 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2628 << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2629 return;
2630 }
2631
2632 if (Idx->isSigned() && Idx->isNegative()) {
2633 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2634 << E->getSourceRange();
2635 return;
2636 }
2637
2638 sentinel = Idx->getZExtValue();
2639 }
2640
2641 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2642 if (AL.getNumArgs() > 1) {
2643 Expr *E = AL.getArgAsExpr(1);
2644 std::optional<llvm::APSInt> Idx = llvm::APSInt(32);
2645 if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) {
2646 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2647 << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2648 return;
2649 }
2650 nullPos = Idx->getZExtValue();
2651
2652 if ((Idx->isSigned() && Idx->isNegative()) || nullPos > 1) {
2653 // FIXME: This error message could be improved, it would be nice
2654 // to say what the bounds actually are.
2655 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2656 << E->getSourceRange();
2657 return;
2658 }
2659 }
2660
2661 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2662 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2663 if (isa<FunctionNoProtoType>(FT)) {
2664 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2665 return;
2666 }
2667
2668 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2669 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2670 return;
2671 }
2672 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
2673 if (!MD->isVariadic()) {
2674 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2675 return;
2676 }
2677 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
2678 if (!BD->isVariadic()) {
2679 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2680 return;
2681 }
2682 } else if (const auto *V = dyn_cast<VarDecl>(D)) {
2683 QualType Ty = V->getType();
2684 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2685 const FunctionType *FT = Ty->isFunctionPointerType()
2686 ? D->getFunctionType()
2687 : Ty->castAs<BlockPointerType>()
2688 ->getPointeeType()
2689 ->castAs<FunctionType>();
2690 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2691 int m = Ty->isFunctionPointerType() ? 0 : 1;
2692 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2693 return;
2694 }
2695 } else {
2696 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2697 << AL << AL.isRegularKeywordAttribute()
2699 return;
2700 }
2701 } else {
2702 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2703 << AL << AL.isRegularKeywordAttribute()
2705 return;
2706 }
2707 D->addAttr(::new (S.Context) SentinelAttr(S.Context, AL, sentinel, nullPos));
2708}
2709
2710static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
2711 if (D->getFunctionType() &&
2713 !isa<CXXConstructorDecl>(D)) {
2714 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0;
2715 return;
2716 }
2717 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
2718 if (MD->getReturnType()->isVoidType()) {
2719 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1;
2720 return;
2721 }
2722
2723 StringRef Str;
2724 if (AL.isStandardAttributeSyntax() && !AL.getScopeName()) {
2725 // The standard attribute cannot be applied to variable declarations such
2726 // as a function pointer.
2727 if (isa<VarDecl>(D))
2728 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str)
2729 << AL << AL.isRegularKeywordAttribute()
2730 << "functions, classes, or enumerations";
2731
2732 // If this is spelled as the standard C++17 attribute, but not in C++17,
2733 // warn about using it as an extension. If there are attribute arguments,
2734 // then claim it's a C++20 extension instead.
2735 // FIXME: If WG14 does not seem likely to adopt the same feature, add an
2736 // extension warning for C23 mode.
2737 const LangOptions &LO = S.getLangOpts();
2738 if (AL.getNumArgs() == 1) {
2739 if (LO.CPlusPlus && !LO.CPlusPlus20)
2740 S.Diag(AL.getLoc(), diag::ext_cxx20_attr) << AL;
2741
2742 // Since this is spelled [[nodiscard]], get the optional string
2743 // literal. If in C++ mode, but not in C++20 mode, diagnose as an
2744 // extension.
2745 // FIXME: C23 should support this feature as well, even as an extension.
2746 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, nullptr))
2747 return;
2748 } else if (LO.CPlusPlus && !LO.CPlusPlus17)
2749 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2750 }
2751
2752 if ((!AL.isGNUAttribute() &&
2753 !(AL.isStandardAttributeSyntax() && AL.isClangScope())) &&
2754 isa<TypedefNameDecl>(D)) {
2755 S.Diag(AL.getLoc(), diag::warn_unused_result_typedef_unsupported_spelling)
2756 << AL.isGNUScope();
2757 return;
2758 }
2759
2760 D->addAttr(::new (S.Context) WarnUnusedResultAttr(S.Context, AL, Str));
2761}
2762
2763static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2764 // weak_import only applies to variable & function declarations.
2765 bool isDef = false;
2766 if (!D->canBeWeakImported(isDef)) {
2767 if (isDef)
2768 S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
2769 << "weak_import";
2770 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2771 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2772 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2773 // Nothing to warn about here.
2774 } else
2775 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2777
2778 return;
2779 }
2780
2781 D->addAttr(::new (S.Context) WeakImportAttr(S.Context, AL));
2782}
2783
2784// Handles reqd_work_group_size and work_group_size_hint.
2785template <typename WorkGroupAttr>
2786static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2787 uint32_t WGSize[3];
2788 for (unsigned i = 0; i < 3; ++i) {
2789 const Expr *E = AL.getArgAsExpr(i);
2790 if (!S.checkUInt32Argument(AL, E, WGSize[i], i,
2791 /*StrictlyUnsigned=*/true))
2792 return;
2793 if (WGSize[i] == 0) {
2794 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2795 << AL << E->getSourceRange();
2796 return;
2797 }
2798 }
2799
2800 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2801 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2802 Existing->getYDim() == WGSize[1] &&
2803 Existing->getZDim() == WGSize[2]))
2804 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2805
2806 D->addAttr(::new (S.Context)
2807 WorkGroupAttr(S.Context, AL, WGSize[0], WGSize[1], WGSize[2]));
2808}
2809
2810static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
2811 if (!AL.hasParsedType()) {
2812 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
2813 return;
2814 }
2815
2816 TypeSourceInfo *ParmTSI = nullptr;
2817 QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
2818 assert(ParmTSI && "no type source info for attribute argument");
2819
2820 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2821 (ParmType->isBooleanType() ||
2822 !ParmType->isIntegralType(S.getASTContext()))) {
2823 S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) << 2 << AL;
2824 return;
2825 }
2826
2827 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2828 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2829 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2830 return;
2831 }
2832 }
2833
2834 D->addAttr(::new (S.Context) VecTypeHintAttr(S.Context, AL, ParmTSI));
2835}
2836
2838 StringRef Name) {
2839 // Explicit or partial specializations do not inherit
2840 // the section attribute from the primary template.
2841 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2842 if (CI.getAttributeSpellingListIndex() == SectionAttr::Declspec_allocate &&
2844 return nullptr;
2845 }
2846 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2847 if (ExistingAttr->getName() == Name)
2848 return nullptr;
2849 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
2850 << 1 /*section*/;
2851 Diag(CI.getLoc(), diag::note_previous_attribute);
2852 return nullptr;
2853 }
2854 return ::new (Context) SectionAttr(Context, CI, Name);
2855}
2856
2857llvm::Error Sema::isValidSectionSpecifier(StringRef SecName) {
2858 if (!Context.getTargetInfo().getTriple().isOSDarwin())
2859 return llvm::Error::success();
2860
2861 // Let MCSectionMachO validate this.
2862 StringRef Segment, Section;
2863 unsigned TAA, StubSize;
2864 bool HasTAA;
2865 return llvm::MCSectionMachO::ParseSectionSpecifier(SecName, Segment, Section,
2866 TAA, HasTAA, StubSize);
2867}
2868
2869bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2870 if (llvm::Error E = isValidSectionSpecifier(SecName)) {
2871 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2872 << toString(std::move(E)) << 1 /*'section'*/;
2873 return false;
2874 }
2875 return true;
2876}
2877
2878static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2879 // Make sure that there is a string literal as the sections's single
2880 // argument.
2881 StringRef Str;
2882 SourceLocation LiteralLoc;
2883 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
2884 return;
2885
2886 if (!S.checkSectionName(LiteralLoc, Str))
2887 return;
2888
2889 SectionAttr *NewAttr = S.mergeSectionAttr(D, AL, Str);
2890 if (NewAttr) {
2891 D->addAttr(NewAttr);
2894 S.UnifySection(NewAttr->getName(),
2896 cast<NamedDecl>(D));
2897 }
2898}
2899
2900static void handleCodeModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2901 StringRef Str;
2902 SourceLocation LiteralLoc;
2903 // Check that it is a string.
2904 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
2905 return;
2906
2907 llvm::CodeModel::Model CM;
2908 if (!CodeModelAttr::ConvertStrToModel(Str, CM)) {
2909 S.Diag(LiteralLoc, diag::err_attr_codemodel_arg) << Str;
2910 return;
2911 }
2912
2913 D->addAttr(::new (S.Context) CodeModelAttr(S.Context, AL, CM));
2914}
2915
2916// This is used for `__declspec(code_seg("segname"))` on a decl.
2917// `#pragma code_seg("segname")` uses checkSectionName() instead.
2918static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc,
2919 StringRef CodeSegName) {
2920 if (llvm::Error E = S.isValidSectionSpecifier(CodeSegName)) {
2921 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2922 << toString(std::move(E)) << 0 /*'code-seg'*/;
2923 return false;
2924 }
2925
2926 return true;
2927}
2928
2930 StringRef Name) {
2931 // Explicit or partial specializations do not inherit
2932 // the code_seg attribute from the primary template.
2933 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2935 return nullptr;
2936 }
2937 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
2938 if (ExistingAttr->getName() == Name)
2939 return nullptr;
2940 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
2941 << 0 /*codeseg*/;
2942 Diag(CI.getLoc(), diag::note_previous_attribute);
2943 return nullptr;
2944 }
2945 return ::new (Context) CodeSegAttr(Context, CI, Name);
2946}
2947
2948static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2949 StringRef Str;
2950 SourceLocation LiteralLoc;
2951 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
2952 return;
2953 if (!checkCodeSegName(S, LiteralLoc, Str))
2954 return;
2955 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
2956 if (!ExistingAttr->isImplicit()) {
2957 S.Diag(AL.getLoc(),
2958 ExistingAttr->getName() == Str
2959 ? diag::warn_duplicate_codeseg_attribute
2960 : diag::err_conflicting_codeseg_attribute);
2961 return;
2962 }
2963 D->dropAttr<CodeSegAttr>();
2964 }
2965 if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL, Str))
2966 D->addAttr(CSA);
2967}
2968
2969bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
2970 enum FirstParam { Unsupported, Duplicate, Unknown };
2971 enum SecondParam { None, CPU, Tune };
2972 enum ThirdParam { Target, TargetClones };
2973 if (AttrStr.contains("fpmath="))
2974 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
2975 << Unsupported << None << "fpmath=" << Target;
2976
2977 // Diagnose use of tune if target doesn't support it.
2979 AttrStr.contains("tune="))
2980 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
2981 << Unsupported << None << "tune=" << Target;
2982
2983 ParsedTargetAttr ParsedAttrs =
2985
2986 if (!ParsedAttrs.CPU.empty() &&
2987 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.CPU))
2988 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
2989 << Unknown << CPU << ParsedAttrs.CPU << Target;
2990
2991 if (!ParsedAttrs.Tune.empty() &&
2992 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Tune))
2993 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
2994 << Unknown << Tune << ParsedAttrs.Tune << Target;
2995
2996 if (Context.getTargetInfo().getTriple().isRISCV() &&
2997 ParsedAttrs.Duplicate != "")
2998 return Diag(LiteralLoc, diag::err_duplicate_target_attribute)
2999 << Duplicate << None << ParsedAttrs.Duplicate << Target;
3000
3001 if (ParsedAttrs.Duplicate != "")
3002 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3003 << Duplicate << None << ParsedAttrs.Duplicate << Target;
3004
3005 for (const auto &Feature : ParsedAttrs.Features) {
3006 auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3007 if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
3008 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3009 << Unsupported << None << CurFeature << Target;
3010 }
3011
3013 StringRef DiagMsg;
3014 if (ParsedAttrs.BranchProtection.empty())
3015 return false;
3017 ParsedAttrs.BranchProtection, ParsedAttrs.CPU, BPI, DiagMsg)) {
3018 if (DiagMsg.empty())
3019 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3020 << Unsupported << None << "branch-protection" << Target;
3021 return Diag(LiteralLoc, diag::err_invalid_branch_protection_spec)
3022 << DiagMsg;
3023 }
3024 if (!DiagMsg.empty())
3025 Diag(LiteralLoc, diag::warn_unsupported_branch_protection_spec) << DiagMsg;
3026
3027 return false;
3028}
3029
3031 StringRef AttrStr) {
3032 enum FirstParam { Unsupported };
3033 enum SecondParam { None };
3034 enum ThirdParam { Target, TargetClones, TargetVersion };
3036 AttrStr.split(Features, "+");
3037 for (auto &CurFeature : Features) {
3038 CurFeature = CurFeature.trim();
3039 if (CurFeature == "default")
3040 continue;
3041 if (!Context.getTargetInfo().validateCpuSupports(CurFeature))
3042 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3043 << Unsupported << None << CurFeature << TargetVersion;
3044 }
3045 return false;
3046}
3047
3048static void handleTargetVersionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3049 StringRef Str;
3050 SourceLocation LiteralLoc;
3051 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
3052 S.checkTargetVersionAttr(LiteralLoc, D, Str))
3053 return;
3054 TargetVersionAttr *NewAttr =
3055 ::new (S.Context) TargetVersionAttr(S.Context, AL, Str);
3056 D->addAttr(NewAttr);
3057}
3058
3059static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3060 StringRef Str;
3061 SourceLocation LiteralLoc;
3062 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
3063 S.checkTargetAttr(LiteralLoc, Str))
3064 return;
3065
3066 TargetAttr *NewAttr = ::new (S.Context) TargetAttr(S.Context, AL, Str);
3067 D->addAttr(NewAttr);
3068}
3069
3071 SourceLocation LiteralLoc, StringRef Str, const StringLiteral *Literal,
3072 Decl *D, bool &HasDefault, bool &HasCommas, bool &HasNotDefault,
3073 SmallVectorImpl<SmallString<64>> &StringsBuffer) {
3074 enum FirstParam { Unsupported, Duplicate, Unknown };
3075 enum SecondParam { None, CPU, Tune };
3076 enum ThirdParam { Target, TargetClones };
3077 HasCommas = HasCommas || Str.contains(',');
3078 const TargetInfo &TInfo = Context.getTargetInfo();
3079 // Warn on empty at the beginning of a string.
3080 if (Str.size() == 0)
3081 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3082 << Unsupported << None << "" << TargetClones;
3083
3084 std::pair<StringRef, StringRef> Parts = {{}, Str};
3085 while (!Parts.second.empty()) {
3086 Parts = Parts.second.split(',');
3087 StringRef Cur = Parts.first.trim();
3088 SourceLocation CurLoc =
3089 Literal->getLocationOfByte(Cur.data() - Literal->getString().data(),
3090 getSourceManager(), getLangOpts(), TInfo);
3091
3092 bool DefaultIsDupe = false;
3093 bool HasCodeGenImpact = false;
3094 if (Cur.empty())
3095 return Diag(CurLoc, diag::warn_unsupported_target_attribute)
3096 << Unsupported << None << "" << TargetClones;
3097
3098 if (TInfo.getTriple().isAArch64()) {
3099 // AArch64 target clones specific
3100 if (Cur == "default") {
3101 DefaultIsDupe = HasDefault;
3102 HasDefault = true;
3103 if (llvm::is_contained(StringsBuffer, Cur) || DefaultIsDupe)
3104 Diag(CurLoc, diag::warn_target_clone_duplicate_options);
3105 else
3106 StringsBuffer.push_back(Cur);
3107 } else {
3108 std::pair<StringRef, StringRef> CurParts = {{}, Cur};
3110 while (!CurParts.second.empty()) {
3111 CurParts = CurParts.second.split('+');
3112 StringRef CurFeature = CurParts.first.trim();
3113 if (!TInfo.validateCpuSupports(CurFeature)) {
3114 Diag(CurLoc, diag::warn_unsupported_target_attribute)
3115 << Unsupported << None << CurFeature << TargetClones;
3116 continue;
3117 }
3118 if (TInfo.doesFeatureAffectCodeGen(CurFeature))
3119 HasCodeGenImpact = true;
3120 CurFeatures.push_back(CurFeature);
3121 }
3122 // Canonize TargetClones Attributes
3123 llvm::sort(CurFeatures);
3124 SmallString<64> Res;
3125 for (auto &CurFeat : CurFeatures) {
3126 if (!Res.empty())
3127 Res.append("+");
3128 Res.append(CurFeat);
3129 }
3130 if (llvm::is_contained(StringsBuffer, Res) || DefaultIsDupe)
3131 Diag(CurLoc, diag::warn_target_clone_duplicate_options);
3132 else if (!HasCodeGenImpact)
3133 // Ignore features in target_clone attribute that don't impact
3134 // code generation
3135 Diag(CurLoc, diag::warn_target_clone_no_impact_options);
3136 else if (!Res.empty()) {
3137 StringsBuffer.push_back(Res);
3138 HasNotDefault = true;
3139 }
3140 }
3141 } else {
3142 // Other targets ( currently X86 )
3143 if (Cur.starts_with("arch=")) {
3145 Cur.drop_front(sizeof("arch=") - 1)))
3146 return Diag(CurLoc, diag::warn_unsupported_target_attribute)
3147 << Unsupported << CPU << Cur.drop_front(sizeof("arch=") - 1)
3148 << TargetClones;
3149 } else if (Cur == "default") {
3150 DefaultIsDupe = HasDefault;
3151 HasDefault = true;
3152 } else if (!Context.getTargetInfo().isValidFeatureName(Cur))
3153 return Diag(CurLoc, diag::warn_unsupported_target_attribute)
3154 << Unsupported << None << Cur << TargetClones;
3155 if (llvm::is_contained(StringsBuffer, Cur) || DefaultIsDupe)
3156 Diag(CurLoc, diag::warn_target_clone_duplicate_options);
3157 // Note: Add even if there are duplicates, since it changes name mangling.
3158 StringsBuffer.push_back(Cur);
3159 }
3160 }
3161 if (Str.rtrim().ends_with(","))
3162 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3163 << Unsupported << None << "" << TargetClones;
3164 return false;
3165}
3166
3167static void handleTargetClonesAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3168 if (S.Context.getTargetInfo().getTriple().isAArch64() &&
3169 !S.Context.getTargetInfo().hasFeature("fmv"))
3170 return;
3171
3172 // Ensure we don't combine these with themselves, since that causes some
3173 // confusing behavior.
3174 if (const auto *Other = D->getAttr<TargetClonesAttr>()) {
3175 S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
3176 S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
3177 return;
3178 }
3179 if (checkAttrMutualExclusion<TargetClonesAttr>(S, D, AL))
3180 return;
3181
3183 SmallVector<SmallString<64>, 2> StringsBuffer;
3184 bool HasCommas = false, HasDefault = false, HasNotDefault = false;
3185
3186 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
3187 StringRef CurStr;
3188 SourceLocation LiteralLoc;
3189 if (!S.checkStringLiteralArgumentAttr(AL, I, CurStr, &LiteralLoc) ||
3191 LiteralLoc, CurStr,
3192 cast<StringLiteral>(AL.getArgAsExpr(I)->IgnoreParenCasts()), D,
3193 HasDefault, HasCommas, HasNotDefault, StringsBuffer))
3194 return;
3195 }
3196 for (auto &SmallStr : StringsBuffer)
3197 Strings.push_back(SmallStr.str());
3198
3199 if (HasCommas && AL.getNumArgs() > 1)
3200 S.Diag(AL.getLoc(), diag::warn_target_clone_mixed_values);
3201
3202 if (S.Context.getTargetInfo().getTriple().isAArch64() && !HasDefault) {
3203 // Add default attribute if there is no one
3204 HasDefault = true;
3205 Strings.push_back("default");
3206 }
3207
3208 if (!HasDefault) {
3209 S.Diag(AL.getLoc(), diag::err_target_clone_must_have_default);
3210 return;
3211 }
3212
3213 // FIXME: We could probably figure out how to get this to work for lambdas
3214 // someday.
3215 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
3216 if (MD->getParent()->isLambda()) {
3217 S.Diag(D->getLocation(), diag::err_multiversion_doesnt_support)
3218 << static_cast<unsigned>(MultiVersionKind::TargetClones)
3219 << /*Lambda*/ 9;
3220 return;
3221 }
3222 }
3223
3224 // No multiversion if we have default version only.
3225 if (S.Context.getTargetInfo().getTriple().isAArch64() && !HasNotDefault)
3226 return;
3227
3228 cast<FunctionDecl>(D)->setIsMultiVersion();
3229 TargetClonesAttr *NewAttr = ::new (S.Context)
3230 TargetClonesAttr(S.Context, AL, Strings.data(), Strings.size());
3231 D->addAttr(NewAttr);
3232}
3233
3234static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3235 Expr *E = AL.getArgAsExpr(0);
3236 uint32_t VecWidth;
3237 if (!S.checkUInt32Argument(AL, E, VecWidth)) {
3238 AL.setInvalid();
3239 return;
3240 }
3241
3242 MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
3243 if (Existing && Existing->getVectorWidth() != VecWidth) {
3244 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3245 return;
3246 }
3247
3248 D->addAttr(::new (S.Context) MinVectorWidthAttr(S.Context, AL, VecWidth));
3249}
3250
3251static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3252 Expr *E = AL.getArgAsExpr(0);
3254 FunctionDecl *FD = nullptr;
3256
3257 // gcc only allows for simple identifiers. Since we support more than gcc, we
3258 // will warn the user.
3259 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3260 if (DRE->hasQualifier())
3261 S.Diag(Loc, diag::warn_cleanup_ext);
3262 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3263 NI = DRE->getNameInfo();
3264 if (!FD) {
3265 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3266 << NI.getName();
3267 return;
3268 }
3269 } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3270 if (ULE->hasExplicitTemplateArgs())
3271 S.Diag(Loc, diag::warn_cleanup_ext);
3273 NI = ULE->getNameInfo();
3274 if (!FD) {
3275 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3276 << NI.getName();
3277 if (ULE->getType() == S.Context.OverloadTy)
3279 return;
3280 }
3281 } else {
3282 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3283 return;
3284 }
3285
3286 if (FD->getNumParams() != 1) {
3287 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3288 << NI.getName();
3289 return;
3290 }
3291
3292 // We're currently more strict than GCC about what function types we accept.
3293 // If this ever proves to be a problem it should be easy to fix.
3294 QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
3295 QualType ParamTy = FD->getParamDecl(0)->getType();
3297 ParamTy, Ty) != Sema::Compatible) {
3298 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3299 << NI.getName() << ParamTy << Ty;
3300 return;
3301 }
3302 VarDecl *VD = cast<VarDecl>(D);
3303 // Create a reference to the variable declaration. This is a fake/dummy
3304 // reference.
3305 DeclRefExpr *VariableReference = DeclRefExpr::Create(
3306 S.Context, NestedNameSpecifierLoc{}, FD->getLocation(), VD, false,
3307 DeclarationNameInfo{VD->getDeclName(), VD->getLocation()}, VD->getType(),
3308 VK_LValue);
3309
3310 // Create a unary operator expression that represents taking the address of
3311 // the variable. This is a fake/dummy expression.
3312 Expr *AddressOfVariable = UnaryOperator::Create(
3313 S.Context, VariableReference, UnaryOperatorKind::UO_AddrOf,
3315 +false, FPOptionsOverride{});
3316
3317 // Create a function call expression. This is a fake/dummy call expression.
3318 CallExpr *FunctionCallExpression =
3319 CallExpr::Create(S.Context, E, ArrayRef{AddressOfVariable},
3321
3322 if (S.CheckFunctionCall(FD, FunctionCallExpression,
3323 FD->getType()->getAs<FunctionProtoType>())) {
3324 return;
3325 }
3326
3327 D->addAttr(::new (S.Context) CleanupAttr(S.Context, AL, FD));
3328}
3329
3331 const ParsedAttr &AL) {
3332 if (!AL.isArgIdent(0)) {
3333 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3334 << AL << 0 << AANT_ArgumentIdentifier;
3335 return;
3336 }
3337
3338 EnumExtensibilityAttr::Kind ExtensibilityKind;
3339 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3340 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3341 ExtensibilityKind)) {
3342 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3343 return;
3344 }
3345
3346 D->addAttr(::new (S.Context)
3347 EnumExtensibilityAttr(S.Context, AL, ExtensibilityKind));
3348}
3349
3350/// Handle __attribute__((format_arg((idx)))) attribute based on
3351/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3352static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3353 const Expr *IdxExpr = AL.getArgAsExpr(0);
3354 ParamIdx Idx;
3355 if (!S.checkFunctionOrMethodParameterIndex(D, AL, 1, IdxExpr, Idx))
3356 return;
3357
3358 // Make sure the format string is really a string.
3360
3361 bool NotNSStringTy = !S.ObjC().isNSStringType(Ty);
3362 if (NotNSStringTy && !S.ObjC().isCFStringType(Ty) &&
3363 (!Ty->isPointerType() ||
3365 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3366 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3367 return;
3368 }
3370 // replace instancetype with the class type
3371 auto Instancetype = S.Context.getObjCInstanceTypeDecl()->getTypeForDecl();
3372 if (Ty->getAs<TypedefType>() == Instancetype)
3373 if (auto *OMD = dyn_cast<ObjCMethodDecl>(D))
3374 if (auto *Interface = OMD->getClassInterface())
3376 QualType(Interface->getTypeForDecl(), 0));
3377 if (!S.ObjC().isNSStringType(Ty, /*AllowNSAttributedString=*/true) &&
3378 !S.ObjC().isCFStringType(Ty) &&
3379 (!Ty->isPointerType() ||
3381 S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
3382 << (NotNSStringTy ? "string type" : "NSString")
3383 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3384 return;
3385 }
3386
3387 D->addAttr(::new (S.Context) FormatArgAttr(S.Context, AL, Idx));
3388}
3389
3398
3399/// getFormatAttrKind - Map from format attribute names to supported format
3400/// types.
3401static FormatAttrKind getFormatAttrKind(StringRef Format) {
3402 return llvm::StringSwitch<FormatAttrKind>(Format)
3403 // Check for formats that get handled specially.
3404 .Case("NSString", NSStringFormat)
3405 .Case("CFString", CFStringFormat)
3406 .Case("strftime", StrftimeFormat)
3407
3408 // Otherwise, check for supported formats.
3409 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3410 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3411 .Cases("kprintf", "syslog", SupportedFormat) // OpenBSD.
3412 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3413 .Case("os_trace", SupportedFormat)
3414 .Case("os_log", SupportedFormat)
3415
3416 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3417 .Default(InvalidFormat);
3418}
3419
3420/// Handle __attribute__((init_priority(priority))) attributes based on
3421/// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3422static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3423 if (!S.getLangOpts().CPlusPlus) {
3424 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
3425 return;
3426 }
3427
3428 if (S.getLangOpts().HLSL) {
3429 S.Diag(AL.getLoc(), diag::err_hlsl_init_priority_unsupported);
3430 return;
3431 }
3432
3434 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3435 AL.setInvalid();
3436 return;
3437 }
3438 QualType T = cast<VarDecl>(D)->getType();
3439 if (S.Context.getAsArrayType(T))
3441 if (!T->getAs<RecordType>()) {
3442 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3443 AL.setInvalid();
3444 return;
3445 }
3446
3447 Expr *E = AL.getArgAsExpr(0);
3448 uint32_t prioritynum;
3449 if (!S.checkUInt32Argument(AL, E, prioritynum)) {
3450 AL.setInvalid();
3451 return;
3452 }
3453
3454 // Only perform the priority check if the attribute is outside of a system
3455 // header. Values <= 100 are reserved for the implementation, and libc++
3456 // benefits from being able to specify values in that range.
3457 if ((prioritynum < 101 || prioritynum > 65535) &&
3459 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
3460 << E->getSourceRange() << AL << 101 << 65535;
3461 AL.setInvalid();
3462 return;
3463 }
3464 D->addAttr(::new (S.Context) InitPriorityAttr(S.Context, AL, prioritynum));
3465}
3466
3468 StringRef NewUserDiagnostic) {
3469 if (const auto *EA = D->getAttr<ErrorAttr>()) {
3470 std::string NewAttr = CI.getNormalizedFullName();
3471 assert((NewAttr == "error" || NewAttr == "warning") &&
3472 "unexpected normalized full name");
3473 bool Match = (EA->isError() && NewAttr == "error") ||
3474 (EA->isWarning() && NewAttr == "warning");
3475 if (!Match) {
3476 Diag(EA->getLocation(), diag::err_attributes_are_not_compatible)
3477 << CI << EA
3478 << (CI.isRegularKeywordAttribute() ||
3479 EA->isRegularKeywordAttribute());
3480 Diag(CI.getLoc(), diag::note_conflicting_attribute);
3481 return nullptr;
3482 }
3483 if (EA->getUserDiagnostic() != NewUserDiagnostic) {
3484 Diag(CI.getLoc(), diag::warn_duplicate_attribute) << EA;
3485 Diag(EA->getLoc(), diag::note_previous_attribute);
3486 }
3487 D->dropAttr<ErrorAttr>();
3488 }
3489 return ::new (Context) ErrorAttr(Context, CI, NewUserDiagnostic);
3490}
3491
3493 IdentifierInfo *Format, int FormatIdx,
3494 int FirstArg) {
3495 // Check whether we already have an equivalent format attribute.
3496 for (auto *F : D->specific_attrs<FormatAttr>()) {
3497 if (F->getType() == Format &&
3498 F->getFormatIdx() == FormatIdx &&
3499 F->getFirstArg() == FirstArg) {
3500 // If we don't have a valid location for this attribute, adopt the
3501 // location.
3502 if (F->getLocation().isInvalid())
3503 F->setRange(CI.getRange());
3504 return nullptr;
3505 }
3506 }
3507
3508 return ::new (Context) FormatAttr(Context, CI, Format, FormatIdx, FirstArg);
3509}
3510
3511/// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3512/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3513static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3514 if (!AL.isArgIdent(0)) {
3515 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3516 << AL << 1 << AANT_ArgumentIdentifier;
3517 return;
3518 }
3519
3520 // In C++ the implicit 'this' function parameter also counts, and they are
3521 // counted from one.
3522 bool HasImplicitThisParam = isInstanceMethod(D);
3523 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3524
3525 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3526 StringRef Format = II->getName();
3527
3528 if (normalizeName(Format)) {
3529 // If we've modified the string name, we need a new identifier for it.
3530 II = &S.Context.Idents.get(Format);
3531 }
3532
3533 // Check for supported formats.
3534 FormatAttrKind Kind = getFormatAttrKind(Format);
3535
3536 if (Kind == IgnoredFormat)
3537 return;
3538
3539 if (Kind == InvalidFormat) {
3540 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
3541 << AL << II->getName();
3542 return;
3543 }
3544
3545 // checks for the 2nd argument
3546 Expr *IdxExpr = AL.getArgAsExpr(1);
3547 uint32_t Idx;
3548 if (!S.checkUInt32Argument(AL, IdxExpr, Idx, 2))
3549 return;
3550
3551 if (Idx < 1 || Idx > NumArgs) {
3552 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3553 << AL << 2 << IdxExpr->getSourceRange();
3554 return;
3555 }
3556
3557 // FIXME: Do we need to bounds check?
3558 unsigned ArgIdx = Idx - 1;
3559
3560 if (HasImplicitThisParam) {
3561 if (ArgIdx == 0) {
3562 S.Diag(AL.getLoc(),
3563 diag::err_format_attribute_implicit_this_format_string)
3564 << IdxExpr->getSourceRange();
3565 return;
3566 }
3567 ArgIdx--;
3568 }
3569
3570 // make sure the format string is really a string
3572
3573 if (!S.ObjC().isNSStringType(Ty, true) && !S.ObjC().isCFStringType(Ty) &&
3574 (!Ty->isPointerType() ||
3576 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3577 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, ArgIdx);
3578 return;
3579 }
3580
3581 // check the 3rd argument
3582 Expr *FirstArgExpr = AL.getArgAsExpr(2);
3583 uint32_t FirstArg;
3584 if (!S.checkUInt32Argument(AL, FirstArgExpr, FirstArg, 3))
3585 return;
3586
3587 // FirstArg == 0 is is always valid.
3588 if (FirstArg != 0) {
3589 if (Kind == StrftimeFormat) {
3590 // If the kind is strftime, FirstArg must be 0 because strftime does not
3591 // use any variadic arguments.
3592 S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
3593 << FirstArgExpr->getSourceRange()
3594 << FixItHint::CreateReplacement(FirstArgExpr->getSourceRange(), "0");
3595 return;
3596 } else if (isFunctionOrMethodVariadic(D)) {
3597 // Else, if the function is variadic, then FirstArg must be 0 or the
3598 // "position" of the ... parameter. It's unusual to use 0 with variadic
3599 // functions, so the fixit proposes the latter.
3600 if (FirstArg != NumArgs + 1) {
3601 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3602 << AL << 3 << FirstArgExpr->getSourceRange()
3604 std::to_string(NumArgs + 1));
3605 return;
3606 }
3607 } else {
3608 // Inescapable GCC compatibility diagnostic.
3609 S.Diag(D->getLocation(), diag::warn_gcc_requires_variadic_function) << AL;
3610 if (FirstArg <= Idx) {
3611 // Else, the function is not variadic, and FirstArg must be 0 or any
3612 // parameter after the format parameter. We don't offer a fixit because
3613 // there are too many possible good values.
3614 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3615 << AL << 3 << FirstArgExpr->getSourceRange();
3616 return;
3617 }
3618 }
3619 }
3620
3621 FormatAttr *NewAttr = S.mergeFormatAttr(D, AL, II, Idx, FirstArg);
3622 if (NewAttr)
3623 D->addAttr(NewAttr);
3624}
3625
3626/// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
3627static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3628 // The index that identifies the callback callee is mandatory.
3629 if (AL.getNumArgs() == 0) {
3630 S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee)
3631 << AL.getRange();
3632 return;
3633 }
3634
3635 bool HasImplicitThisParam = isInstanceMethod(D);
3636 int32_t NumArgs = getFunctionOrMethodNumParams(D);
3637
3638 FunctionDecl *FD = D->getAsFunction();
3639 assert(FD && "Expected a function declaration!");
3640
3641 llvm::StringMap<int> NameIdxMapping;
3642 NameIdxMapping["__"] = -1;
3643
3644 NameIdxMapping["this"] = 0;
3645
3646 int Idx = 1;
3647 for (const ParmVarDecl *PVD : FD->parameters())
3648 NameIdxMapping[PVD->getName()] = Idx++;
3649
3650 auto UnknownName = NameIdxMapping.end();
3651
3652 SmallVector<int, 8> EncodingIndices;
3653 for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) {
3654 SourceRange SR;
3655 int32_t ArgIdx;
3656
3657 if (AL.isArgIdent(I)) {
3658 IdentifierLoc *IdLoc = AL.getArgAsIdent(I);
3659 auto It = NameIdxMapping.find(IdLoc->Ident->getName());
3660 if (It == UnknownName) {
3661 S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown)
3662 << IdLoc->Ident << IdLoc->Loc;
3663 return;
3664 }
3665
3666 SR = SourceRange(IdLoc->Loc);
3667 ArgIdx = It->second;
3668 } else if (AL.isArgExpr(I)) {
3669 Expr *IdxExpr = AL.getArgAsExpr(I);
3670
3671 // If the expression is not parseable as an int32_t we have a problem.
3672 if (!S.checkUInt32Argument(AL, IdxExpr, (uint32_t &)ArgIdx, I + 1,
3673 false)) {
3674 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3675 << AL << (I + 1) << IdxExpr->getSourceRange();
3676 return;
3677 }
3678
3679 // Check oob, excluding the special values, 0 and -1.
3680 if (ArgIdx < -1 || ArgIdx > NumArgs) {
3681 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3682 << AL << (I + 1) << IdxExpr->getSourceRange();
3683 return;
3684 }
3685
3686 SR = IdxExpr->getSourceRange();
3687 } else {
3688 llvm_unreachable("Unexpected ParsedAttr argument type!");
3689 }
3690
3691 if (ArgIdx == 0 && !HasImplicitThisParam) {
3692 S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available)
3693 << (I + 1) << SR;
3694 return;
3695 }
3696
3697 // Adjust for the case we do not have an implicit "this" parameter. In this
3698 // case we decrease all positive values by 1 to get LLVM argument indices.
3699 if (!HasImplicitThisParam && ArgIdx > 0)
3700 ArgIdx -= 1;
3701
3702 EncodingIndices.push_back(ArgIdx);
3703 }
3704
3705 int CalleeIdx = EncodingIndices.front();
3706 // Check if the callee index is proper, thus not "this" and not "unknown".
3707 // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam"
3708 // is false and positive if "HasImplicitThisParam" is true.
3709 if (CalleeIdx < (int)HasImplicitThisParam) {
3710 S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee)
3711 << AL.getRange();
3712 return;
3713 }
3714
3715 // Get the callee type, note the index adjustment as the AST doesn't contain
3716 // the this type (which the callee cannot reference anyway!).
3717 const Type *CalleeType =
3718 getFunctionOrMethodParamType(D, CalleeIdx - HasImplicitThisParam)
3719 .getTypePtr();
3720 if (!CalleeType || !CalleeType->isFunctionPointerType()) {
3721 S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3722 << AL.getRange();
3723 return;
3724 }
3725
3726 const Type *CalleeFnType =
3728
3729 // TODO: Check the type of the callee arguments.
3730
3731 const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(CalleeFnType);
3732 if (!CalleeFnProtoType) {
3733 S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3734 << AL.getRange();
3735 return;
3736 }
3737
3738 if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) {
3739 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3740 << AL << (unsigned)(EncodingIndices.size() - 1);
3741 return;
3742 }
3743
3744 if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) {
3745 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3746 << AL << (unsigned)(EncodingIndices.size() - 1);
3747 return;
3748 }
3749
3750 if (CalleeFnProtoType->isVariadic()) {
3751 S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange();
3752 return;
3753 }
3754
3755 // Do not allow multiple callback attributes.
3756 if (D->hasAttr<CallbackAttr>()) {
3757 S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange();
3758 return;
3759 }
3760
3761 D->addAttr(::new (S.Context) CallbackAttr(
3762 S.Context, AL, EncodingIndices.data(), EncodingIndices.size()));
3763}
3764
3765static bool isFunctionLike(const Type &T) {
3766 // Check for explicit function types.
3767 // 'called_once' is only supported in Objective-C and it has
3768 // function pointers and block pointers.
3770}
3771
3772/// Handle 'called_once' attribute.
3773static void handleCalledOnceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3774 // 'called_once' only applies to parameters representing functions.
3775 QualType T = cast<ParmVarDecl>(D)->getType();
3776
3777 if (!isFunctionLike(*T)) {
3778 S.Diag(AL.getLoc(), diag::err_called_once_attribute_wrong_type);
3779 return;
3780 }
3781
3782 D->addAttr(::new (S.Context) CalledOnceAttr(S.Context, AL));
3783}
3784
3785static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3786 // Try to find the underlying union declaration.
3787 RecordDecl *RD = nullptr;
3788 const auto *TD = dyn_cast<TypedefNameDecl>(D);
3789 if (TD && TD->getUnderlyingType()->isUnionType())
3790 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3791 else
3792 RD = dyn_cast<RecordDecl>(D);
3793
3794 if (!RD || !RD->isUnion()) {
3795 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
3797 return;
3798 }
3799
3800 if (!RD->isCompleteDefinition()) {
3801 if (!RD->isBeingDefined())
3802 S.Diag(AL.getLoc(),
3803 diag::warn_transparent_union_attribute_not_definition);
3804 return;
3805 }
3806
3808 FieldEnd = RD->field_end();
3809 if (Field == FieldEnd) {
3810 S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3811 return;
3812 }
3813
3814 FieldDecl *FirstField = *Field;
3815 QualType FirstType = FirstField->getType();
3816 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3817 S.Diag(FirstField->getLocation(),
3818 diag::warn_transparent_union_attribute_floating)
3819 << FirstType->isVectorType() << FirstType;
3820 return;
3821 }
3822
3823 if (FirstType->isIncompleteType())
3824 return;
3825 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3826 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3827 for (; Field != FieldEnd; ++Field) {
3828 QualType FieldType = Field->getType();
3829 if (FieldType->isIncompleteType())
3830 return;
3831 // FIXME: this isn't fully correct; we also need to test whether the
3832 // members of the union would all have the same calling convention as the
3833 // first member of the union. Checking just the size and alignment isn't
3834 // sufficient (consider structs passed on the stack instead of in registers
3835 // as an example).
3836 if (S.Context.getTypeSize(FieldType) != FirstSize ||
3837 S.Context.getTypeAlign(FieldType) > FirstAlign) {
3838 // Warn if we drop the attribute.
3839 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3840 unsigned FieldBits = isSize ? S.Context.getTypeSize(FieldType)
3841 : S.Context.getTypeAlign(FieldType);
3842 S.Diag(Field->getLocation(),
3843 diag::warn_transparent_union_attribute_field_size_align)
3844 << isSize << *Field << FieldBits;
3845 unsigned FirstBits = isSize ? FirstSize : FirstAlign;
3846 S.Diag(FirstField->getLocation(),
3847 diag::note_transparent_union_first_field_size_align)
3848 << isSize << FirstBits;
3849 return;
3850 }
3851 }
3852
3853 RD->addAttr(::new (S.Context) TransparentUnionAttr(S.Context, AL));
3854}
3855
3857 StringRef Str, MutableArrayRef<Expr *> Args) {
3858 auto *Attr = AnnotateAttr::Create(Context, Str, Args.data(), Args.size(), CI);
3860 CI, MutableArrayRef<Expr *>(Attr->args_begin(), Attr->args_end()))) {
3861 D->addAttr(Attr);
3862 }
3863}
3864
3865static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3866 // Make sure that there is a string literal as the annotation's first
3867 // argument.
3868 StringRef Str;
3869 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
3870 return;
3871
3873 Args.reserve(AL.getNumArgs() - 1);
3874 for (unsigned Idx = 1; Idx < AL.getNumArgs(); Idx++) {
3875 assert(!AL.isArgIdent(Idx));
3876 Args.push_back(AL.getArgAsExpr(Idx));
3877 }
3878
3879 S.AddAnnotationAttr(D, AL, Str, Args);
3880}
3881
3882static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3883 S.AddAlignValueAttr(D, AL, AL.getArgAsExpr(0));
3884}
3885
3887 AlignValueAttr TmpAttr(Context, CI, E);
3888 SourceLocation AttrLoc = CI.getLoc();
3889
3890 QualType T;
3891 if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
3892 T = TD->getUnderlyingType();
3893 else if (const auto *VD = dyn_cast<ValueDecl>(D))
3894 T = VD->getType();
3895 else
3896 llvm_unreachable("Unknown decl type for align_value");
3897
3898 if (!T->isDependentType() && !T->isAnyPointerType() &&
3900 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3901 << &TmpAttr << T << D->getSourceRange();
3902 return;
3903 }
3904
3905 if (!E->isValueDependent()) {
3906 llvm::APSInt Alignment;
3908 E, &Alignment, diag::err_align_value_attribute_argument_not_int);
3909 if (ICE.isInvalid())
3910 return;
3911
3912 if (!Alignment.isPowerOf2()) {
3913 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3914 << E->getSourceRange();
3915 return;
3916 }
3917
3918 D->addAttr(::new (Context) AlignValueAttr(Context, CI, ICE.get()));
3919 return;
3920 }
3921
3922 // Save dependent expressions in the AST to be instantiated.
3923 D->addAttr(::new (Context) AlignValueAttr(Context, CI, E));
3924}
3925
3926static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3927 if (AL.hasParsedType()) {
3928 const ParsedType &TypeArg = AL.getTypeArg();
3929 TypeSourceInfo *TInfo;
3930 (void)S.GetTypeFromParser(
3931 ParsedType::getFromOpaquePtr(TypeArg.getAsOpaquePtr()), &TInfo);
3932 if (AL.isPackExpansion() &&
3934 S.Diag(AL.getEllipsisLoc(),
3935 diag::err_pack_expansion_without_parameter_packs);
3936 return;
3937 }
3938
3939 if (!AL.isPackExpansion() &&
3941 TInfo, Sema::UPPC_Expression))
3942 return;
3943
3944 S.AddAlignedAttr(D, AL, TInfo, AL.isPackExpansion());
3945 return;
3946 }
3947
3948 // check the attribute arguments.
3949 if (AL.getNumArgs() > 1) {
3950 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3951 return;
3952 }
3953
3954 if (AL.getNumArgs() == 0) {
3955 D->addAttr(::new (S.Context) AlignedAttr(S.Context, AL, true, nullptr));
3956 return;
3957 }
3958
3959 Expr *E = AL.getArgAsExpr(0);
3961 S.Diag(AL.getEllipsisLoc(),
3962 diag::err_pack_expansion_without_parameter_packs);
3963 return;
3964 }
3965
3967 return;
3968
3969 S.AddAlignedAttr(D, AL, E, AL.isPackExpansion());
3970}
3971
3972/// Perform checking of type validity
3973///
3974/// C++11 [dcl.align]p1:
3975/// An alignment-specifier may be applied to a variable or to a class
3976/// data member, but it shall not be applied to a bit-field, a function
3977/// parameter, the formal parameter of a catch clause, or a variable
3978/// declared with the register storage class specifier. An
3979/// alignment-specifier may also be applied to the declaration of a class
3980/// or enumeration type.
3981/// CWG 2354:
3982/// CWG agreed to remove permission for alignas to be applied to
3983/// enumerations.
3984/// C11 6.7.5/2:
3985/// An alignment attribute shall not be specified in a declaration of
3986/// a typedef, or a bit-field, or a function, or a parameter, or an
3987/// object declared with the register storage-class specifier.
3989 const AlignedAttr &Attr,
3990 SourceLocation AttrLoc) {
3991 int DiagKind = -1;
3992 if (isa<ParmVarDecl>(D)) {
3993 DiagKind = 0;
3994 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
3995 if (VD->getStorageClass() == SC_Register)
3996 DiagKind = 1;
3997 if (VD->isExceptionVariable())
3998 DiagKind = 2;
3999 } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
4000 if (FD->isBitField())
4001 DiagKind = 3;
4002 } else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
4003 if (ED->getLangOpts().CPlusPlus)
4004 DiagKind = 4;
4005 } else if (!isa<TagDecl>(D)) {
4006 return S.Diag(AttrLoc, diag::err_attribute_wrong_decl_type)
4008 << (Attr.isC11() ? ExpectedVariableOrField
4010 }
4011 if (DiagKind != -1) {
4012 return S.Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
4013 << &Attr << DiagKind;
4014 }
4015 return false;
4016}
4017
4019 bool IsPackExpansion) {
4020 AlignedAttr TmpAttr(Context, CI, true, E);
4021 SourceLocation AttrLoc = CI.getLoc();
4022
4023 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
4024 if (TmpAttr.isAlignas() &&
4025 validateAlignasAppliedType(*this, D, TmpAttr, AttrLoc))
4026 return;
4027
4028 if (E->isValueDependent()) {
4029 // We can't support a dependent alignment on a non-dependent type,
4030 // because we have no way to model that a type is "alignment-dependent"
4031 // but not dependent in any other way.
4032 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
4033 if (!TND->getUnderlyingType()->isDependentType()) {
4034 Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
4035 << E->getSourceRange();
4036 return;
4037 }
4038 }
4039
4040 // Save dependent expressions in the AST to be instantiated.
4041 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, E);
4042 AA->setPackExpansion(IsPackExpansion);
4043 D->addAttr(AA);
4044 return;
4045 }
4046
4047 // FIXME: Cache the number on the AL object?
4048 llvm::APSInt Alignment;
4050 E, &Alignment, diag::err_aligned_attribute_argument_not_int);
4051 if (ICE.isInvalid())
4052 return;
4053
4055 if (Context.getTargetInfo().getTriple().isOSBinFormatCOFF())
4056 MaximumAlignment = std::min(MaximumAlignment, uint64_t(8192));
4057 if (Alignment > MaximumAlignment) {
4058 Diag(AttrLoc, diag::err_attribute_aligned_too_great)
4060 return;
4061 }
4062
4063 uint64_t AlignVal = Alignment.getZExtValue();
4064 // C++11 [dcl.align]p2:
4065 // -- if the constant expression evaluates to zero, the alignment
4066 // specifier shall have no effect
4067 // C11 6.7.5p6:
4068 // An alignment specification of zero has no effect.
4069 if (!(TmpAttr.isAlignas() && !Alignment)) {
4070 if (!llvm::isPowerOf2_64(AlignVal)) {
4071 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
4072 << E->getSourceRange();
4073 return;
4074 }
4075 }
4076
4077 const auto *VD = dyn_cast<VarDecl>(D);
4078 if (VD) {
4079 unsigned MaxTLSAlign =
4081 .getQuantity();
4082 if (MaxTLSAlign && AlignVal > MaxTLSAlign &&
4083 VD->getTLSKind() != VarDecl::TLS_None) {
4084 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
4085 << (unsigned)AlignVal << VD << MaxTLSAlign;
4086 return;
4087 }
4088 }
4089
4090 // On AIX, an aligned attribute can not decrease the alignment when applied
4091 // to a variable declaration with vector type.
4092 if (VD && Context.getTargetInfo().getTriple().isOSAIX()) {
4093 const Type *Ty = VD->getType().getTypePtr();
4094 if (Ty->isVectorType() && AlignVal < 16) {
4095 Diag(VD->getLocation(), diag::warn_aligned_attr_underaligned)
4096 << VD->getType() << 16;
4097 return;
4098 }
4099 }
4100
4101 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, ICE.get());
4102 AA->setPackExpansion(IsPackExpansion);
4103 AA->setCachedAlignmentValue(
4104 static_cast<unsigned>(AlignVal * Context.getCharWidth()));
4105 D->addAttr(AA);
4106}
4107
4109 TypeSourceInfo *TS, bool IsPackExpansion) {
4110 AlignedAttr TmpAttr(Context, CI, false, TS);
4111 SourceLocation AttrLoc = CI.getLoc();
4112
4113 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
4114 if (TmpAttr.isAlignas() &&
4115 validateAlignasAppliedType(*this, D, TmpAttr, AttrLoc))
4116 return;
4117
4118 if (TS->getType()->isDependentType()) {
4119 // We can't support a dependent alignment on a non-dependent type,
4120 // because we have no way to model that a type is "type-dependent"
4121 // but not dependent in any other way.
4122 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
4123 if (!TND->getUnderlyingType()->isDependentType()) {
4124 Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
4125 << TS->getTypeLoc().getSourceRange();
4126 return;
4127 }
4128 }
4129
4130 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
4131 AA->setPackExpansion(IsPackExpansion);
4132 D->addAttr(AA);
4133 return;
4134 }
4135
4136 const auto *VD = dyn_cast<VarDecl>(D);
4137 unsigned AlignVal = TmpAttr.getAlignment(Context);
4138 // On AIX, an aligned attribute can not decrease the alignment when applied
4139 // to a variable declaration with vector type.
4140 if (VD && Context.getTargetInfo().getTriple().isOSAIX()) {
4141 const Type *Ty = VD->getType().getTypePtr();
4142 if (Ty->isVectorType() &&
4143 Context.toCharUnitsFromBits(AlignVal).getQuantity() < 16) {
4144 Diag(VD->getLocation(), diag::warn_aligned_attr_underaligned)
4145 << VD->getType() << 16;
4146 return;
4147 }
4148 }
4149
4150 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
4151 AA->setPackExpansion(IsPackExpansion);
4152 AA->setCachedAlignmentValue(AlignVal);
4153 D->addAttr(AA);
4154}
4155
4157 assert(D->hasAttrs() && "no attributes on decl");
4158
4159 QualType UnderlyingTy, DiagTy;
4160 if (const auto *VD = dyn_cast<ValueDecl>(D)) {
4161 UnderlyingTy = DiagTy = VD->getType();
4162 } else {
4163 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
4164 if (const auto *ED = dyn_cast<EnumDecl>(D))
4165 UnderlyingTy = ED->getIntegerType();
4166 }
4167 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
4168 return;
4169
4170 // C++11 [dcl.align]p5, C11 6.7.5/4:
4171 // The combined effect of all alignment attributes in a declaration shall
4172 // not specify an alignment that is less strict than the alignment that
4173 // would otherwise be required for the entity being declared.
4174 AlignedAttr *AlignasAttr = nullptr;
4175 AlignedAttr *LastAlignedAttr = nullptr;
4176 unsigned Align = 0;
4177 for (auto *I : D->specific_attrs<AlignedAttr>()) {
4178 if (I->isAlignmentDependent())
4179 return;
4180 if (I->isAlignas())
4181 AlignasAttr = I;
4182 Align = std::max(Align, I->getAlignment(Context));
4183 LastAlignedAttr = I;
4184 }
4185
4186 if (Align && DiagTy->isSizelessType()) {
4187 Diag(LastAlignedAttr->getLocation(), diag::err_attribute_sizeless_type)
4188 << LastAlignedAttr << DiagTy;
4189 } else if (AlignasAttr && Align) {
4190 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
4191 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
4192 if (NaturalAlign > RequestedAlign)
4193 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
4194 << DiagTy << (unsigned)NaturalAlign.getQuantity();
4195 }
4196}
4197
4199 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4200 MSInheritanceModel ExplicitModel) {
4201 assert(RD->hasDefinition() && "RD has no definition!");
4202
4203 // We may not have seen base specifiers or any virtual methods yet. We will
4204 // have to wait until the record is defined to catch any mismatches.
4205 if (!RD->getDefinition()->isCompleteDefinition())
4206 return false;
4207
4208 // The unspecified model never matches what a definition could need.
4209 if (ExplicitModel == MSInheritanceModel::Unspecified)
4210 return false;
4211
4212 if (BestCase) {
4213 if (RD->calculateInheritanceModel() == ExplicitModel)
4214 return false;
4215 } else {
4216 if (RD->calculateInheritanceModel() <= ExplicitModel)
4217 return false;
4218 }
4219
4220 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
4221 << 0 /*definition*/;
4222 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) << RD;
4223 return true;
4224}
4225
4226/// parseModeAttrArg - Parses attribute mode string and returns parsed type
4227/// attribute.
4228static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
4229 bool &IntegerMode, bool &ComplexMode,
4230 FloatModeKind &ExplicitType) {
4231 IntegerMode = true;
4232 ComplexMode = false;
4233 ExplicitType = FloatModeKind::NoFloat;
4234 switch (Str.size()) {
4235 case 2:
4236 switch (Str[0]) {
4237 case 'Q':
4238 DestWidth = 8;
4239 break;
4240 case 'H':
4241 DestWidth = 16;
4242 break;
4243 case 'S':
4244 DestWidth = 32;
4245 break;
4246 case 'D':
4247 DestWidth = 64;
4248 break;
4249 case 'X':
4250 DestWidth = 96;
4251 break;
4252 case 'K': // KFmode - IEEE quad precision (__float128)
4253 ExplicitType = FloatModeKind::Float128;
4254 DestWidth = Str[1] == 'I' ? 0 : 128;
4255 break;
4256 case 'T':
4257 ExplicitType = FloatModeKind::LongDouble;
4258 DestWidth = 128;
4259 break;
4260 case 'I':
4261 ExplicitType = FloatModeKind::Ibm128;
4262 DestWidth = Str[1] == 'I' ? 0 : 128;
4263 break;
4264 }
4265 if (Str[1] == 'F') {
4266 IntegerMode = false;
4267 } else if (Str[1] == 'C') {
4268 IntegerMode = false;
4269 ComplexMode = true;
4270 } else if (Str[1] != 'I') {
4271 DestWidth = 0;
4272 }
4273 break;
4274 case 4:
4275 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
4276 // pointer on PIC16 and other embedded platforms.
4277 if (Str == "word")
4278 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
4279 else if (Str == "byte")
4280 DestWidth = S.Context.getTargetInfo().getCharWidth();
4281 break;
4282 case 7:
4283 if (Str == "pointer")
4285 break;
4286 case 11:
4287 if (Str == "unwind_word")
4288 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
4289 break;
4290 }
4291}
4292
4293/// handleModeAttr - This attribute modifies the width of a decl with primitive
4294/// type.
4295///
4296/// Despite what would be logical, the mode attribute is a decl attribute, not a
4297/// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
4298/// HImode, not an intermediate pointer.
4299static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4300 // This attribute isn't documented, but glibc uses it. It changes
4301 // the width of an int or unsigned int to the specified size.
4302 if (!AL.isArgIdent(0)) {
4303 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
4304 << AL << AANT_ArgumentIdentifier;
4305 return;
4306 }
4307
4308 IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
4309
4310 S.AddModeAttr(D, AL, Name);
4311}
4312
4314 IdentifierInfo *Name, bool InInstantiation) {
4315 StringRef Str = Name->getName();
4316 normalizeName(Str);
4317 SourceLocation AttrLoc = CI.getLoc();
4318
4319 unsigned DestWidth = 0;
4320 bool IntegerMode = true;
4321 bool ComplexMode = false;
4323 llvm::APInt VectorSize(64, 0);
4324 if (Str.size() >= 4 && Str[0] == 'V') {
4325 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
4326 size_t StrSize = Str.size();
4327 size_t VectorStringLength = 0;
4328 while ((VectorStringLength + 1) < StrSize &&
4329 isdigit(Str[VectorStringLength + 1]))
4330 ++VectorStringLength;
4331 if (VectorStringLength &&
4332 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
4333 VectorSize.isPowerOf2()) {
4334 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
4335 IntegerMode, ComplexMode, ExplicitType);
4336 // Avoid duplicate warning from template instantiation.
4337 if (!InInstantiation)
4338 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
4339 } else {
4340 VectorSize = 0;
4341 }
4342 }
4343
4344 if (!VectorSize)
4345 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode,
4346 ExplicitType);
4347
4348 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
4349 // and friends, at least with glibc.
4350 // FIXME: Make sure floating-point mappings are accurate
4351 // FIXME: Support XF and TF types
4352 if (!DestWidth) {
4353 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
4354 return;
4355 }
4356
4357 QualType OldTy;
4358 if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
4359 OldTy = TD->getUnderlyingType();
4360 else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
4361 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
4362 // Try to get type from enum declaration, default to int.
4363 OldTy = ED->getIntegerType();
4364 if (OldTy.isNull())
4365 OldTy = Context.IntTy;
4366 } else
4367 OldTy = cast<ValueDecl>(D)->getType();
4368
4369 if (OldTy->isDependentType()) {
4370 D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4371 return;
4372 }
4373
4374 // Base type can also be a vector type (see PR17453).
4375 // Distinguish between base type and base element type.
4376 QualType OldElemTy = OldTy;
4377 if (const auto *VT = OldTy->getAs<VectorType>())
4378 OldElemTy = VT->getElementType();
4379
4380 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
4381 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
4382 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
4383 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
4384 VectorSize.getBoolValue()) {
4385 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << CI.getRange();
4386 return;
4387 }
4388 bool IntegralOrAnyEnumType = (OldElemTy->isIntegralOrEnumerationType() &&
4389 !OldElemTy->isBitIntType()) ||
4390 OldElemTy->getAs<EnumType>();
4391
4392 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
4393 !IntegralOrAnyEnumType)
4394 Diag(AttrLoc, diag::err_mode_not_primitive);
4395 else if (IntegerMode) {
4396 if (!IntegralOrAnyEnumType)
4397 Diag(AttrLoc, diag::err_mode_wrong_type);
4398 } else if (ComplexMode) {
4399 if (!OldElemTy->isComplexType())
4400 Diag(AttrLoc, diag::err_mode_wrong_type);
4401 } else {
4402 if (!OldElemTy->isFloatingType())
4403 Diag(AttrLoc, diag::err_mode_wrong_type);
4404 }
4405
4406 QualType NewElemTy;
4407
4408 if (IntegerMode)
4409 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
4410 OldElemTy->isSignedIntegerType());
4411 else
4412 NewElemTy = Context.getRealTypeForBitwidth(DestWidth, ExplicitType);
4413
4414 if (NewElemTy.isNull()) {
4415 // Only emit diagnostic on host for 128-bit mode attribute
4416 if (!(DestWidth == 128 && getLangOpts().CUDAIsDevice))
4417 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
4418 return;
4419 }
4420
4421 if (ComplexMode) {
4422 NewElemTy = Context.getComplexType(NewElemTy);
4423 }
4424
4425 QualType NewTy = NewElemTy;
4426 if (VectorSize.getBoolValue()) {
4427 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
4429 } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
4430 // Complex machine mode does not support base vector types.
4431 if (ComplexMode) {
4432 Diag(AttrLoc, diag::err_complex_mode_vector_type);
4433 return;
4434 }
4435 unsigned NumElements = Context.getTypeSize(OldElemTy) *
4436 OldVT->getNumElements() /
4437 Context.getTypeSize(NewElemTy);
4438 NewTy =
4439 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
4440 }
4441
4442 if (NewTy.isNull()) {
4443 Diag(AttrLoc, diag::err_mode_wrong_type);
4444 return;
4445 }
4446
4447 // Install the new type.
4448 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
4449 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
4450 else if (auto *ED = dyn_cast<EnumDecl>(D))
4451 ED->setIntegerType(NewTy);
4452 else
4453 cast<ValueDecl>(D)->setType(NewTy);
4454
4455 D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4456}
4457
4458static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4459 D->addAttr(::new (S.Context) NoDebugAttr(S.Context, AL));
4460}
4461
4463 const AttributeCommonInfo &CI,
4464 const IdentifierInfo *Ident) {
4465 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4466 Diag(CI.getLoc(), diag::warn_attribute_ignored) << Ident;
4467 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4468 return nullptr;
4469 }
4470
4471 if (D->hasAttr<AlwaysInlineAttr>())
4472 return nullptr;
4473
4474 return ::new (Context) AlwaysInlineAttr(Context, CI);
4475}
4476
4478 const ParsedAttr &AL) {
4479 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4480 // Attribute applies to Var but not any subclass of it (like ParmVar,
4481 // ImplicitParm or VarTemplateSpecialization).
4482 if (VD->getKind() != Decl::Var) {
4483 Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4484 << AL << AL.isRegularKeywordAttribute()
4487 return nullptr;
4488 }
4489 // Attribute does not apply to non-static local variables.
4490 if (VD->hasLocalStorage()) {
4491 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4492 return nullptr;
4493 }
4494 }
4495
4496 return ::new (Context) InternalLinkageAttr(Context, AL);
4497}
4498InternalLinkageAttr *
4499Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
4500 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4501 // Attribute applies to Var but not any subclass of it (like ParmVar,
4502 // ImplicitParm or VarTemplateSpecialization).
4503 if (VD->getKind() != Decl::Var) {
4504 Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
4505 << &AL << AL.isRegularKeywordAttribute()
4508 return nullptr;
4509 }
4510 // Attribute does not apply to non-static local variables.
4511 if (VD->hasLocalStorage()) {
4512 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4513 return nullptr;
4514 }
4515 }
4516
4517 return ::new (Context) InternalLinkageAttr(Context, AL);
4518}
4519
4521 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4522 Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'minsize'";
4523 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4524 return nullptr;
4525 }
4526
4527 if (D->hasAttr<MinSizeAttr>())
4528 return nullptr;
4529
4530 return ::new (Context) MinSizeAttr(Context, CI);
4531}
4532
4534 const AttributeCommonInfo &CI) {
4535 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4536 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4537 Diag(CI.getLoc(), diag::note_conflicting_attribute);
4538 D->dropAttr<AlwaysInlineAttr>();
4539 }
4540 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4541 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4542 Diag(CI.getLoc(), diag::note_conflicting_attribute);
4543 D->dropAttr<MinSizeAttr>();
4544 }
4545
4546 if (D->hasAttr<OptimizeNoneAttr>())
4547 return nullptr;
4548
4549 return ::new (Context) OptimizeNoneAttr(Context, CI);
4550}
4551
4552static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4553 if (AlwaysInlineAttr *Inline =
4554 S.mergeAlwaysInlineAttr(D, AL, AL.getAttrName()))
4555 D->addAttr(Inline);
4556}
4557
4558static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4559 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(D, AL))
4560 D->addAttr(MinSize);
4561}
4562
4563static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4564 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(D, AL))
4565 D->addAttr(Optnone);
4566}
4567
4568static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4569 const auto *VD = cast<VarDecl>(D);
4570 if (VD->hasLocalStorage()) {
4571 S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4572 return;
4573 }
4574 // constexpr variable may already get an implicit constant attr, which should
4575 // be replaced by the explicit constant attr.
4576 if (auto *A = D->getAttr<CUDAConstantAttr>()) {
4577 if (!A->isImplicit())
4578 return;
4579 D->dropAttr<CUDAConstantAttr>();
4580 }
4581 D->addAttr(::new (S.Context) CUDAConstantAttr(S.Context, AL));
4582}
4583
4584static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4585 const auto *VD = cast<VarDecl>(D);
4586 // extern __shared__ is only allowed on arrays with no length (e.g.
4587 // "int x[]").
4588 if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
4589 !isa<IncompleteArrayType>(VD->getType())) {
4590 S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
4591 return;
4592 }
4593 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4594 S.CUDA().DiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
4595 << llvm::to_underlying(S.CUDA().CurrentTarget()))
4596 return;
4597 D->addAttr(::new (S.Context) CUDASharedAttr(S.Context, AL));
4598}
4599
4600static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4601 const auto *FD = cast<FunctionDecl>(D);
4602 if (!FD->getReturnType()->isVoidType() &&
4603 !FD->getReturnType()->getAs<AutoType>() &&
4605 SourceRange RTRange = FD->getReturnTypeSourceRange();
4606 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4607 << FD->getType()
4608 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4609 : FixItHint());
4610 return;
4611 }
4612 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4613 if (Method->isInstance()) {
4614 S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
4615 << Method;
4616 return;
4617 }
4618 S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
4619 }
4620 // Only warn for "inline" when compiling for host, to cut down on noise.
4621 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4622 S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
4623
4624 if (AL.getKind() == ParsedAttr::AT_NVPTXKernel)
4625 D->addAttr(::new (S.Context) NVPTXKernelAttr(S.Context, AL));
4626 else
4627 D->addAttr(::new (S.Context) CUDAGlobalAttr(S.Context, AL));
4628 // In host compilation the kernel is emitted as a stub function, which is
4629 // a helper function for launching the kernel. The instructions in the helper
4630 // function has nothing to do with the source code of the kernel. Do not emit
4631 // debug info for the stub function to avoid confusing the debugger.
4632 if (S.LangOpts.HIP && !S.LangOpts.CUDAIsDevice)
4633 D->addAttr(NoDebugAttr::CreateImplicit(S.Context));
4634}
4635
4636static void handleDeviceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4637 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4638 if (VD->hasLocalStorage()) {
4639 S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4640 return;
4641 }
4642 }
4643
4644 if (auto *A = D->getAttr<CUDADeviceAttr>()) {
4645 if (!A->isImplicit())
4646 return;
4647 D->dropAttr<CUDADeviceAttr>();
4648 }
4649 D->addAttr(::new (S.Context) CUDADeviceAttr(S.Context, AL));
4650}
4651
4652static void handleManagedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4653 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4654 if (VD->hasLocalStorage()) {
4655 S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4656 return;
4657 }
4658 }
4659 if (!D->hasAttr<HIPManagedAttr>())
4660 D->addAttr(::new (S.