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