Bug Summary

File:build-llvm/tools/clang/include/clang/AST/Attrs.inc
Warning:line 521, column 9
Null pointer passed as an argument to a 'nonnull' parameter

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaDeclAttr.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn337490/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn337490/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn337490/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn337490/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn337490/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/lib/gcc/x86_64-linux-gnu/8/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn337490/build-llvm/tools/clang/lib/Sema -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-07-20-043646-20380-1 -x c++ /build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp -faddrsig

/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp

1//===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements decl-related attribute processing.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/Mangle.h"
24#include "clang/AST/RecursiveASTVisitor.h"
25#include "clang/Basic/CharInfo.h"
26#include "clang/Basic/SourceManager.h"
27#include "clang/Basic/TargetInfo.h"
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Sema/DeclSpec.h"
30#include "clang/Sema/DelayedDiagnostic.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Scope.h"
34#include "clang/Sema/ScopeInfo.h"
35#include "clang/Sema/SemaInternal.h"
36#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/StringExtras.h"
38#include "llvm/Support/MathExtras.h"
39
40using namespace clang;
41using namespace sema;
42
43namespace AttributeLangSupport {
44 enum LANG {
45 C,
46 Cpp,
47 ObjC
48 };
49} // end namespace AttributeLangSupport
50
51//===----------------------------------------------------------------------===//
52// Helper functions
53//===----------------------------------------------------------------------===//
54
55/// isFunctionOrMethod - Return true if the given decl has function
56/// type (function or function-typed variable) or an Objective-C
57/// method.
58static bool isFunctionOrMethod(const Decl *D) {
59 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
60}
61
62/// Return true if the given decl has function type (function or
63/// function-typed variable) or an Objective-C method or a block.
64static bool isFunctionOrMethodOrBlock(const Decl *D) {
65 return isFunctionOrMethod(D) || isa<BlockDecl>(D);
66}
67
68/// Return true if the given decl has a declarator that should have
69/// been processed by Sema::GetTypeForDeclarator.
70static bool hasDeclarator(const Decl *D) {
71 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
72 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
73 isa<ObjCPropertyDecl>(D);
74}
75
76/// hasFunctionProto - Return true if the given decl has a argument
77/// information. This decl should have already passed
78/// isFunctionOrMethod or isFunctionOrMethodOrBlock.
79static bool hasFunctionProto(const Decl *D) {
80 if (const FunctionType *FnTy = D->getFunctionType())
81 return isa<FunctionProtoType>(FnTy);
82 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
83}
84
85/// getFunctionOrMethodNumParams - Return number of function or method
86/// parameters. It is an error to call this on a K&R function (use
87/// hasFunctionProto first).
88static unsigned getFunctionOrMethodNumParams(const Decl *D) {
89 if (const FunctionType *FnTy = D->getFunctionType())
90 return cast<FunctionProtoType>(FnTy)->getNumParams();
91 if (const auto *BD = dyn_cast<BlockDecl>(D))
92 return BD->getNumParams();
93 return cast<ObjCMethodDecl>(D)->param_size();
94}
95
96static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
97 if (const FunctionType *FnTy = D->getFunctionType())
98 return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
99 if (const auto *BD = dyn_cast<BlockDecl>(D))
100 return BD->getParamDecl(Idx)->getType();
101
102 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
103}
104
105static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
106 if (const auto *FD = dyn_cast<FunctionDecl>(D))
107 return FD->getParamDecl(Idx)->getSourceRange();
108 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
109 return MD->parameters()[Idx]->getSourceRange();
110 if (const auto *BD = dyn_cast<BlockDecl>(D))
111 return BD->getParamDecl(Idx)->getSourceRange();
112 return SourceRange();
113}
114
115static QualType getFunctionOrMethodResultType(const Decl *D) {
116 if (const FunctionType *FnTy = D->getFunctionType())
117 return FnTy->getReturnType();
118 return cast<ObjCMethodDecl>(D)->getReturnType();
119}
120
121static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
122 if (const auto *FD = dyn_cast<FunctionDecl>(D))
123 return FD->getReturnTypeSourceRange();
124 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
125 return MD->getReturnTypeSourceRange();
126 return SourceRange();
127}
128
129static bool isFunctionOrMethodVariadic(const Decl *D) {
130 if (const FunctionType *FnTy = D->getFunctionType())
131 return cast<FunctionProtoType>(FnTy)->isVariadic();
132 if (const auto *BD = dyn_cast<BlockDecl>(D))
133 return BD->isVariadic();
134 return cast<ObjCMethodDecl>(D)->isVariadic();
135}
136
137static bool isInstanceMethod(const Decl *D) {
138 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(D))
139 return MethodDecl->isInstance();
140 return false;
141}
142
143static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
144 const auto *PT = T->getAs<ObjCObjectPointerType>();
145 if (!PT)
146 return false;
147
148 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
149 if (!Cls)
150 return false;
151
152 IdentifierInfo* ClsName = Cls->getIdentifier();
153
154 // FIXME: Should we walk the chain of classes?
155 return ClsName == &Ctx.Idents.get("NSString") ||
156 ClsName == &Ctx.Idents.get("NSMutableString");
157}
158
159static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
160 const auto *PT = T->getAs<PointerType>();
161 if (!PT)
162 return false;
163
164 const auto *RT = PT->getPointeeType()->getAs<RecordType>();
165 if (!RT)
166 return false;
167
168 const RecordDecl *RD = RT->getDecl();
169 if (RD->getTagKind() != TTK_Struct)
170 return false;
171
172 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
173}
174
175static unsigned getNumAttributeArgs(const ParsedAttr &AL) {
176 // FIXME: Include the type in the argument list.
177 return AL.getNumArgs() + AL.hasParsedType();
178}
179
180template <typename Compare>
181static bool checkAttributeNumArgsImpl(Sema &S, const ParsedAttr &AL,
182 unsigned Num, unsigned Diag,
183 Compare Comp) {
184 if (Comp(getNumAttributeArgs(AL), Num)) {
185 S.Diag(AL.getLoc(), Diag) << AL.getName() << Num;
186 return false;
187 }
188
189 return true;
190}
191
192/// Check if the attribute has exactly as many args as Num. May
193/// output an error.
194static bool checkAttributeNumArgs(Sema &S, const ParsedAttr &AL, unsigned Num) {
195 return checkAttributeNumArgsImpl(S, AL, Num,
196 diag::err_attribute_wrong_number_arguments,
197 std::not_equal_to<unsigned>());
198}
199
200/// Check if the attribute has at least as many args as Num. May
201/// output an error.
202static bool checkAttributeAtLeastNumArgs(Sema &S, const ParsedAttr &AL,
203 unsigned Num) {
204 return checkAttributeNumArgsImpl(S, AL, Num,
205 diag::err_attribute_too_few_arguments,
206 std::less<unsigned>());
207}
208
209/// Check if the attribute has at most as many args as Num. May
210/// output an error.
211static bool checkAttributeAtMostNumArgs(Sema &S, const ParsedAttr &AL,
212 unsigned Num) {
213 return checkAttributeNumArgsImpl(S, AL, Num,
214 diag::err_attribute_too_many_arguments,
215 std::greater<unsigned>());
216}
217
218/// A helper function to provide Attribute Location for the Attr types
219/// AND the ParsedAttr.
220template <typename AttrInfo>
221static typename std::enable_if<std::is_base_of<Attr, AttrInfo>::value,
222 SourceLocation>::type
223getAttrLoc(const AttrInfo &AL) {
224 return AL.getLocation();
225}
226static SourceLocation getAttrLoc(const ParsedAttr &AL) { return AL.getLoc(); }
227
228/// A helper function to provide Attribute Name for the Attr types
229/// AND the ParsedAttr.
230template <typename AttrInfo>
231static typename std::enable_if<std::is_base_of<Attr, AttrInfo>::value,
232 const AttrInfo *>::type
233getAttrName(const AttrInfo &AL) {
234 return &AL;
235}
236static const IdentifierInfo *getAttrName(const ParsedAttr &AL) {
237 return AL.getName();
238}
239
240/// If Expr is a valid integer constant, get the value of the integer
241/// expression and return success or failure. May output an error.
242template <typename AttrInfo>
243static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr,
244 uint32_t &Val, unsigned Idx = UINT_MAX(2147483647 *2U +1U)) {
245 llvm::APSInt I(32);
246 if (Expr->isTypeDependent() || Expr->isValueDependent() ||
247 !Expr->isIntegerConstantExpr(I, S.Context)) {
248 if (Idx != UINT_MAX(2147483647 *2U +1U))
249 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
250 << getAttrName(AI) << Idx << AANT_ArgumentIntegerConstant
251 << Expr->getSourceRange();
252 else
253 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
254 << getAttrName(AI) << AANT_ArgumentIntegerConstant
255 << Expr->getSourceRange();
256 return false;
257 }
258
259 if (!I.isIntN(32)) {
260 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
261 << I.toString(10, false) << 32 << /* Unsigned */ 1;
262 return false;
263 }
264
265 Val = (uint32_t)I.getZExtValue();
266 return true;
267}
268
269/// Wrapper around checkUInt32Argument, with an extra check to be sure
270/// that the result will fit into a regular (signed) int. All args have the same
271/// purpose as they do in checkUInt32Argument.
272template <typename AttrInfo>
273static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr,
274 int &Val, unsigned Idx = UINT_MAX(2147483647 *2U +1U)) {
275 uint32_t UVal;
276 if (!checkUInt32Argument(S, AI, Expr, UVal, Idx))
277 return false;
278
279 if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
280 llvm::APSInt I(32); // for toString
281 I = UVal;
282 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
283 << I.toString(10, false) << 32 << /* Unsigned */ 0;
284 return false;
285 }
286
287 Val = UVal;
288 return true;
289}
290
291/// Diagnose mutually exclusive attributes when present on a given
292/// declaration. Returns true if diagnosed.
293template <typename AttrTy>
294static bool checkAttrMutualExclusion(Sema &S, Decl *D, SourceRange Range,
295 IdentifierInfo *Ident) {
296 if (const auto *A = D->getAttr<AttrTy>()) {
297 S.Diag(Range.getBegin(), diag::err_attributes_are_not_compatible) << Ident
298 << A;
299 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
300 return true;
301 }
302 return false;
303}
304
305/// Check if IdxExpr is a valid parameter index for a function or
306/// instance method D. May output an error.
307///
308/// \returns true if IdxExpr is a valid index.
309template <typename AttrInfo>
310static bool checkFunctionOrMethodParameterIndex(
311 Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
312 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) {
313 assert(isFunctionOrMethodOrBlock(D))(static_cast <bool> (isFunctionOrMethodOrBlock(D)) ? void
(0) : __assert_fail ("isFunctionOrMethodOrBlock(D)", "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 313, __extension__ __PRETTY_FUNCTION__))
;
314
315 // In C++ the implicit 'this' function parameter also counts.
316 // Parameters are counted from one.
317 bool HP = hasFunctionProto(D);
318 bool HasImplicitThisParam = isInstanceMethod(D);
319 bool IV = HP && isFunctionOrMethodVariadic(D);
320 unsigned NumParams =
321 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
322
323 llvm::APSInt IdxInt;
324 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
325 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
326 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
327 << getAttrName(AI) << AttrArgNum << AANT_ArgumentIntegerConstant
328 << IdxExpr->getSourceRange();
329 return false;
330 }
331
332 unsigned IdxSource = IdxInt.getLimitedValue(UINT_MAX(2147483647 *2U +1U));
333 if (IdxSource < 1 || (!IV && IdxSource > NumParams)) {
334 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
335 << getAttrName(AI) << AttrArgNum << IdxExpr->getSourceRange();
336 return false;
337 }
338 if (HasImplicitThisParam && !CanIndexImplicitThis) {
339 if (IdxSource == 1) {
340 S.Diag(getAttrLoc(AI),
341 diag::err_attribute_invalid_implicit_this_argument)
342 << getAttrName(AI) << IdxExpr->getSourceRange();
343 return false;
344 }
345 }
346
347 Idx = ParamIdx(IdxSource, D);
348 return true;
349}
350
351/// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
352/// If not emit an error and return false. If the argument is an identifier it
353/// will emit an error with a fixit hint and treat it as if it was a string
354/// literal.
355bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum,
356 StringRef &Str,
357 SourceLocation *ArgLocation) {
358 // Look for identifiers. If we have one emit a hint to fix it to a literal.
359 if (AL.isArgIdent(ArgNum)) {
360 IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum);
361 Diag(Loc->Loc, diag::err_attribute_argument_type)
362 << AL.getName() << AANT_ArgumentString
363 << FixItHint::CreateInsertion(Loc->Loc, "\"")
364 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
365 Str = Loc->Ident->getName();
366 if (ArgLocation)
367 *ArgLocation = Loc->Loc;
368 return true;
369 }
370
371 // Now check for an actual string literal.
372 Expr *ArgExpr = AL.getArgAsExpr(ArgNum);
373 const auto *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
374 if (ArgLocation)
375 *ArgLocation = ArgExpr->getLocStart();
376
377 if (!Literal || !Literal->isAscii()) {
378 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
379 << AL.getName() << AANT_ArgumentString;
380 return false;
381 }
382
383 Str = Literal->getString();
384 return true;
385}
386
387/// Applies the given attribute to the Decl without performing any
388/// additional semantic checking.
389template <typename AttrType>
390static void handleSimpleAttribute(Sema &S, Decl *D, const ParsedAttr &AL) {
391 D->addAttr(::new (S.Context) AttrType(AL.getRange(), S.Context,
392 AL.getAttributeSpellingListIndex()));
393}
394
395template <typename AttrType>
396static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
397 const ParsedAttr &AL) {
398 handleSimpleAttribute<AttrType>(S, D, AL);
399}
400
401/// Applies the given attribute to the Decl so long as the Decl doesn't
402/// already have one of the given incompatible attributes.
403template <typename AttrType, typename IncompatibleAttrType,
404 typename... IncompatibleAttrTypes>
405static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
406 const ParsedAttr &AL) {
407 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, AL.getRange(),
408 AL.getName()))
409 return;
410 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
411 AL);
412}
413
414/// Check if the passed-in expression is of type int or bool.
415static bool isIntOrBool(Expr *Exp) {
416 QualType QT = Exp->getType();
417 return QT->isBooleanType() || QT->isIntegerType();
418}
419
420
421// Check to see if the type is a smart pointer of some kind. We assume
422// it's a smart pointer if it defines both operator-> and operator*.
423static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
424 DeclContextLookupResult Res1 = RT->getDecl()->lookup(
425 S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
426 if (Res1.empty())
427 return false;
428
429 DeclContextLookupResult Res2 = RT->getDecl()->lookup(
430 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
431 if (Res2.empty())
432 return false;
433
434 return true;
435}
436
437/// Check if passed in Decl is a pointer type.
438/// Note that this function may produce an error message.
439/// \return true if the Decl is a pointer type; false otherwise
440static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
441 const ParsedAttr &AL) {
442 const auto *VD = cast<ValueDecl>(D);
443 QualType QT = VD->getType();
444 if (QT->isAnyPointerType())
445 return true;
446
447 if (const auto *RT = QT->getAs<RecordType>()) {
448 // If it's an incomplete type, it could be a smart pointer; skip it.
449 // (We don't want to force template instantiation if we can avoid it,
450 // since that would alter the order in which templates are instantiated.)
451 if (RT->isIncompleteType())
452 return true;
453
454 if (threadSafetyCheckIsSmartPointer(S, RT))
455 return true;
456 }
457
458 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
459 << AL.getName() << QT;
460 return false;
461}
462
463/// Checks that the passed in QualType either is of RecordType or points
464/// to RecordType. Returns the relevant RecordType, null if it does not exit.
465static const RecordType *getRecordType(QualType QT) {
466 if (const auto *RT = QT->getAs<RecordType>())
467 return RT;
468
469 // Now check if we point to record type.
470 if (const auto *PT = QT->getAs<PointerType>())
471 return PT->getPointeeType()->getAs<RecordType>();
472
473 return nullptr;
474}
475
476static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
477 const RecordType *RT = getRecordType(Ty);
478
479 if (!RT)
480 return false;
481
482 // Don't check for the capability if the class hasn't been defined yet.
483 if (RT->isIncompleteType())
484 return true;
485
486 // Allow smart pointers to be used as capability objects.
487 // FIXME -- Check the type that the smart pointer points to.
488 if (threadSafetyCheckIsSmartPointer(S, RT))
489 return true;
490
491 // Check if the record itself has a capability.
492 RecordDecl *RD = RT->getDecl();
493 if (RD->hasAttr<CapabilityAttr>())
494 return true;
495
496 // Else check if any base classes have a capability.
497 if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
498 CXXBasePaths BPaths(false, false);
499 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) {
500 const auto *Type = BS->getType()->getAs<RecordType>();
501 return Type->getDecl()->hasAttr<CapabilityAttr>();
502 }, BPaths))
503 return true;
504 }
505 return false;
506}
507
508static bool checkTypedefTypeForCapability(QualType Ty) {
509 const auto *TD = Ty->getAs<TypedefType>();
510 if (!TD)
511 return false;
512
513 TypedefNameDecl *TN = TD->getDecl();
514 if (!TN)
515 return false;
516
517 return TN->hasAttr<CapabilityAttr>();
518}
519
520static bool typeHasCapability(Sema &S, QualType Ty) {
521 if (checkTypedefTypeForCapability(Ty))
522 return true;
523
524 if (checkRecordTypeForCapability(S, Ty))
525 return true;
526
527 return false;
528}
529
530static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
531 // Capability expressions are simple expressions involving the boolean logic
532 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
533 // a DeclRefExpr is found, its type should be checked to determine whether it
534 // is a capability or not.
535
536 if (const auto *E = dyn_cast<CastExpr>(Ex))
537 return isCapabilityExpr(S, E->getSubExpr());
538 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
539 return isCapabilityExpr(S, E->getSubExpr());
540 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
541 if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
542 E->getOpcode() == UO_Deref)
543 return isCapabilityExpr(S, E->getSubExpr());
544 return false;
545 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
546 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
547 return isCapabilityExpr(S, E->getLHS()) &&
548 isCapabilityExpr(S, E->getRHS());
549 return false;
550 }
551
552 return typeHasCapability(S, Ex->getType());
553}
554
555/// Checks that all attribute arguments, starting from Sidx, resolve to
556/// a capability object.
557/// \param Sidx The attribute argument index to start checking with.
558/// \param ParamIdxOk Whether an argument can be indexing into a function
559/// parameter list.
560static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
561 const ParsedAttr &AL,
562 SmallVectorImpl<Expr *> &Args,
563 int Sidx = 0,
564 bool ParamIdxOk = false) {
565 for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) {
566 Expr *ArgExp = AL.getArgAsExpr(Idx);
567
568 if (ArgExp->isTypeDependent()) {
569 // FIXME -- need to check this again on template instantiation
570 Args.push_back(ArgExp);
571 continue;
572 }
573
574 if (const auto *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
575 if (StrLit->getLength() == 0 ||
576 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
577 // Pass empty strings to the analyzer without warnings.
578 // Treat "*" as the universal lock.
579 Args.push_back(ArgExp);
580 continue;
581 }
582
583 // We allow constant strings to be used as a placeholder for expressions
584 // that are not valid C++ syntax, but warn that they are ignored.
585 S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL.getName();
586 Args.push_back(ArgExp);
587 continue;
588 }
589
590 QualType ArgTy = ArgExp->getType();
591
592 // A pointer to member expression of the form &MyClass::mu is treated
593 // specially -- we need to look at the type of the member.
594 if (const auto *UOp = dyn_cast<UnaryOperator>(ArgExp))
595 if (UOp->getOpcode() == UO_AddrOf)
596 if (const auto *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
597 if (DRE->getDecl()->isCXXInstanceMember())
598 ArgTy = DRE->getDecl()->getType();
599
600 // First see if we can just cast to record type, or pointer to record type.
601 const RecordType *RT = getRecordType(ArgTy);
602
603 // Now check if we index into a record type function param.
604 if(!RT && ParamIdxOk) {
605 const auto *FD = dyn_cast<FunctionDecl>(D);
606 const auto *IL = dyn_cast<IntegerLiteral>(ArgExp);
607 if(FD && IL) {
608 unsigned int NumParams = FD->getNumParams();
609 llvm::APInt ArgValue = IL->getValue();
610 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
611 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
612 if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
613 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
614 << AL.getName() << Idx + 1 << NumParams;
615 continue;
616 }
617 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
618 }
619 }
620
621 // If the type does not have a capability, see if the components of the
622 // expression have capabilities. This allows for writing C code where the
623 // capability may be on the type, and the expression is a capability
624 // boolean logic expression. Eg) requires_capability(A || B && !C)
625 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
626 S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
627 << AL.getName() << ArgTy;
628
629 Args.push_back(ArgExp);
630 }
631}
632
633//===----------------------------------------------------------------------===//
634// Attribute Implementations
635//===----------------------------------------------------------------------===//
636
637static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
638 if (!threadSafetyCheckIsPointer(S, D, AL))
639 return;
640
641 D->addAttr(::new (S.Context)
642 PtGuardedVarAttr(AL.getRange(), S.Context,
643 AL.getAttributeSpellingListIndex()));
644}
645
646static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
647 Expr *&Arg) {
648 SmallVector<Expr *, 1> Args;
649 // check that all arguments are lockable objects
650 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
651 unsigned Size = Args.size();
652 if (Size != 1)
653 return false;
654
655 Arg = Args[0];
656
657 return true;
658}
659
660static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
661 Expr *Arg = nullptr;
662 if (!checkGuardedByAttrCommon(S, D, AL, Arg))
663 return;
664
665 D->addAttr(::new (S.Context) GuardedByAttr(
666 AL.getRange(), S.Context, Arg, AL.getAttributeSpellingListIndex()));
667}
668
669static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
670 Expr *Arg = nullptr;
671 if (!checkGuardedByAttrCommon(S, D, AL, Arg))
672 return;
673
674 if (!threadSafetyCheckIsPointer(S, D, AL))
675 return;
676
677 D->addAttr(::new (S.Context) PtGuardedByAttr(
678 AL.getRange(), S.Context, Arg, AL.getAttributeSpellingListIndex()));
679}
680
681static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
682 SmallVectorImpl<Expr *> &Args) {
683 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
684 return false;
685
686 // Check that this attribute only applies to lockable types.
687 QualType QT = cast<ValueDecl>(D)->getType();
688 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
689 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
690 << AL.getName();
691 return false;
692 }
693
694 // Check that all arguments are lockable objects.
695 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
696 if (Args.empty())
697 return false;
698
699 return true;
700}
701
702static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
703 SmallVector<Expr *, 1> Args;
704 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
705 return;
706
707 Expr **StartArg = &Args[0];
708 D->addAttr(::new (S.Context) AcquiredAfterAttr(
709 AL.getRange(), S.Context, StartArg, Args.size(),
710 AL.getAttributeSpellingListIndex()));
711}
712
713static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
714 SmallVector<Expr *, 1> Args;
715 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
716 return;
717
718 Expr **StartArg = &Args[0];
719 D->addAttr(::new (S.Context) AcquiredBeforeAttr(
720 AL.getRange(), S.Context, StartArg, Args.size(),
721 AL.getAttributeSpellingListIndex()));
722}
723
724static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
725 SmallVectorImpl<Expr *> &Args) {
726 // zero or more arguments ok
727 // check that all arguments are lockable objects
728 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, /*ParamIdxOk=*/true);
729
730 return true;
731}
732
733static void handleAssertSharedLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
734 SmallVector<Expr *, 1> Args;
735 if (!checkLockFunAttrCommon(S, D, AL, Args))
736 return;
737
738 unsigned Size = Args.size();
739 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
740 D->addAttr(::new (S.Context)
741 AssertSharedLockAttr(AL.getRange(), S.Context, StartArg, Size,
742 AL.getAttributeSpellingListIndex()));
743}
744
745static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
746 const ParsedAttr &AL) {
747 SmallVector<Expr *, 1> Args;
748 if (!checkLockFunAttrCommon(S, D, AL, Args))
749 return;
750
751 unsigned Size = Args.size();
752 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
753 D->addAttr(::new (S.Context) AssertExclusiveLockAttr(
754 AL.getRange(), S.Context, StartArg, Size,
755 AL.getAttributeSpellingListIndex()));
756}
757
758/// Checks to be sure that the given parameter number is in bounds, and
759/// is an integral type. Will emit appropriate diagnostics if this returns
760/// false.
761///
762/// AttrArgNo is used to actually retrieve the argument, so it's base-0.
763template <typename AttrInfo>
764static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
765 const AttrInfo &AI, unsigned AttrArgNo) {
766 assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument")(static_cast <bool> (AI.isArgExpr(AttrArgNo) &&
"Expected expression argument") ? void (0) : __assert_fail (
"AI.isArgExpr(AttrArgNo) && \"Expected expression argument\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 766, __extension__ __PRETTY_FUNCTION__))
;
767 Expr *AttrArg = AI.getArgAsExpr(AttrArgNo);
768 ParamIdx Idx;
769 if (!checkFunctionOrMethodParameterIndex(S, FD, AI, AttrArgNo + 1, AttrArg,
770 Idx))
771 return false;
772
773 const ParmVarDecl *Param = FD->getParamDecl(Idx.getASTIndex());
774 if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) {
775 SourceLocation SrcLoc = AttrArg->getLocStart();
776 S.Diag(SrcLoc, diag::err_attribute_integers_only)
777 << getAttrName(AI) << Param->getSourceRange();
778 return false;
779 }
780 return true;
781}
782
783static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
784 if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
785 !checkAttributeAtMostNumArgs(S, AL, 2))
786 return;
787
788 const auto *FD = cast<FunctionDecl>(D);
789 if (!FD->getReturnType()->isPointerType()) {
790 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
791 << AL.getName();
792 return;
793 }
794
795 const Expr *SizeExpr = AL.getArgAsExpr(0);
796 int SizeArgNoVal;
797 // Parameter indices are 1-indexed, hence Index=1
798 if (!checkPositiveIntArgument(S, AL, SizeExpr, SizeArgNoVal, /*Index=*/1))
799 return;
800 if (!checkParamIsIntegerType(S, FD, AL, /*AttrArgNo=*/0))
801 return;
802 ParamIdx SizeArgNo(SizeArgNoVal, D);
803
804 ParamIdx NumberArgNo;
805 if (AL.getNumArgs() == 2) {
806 const Expr *NumberExpr = AL.getArgAsExpr(1);
807 int Val;
808 // Parameter indices are 1-based, hence Index=2
809 if (!checkPositiveIntArgument(S, AL, NumberExpr, Val, /*Index=*/2))
810 return;
811 if (!checkParamIsIntegerType(S, FD, AL, /*AttrArgNo=*/1))
812 return;
813 NumberArgNo = ParamIdx(Val, D);
814 }
815
816 D->addAttr(::new (S.Context)
817 AllocSizeAttr(AL.getRange(), S.Context, SizeArgNo, NumberArgNo,
818 AL.getAttributeSpellingListIndex()));
819}
820
821static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
822 SmallVectorImpl<Expr *> &Args) {
823 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
824 return false;
825
826 if (!isIntOrBool(AL.getArgAsExpr(0))) {
827 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
828 << AL.getName() << 1 << AANT_ArgumentIntOrBool;
829 return false;
830 }
831
832 // check that all arguments are lockable objects
833 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 1);
834
835 return true;
836}
837
838static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
839 const ParsedAttr &AL) {
840 SmallVector<Expr*, 2> Args;
841 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
842 return;
843
844 D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(
845 AL.getRange(), S.Context, AL.getArgAsExpr(0), Args.data(), Args.size(),
846 AL.getAttributeSpellingListIndex()));
847}
848
849static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
850 const ParsedAttr &AL) {
851 SmallVector<Expr*, 2> Args;
852 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
853 return;
854
855 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
856 AL.getRange(), S.Context, AL.getArgAsExpr(0), Args.data(),
857 Args.size(), AL.getAttributeSpellingListIndex()));
858}
859
860static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
861 // check that the argument is lockable object
862 SmallVector<Expr*, 1> Args;
863 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
864 unsigned Size = Args.size();
865 if (Size == 0)
866 return;
867
868 D->addAttr(::new (S.Context)
869 LockReturnedAttr(AL.getRange(), S.Context, Args[0],
870 AL.getAttributeSpellingListIndex()));
871}
872
873static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
874 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
875 return;
876
877 // check that all arguments are lockable objects
878 SmallVector<Expr*, 1> Args;
879 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
880 unsigned Size = Args.size();
881 if (Size == 0)
882 return;
883 Expr **StartArg = &Args[0];
884
885 D->addAttr(::new (S.Context)
886 LocksExcludedAttr(AL.getRange(), S.Context, StartArg, Size,
887 AL.getAttributeSpellingListIndex()));
888}
889
890static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL,
891 Expr *&Cond, StringRef &Msg) {
892 Cond = AL.getArgAsExpr(0);
893 if (!Cond->isTypeDependent()) {
894 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
895 if (Converted.isInvalid())
896 return false;
897 Cond = Converted.get();
898 }
899
900 if (!S.checkStringLiteralArgumentAttr(AL, 1, Msg))
901 return false;
902
903 if (Msg.empty())
904 Msg = "<no message provided>";
905
906 SmallVector<PartialDiagnosticAt, 8> Diags;
907 if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
908 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
909 Diags)) {
910 S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr)
911 << AL.getName();
912 for (const PartialDiagnosticAt &PDiag : Diags)
913 S.Diag(PDiag.first, PDiag.second);
914 return false;
915 }
916 return true;
917}
918
919static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
920 S.Diag(AL.getLoc(), diag::ext_clang_enable_if);
921
922 Expr *Cond;
923 StringRef Msg;
924 if (checkFunctionConditionAttr(S, D, AL, Cond, Msg))
925 D->addAttr(::new (S.Context)
926 EnableIfAttr(AL.getRange(), S.Context, Cond, Msg,
927 AL.getAttributeSpellingListIndex()));
928}
929
930namespace {
931/// Determines if a given Expr references any of the given function's
932/// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
933class ArgumentDependenceChecker
934 : public RecursiveASTVisitor<ArgumentDependenceChecker> {
935#ifndef NDEBUG
936 const CXXRecordDecl *ClassType;
937#endif
938 llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
939 bool Result;
940
941public:
942 ArgumentDependenceChecker(const FunctionDecl *FD) {
943#ifndef NDEBUG
944 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
945 ClassType = MD->getParent();
946 else
947 ClassType = nullptr;
948#endif
949 Parms.insert(FD->param_begin(), FD->param_end());
950 }
951
952 bool referencesArgs(Expr *E) {
953 Result = false;
954 TraverseStmt(E);
955 return Result;
956 }
957
958 bool VisitCXXThisExpr(CXXThisExpr *E) {
959 assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&(static_cast <bool> (E->getType()->getPointeeCXXRecordDecl
() == ClassType && "`this` doesn't refer to the enclosing class?"
) ? void (0) : __assert_fail ("E->getType()->getPointeeCXXRecordDecl() == ClassType && \"`this` doesn't refer to the enclosing class?\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 960, __extension__ __PRETTY_FUNCTION__))
960 "`this` doesn't refer to the enclosing class?")(static_cast <bool> (E->getType()->getPointeeCXXRecordDecl
() == ClassType && "`this` doesn't refer to the enclosing class?"
) ? void (0) : __assert_fail ("E->getType()->getPointeeCXXRecordDecl() == ClassType && \"`this` doesn't refer to the enclosing class?\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 960, __extension__ __PRETTY_FUNCTION__))
;
961 Result = true;
962 return false;
963 }
964
965 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
966 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
967 if (Parms.count(PVD)) {
968 Result = true;
969 return false;
970 }
971 return true;
972 }
973};
974}
975
976static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
977 S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if);
978
979 Expr *Cond;
980 StringRef Msg;
981 if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg))
982 return;
983
984 StringRef DiagTypeStr;
985 if (!S.checkStringLiteralArgumentAttr(AL, 2, DiagTypeStr))
986 return;
987
988 DiagnoseIfAttr::DiagnosticType DiagType;
989 if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
990 S.Diag(AL.getArgAsExpr(2)->getLocStart(),
991 diag::err_diagnose_if_invalid_diagnostic_type);
992 return;
993 }
994
995 bool ArgDependent = false;
996 if (const auto *FD = dyn_cast<FunctionDecl>(D))
997 ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
998 D->addAttr(::new (S.Context) DiagnoseIfAttr(
999 AL.getRange(), S.Context, Cond, Msg, DiagType, ArgDependent,
1000 cast<NamedDecl>(D), AL.getAttributeSpellingListIndex()));
1001}
1002
1003static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1004 if (D->hasAttr<PassObjectSizeAttr>()) {
1005 S.Diag(D->getLocStart(), diag::err_attribute_only_once_per_parameter)
1006 << AL.getName();
1007 return;
1008 }
1009
1010 Expr *E = AL.getArgAsExpr(0);
1011 uint32_t Type;
1012 if (!checkUInt32Argument(S, AL, E, Type, /*Idx=*/1))
1013 return;
1014
1015 // pass_object_size's argument is passed in as the second argument of
1016 // __builtin_object_size. So, it has the same constraints as that second
1017 // argument; namely, it must be in the range [0, 3].
1018 if (Type > 3) {
1019 S.Diag(E->getLocStart(), diag::err_attribute_argument_outof_range)
1020 << AL.getName() << 0 << 3 << E->getSourceRange();
1021 return;
1022 }
1023
1024 // pass_object_size is only supported on constant pointer parameters; as a
1025 // kindness to users, we allow the parameter to be non-const for declarations.
1026 // At this point, we have no clue if `D` belongs to a function declaration or
1027 // definition, so we defer the constness check until later.
1028 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1029 S.Diag(D->getLocStart(), diag::err_attribute_pointers_only)
1030 << AL.getName() << 1;
1031 return;
1032 }
1033
1034 D->addAttr(::new (S.Context) PassObjectSizeAttr(
1035 AL.getRange(), S.Context, (int)Type, AL.getAttributeSpellingListIndex()));
1036}
1037
1038static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1039 ConsumableAttr::ConsumedState DefaultState;
1040
1041 if (AL.isArgIdent(0)) {
1042 IdentifierLoc *IL = AL.getArgAsIdent(0);
1043 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1044 DefaultState)) {
1045 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
1046 << AL.getName() << IL->Ident;
1047 return;
1048 }
1049 } else {
1050 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1051 << AL.getName() << AANT_ArgumentIdentifier;
1052 return;
1053 }
1054
1055 D->addAttr(::new (S.Context)
1056 ConsumableAttr(AL.getRange(), S.Context, DefaultState,
1057 AL.getAttributeSpellingListIndex()));
1058}
1059
1060static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1061 const ParsedAttr &AL) {
1062 ASTContext &CurrContext = S.getASTContext();
1063 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
1064
1065 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1066 if (!RD->hasAttr<ConsumableAttr>()) {
1067 S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) <<
1068 RD->getNameAsString();
1069
1070 return false;
1071 }
1072 }
1073
1074 return true;
1075}
1076
1077static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1078 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
1079 return;
1080
1081 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1082 return;
1083
1084 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1085 for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
1086 CallableWhenAttr::ConsumedState CallableState;
1087
1088 StringRef StateString;
1089 SourceLocation Loc;
1090 if (AL.isArgIdent(ArgIndex)) {
1091 IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
1092 StateString = Ident->Ident->getName();
1093 Loc = Ident->Loc;
1094 } else {
1095 if (!S.checkStringLiteralArgumentAttr(AL, ArgIndex, StateString, &Loc))
1096 return;
1097 }
1098
1099 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1100 CallableState)) {
1101 S.Diag(Loc, diag::warn_attribute_type_not_supported)
1102 << AL.getName() << StateString;
1103 return;
1104 }
1105
1106 States.push_back(CallableState);
1107 }
1108
1109 D->addAttr(::new (S.Context)
1110 CallableWhenAttr(AL.getRange(), S.Context, States.data(),
1111 States.size(), AL.getAttributeSpellingListIndex()));
1112}
1113
1114static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1115 ParamTypestateAttr::ConsumedState ParamState;
1116
1117 if (AL.isArgIdent(0)) {
1118 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1119 StringRef StateString = Ident->Ident->getName();
1120
1121 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1122 ParamState)) {
1123 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1124 << AL.getName() << StateString;
1125 return;
1126 }
1127 } else {
1128 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) <<
1129 AL.getName() << AANT_ArgumentIdentifier;
1130 return;
1131 }
1132
1133 // FIXME: This check is currently being done in the analysis. It can be
1134 // enabled here only after the parser propagates attributes at
1135 // template specialization definition, not declaration.
1136 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1137 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1138 //
1139 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1140 // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1141 // ReturnType.getAsString();
1142 // return;
1143 //}
1144
1145 D->addAttr(::new (S.Context)
1146 ParamTypestateAttr(AL.getRange(), S.Context, ParamState,
1147 AL.getAttributeSpellingListIndex()));
1148}
1149
1150static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1151 ReturnTypestateAttr::ConsumedState ReturnState;
1152
1153 if (AL.isArgIdent(0)) {
1154 IdentifierLoc *IL = AL.getArgAsIdent(0);
1155 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1156 ReturnState)) {
1157 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
1158 << AL.getName() << IL->Ident;
1159 return;
1160 }
1161 } else {
1162 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) <<
1163 AL.getName() << AANT_ArgumentIdentifier;
1164 return;
1165 }
1166
1167 // FIXME: This check is currently being done in the analysis. It can be
1168 // enabled here only after the parser propagates attributes at
1169 // template specialization definition, not declaration.
1170 //QualType ReturnType;
1171 //
1172 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1173 // ReturnType = Param->getType();
1174 //
1175 //} else if (const CXXConstructorDecl *Constructor =
1176 // dyn_cast<CXXConstructorDecl>(D)) {
1177 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
1178 //
1179 //} else {
1180 //
1181 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1182 //}
1183 //
1184 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1185 //
1186 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1187 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1188 // ReturnType.getAsString();
1189 // return;
1190 //}
1191
1192 D->addAttr(::new (S.Context)
1193 ReturnTypestateAttr(AL.getRange(), S.Context, ReturnState,
1194 AL.getAttributeSpellingListIndex()));
1195}
1196
1197static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1198 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1199 return;
1200
1201 SetTypestateAttr::ConsumedState NewState;
1202 if (AL.isArgIdent(0)) {
1203 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1204 StringRef Param = Ident->Ident->getName();
1205 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1206 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1207 << AL.getName() << Param;
1208 return;
1209 }
1210 } else {
1211 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) <<
1212 AL.getName() << AANT_ArgumentIdentifier;
1213 return;
1214 }
1215
1216 D->addAttr(::new (S.Context)
1217 SetTypestateAttr(AL.getRange(), S.Context, NewState,
1218 AL.getAttributeSpellingListIndex()));
1219}
1220
1221static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1222 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1223 return;
1224
1225 TestTypestateAttr::ConsumedState TestState;
1226 if (AL.isArgIdent(0)) {
1227 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1228 StringRef Param = Ident->Ident->getName();
1229 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1230 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1231 << AL.getName() << Param;
1232 return;
1233 }
1234 } else {
1235 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) <<
1236 AL.getName() << AANT_ArgumentIdentifier;
1237 return;
1238 }
1239
1240 D->addAttr(::new (S.Context)
1241 TestTypestateAttr(AL.getRange(), S.Context, TestState,
1242 AL.getAttributeSpellingListIndex()));
1243}
1244
1245static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1246 // Remember this typedef decl, we will need it later for diagnostics.
1247 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1248}
1249
1250static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1251 if (auto *TD = dyn_cast<TagDecl>(D))
1252 TD->addAttr(::new (S.Context) PackedAttr(AL.getRange(), S.Context,
1253 AL.getAttributeSpellingListIndex()));
1254 else if (auto *FD = dyn_cast<FieldDecl>(D)) {
1255 bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
1256 !FD->getType()->isIncompleteType() &&
1257 FD->isBitField() &&
1258 S.Context.getTypeAlign(FD->getType()) <= 8);
1259
1260 if (S.getASTContext().getTargetInfo().getTriple().isPS4()) {
1261 if (BitfieldByteAligned)
1262 // The PS4 target needs to maintain ABI backwards compatibility.
1263 S.Diag(AL.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1264 << AL.getName() << FD->getType();
1265 else
1266 FD->addAttr(::new (S.Context) PackedAttr(
1267 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
1268 } else {
1269 // Report warning about changed offset in the newer compiler versions.
1270 if (BitfieldByteAligned)
1271 S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield);
1272
1273 FD->addAttr(::new (S.Context) PackedAttr(
1274 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
1275 }
1276
1277 } else
1278 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL.getName();
1279}
1280
1281static bool checkIBOutletCommon(Sema &S, Decl *D, const ParsedAttr &AL) {
1282 // The IBOutlet/IBOutletCollection attributes only apply to instance
1283 // variables or properties of Objective-C classes. The outlet must also
1284 // have an object reference type.
1285 if (const auto *VD = dyn_cast<ObjCIvarDecl>(D)) {
1286 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1287 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1288 << AL.getName() << VD->getType() << 0;
1289 return false;
1290 }
1291 }
1292 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1293 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1294 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1295 << AL.getName() << PD->getType() << 1;
1296 return false;
1297 }
1298 }
1299 else {
1300 S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL.getName();
1301 return false;
1302 }
1303
1304 return true;
1305}
1306
1307static void handleIBOutlet(Sema &S, Decl *D, const ParsedAttr &AL) {
1308 if (!checkIBOutletCommon(S, D, AL))
1309 return;
1310
1311 D->addAttr(::new (S.Context)
1312 IBOutletAttr(AL.getRange(), S.Context,
1313 AL.getAttributeSpellingListIndex()));
1314}
1315
1316static void handleIBOutletCollection(Sema &S, Decl *D, const ParsedAttr &AL) {
1317
1318 // The iboutletcollection attribute can have zero or one arguments.
1319 if (AL.getNumArgs() > 1) {
1320 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
1321 << AL.getName() << 1;
1322 return;
1323 }
1324
1325 if (!checkIBOutletCommon(S, D, AL))
1326 return;
1327
1328 ParsedType PT;
1329
1330 if (AL.hasParsedType())
1331 PT = AL.getTypeArg();
1332 else {
1333 PT = S.getTypeName(S.Context.Idents.get("NSObject"), AL.getLoc(),
1334 S.getScopeForContext(D->getDeclContext()->getParent()));
1335 if (!PT) {
1336 S.Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1337 return;
1338 }
1339 }
1340
1341 TypeSourceInfo *QTLoc = nullptr;
1342 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1343 if (!QTLoc)
1344 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, AL.getLoc());
1345
1346 // Diagnose use of non-object type in iboutletcollection attribute.
1347 // FIXME. Gnu attribute extension ignores use of builtin types in
1348 // attributes. So, __attribute__((iboutletcollection(char))) will be
1349 // treated as __attribute__((iboutletcollection())).
1350 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1351 S.Diag(AL.getLoc(),
1352 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1353 : diag::err_iboutletcollection_type) << QT;
1354 return;
1355 }
1356
1357 D->addAttr(::new (S.Context)
1358 IBOutletCollectionAttr(AL.getRange(), S.Context, QTLoc,
1359 AL.getAttributeSpellingListIndex()));
1360}
1361
1362bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1363 if (RefOkay) {
1364 if (T->isReferenceType())
1365 return true;
1366 } else {
1367 T = T.getNonReferenceType();
1368 }
1369
1370 // The nonnull attribute, and other similar attributes, can be applied to a
1371 // transparent union that contains a pointer type.
1372 if (const RecordType *UT = T->getAsUnionType()) {
1373 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1374 RecordDecl *UD = UT->getDecl();
1375 for (const auto *I : UD->fields()) {
1376 QualType QT = I->getType();
1377 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1378 return true;
1379 }
1380 }
1381 }
1382
1383 return T->isAnyPointerType() || T->isBlockPointerType();
1384}
1385
1386static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL,
1387 SourceRange AttrParmRange,
1388 SourceRange TypeRange,
1389 bool isReturnValue = false) {
1390 if (!S.isValidPointerAttrType(T)) {
1391 if (isReturnValue)
1392 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1393 << AL.getName() << AttrParmRange << TypeRange;
1394 else
1395 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1396 << AL.getName() << AttrParmRange << TypeRange << 0;
1397 return false;
1398 }
1399 return true;
1400}
1401
1402static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1403 SmallVector<ParamIdx, 8> NonNullArgs;
1404 for (unsigned I = 0; I < AL.getNumArgs(); ++I) {
1405 Expr *Ex = AL.getArgAsExpr(I);
1406 ParamIdx Idx;
1407 if (!checkFunctionOrMethodParameterIndex(S, D, AL, I + 1, Ex, Idx))
1408 return;
1409
1410 // Is the function argument a pointer type?
1411 if (Idx.getASTIndex() < getFunctionOrMethodNumParams(D) &&
1412 !attrNonNullArgCheck(
1413 S, getFunctionOrMethodParamType(D, Idx.getASTIndex()), AL,
1414 Ex->getSourceRange(),
1415 getFunctionOrMethodParamRange(D, Idx.getASTIndex())))
1416 continue;
1417
1418 NonNullArgs.push_back(Idx);
1419 }
1420
1421 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1422 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1423 // check if the attribute came from a macro expansion or a template
1424 // instantiation.
1425 if (NonNullArgs.empty() && AL.getLoc().isFileID() &&
1426 !S.inTemplateInstantiation()) {
1427 bool AnyPointers = isFunctionOrMethodVariadic(D);
1428 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1429 I != E && !AnyPointers; ++I) {
1430 QualType T = getFunctionOrMethodParamType(D, I);
1431 if (T->isDependentType() || S.isValidPointerAttrType(T))
1432 AnyPointers = true;
1433 }
1434
1435 if (!AnyPointers)
1436 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1437 }
1438
1439 ParamIdx *Start = NonNullArgs.data();
1440 unsigned Size = NonNullArgs.size();
1441 llvm::array_pod_sort(Start, Start + Size);
1442 D->addAttr(::new (S.Context)
1443 NonNullAttr(AL.getRange(), S.Context, Start, Size,
1444 AL.getAttributeSpellingListIndex()));
1445}
1446
1447static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1448 const ParsedAttr &AL) {
1449 if (AL.getNumArgs() > 0) {
1450 if (D->getFunctionType()) {
1451 handleNonNullAttr(S, D, AL);
1452 } else {
1453 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1454 << D->getSourceRange();
1455 }
1456 return;
1457 }
1458
1459 // Is the argument a pointer type?
1460 if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(),
1461 D->getSourceRange()))
1462 return;
1463
1464 D->addAttr(::new (S.Context)
1465 NonNullAttr(AL.getRange(), S.Context, nullptr, 0,
1466 AL.getAttributeSpellingListIndex()));
1467}
1468
1469static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1470 QualType ResultType = getFunctionOrMethodResultType(D);
1471 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1472 if (!attrNonNullArgCheck(S, ResultType, AL, SourceRange(), SR,
1473 /* isReturnValue */ true))
1474 return;
1475
1476 D->addAttr(::new (S.Context)
1477 ReturnsNonNullAttr(AL.getRange(), S.Context,
1478 AL.getAttributeSpellingListIndex()));
1479}
1480
1481static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1482 if (D->isInvalidDecl())
1483 return;
1484
1485 // noescape only applies to pointer types.
1486 QualType T = cast<ParmVarDecl>(D)->getType();
1487 if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
1488 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1489 << AL.getName() << AL.getRange() << 0;
1490 return;
1491 }
1492
1493 D->addAttr(::new (S.Context) NoEscapeAttr(
1494 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
1495}
1496
1497static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1498 Expr *E = AL.getArgAsExpr(0),
1499 *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr;
1500 S.AddAssumeAlignedAttr(AL.getRange(), D, E, OE,
1501 AL.getAttributeSpellingListIndex());
1502}
1503
1504static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1505 S.AddAllocAlignAttr(AL.getRange(), D, AL.getArgAsExpr(0),
1506 AL.getAttributeSpellingListIndex());
1507}
1508
1509void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
1510 Expr *OE, unsigned SpellingListIndex) {
1511 QualType ResultType = getFunctionOrMethodResultType(D);
1512 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1513
1514 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
1515 SourceLocation AttrLoc = AttrRange.getBegin();
1516
1517 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1518 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1519 << &TmpAttr << AttrRange << SR;
1520 return;
1521 }
1522
1523 if (!E->isValueDependent()) {
1524 llvm::APSInt I(64);
1525 if (!E->isIntegerConstantExpr(I, Context)) {
1526 if (OE)
1527 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1528 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1529 << E->getSourceRange();
1530 else
1531 Diag(AttrLoc, diag::err_attribute_argument_type)
1532 << &TmpAttr << AANT_ArgumentIntegerConstant
1533 << E->getSourceRange();
1534 return;
1535 }
1536
1537 if (!I.isPowerOf2()) {
1538 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1539 << E->getSourceRange();
1540 return;
1541 }
1542 }
1543
1544 if (OE) {
1545 if (!OE->isValueDependent()) {
1546 llvm::APSInt I(64);
1547 if (!OE->isIntegerConstantExpr(I, Context)) {
1548 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1549 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1550 << OE->getSourceRange();
1551 return;
1552 }
1553 }
1554 }
1555
1556 D->addAttr(::new (Context)
1557 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
1558}
1559
1560void Sema::AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr,
1561 unsigned SpellingListIndex) {
1562 QualType ResultType = getFunctionOrMethodResultType(D);
1563
1564 AllocAlignAttr TmpAttr(AttrRange, Context, ParamIdx(), SpellingListIndex);
1565 SourceLocation AttrLoc = AttrRange.getBegin();
1566
1567 if (!ResultType->isDependentType() &&
1568 !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1569 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1570 << &TmpAttr << AttrRange << getFunctionOrMethodResultSourceRange(D);
1571 return;
1572 }
1573
1574 ParamIdx Idx;
1575 const auto *FuncDecl = cast<FunctionDecl>(D);
1576 if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
1577 /*AttrArgNo=*/1, ParamExpr, Idx))
1578 return;
1579
1580 QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
1581 if (!Ty->isDependentType() && !Ty->isIntegralType(Context)) {
1582 Diag(ParamExpr->getLocStart(), diag::err_attribute_integers_only)
1583 << &TmpAttr
1584 << FuncDecl->getParamDecl(Idx.getASTIndex())->getSourceRange();
1585 return;
1586 }
1587
1588 D->addAttr(::new (Context)
1589 AllocAlignAttr(AttrRange, Context, Idx, SpellingListIndex));
1590}
1591
1592/// Normalize the attribute, __foo__ becomes foo.
1593/// Returns true if normalization was applied.
1594static bool normalizeName(StringRef &AttrName) {
1595 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1596 AttrName.endswith("__")) {
1597 AttrName = AttrName.drop_front(2).drop_back(2);
1598 return true;
1599 }
1600 return false;
1601}
1602
1603static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1604 // This attribute must be applied to a function declaration. The first
1605 // argument to the attribute must be an identifier, the name of the resource,
1606 // for example: malloc. The following arguments must be argument indexes, the
1607 // arguments must be of integer type for Returns, otherwise of pointer type.
1608 // The difference between Holds and Takes is that a pointer may still be used
1609 // after being held. free() should be __attribute((ownership_takes)), whereas
1610 // a list append function may well be __attribute((ownership_holds)).
1611
1612 if (!AL.isArgIdent(0)) {
1613 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1614 << AL.getName() << 1 << AANT_ArgumentIdentifier;
1615 return;
1616 }
1617
1618 // Figure out our Kind.
1619 OwnershipAttr::OwnershipKind K =
1620 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
1621 AL.getAttributeSpellingListIndex()).getOwnKind();
1622
1623 // Check arguments.
1624 switch (K) {
1625 case OwnershipAttr::Takes:
1626 case OwnershipAttr::Holds:
1627 if (AL.getNumArgs() < 2) {
1628 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
1629 << AL.getName() << 2;
1630 return;
1631 }
1632 break;
1633 case OwnershipAttr::Returns:
1634 if (AL.getNumArgs() > 2) {
1635 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
1636 << AL.getName() << 1;
1637 return;
1638 }
1639 break;
1640 }
1641
1642 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1643
1644 StringRef ModuleName = Module->getName();
1645 if (normalizeName(ModuleName)) {
1646 Module = &S.PP.getIdentifierTable().get(ModuleName);
1647 }
1648
1649 SmallVector<ParamIdx, 8> OwnershipArgs;
1650 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1651 Expr *Ex = AL.getArgAsExpr(i);
1652 ParamIdx Idx;
1653 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1654 return;
1655
1656 // Is the function argument a pointer type?
1657 QualType T = getFunctionOrMethodParamType(D, Idx.getASTIndex());
1658 int Err = -1; // No error
1659 switch (K) {
1660 case OwnershipAttr::Takes:
1661 case OwnershipAttr::Holds:
1662 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1663 Err = 0;
1664 break;
1665 case OwnershipAttr::Returns:
1666 if (!T->isIntegerType())
1667 Err = 1;
1668 break;
1669 }
1670 if (-1 != Err) {
1671 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
1672 << Ex->getSourceRange();
1673 return;
1674 }
1675
1676 // Check we don't have a conflict with another ownership attribute.
1677 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1678 // Cannot have two ownership attributes of different kinds for the same
1679 // index.
1680 if (I->getOwnKind() != K && I->args_end() !=
1681 std::find(I->args_begin(), I->args_end(), Idx)) {
1682 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
1683 << AL.getName() << I;
1684 return;
1685 } else if (K == OwnershipAttr::Returns &&
1686 I->getOwnKind() == OwnershipAttr::Returns) {
1687 // A returns attribute conflicts with any other returns attribute using
1688 // a different index.
1689 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1690 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1691 << I->args_begin()->getSourceIndex();
1692 if (I->args_size())
1693 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1694 << Idx.getSourceIndex() << Ex->getSourceRange();
1695 return;
1696 }
1697 }
1698 }
1699 OwnershipArgs.push_back(Idx);
1700 }
1701
1702 ParamIdx *Start = OwnershipArgs.data();
1703 unsigned Size = OwnershipArgs.size();
1704 llvm::array_pod_sort(Start, Start + Size);
1705 D->addAttr(::new (S.Context)
1706 OwnershipAttr(AL.getLoc(), S.Context, Module, Start, Size,
1707 AL.getAttributeSpellingListIndex()));
1708}
1709
1710static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1711 // Check the attribute arguments.
1712 if (AL.getNumArgs() > 1) {
1713 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
1714 << AL.getName() << 1;
1715 return;
1716 }
1717
1718 // gcc rejects
1719 // class c {
1720 // static int a __attribute__((weakref ("v2")));
1721 // static int b() __attribute__((weakref ("f3")));
1722 // };
1723 // and ignores the attributes of
1724 // void f(void) {
1725 // static int a __attribute__((weakref ("v2")));
1726 // }
1727 // we reject them
1728 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1729 if (!Ctx->isFileContext()) {
1730 S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context)
1731 << cast<NamedDecl>(D);
1732 return;
1733 }
1734
1735 // The GCC manual says
1736 //
1737 // At present, a declaration to which `weakref' is attached can only
1738 // be `static'.
1739 //
1740 // It also says
1741 //
1742 // Without a TARGET,
1743 // given as an argument to `weakref' or to `alias', `weakref' is
1744 // equivalent to `weak'.
1745 //
1746 // gcc 4.4.1 will accept
1747 // int a7 __attribute__((weakref));
1748 // as
1749 // int a7 __attribute__((weak));
1750 // This looks like a bug in gcc. We reject that for now. We should revisit
1751 // it if this behaviour is actually used.
1752
1753 // GCC rejects
1754 // static ((alias ("y"), weakref)).
1755 // Should we? How to check that weakref is before or after alias?
1756
1757 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1758 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1759 // StringRef parameter it was given anyway.
1760 StringRef Str;
1761 if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, 0, Str))
1762 // GCC will accept anything as the argument of weakref. Should we
1763 // check for an existing decl?
1764 D->addAttr(::new (S.Context) AliasAttr(AL.getRange(), S.Context, Str,
1765 AL.getAttributeSpellingListIndex()));
1766
1767 D->addAttr(::new (S.Context)
1768 WeakRefAttr(AL.getRange(), S.Context,
1769 AL.getAttributeSpellingListIndex()));
1770}
1771
1772static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1773 StringRef Str;
1774 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1775 return;
1776
1777 // Aliases should be on declarations, not definitions.
1778 const auto *FD = cast<FunctionDecl>(D);
1779 if (FD->isThisDeclarationADefinition()) {
1780 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1;
1781 return;
1782 }
1783
1784 D->addAttr(::new (S.Context) IFuncAttr(AL.getRange(), S.Context, Str,
1785 AL.getAttributeSpellingListIndex()));
1786}
1787
1788static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1789 StringRef Str;
1790 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1791 return;
1792
1793 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1794 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin);
1795 return;
1796 }
1797 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1798 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx);
1799 }
1800
1801 // Aliases should be on declarations, not definitions.
1802 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1803 if (FD->isThisDeclarationADefinition()) {
1804 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0;
1805 return;
1806 }
1807 } else {
1808 const auto *VD = cast<VarDecl>(D);
1809 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1810 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0;
1811 return;
1812 }
1813 }
1814
1815 // FIXME: check if target symbol exists in current file
1816
1817 D->addAttr(::new (S.Context) AliasAttr(AL.getRange(), S.Context, Str,
1818 AL.getAttributeSpellingListIndex()));
1819}
1820
1821static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1822 StringRef Model;
1823 SourceLocation LiteralLoc;
1824 // Check that it is a string.
1825 if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc))
1826 return;
1827
1828 // Check that the value.
1829 if (Model != "global-dynamic" && Model != "local-dynamic"
1830 && Model != "initial-exec" && Model != "local-exec") {
1831 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1832 return;
1833 }
1834
1835 D->addAttr(::new (S.Context)
1836 TLSModelAttr(AL.getRange(), S.Context, Model,
1837 AL.getAttributeSpellingListIndex()));
1838}
1839
1840static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1841 QualType ResultType = getFunctionOrMethodResultType(D);
1842 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1843 D->addAttr(::new (S.Context) RestrictAttr(
1844 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
1845 return;
1846 }
1847
1848 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1849 << AL.getName() << getFunctionOrMethodResultSourceRange(D);
1850}
1851
1852static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1853 if (S.LangOpts.CPlusPlus) {
1854 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
1855 << AL.getName() << AttributeLangSupport::Cpp;
1856 return;
1857 }
1858
1859 if (CommonAttr *CA = S.mergeCommonAttr(D, AL.getRange(), AL.getName(),
1860 AL.getAttributeSpellingListIndex()))
1861 D->addAttr(CA);
1862}
1863
1864static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1865 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, AL.getRange(),
1866 AL.getName()))
1867 return;
1868
1869 if (AL.isDeclspecAttribute()) {
1870 const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
1871 const auto &Arch = Triple.getArch();
1872 if (Arch != llvm::Triple::x86 &&
1873 (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
1874 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch)
1875 << AL.getName() << Triple.getArchName();
1876 return;
1877 }
1878 }
1879
1880 D->addAttr(::new (S.Context) NakedAttr(AL.getRange(), S.Context,
1881 AL.getAttributeSpellingListIndex()));
1882}
1883
1884static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
1885 if (hasDeclarator(D)) return;
1886
1887 if (!isa<ObjCMethodDecl>(D)) {
1888 S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
1889 << Attrs.getName() << ExpectedFunctionOrMethod;
1890 return;
1891 }
1892
1893 D->addAttr(::new (S.Context) NoReturnAttr(
1894 Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
1895}
1896
1897static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
1898 if (!S.getLangOpts().CFProtectionBranch)
1899 S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored);
1900 else
1901 handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs);
1902}
1903
1904bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) {
1905 if (!checkAttributeNumArgs(*this, Attrs, 0)) {
1906 Attrs.setInvalid();
1907 return true;
1908 }
1909
1910 return false;
1911}
1912
1913bool Sema::CheckAttrTarget(const ParsedAttr &AL) {
1914 // Check whether the attribute is valid on the current target.
1915 if (!AL.existsInTarget(Context.getTargetInfo())) {
1916 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL.getName();
1917 AL.setInvalid();
1918 return true;
1919 }
1920
1921 return false;
1922}
1923
1924static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1925
1926 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
1927 // because 'analyzer_noreturn' does not impact the type.
1928 if (!isFunctionOrMethodOrBlock(D)) {
1929 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1930 if (!VD || (!VD->getType()->isBlockPointerType() &&
1931 !VD->getType()->isFunctionPointerType())) {
1932 S.Diag(AL.getLoc(),
1933 AL.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
1934 : diag::warn_attribute_wrong_decl_type)
1935 << AL.getName() << ExpectedFunctionMethodOrBlock;
1936 return;
1937 }
1938 }
1939
1940 D->addAttr(::new (S.Context)
1941 AnalyzerNoReturnAttr(AL.getRange(), S.Context,
1942 AL.getAttributeSpellingListIndex()));
1943}
1944
1945// PS3 PPU-specific.
1946static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1947 /*
1948 Returning a Vector Class in Registers
1949
1950 According to the PPU ABI specifications, a class with a single member of
1951 vector type is returned in memory when used as the return value of a
1952 function.
1953 This results in inefficient code when implementing vector classes. To return
1954 the value in a single vector register, add the vecreturn attribute to the
1955 class definition. This attribute is also applicable to struct types.
1956
1957 Example:
1958
1959 struct Vector
1960 {
1961 __vector float xyzw;
1962 } __attribute__((vecreturn));
1963
1964 Vector Add(Vector lhs, Vector rhs)
1965 {
1966 Vector result;
1967 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
1968 return result; // This will be returned in a register
1969 }
1970 */
1971 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
1972 S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A;
1973 return;
1974 }
1975
1976 const auto *R = cast<RecordDecl>(D);
1977 int count = 0;
1978
1979 if (!isa<CXXRecordDecl>(R)) {
1980 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1981 return;
1982 }
1983
1984 if (!cast<CXXRecordDecl>(R)->isPOD()) {
1985 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
1986 return;
1987 }
1988
1989 for (const auto *I : R->fields()) {
1990 if ((count == 1) || !I->getType()->isVectorType()) {
1991 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
1992 return;
1993 }
1994 count++;
1995 }
1996
1997 D->addAttr(::new (S.Context) VecReturnAttr(
1998 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
1999}
2000
2001static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
2002 const ParsedAttr &AL) {
2003 if (isa<ParmVarDecl>(D)) {
2004 // [[carries_dependency]] can only be applied to a parameter if it is a
2005 // parameter of a function declaration or lambda.
2006 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
2007 S.Diag(AL.getLoc(),
2008 diag::err_carries_dependency_param_not_function_decl);
2009 return;
2010 }
2011 }
2012
2013 D->addAttr(::new (S.Context) CarriesDependencyAttr(
2014 AL.getRange(), S.Context,
2015 AL.getAttributeSpellingListIndex()));
2016}
2017
2018static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2019 bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName();
2020
2021 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2022 // about using it as an extension.
2023 if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
2024 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL.getName();
2025
2026 D->addAttr(::new (S.Context) UnusedAttr(
2027 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
2028}
2029
2030static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2031 uint32_t priority = ConstructorAttr::DefaultPriority;
2032 if (AL.getNumArgs() &&
2033 !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2034 return;
2035
2036 D->addAttr(::new (S.Context)
2037 ConstructorAttr(AL.getRange(), S.Context, priority,
2038 AL.getAttributeSpellingListIndex()));
2039}
2040
2041static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2042 uint32_t priority = DestructorAttr::DefaultPriority;
2043 if (AL.getNumArgs() &&
2044 !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2045 return;
2046
2047 D->addAttr(::new (S.Context)
2048 DestructorAttr(AL.getRange(), S.Context, priority,
2049 AL.getAttributeSpellingListIndex()));
2050}
2051
2052template <typename AttrTy>
2053static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) {
2054 // Handle the case where the attribute has a text message.
2055 StringRef Str;
2056 if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str))
2057 return;
2058
2059 D->addAttr(::new (S.Context) AttrTy(AL.getRange(), S.Context, Str,
2060 AL.getAttributeSpellingListIndex()));
2061}
2062
2063static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
2064 const ParsedAttr &AL) {
2065 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
2066 S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2067 << AL.getName() << AL.getRange();
2068 return;
2069 }
2070
2071 D->addAttr(::new (S.Context)
2072 ObjCExplicitProtocolImplAttr(AL.getRange(), S.Context,
2073 AL.getAttributeSpellingListIndex()));
2074}
2075
2076static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2077 IdentifierInfo *Platform,
2078 VersionTuple Introduced,
2079 VersionTuple Deprecated,
2080 VersionTuple Obsoleted) {
2081 StringRef PlatformName
2082 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2083 if (PlatformName.empty())
2084 PlatformName = Platform->getName();
2085
2086 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2087 // of these steps are needed).
2088 if (!Introduced.empty() && !Deprecated.empty() &&
2089 !(Introduced <= Deprecated)) {
2090 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2091 << 1 << PlatformName << Deprecated.getAsString()
2092 << 0 << Introduced.getAsString();
2093 return true;
2094 }
2095
2096 if (!Introduced.empty() && !Obsoleted.empty() &&
2097 !(Introduced <= Obsoleted)) {
2098 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2099 << 2 << PlatformName << Obsoleted.getAsString()
2100 << 0 << Introduced.getAsString();
2101 return true;
2102 }
2103
2104 if (!Deprecated.empty() && !Obsoleted.empty() &&
2105 !(Deprecated <= Obsoleted)) {
2106 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2107 << 2 << PlatformName << Obsoleted.getAsString()
2108 << 1 << Deprecated.getAsString();
2109 return true;
2110 }
2111
2112 return false;
2113}
2114
2115/// Check whether the two versions match.
2116///
2117/// If either version tuple is empty, then they are assumed to match. If
2118/// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2119static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2120 bool BeforeIsOkay) {
2121 if (X.empty() || Y.empty())
2122 return true;
2123
2124 if (X == Y)
2125 return true;
2126
2127 if (BeforeIsOkay && X < Y)
2128 return true;
2129
2130 return false;
2131}
2132
2133AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
2134 IdentifierInfo *Platform,
2135 bool Implicit,
2136 VersionTuple Introduced,
2137 VersionTuple Deprecated,
2138 VersionTuple Obsoleted,
2139 bool IsUnavailable,
2140 StringRef Message,
2141 bool IsStrict,
2142 StringRef Replacement,
2143 AvailabilityMergeKind AMK,
2144 unsigned AttrSpellingListIndex) {
2145 VersionTuple MergedIntroduced = Introduced;
2146 VersionTuple MergedDeprecated = Deprecated;
2147 VersionTuple MergedObsoleted = Obsoleted;
2148 bool FoundAny = false;
2149 bool OverrideOrImpl = false;
2150 switch (AMK) {
2151 case AMK_None:
2152 case AMK_Redeclaration:
2153 OverrideOrImpl = false;
2154 break;
2155
2156 case AMK_Override:
2157 case AMK_ProtocolImplementation:
2158 OverrideOrImpl = true;
2159 break;
2160 }
2161
2162 if (D->hasAttrs()) {
2163 AttrVec &Attrs = D->getAttrs();
2164 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2165 const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2166 if (!OldAA) {
2167 ++i;
2168 continue;
2169 }
2170
2171 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2172 if (OldPlatform != Platform) {
2173 ++i;
2174 continue;
2175 }
2176
2177 // If there is an existing availability attribute for this platform that
2178 // is explicit and the new one is implicit use the explicit one and
2179 // discard the new implicit attribute.
2180 if (!OldAA->isImplicit() && Implicit) {
2181 return nullptr;
2182 }
2183
2184 // If there is an existing attribute for this platform that is implicit
2185 // and the new attribute is explicit then erase the old one and
2186 // continue processing the attributes.
2187 if (!Implicit && OldAA->isImplicit()) {
2188 Attrs.erase(Attrs.begin() + i);
2189 --e;
2190 continue;
2191 }
2192
2193 FoundAny = true;
2194 VersionTuple OldIntroduced = OldAA->getIntroduced();
2195 VersionTuple OldDeprecated = OldAA->getDeprecated();
2196 VersionTuple OldObsoleted = OldAA->getObsoleted();
2197 bool OldIsUnavailable = OldAA->getUnavailable();
2198
2199 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2200 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2201 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2202 !(OldIsUnavailable == IsUnavailable ||
2203 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2204 if (OverrideOrImpl) {
2205 int Which = -1;
2206 VersionTuple FirstVersion;
2207 VersionTuple SecondVersion;
2208 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2209 Which = 0;
2210 FirstVersion = OldIntroduced;
2211 SecondVersion = Introduced;
2212 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2213 Which = 1;
2214 FirstVersion = Deprecated;
2215 SecondVersion = OldDeprecated;
2216 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2217 Which = 2;
2218 FirstVersion = Obsoleted;
2219 SecondVersion = OldObsoleted;
2220 }
2221
2222 if (Which == -1) {
2223 Diag(OldAA->getLocation(),
2224 diag::warn_mismatched_availability_override_unavail)
2225 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2226 << (AMK == AMK_Override);
2227 } else {
2228 Diag(OldAA->getLocation(),
2229 diag::warn_mismatched_availability_override)
2230 << Which
2231 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2232 << FirstVersion.getAsString() << SecondVersion.getAsString()
2233 << (AMK == AMK_Override);
2234 }
2235 if (AMK == AMK_Override)
2236 Diag(Range.getBegin(), diag::note_overridden_method);
2237 else
2238 Diag(Range.getBegin(), diag::note_protocol_method);
2239 } else {
2240 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2241 Diag(Range.getBegin(), diag::note_previous_attribute);
2242 }
2243
2244 Attrs.erase(Attrs.begin() + i);
2245 --e;
2246 continue;
2247 }
2248
2249 VersionTuple MergedIntroduced2 = MergedIntroduced;
2250 VersionTuple MergedDeprecated2 = MergedDeprecated;
2251 VersionTuple MergedObsoleted2 = MergedObsoleted;
2252
2253 if (MergedIntroduced2.empty())
2254 MergedIntroduced2 = OldIntroduced;
2255 if (MergedDeprecated2.empty())
2256 MergedDeprecated2 = OldDeprecated;
2257 if (MergedObsoleted2.empty())
2258 MergedObsoleted2 = OldObsoleted;
2259
2260 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2261 MergedIntroduced2, MergedDeprecated2,
2262 MergedObsoleted2)) {
2263 Attrs.erase(Attrs.begin() + i);
2264 --e;
2265 continue;
2266 }
2267
2268 MergedIntroduced = MergedIntroduced2;
2269 MergedDeprecated = MergedDeprecated2;
2270 MergedObsoleted = MergedObsoleted2;
2271 ++i;
2272 }
2273 }
2274
2275 if (FoundAny &&
2276 MergedIntroduced == Introduced &&
2277 MergedDeprecated == Deprecated &&
2278 MergedObsoleted == Obsoleted)
2279 return nullptr;
2280
2281 // Only create a new attribute if !OverrideOrImpl, but we want to do
2282 // the checking.
2283 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
2284 MergedDeprecated, MergedObsoleted) &&
2285 !OverrideOrImpl) {
2286 auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform,
2287 Introduced, Deprecated,
2288 Obsoleted, IsUnavailable, Message,
2289 IsStrict, Replacement,
2290 AttrSpellingListIndex);
2291 Avail->setImplicit(Implicit);
2292 return Avail;
2293 }
2294 return nullptr;
2295}
2296
2297static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2298 if (!checkAttributeNumArgs(S, AL, 1))
2299 return;
2300 IdentifierLoc *Platform = AL.getArgAsIdent(0);
2301 unsigned Index = AL.getAttributeSpellingListIndex();
2302
2303 IdentifierInfo *II = Platform->Ident;
2304 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2305 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2306 << Platform->Ident;
2307
2308 auto *ND = dyn_cast<NamedDecl>(D);
2309 if (!ND) // We warned about this already, so just return.
2310 return;
2311
2312 AvailabilityChange Introduced = AL.getAvailabilityIntroduced();
2313 AvailabilityChange Deprecated = AL.getAvailabilityDeprecated();
2314 AvailabilityChange Obsoleted = AL.getAvailabilityObsoleted();
2315 bool IsUnavailable = AL.getUnavailableLoc().isValid();
2316 bool IsStrict = AL.getStrictLoc().isValid();
2317 StringRef Str;
2318 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getMessageExpr()))
2319 Str = SE->getString();
2320 StringRef Replacement;
2321 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getReplacementExpr()))
2322 Replacement = SE->getString();
2323
2324 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, AL.getRange(), II,
2325 false/*Implicit*/,
2326 Introduced.Version,
2327 Deprecated.Version,
2328 Obsoleted.Version,
2329 IsUnavailable, Str,
2330 IsStrict, Replacement,
2331 Sema::AMK_None,
2332 Index);
2333 if (NewAttr)
2334 D->addAttr(NewAttr);
2335
2336 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2337 // matches before the start of the watchOS platform.
2338 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2339 IdentifierInfo *NewII = nullptr;
2340 if (II->getName() == "ios")
2341 NewII = &S.Context.Idents.get("watchos");
2342 else if (II->getName() == "ios_app_extension")
2343 NewII = &S.Context.Idents.get("watchos_app_extension");
2344
2345 if (NewII) {
2346 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2347 if (Version.empty())
2348 return Version;
2349 auto Major = Version.getMajor();
2350 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2351 if (NewMajor >= 2) {
2352 if (Version.getMinor().hasValue()) {
2353 if (Version.getSubminor().hasValue())
2354 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2355 Version.getSubminor().getValue());
2356 else
2357 return VersionTuple(NewMajor, Version.getMinor().getValue());
2358 }
2359 }
2360
2361 return VersionTuple(2, 0);
2362 };
2363
2364 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2365 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2366 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2367
2368 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2369 AL.getRange(),
2370 NewII,
2371 true/*Implicit*/,
2372 NewIntroduced,
2373 NewDeprecated,
2374 NewObsoleted,
2375 IsUnavailable, Str,
2376 IsStrict,
2377 Replacement,
2378 Sema::AMK_None,
2379 Index);
2380 if (NewAttr)
2381 D->addAttr(NewAttr);
2382 }
2383 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2384 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2385 // matches before the start of the tvOS platform.
2386 IdentifierInfo *NewII = nullptr;
2387 if (II->getName() == "ios")
2388 NewII = &S.Context.Idents.get("tvos");
2389 else if (II->getName() == "ios_app_extension")
2390 NewII = &S.Context.Idents.get("tvos_app_extension");
2391
2392 if (NewII) {
2393 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
2394 AL.getRange(),
2395 NewII,
2396 true/*Implicit*/,
2397 Introduced.Version,
2398 Deprecated.Version,
2399 Obsoleted.Version,
2400 IsUnavailable, Str,
2401 IsStrict,
2402 Replacement,
2403 Sema::AMK_None,
2404 Index);
2405 if (NewAttr)
2406 D->addAttr(NewAttr);
2407 }
2408 }
2409}
2410
2411static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2412 const ParsedAttr &AL) {
2413 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
2414 return;
2415 assert(checkAttributeAtMostNumArgs(S, AL, 3) &&(static_cast <bool> (checkAttributeAtMostNumArgs(S, AL,
3) && "Invalid number of arguments in an external_source_symbol attribute"
) ? void (0) : __assert_fail ("checkAttributeAtMostNumArgs(S, AL, 3) && \"Invalid number of arguments in an external_source_symbol attribute\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 2416, __extension__ __PRETTY_FUNCTION__))
2416 "Invalid number of arguments in an external_source_symbol attribute")(static_cast <bool> (checkAttributeAtMostNumArgs(S, AL,
3) && "Invalid number of arguments in an external_source_symbol attribute"
) ? void (0) : __assert_fail ("checkAttributeAtMostNumArgs(S, AL, 3) && \"Invalid number of arguments in an external_source_symbol attribute\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 2416, __extension__ __PRETTY_FUNCTION__))
;
2417
2418 StringRef Language;
2419 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(0)))
2420 Language = SE->getString();
2421 StringRef DefinedIn;
2422 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(1)))
2423 DefinedIn = SE->getString();
2424 bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
2425
2426 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2427 AL.getRange(), S.Context, Language, DefinedIn, IsGeneratedDeclaration,
2428 AL.getAttributeSpellingListIndex()));
2429}
2430
2431template <class T>
2432static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2433 typename T::VisibilityType value,
2434 unsigned attrSpellingListIndex) {
2435 T *existingAttr = D->getAttr<T>();
2436 if (existingAttr) {
2437 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2438 if (existingValue == value)
2439 return nullptr;
2440 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2441 S.Diag(range.getBegin(), diag::note_previous_attribute);
2442 D->dropAttr<T>();
2443 }
2444 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2445}
2446
2447VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2448 VisibilityAttr::VisibilityType Vis,
2449 unsigned AttrSpellingListIndex) {
2450 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2451 AttrSpellingListIndex);
2452}
2453
2454TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2455 TypeVisibilityAttr::VisibilityType Vis,
2456 unsigned AttrSpellingListIndex) {
2457 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2458 AttrSpellingListIndex);
2459}
2460
2461static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
2462 bool isTypeVisibility) {
2463 // Visibility attributes don't mean anything on a typedef.
2464 if (isa<TypedefNameDecl>(D)) {
2465 S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored)
2466 << AL.getName();
2467 return;
2468 }
2469
2470 // 'type_visibility' can only go on a type or namespace.
2471 if (isTypeVisibility &&
2472 !(isa<TagDecl>(D) ||
2473 isa<ObjCInterfaceDecl>(D) ||
2474 isa<NamespaceDecl>(D))) {
2475 S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2476 << AL.getName() << ExpectedTypeOrNamespace;
2477 return;
2478 }
2479
2480 // Check that the argument is a string literal.
2481 StringRef TypeStr;
2482 SourceLocation LiteralLoc;
2483 if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc))
2484 return;
2485
2486 VisibilityAttr::VisibilityType type;
2487 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2488 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
2489 << AL.getName() << TypeStr;
2490 return;
2491 }
2492
2493 // Complain about attempts to use protected visibility on targets
2494 // (like Darwin) that don't support it.
2495 if (type == VisibilityAttr::Protected &&
2496 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2497 S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
2498 type = VisibilityAttr::Default;
2499 }
2500
2501 unsigned Index = AL.getAttributeSpellingListIndex();
2502 Attr *newAttr;
2503 if (isTypeVisibility) {
2504 newAttr = S.mergeTypeVisibilityAttr(D, AL.getRange(),
2505 (TypeVisibilityAttr::VisibilityType) type,
2506 Index);
2507 } else {
2508 newAttr = S.mergeVisibilityAttr(D, AL.getRange(), type, Index);
2509 }
2510 if (newAttr)
2511 D->addAttr(newAttr);
2512}
2513
2514static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2515 const auto *M = cast<ObjCMethodDecl>(D);
2516 if (!AL.isArgIdent(0)) {
2517 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2518 << AL.getName() << 1 << AANT_ArgumentIdentifier;
2519 return;
2520 }
2521
2522 IdentifierLoc *IL = AL.getArgAsIdent(0);
2523 ObjCMethodFamilyAttr::FamilyKind F;
2524 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2525 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
2526 << AL.getName() << IL->Ident;
2527 return;
2528 }
2529
2530 if (F == ObjCMethodFamilyAttr::OMF_init &&
2531 !M->getReturnType()->isObjCObjectPointerType()) {
2532 S.Diag(M->getLocation(), diag::err_init_method_bad_return_type)
2533 << M->getReturnType();
2534 // Ignore the attribute.
2535 return;
2536 }
2537
2538 D->addAttr(new (S.Context) ObjCMethodFamilyAttr(
2539 AL.getRange(), S.Context, F, AL.getAttributeSpellingListIndex()));
2540}
2541
2542static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) {
2543 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2544 QualType T = TD->getUnderlyingType();
2545 if (!T->isCARCBridgableType()) {
2546 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2547 return;
2548 }
2549 }
2550 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2551 QualType T = PD->getType();
2552 if (!T->isCARCBridgableType()) {
2553 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2554 return;
2555 }
2556 }
2557 else {
2558 // It is okay to include this attribute on properties, e.g.:
2559 //
2560 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2561 //
2562 // In this case it follows tradition and suppresses an error in the above
2563 // case.
2564 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2565 }
2566 D->addAttr(::new (S.Context)
2567 ObjCNSObjectAttr(AL.getRange(), S.Context,
2568 AL.getAttributeSpellingListIndex()));
2569}
2570
2571static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) {
2572 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2573 QualType T = TD->getUnderlyingType();
2574 if (!T->isObjCObjectPointerType()) {
2575 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2576 return;
2577 }
2578 } else {
2579 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2580 return;
2581 }
2582 D->addAttr(::new (S.Context)
2583 ObjCIndependentClassAttr(AL.getRange(), S.Context,
2584 AL.getAttributeSpellingListIndex()));
2585}
2586
2587static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2588 if (!AL.isArgIdent(0)) {
2589 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2590 << AL.getName() << 1 << AANT_ArgumentIdentifier;
2591 return;
2592 }
2593
2594 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
2595 BlocksAttr::BlockType type;
2596 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2597 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
2598 << AL.getName() << II;
2599 return;
2600 }
2601
2602 D->addAttr(::new (S.Context)
2603 BlocksAttr(AL.getRange(), S.Context, type,
2604 AL.getAttributeSpellingListIndex()));
2605}
2606
2607static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2608 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2609 if (AL.getNumArgs() > 0) {
2610 Expr *E = AL.getArgAsExpr(0);
2611 llvm::APSInt Idx(32);
2612 if (E->isTypeDependent() || E->isValueDependent() ||
2613 !E->isIntegerConstantExpr(Idx, S.Context)) {
2614 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2615 << AL.getName() << 1 << AANT_ArgumentIntegerConstant
2616 << E->getSourceRange();
2617 return;
2618 }
2619
2620 if (Idx.isSigned() && Idx.isNegative()) {
2621 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2622 << E->getSourceRange();
2623 return;
2624 }
2625
2626 sentinel = Idx.getZExtValue();
2627 }
2628
2629 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2630 if (AL.getNumArgs() > 1) {
2631 Expr *E = AL.getArgAsExpr(1);
2632 llvm::APSInt Idx(32);
2633 if (E->isTypeDependent() || E->isValueDependent() ||
2634 !E->isIntegerConstantExpr(Idx, S.Context)) {
2635 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2636 << AL.getName() << 2 << AANT_ArgumentIntegerConstant
2637 << E->getSourceRange();
2638 return;
2639 }
2640 nullPos = Idx.getZExtValue();
2641
2642 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2643 // FIXME: This error message could be improved, it would be nice
2644 // to say what the bounds actually are.
2645 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2646 << E->getSourceRange();
2647 return;
2648 }
2649 }
2650
2651 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2652 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2653 if (isa<FunctionNoProtoType>(FT)) {
2654 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2655 return;
2656 }
2657
2658 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2659 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2660 return;
2661 }
2662 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
2663 if (!MD->isVariadic()) {
2664 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2665 return;
2666 }
2667 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
2668 if (!BD->isVariadic()) {
2669 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2670 return;
2671 }
2672 } else if (const auto *V = dyn_cast<VarDecl>(D)) {
2673 QualType Ty = V->getType();
2674 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2675 const FunctionType *FT = Ty->isFunctionPointerType()
2676 ? D->getFunctionType()
2677 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2678 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2679 int m = Ty->isFunctionPointerType() ? 0 : 1;
2680 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2681 return;
2682 }
2683 } else {
2684 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2685 << AL.getName() << ExpectedFunctionMethodOrBlock;
2686 return;
2687 }
2688 } else {
2689 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2690 << AL.getName() << ExpectedFunctionMethodOrBlock;
2691 return;
2692 }
2693 D->addAttr(::new (S.Context)
2694 SentinelAttr(AL.getRange(), S.Context, sentinel, nullPos,
2695 AL.getAttributeSpellingListIndex()));
2696}
2697
2698static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
2699 if (D->getFunctionType() &&
2700 D->getFunctionType()->getReturnType()->isVoidType()) {
2701 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method)
2702 << AL.getName() << 0;
2703 return;
2704 }
2705 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
2706 if (MD->getReturnType()->isVoidType()) {
2707 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method)
2708 << AL.getName() << 1;
2709 return;
2710 }
2711
2712 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2713 // about using it as an extension.
2714 if (!S.getLangOpts().CPlusPlus17 && AL.isCXX11Attribute() &&
2715 !AL.getScopeName())
2716 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL.getName();
2717
2718 D->addAttr(::new (S.Context)
2719 WarnUnusedResultAttr(AL.getRange(), S.Context,
2720 AL.getAttributeSpellingListIndex()));
2721}
2722
2723static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2724 // weak_import only applies to variable & function declarations.
2725 bool isDef = false;
2726 if (!D->canBeWeakImported(isDef)) {
2727 if (isDef)
2728 S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
2729 << "weak_import";
2730 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2731 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2732 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2733 // Nothing to warn about here.
2734 } else
2735 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2736 << AL.getName() << ExpectedVariableOrFunction;
2737
2738 return;
2739 }
2740
2741 D->addAttr(::new (S.Context)
2742 WeakImportAttr(AL.getRange(), S.Context,
2743 AL.getAttributeSpellingListIndex()));
2744}
2745
2746// Handles reqd_work_group_size and work_group_size_hint.
2747template <typename WorkGroupAttr>
2748static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2749 uint32_t WGSize[3];
2750 for (unsigned i = 0; i < 3; ++i) {
2751 const Expr *E = AL.getArgAsExpr(i);
2752 if (!checkUInt32Argument(S, AL, E, WGSize[i], i))
2753 return;
2754 if (WGSize[i] == 0) {
2755 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2756 << AL.getName() << E->getSourceRange();
2757 return;
2758 }
2759 }
2760
2761 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2762 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2763 Existing->getYDim() == WGSize[1] &&
2764 Existing->getZDim() == WGSize[2]))
2765 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL.getName();
2766
2767 D->addAttr(::new (S.Context) WorkGroupAttr(AL.getRange(), S.Context,
2768 WGSize[0], WGSize[1], WGSize[2],
2769 AL.getAttributeSpellingListIndex()));
2770}
2771
2772// Handles intel_reqd_sub_group_size.
2773static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2774 uint32_t SGSize;
2775 const Expr *E = AL.getArgAsExpr(0);
2776 if (!checkUInt32Argument(S, AL, E, SGSize))
2777 return;
2778 if (SGSize == 0) {
2779 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2780 << AL.getName() << E->getSourceRange();
2781 return;
2782 }
2783
2784 OpenCLIntelReqdSubGroupSizeAttr *Existing =
2785 D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
2786 if (Existing && Existing->getSubGroupSize() != SGSize)
2787 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL.getName();
2788
2789 D->addAttr(::new (S.Context) OpenCLIntelReqdSubGroupSizeAttr(
2790 AL.getRange(), S.Context, SGSize,
2791 AL.getAttributeSpellingListIndex()));
2792}
2793
2794static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
2795 if (!AL.hasParsedType()) {
2796 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
2797 << AL.getName() << 1;
2798 return;
2799 }
2800
2801 TypeSourceInfo *ParmTSI = nullptr;
2802 QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
2803 assert(ParmTSI && "no type source info for attribute argument")(static_cast <bool> (ParmTSI && "no type source info for attribute argument"
) ? void (0) : __assert_fail ("ParmTSI && \"no type source info for attribute argument\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 2803, __extension__ __PRETTY_FUNCTION__))
;
2804
2805 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2806 (ParmType->isBooleanType() ||
2807 !ParmType->isIntegralType(S.getASTContext()))) {
2808 S.Diag(AL.getLoc(), diag::err_attribute_argument_vec_type_hint)
2809 << ParmType;
2810 return;
2811 }
2812
2813 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2814 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2815 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL.getName();
2816 return;
2817 }
2818 }
2819
2820 D->addAttr(::new (S.Context) VecTypeHintAttr(AL.getLoc(), S.Context,
2821 ParmTSI,
2822 AL.getAttributeSpellingListIndex()));
2823}
2824
2825SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2826 StringRef Name,
2827 unsigned AttrSpellingListIndex) {
2828 // Explicit or partial specializations do not inherit
2829 // the section attribute from the primary template.
2830 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2831 if (AttrSpellingListIndex == SectionAttr::Declspec_allocate &&
2832 FD->isFunctionTemplateSpecialization())
2833 return nullptr;
2834 }
2835 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2836 if (ExistingAttr->getName() == Name)
2837 return nullptr;
2838 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
2839 << 1 /*section*/;
2840 Diag(Range.getBegin(), diag::note_previous_attribute);
2841 return nullptr;
2842 }
2843 return ::new (Context) SectionAttr(Range, Context, Name,
2844 AttrSpellingListIndex);
2845}
2846
2847bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2848 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2849 if (!Error.empty()) {
2850 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error
2851 << 1 /*'section'*/;
2852 return false;
2853 }
2854 return true;
2855}
2856
2857static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2858 // Make sure that there is a string literal as the sections's single
2859 // argument.
2860 StringRef Str;
2861 SourceLocation LiteralLoc;
2862 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
2863 return;
2864
2865 if (!S.checkSectionName(LiteralLoc, Str))
2866 return;
2867
2868 // If the target wants to validate the section specifier, make it happen.
2869 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
2870 if (!Error.empty()) {
2871 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2872 << Error;
2873 return;
2874 }
2875
2876 unsigned Index = AL.getAttributeSpellingListIndex();
2877 SectionAttr *NewAttr = S.mergeSectionAttr(D, AL.getRange(), Str, Index);
2878 if (NewAttr)
2879 D->addAttr(NewAttr);
2880}
2881
2882static bool checkCodeSegName(Sema&S, SourceLocation LiteralLoc, StringRef CodeSegName) {
2883 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(CodeSegName);
2884 if (!Error.empty()) {
2885 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error
2886 << 0 /*'code-seg'*/;
2887 return false;
2888 }
2889 return true;
2890}
2891
2892CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, SourceRange Range,
2893 StringRef Name,
2894 unsigned AttrSpellingListIndex) {
2895 // Explicit or partial specializations do not inherit
2896 // the code_seg attribute from the primary template.
2897 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2898 if (FD->isFunctionTemplateSpecialization())
2899 return nullptr;
2900 }
2901 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
2902 if (ExistingAttr->getName() == Name)
2903 return nullptr;
2904 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
2905 << 0 /*codeseg*/;
2906 Diag(Range.getBegin(), diag::note_previous_attribute);
2907 return nullptr;
2908 }
2909 return ::new (Context) CodeSegAttr(Range, Context, Name,
2910 AttrSpellingListIndex);
2911}
2912
2913static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2914 StringRef Str;
2915 SourceLocation LiteralLoc;
2916 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
2917 return;
2918 if (!checkCodeSegName(S, LiteralLoc, Str))
2919 return;
2920 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
2921 if (!ExistingAttr->isImplicit()) {
2922 S.Diag(AL.getLoc(),
2923 ExistingAttr->getName() == Str
2924 ? diag::warn_duplicate_codeseg_attribute
2925 : diag::err_conflicting_codeseg_attribute);
2926 return;
2927 }
2928 D->dropAttr<CodeSegAttr>();
2929 }
2930 if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL.getRange(), Str,
2931 AL.getAttributeSpellingListIndex()))
2932 D->addAttr(CSA);
2933}
2934
2935// Check for things we'd like to warn about. Multiversioning issues are
2936// handled later in the process, once we know how many exist.
2937bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
2938 enum FirstParam { Unsupported, Duplicate };
2939 enum SecondParam { None, Architecture };
2940 for (auto Str : {"tune=", "fpmath="})
2941 if (AttrStr.find(Str) != StringRef::npos)
2942 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
2943 << Unsupported << None << Str;
2944
2945 TargetAttr::ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr);
2946
2947 if (!ParsedAttrs.Architecture.empty() &&
2948 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture))
2949 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
2950 << Unsupported << Architecture << ParsedAttrs.Architecture;
2951
2952 if (ParsedAttrs.DuplicateArchitecture)
2953 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
2954 << Duplicate << None << "arch=";
2955
2956 for (const auto &Feature : ParsedAttrs.Features) {
2957 auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
2958 if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
2959 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
2960 << Unsupported << None << CurFeature;
2961 }
2962
2963 return false;
2964}
2965
2966static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2967 StringRef Str;
2968 SourceLocation LiteralLoc;
2969 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
2970 S.checkTargetAttr(LiteralLoc, Str))
2971 return;
2972
2973 unsigned Index = AL.getAttributeSpellingListIndex();
2974 TargetAttr *NewAttr =
2975 ::new (S.Context) TargetAttr(AL.getRange(), S.Context, Str, Index);
2976 D->addAttr(NewAttr);
2977}
2978
2979static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2980 Expr *E = AL.getArgAsExpr(0);
2981 uint32_t VecWidth;
2982 if (!checkUInt32Argument(S, AL, E, VecWidth)) {
2983 AL.setInvalid();
2984 return;
2985 }
2986
2987 MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
2988 if (Existing && Existing->getVectorWidth() != VecWidth) {
2989 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL.getName();
2990 return;
2991 }
2992
2993 D->addAttr(::new (S.Context)
2994 MinVectorWidthAttr(AL.getRange(), S.Context, VecWidth,
2995 AL.getAttributeSpellingListIndex()));
2996}
2997
2998static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2999 Expr *E = AL.getArgAsExpr(0);
3000 SourceLocation Loc = E->getExprLoc();
3001 FunctionDecl *FD = nullptr;
3002 DeclarationNameInfo NI;
3003
3004 // gcc only allows for simple identifiers. Since we support more than gcc, we
3005 // will warn the user.
3006 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3007 if (DRE->hasQualifier())
3008 S.Diag(Loc, diag::warn_cleanup_ext);
3009 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3010 NI = DRE->getNameInfo();
3011 if (!FD) {
3012 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3013 << NI.getName();
3014 return;
3015 }
3016 } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3017 if (ULE->hasExplicitTemplateArgs())
3018 S.Diag(Loc, diag::warn_cleanup_ext);
3019 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
3020 NI = ULE->getNameInfo();
3021 if (!FD) {
3022 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3023 << NI.getName();
3024 if (ULE->getType() == S.Context.OverloadTy)
3025 S.NoteAllOverloadCandidates(ULE);
3026 return;
3027 }
3028 } else {
3029 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3030 return;
3031 }
3032
3033 if (FD->getNumParams() != 1) {
3034 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3035 << NI.getName();
3036 return;
3037 }
3038
3039 // We're currently more strict than GCC about what function types we accept.
3040 // If this ever proves to be a problem it should be easy to fix.
3041 QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
3042 QualType ParamTy = FD->getParamDecl(0)->getType();
3043 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
3044 ParamTy, Ty) != Sema::Compatible) {
3045 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3046 << NI.getName() << ParamTy << Ty;
3047 return;
3048 }
3049
3050 D->addAttr(::new (S.Context)
3051 CleanupAttr(AL.getRange(), S.Context, FD,
3052 AL.getAttributeSpellingListIndex()));
3053}
3054
3055static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3056 const ParsedAttr &AL) {
3057 if (!AL.isArgIdent(0)) {
3058 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3059 << AL.getName() << 0 << AANT_ArgumentIdentifier;
3060 return;
3061 }
3062
3063 EnumExtensibilityAttr::Kind ExtensibilityKind;
3064 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3065 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3066 ExtensibilityKind)) {
3067 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
3068 << AL.getName() << II;
3069 return;
3070 }
3071
3072 D->addAttr(::new (S.Context) EnumExtensibilityAttr(
3073 AL.getRange(), S.Context, ExtensibilityKind,
3074 AL.getAttributeSpellingListIndex()));
3075}
3076
3077/// Handle __attribute__((format_arg((idx)))) attribute based on
3078/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3079static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3080 Expr *IdxExpr = AL.getArgAsExpr(0);
3081 ParamIdx Idx;
3082 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx))
3083 return;
3084
3085 // Make sure the format string is really a string.
3086 QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
3087
3088 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3089 if (NotNSStringTy &&
3090 !isCFStringType(Ty, S.Context) &&
3091 (!Ty->isPointerType() ||
3092 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3093 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3094 << "a string type" << IdxExpr->getSourceRange()
3095 << getFunctionOrMethodParamRange(D, 0);
3096 return;
3097 }
3098 Ty = getFunctionOrMethodResultType(D);
3099 if (!isNSStringType(Ty, S.Context) &&
3100 !isCFStringType(Ty, S.Context) &&
3101 (!Ty->isPointerType() ||
3102 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3103 S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
3104 << (NotNSStringTy ? "string type" : "NSString")
3105 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3106 return;
3107 }
3108
3109 D->addAttr(::new (S.Context) FormatArgAttr(
3110 AL.getRange(), S.Context, Idx, AL.getAttributeSpellingListIndex()));
3111}
3112
3113enum FormatAttrKind {
3114 CFStringFormat,
3115 NSStringFormat,
3116 StrftimeFormat,
3117 SupportedFormat,
3118 IgnoredFormat,
3119 InvalidFormat
3120};
3121
3122/// getFormatAttrKind - Map from format attribute names to supported format
3123/// types.
3124static FormatAttrKind getFormatAttrKind(StringRef Format) {
3125 return llvm::StringSwitch<FormatAttrKind>(Format)
3126 // Check for formats that get handled specially.
3127 .Case("NSString", NSStringFormat)
3128 .Case("CFString", CFStringFormat)
3129 .Case("strftime", StrftimeFormat)
3130
3131 // Otherwise, check for supported formats.
3132 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3133 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3134 .Case("kprintf", SupportedFormat) // OpenBSD.
3135 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3136 .Case("os_trace", SupportedFormat)
3137 .Case("os_log", SupportedFormat)
3138
3139 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3140 .Default(InvalidFormat);
3141}
3142
3143/// Handle __attribute__((init_priority(priority))) attributes based on
3144/// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3145static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3146 if (!S.getLangOpts().CPlusPlus) {
3147 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL.getName();
3148 return;
3149 }
3150
3151 if (S.getCurFunctionOrMethodDecl()) {
3152 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3153 AL.setInvalid();
3154 return;
3155 }
3156 QualType T = cast<VarDecl>(D)->getType();
3157 if (S.Context.getAsArrayType(T))
3158 T = S.Context.getBaseElementType(T);
3159 if (!T->getAs<RecordType>()) {
3160 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3161 AL.setInvalid();
3162 return;
3163 }
3164
3165 Expr *E = AL.getArgAsExpr(0);
3166 uint32_t prioritynum;
3167 if (!checkUInt32Argument(S, AL, E, prioritynum)) {
3168 AL.setInvalid();
3169 return;
3170 }
3171
3172 if (prioritynum < 101 || prioritynum > 65535) {
3173 S.Diag(AL.getLoc(), diag::err_attribute_argument_outof_range)
3174 << E->getSourceRange() << AL.getName() << 101 << 65535;
3175 AL.setInvalid();
3176 return;
3177 }
3178 D->addAttr(::new (S.Context)
3179 InitPriorityAttr(AL.getRange(), S.Context, prioritynum,
3180 AL.getAttributeSpellingListIndex()));
3181}
3182
3183FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
3184 IdentifierInfo *Format, int FormatIdx,
3185 int FirstArg,
3186 unsigned AttrSpellingListIndex) {
3187 // Check whether we already have an equivalent format attribute.
3188 for (auto *F : D->specific_attrs<FormatAttr>()) {
3189 if (F->getType() == Format &&
3190 F->getFormatIdx() == FormatIdx &&
3191 F->getFirstArg() == FirstArg) {
3192 // If we don't have a valid location for this attribute, adopt the
3193 // location.
3194 if (F->getLocation().isInvalid())
3195 F->setRange(Range);
3196 return nullptr;
3197 }
3198 }
3199
3200 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
3201 FirstArg, AttrSpellingListIndex);
3202}
3203
3204/// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3205/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3206static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3207 if (!AL.isArgIdent(0)) {
3208 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3209 << AL.getName() << 1 << AANT_ArgumentIdentifier;
3210 return;
3211 }
3212
3213 // In C++ the implicit 'this' function parameter also counts, and they are
3214 // counted from one.
3215 bool HasImplicitThisParam = isInstanceMethod(D);
3216 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3217
3218 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3219 StringRef Format = II->getName();
3220
3221 if (normalizeName(Format)) {
3222 // If we've modified the string name, we need a new identifier for it.
3223 II = &S.Context.Idents.get(Format);
3224 }
3225
3226 // Check for supported formats.
3227 FormatAttrKind Kind = getFormatAttrKind(Format);
3228
3229 if (Kind == IgnoredFormat)
3230 return;
3231
3232 if (Kind == InvalidFormat) {
3233 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
3234 << AL.getName() << II->getName();
3235 return;
3236 }
3237
3238 // checks for the 2nd argument
3239 Expr *IdxExpr = AL.getArgAsExpr(1);
3240 uint32_t Idx;
3241 if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2))
3242 return;
3243
3244 if (Idx < 1 || Idx > NumArgs) {
3245 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3246 << AL.getName() << 2 << IdxExpr->getSourceRange();
3247 return;
3248 }
3249
3250 // FIXME: Do we need to bounds check?
3251 unsigned ArgIdx = Idx - 1;
3252
3253 if (HasImplicitThisParam) {
3254 if (ArgIdx == 0) {
3255 S.Diag(AL.getLoc(),
3256 diag::err_format_attribute_implicit_this_format_string)
3257 << IdxExpr->getSourceRange();
3258 return;
3259 }
3260 ArgIdx--;
3261 }
3262
3263 // make sure the format string is really a string
3264 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3265
3266 if (Kind == CFStringFormat) {
3267 if (!isCFStringType(Ty, S.Context)) {
3268 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3269 << "a CFString" << IdxExpr->getSourceRange()
3270 << getFunctionOrMethodParamRange(D, ArgIdx);
3271 return;
3272 }
3273 } else if (Kind == NSStringFormat) {
3274 // FIXME: do we need to check if the type is NSString*? What are the
3275 // semantics?
3276 if (!isNSStringType(Ty, S.Context)) {
3277 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3278 << "an NSString" << IdxExpr->getSourceRange()
3279 << getFunctionOrMethodParamRange(D, ArgIdx);
3280 return;
3281 }
3282 } else if (!Ty->isPointerType() ||
3283 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
3284 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3285 << "a string type" << IdxExpr->getSourceRange()
3286 << getFunctionOrMethodParamRange(D, ArgIdx);
3287 return;
3288 }
3289
3290 // check the 3rd argument
3291 Expr *FirstArgExpr = AL.getArgAsExpr(2);
3292 uint32_t FirstArg;
3293 if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3))
3294 return;
3295
3296 // check if the function is variadic if the 3rd argument non-zero
3297 if (FirstArg != 0) {
3298 if (isFunctionOrMethodVariadic(D)) {
3299 ++NumArgs; // +1 for ...
3300 } else {
3301 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3302 return;
3303 }
3304 }
3305
3306 // strftime requires FirstArg to be 0 because it doesn't read from any
3307 // variable the input is just the current time + the format string.
3308 if (Kind == StrftimeFormat) {
3309 if (FirstArg != 0) {
3310 S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
3311 << FirstArgExpr->getSourceRange();
3312 return;
3313 }
3314 // if 0 it disables parameter checking (to use with e.g. va_list)
3315 } else if (FirstArg != 0 && FirstArg != NumArgs) {
3316 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3317 << AL.getName() << 3 << FirstArgExpr->getSourceRange();
3318 return;
3319 }
3320
3321 FormatAttr *NewAttr = S.mergeFormatAttr(D, AL.getRange(), II,
3322 Idx, FirstArg,
3323 AL.getAttributeSpellingListIndex());
3324 if (NewAttr)
3325 D->addAttr(NewAttr);
3326}
3327
3328static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3329 // Try to find the underlying union declaration.
3330 RecordDecl *RD = nullptr;
3331 const auto *TD = dyn_cast<TypedefNameDecl>(D);
3332 if (TD && TD->getUnderlyingType()->isUnionType())
3333 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3334 else
3335 RD = dyn_cast<RecordDecl>(D);
3336
3337 if (!RD || !RD->isUnion()) {
3338 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
3339 << AL.getName() << ExpectedUnion;
3340 return;
3341 }
3342
3343 if (!RD->isCompleteDefinition()) {
3344 if (!RD->isBeingDefined())
3345 S.Diag(AL.getLoc(),
3346 diag::warn_transparent_union_attribute_not_definition);
3347 return;
3348 }
3349
3350 RecordDecl::field_iterator Field = RD->field_begin(),
3351 FieldEnd = RD->field_end();
3352 if (Field == FieldEnd) {
3353 S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3354 return;
3355 }
3356
3357 FieldDecl *FirstField = *Field;
3358 QualType FirstType = FirstField->getType();
3359 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3360 S.Diag(FirstField->getLocation(),
3361 diag::warn_transparent_union_attribute_floating)
3362 << FirstType->isVectorType() << FirstType;
3363 return;
3364 }
3365
3366 if (FirstType->isIncompleteType())
3367 return;
3368 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3369 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3370 for (; Field != FieldEnd; ++Field) {
3371 QualType FieldType = Field->getType();
3372 if (FieldType->isIncompleteType())
3373 return;
3374 // FIXME: this isn't fully correct; we also need to test whether the
3375 // members of the union would all have the same calling convention as the
3376 // first member of the union. Checking just the size and alignment isn't
3377 // sufficient (consider structs passed on the stack instead of in registers
3378 // as an example).
3379 if (S.Context.getTypeSize(FieldType) != FirstSize ||
3380 S.Context.getTypeAlign(FieldType) > FirstAlign) {
3381 // Warn if we drop the attribute.
3382 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3383 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3384 : S.Context.getTypeAlign(FieldType);
3385 S.Diag(Field->getLocation(),
3386 diag::warn_transparent_union_attribute_field_size_align)
3387 << isSize << Field->getDeclName() << FieldBits;
3388 unsigned FirstBits = isSize? FirstSize : FirstAlign;
3389 S.Diag(FirstField->getLocation(),
3390 diag::note_transparent_union_first_field_size_align)
3391 << isSize << FirstBits;
3392 return;
3393 }
3394 }
3395
3396 RD->addAttr(::new (S.Context)
3397 TransparentUnionAttr(AL.getRange(), S.Context,
3398 AL.getAttributeSpellingListIndex()));
3399}
3400
3401static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3402 // Make sure that there is a string literal as the annotation's single
3403 // argument.
3404 StringRef Str;
3405 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
3406 return;
3407
3408 // Don't duplicate annotations that are already set.
3409 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3410 if (I->getAnnotation() == Str)
3411 return;
3412 }
3413
3414 D->addAttr(::new (S.Context)
3415 AnnotateAttr(AL.getRange(), S.Context, Str,
3416 AL.getAttributeSpellingListIndex()));
3417}
3418
3419static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3420 S.AddAlignValueAttr(AL.getRange(), D, AL.getArgAsExpr(0),
3421 AL.getAttributeSpellingListIndex());
3422}
3423
3424void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3425 unsigned SpellingListIndex) {
3426 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3427 SourceLocation AttrLoc = AttrRange.getBegin();
3428
3429 QualType T;
3430 if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
3431 T = TD->getUnderlyingType();
3432 else if (const auto *VD = dyn_cast<ValueDecl>(D))
3433 T = VD->getType();
3434 else
3435 llvm_unreachable("Unknown decl type for align_value")::llvm::llvm_unreachable_internal("Unknown decl type for align_value"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 3435)
;
3436
3437 if (!T->isDependentType() && !T->isAnyPointerType() &&
3438 !T->isReferenceType() && !T->isMemberPointerType()) {
3439 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3440 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3441 return;
3442 }
3443
3444 if (!E->isValueDependent()) {
3445 llvm::APSInt Alignment;
3446 ExprResult ICE
3447 = VerifyIntegerConstantExpression(E, &Alignment,
3448 diag::err_align_value_attribute_argument_not_int,
3449 /*AllowFold*/ false);
3450 if (ICE.isInvalid())
3451 return;
3452
3453 if (!Alignment.isPowerOf2()) {
3454 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3455 << E->getSourceRange();
3456 return;
3457 }
3458
3459 D->addAttr(::new (Context)
3460 AlignValueAttr(AttrRange, Context, ICE.get(),
3461 SpellingListIndex));
3462 return;
3463 }
3464
3465 // Save dependent expressions in the AST to be instantiated.
3466 D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
3467}
3468
3469static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3470 // check the attribute arguments.
3471 if (AL.getNumArgs() > 1) {
3472 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3473 << AL.getName() << 1;
3474 return;
3475 }
3476
3477 if (AL.getNumArgs() == 0) {
3478 D->addAttr(::new (S.Context) AlignedAttr(AL.getRange(), S.Context,
3479 true, nullptr, AL.getAttributeSpellingListIndex()));
3480 return;
3481 }
3482
3483 Expr *E = AL.getArgAsExpr(0);
3484 if (AL.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3485 S.Diag(AL.getEllipsisLoc(),
3486 diag::err_pack_expansion_without_parameter_packs);
3487 return;
3488 }
3489
3490 if (!AL.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3491 return;
3492
3493 S.AddAlignedAttr(AL.getRange(), D, E, AL.getAttributeSpellingListIndex(),
3494 AL.isPackExpansion());
3495}
3496
3497void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
3498 unsigned SpellingListIndex, bool IsPackExpansion) {
3499 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3500 SourceLocation AttrLoc = AttrRange.getBegin();
3501
3502 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3503 if (TmpAttr.isAlignas()) {
3504 // C++11 [dcl.align]p1:
3505 // An alignment-specifier may be applied to a variable or to a class
3506 // data member, but it shall not be applied to a bit-field, a function
3507 // parameter, the formal parameter of a catch clause, or a variable
3508 // declared with the register storage class specifier. An
3509 // alignment-specifier may also be applied to the declaration of a class
3510 // or enumeration type.
3511 // C11 6.7.5/2:
3512 // An alignment attribute shall not be specified in a declaration of
3513 // a typedef, or a bit-field, or a function, or a parameter, or an
3514 // object declared with the register storage-class specifier.
3515 int DiagKind = -1;
3516 if (isa<ParmVarDecl>(D)) {
3517 DiagKind = 0;
3518 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
3519 if (VD->getStorageClass() == SC_Register)
3520 DiagKind = 1;
3521 if (VD->isExceptionVariable())
3522 DiagKind = 2;
3523 } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
3524 if (FD->isBitField())
3525 DiagKind = 3;
3526 } else if (!isa<TagDecl>(D)) {
3527 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3528 << (TmpAttr.isC11() ? ExpectedVariableOrField
3529 : ExpectedVariableFieldOrTag);
3530 return;
3531 }
3532 if (DiagKind != -1) {
3533 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3534 << &TmpAttr << DiagKind;
3535 return;
3536 }
3537 }
3538
3539 if (E->isValueDependent()) {
3540 // We can't support a dependent alignment on a non-dependent type,
3541 // because we have no way to model that a type is "alignment-dependent"
3542 // but not dependent in any other way.
3543 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3544 if (!TND->getUnderlyingType()->isDependentType()) {
3545 Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
3546 << E->getSourceRange();
3547 return;
3548 }
3549 }
3550
3551 // Save dependent expressions in the AST to be instantiated.
3552 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3553 AA->setPackExpansion(IsPackExpansion);
3554 D->addAttr(AA);
3555 return;
3556 }
3557
3558 // FIXME: Cache the number on the AL object?
3559 llvm::APSInt Alignment;
3560 ExprResult ICE
3561 = VerifyIntegerConstantExpression(E, &Alignment,
3562 diag::err_aligned_attribute_argument_not_int,
3563 /*AllowFold*/ false);
3564 if (ICE.isInvalid())
3565 return;
3566
3567 uint64_t AlignVal = Alignment.getZExtValue();
3568
3569 // C++11 [dcl.align]p2:
3570 // -- if the constant expression evaluates to zero, the alignment
3571 // specifier shall have no effect
3572 // C11 6.7.5p6:
3573 // An alignment specification of zero has no effect.
3574 if (!(TmpAttr.isAlignas() && !Alignment)) {
3575 if (!llvm::isPowerOf2_64(AlignVal)) {
3576 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3577 << E->getSourceRange();
3578 return;
3579 }
3580 }
3581
3582 // Alignment calculations can wrap around if it's greater than 2**28.
3583 unsigned MaxValidAlignment =
3584 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3585 : 268435456;
3586 if (AlignVal > MaxValidAlignment) {
3587 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3588 << E->getSourceRange();
3589 return;
3590 }
3591
3592 if (Context.getTargetInfo().isTLSSupported()) {
3593 unsigned MaxTLSAlign =
3594 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3595 .getQuantity();
3596 const auto *VD = dyn_cast<VarDecl>(D);
3597 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3598 VD->getTLSKind() != VarDecl::TLS_None) {
3599 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3600 << (unsigned)AlignVal << VD << MaxTLSAlign;
3601 return;
3602 }
3603 }
3604
3605 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3606 ICE.get(), SpellingListIndex);
3607 AA->setPackExpansion(IsPackExpansion);
3608 D->addAttr(AA);
3609}
3610
3611void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3612 unsigned SpellingListIndex, bool IsPackExpansion) {
3613 // FIXME: Cache the number on the AL object if non-dependent?
3614 // FIXME: Perform checking of type validity
3615 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3616 SpellingListIndex);
3617 AA->setPackExpansion(IsPackExpansion);
3618 D->addAttr(AA);
3619}
3620
3621void Sema::CheckAlignasUnderalignment(Decl *D) {
3622 assert(D->hasAttrs() && "no attributes on decl")(static_cast <bool> (D->hasAttrs() && "no attributes on decl"
) ? void (0) : __assert_fail ("D->hasAttrs() && \"no attributes on decl\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 3622, __extension__ __PRETTY_FUNCTION__))
;
3623
3624 QualType UnderlyingTy, DiagTy;
3625 if (const auto *VD = dyn_cast<ValueDecl>(D)) {
3626 UnderlyingTy = DiagTy = VD->getType();
3627 } else {
3628 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3629 if (const auto *ED = dyn_cast<EnumDecl>(D))
3630 UnderlyingTy = ED->getIntegerType();
3631 }
3632 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3633 return;
3634
3635 // C++11 [dcl.align]p5, C11 6.7.5/4:
3636 // The combined effect of all alignment attributes in a declaration shall
3637 // not specify an alignment that is less strict than the alignment that
3638 // would otherwise be required for the entity being declared.
3639 AlignedAttr *AlignasAttr = nullptr;
3640 unsigned Align = 0;
3641 for (auto *I : D->specific_attrs<AlignedAttr>()) {
3642 if (I->isAlignmentDependent())
3643 return;
3644 if (I->isAlignas())
3645 AlignasAttr = I;
3646 Align = std::max(Align, I->getAlignment(Context));
3647 }
3648
3649 if (AlignasAttr && Align) {
3650 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3651 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3652 if (NaturalAlign > RequestedAlign)
3653 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3654 << DiagTy << (unsigned)NaturalAlign.getQuantity();
3655 }
3656}
3657
3658bool Sema::checkMSInheritanceAttrOnDefinition(
3659 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3660 MSInheritanceAttr::Spelling SemanticSpelling) {
3661 assert(RD->hasDefinition() && "RD has no definition!")(static_cast <bool> (RD->hasDefinition() && "RD has no definition!"
) ? void (0) : __assert_fail ("RD->hasDefinition() && \"RD has no definition!\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 3661, __extension__ __PRETTY_FUNCTION__))
;
3662
3663 // We may not have seen base specifiers or any virtual methods yet. We will
3664 // have to wait until the record is defined to catch any mismatches.
3665 if (!RD->getDefinition()->isCompleteDefinition())
3666 return false;
3667
3668 // The unspecified model never matches what a definition could need.
3669 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3670 return false;
3671
3672 if (BestCase) {
3673 if (RD->calculateInheritanceModel() == SemanticSpelling)
3674 return false;
3675 } else {
3676 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3677 return false;
3678 }
3679
3680 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3681 << 0 /*definition*/;
3682 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3683 << RD->getNameAsString();
3684 return true;
3685}
3686
3687/// parseModeAttrArg - Parses attribute mode string and returns parsed type
3688/// attribute.
3689static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3690 bool &IntegerMode, bool &ComplexMode) {
3691 IntegerMode = true;
3692 ComplexMode = false;
3693 switch (Str.size()) {
3694 case 2:
3695 switch (Str[0]) {
3696 case 'Q':
3697 DestWidth = 8;
3698 break;
3699 case 'H':
3700 DestWidth = 16;
3701 break;
3702 case 'S':
3703 DestWidth = 32;
3704 break;
3705 case 'D':
3706 DestWidth = 64;
3707 break;
3708 case 'X':
3709 DestWidth = 96;
3710 break;
3711 case 'T':
3712 DestWidth = 128;
3713 break;
3714 }
3715 if (Str[1] == 'F') {
3716 IntegerMode = false;
3717 } else if (Str[1] == 'C') {
3718 IntegerMode = false;
3719 ComplexMode = true;
3720 } else if (Str[1] != 'I') {
3721 DestWidth = 0;
3722 }
3723 break;
3724 case 4:
3725 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3726 // pointer on PIC16 and other embedded platforms.
3727 if (Str == "word")
3728 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
3729 else if (Str == "byte")
3730 DestWidth = S.Context.getTargetInfo().getCharWidth();
3731 break;
3732 case 7:
3733 if (Str == "pointer")
3734 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3735 break;
3736 case 11:
3737 if (Str == "unwind_word")
3738 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3739 break;
3740 }
3741}
3742
3743/// handleModeAttr - This attribute modifies the width of a decl with primitive
3744/// type.
3745///
3746/// Despite what would be logical, the mode attribute is a decl attribute, not a
3747/// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3748/// HImode, not an intermediate pointer.
3749static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3750 // This attribute isn't documented, but glibc uses it. It changes
3751 // the width of an int or unsigned int to the specified size.
3752 if (!AL.isArgIdent(0)) {
3753 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) << AL.getName()
3754 << AANT_ArgumentIdentifier;
3755 return;
3756 }
3757
3758 IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
3759
3760 S.AddModeAttr(AL.getRange(), D, Name, AL.getAttributeSpellingListIndex());
3761}
3762
3763void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
3764 unsigned SpellingListIndex, bool InInstantiation) {
3765 StringRef Str = Name->getName();
3766 normalizeName(Str);
3767 SourceLocation AttrLoc = AttrRange.getBegin();
3768
3769 unsigned DestWidth = 0;
3770 bool IntegerMode = true;
3771 bool ComplexMode = false;
3772 llvm::APInt VectorSize(64, 0);
3773 if (Str.size() >= 4 && Str[0] == 'V') {
3774 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3775 size_t StrSize = Str.size();
3776 size_t VectorStringLength = 0;
3777 while ((VectorStringLength + 1) < StrSize &&
3778 isdigit(Str[VectorStringLength + 1]))
3779 ++VectorStringLength;
3780 if (VectorStringLength &&
3781 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3782 VectorSize.isPowerOf2()) {
3783 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
3784 IntegerMode, ComplexMode);
3785 // Avoid duplicate warning from template instantiation.
3786 if (!InInstantiation)
3787 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
3788 } else {
3789 VectorSize = 0;
3790 }
3791 }
3792
3793 if (!VectorSize)
3794 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
3795
3796 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3797 // and friends, at least with glibc.
3798 // FIXME: Make sure floating-point mappings are accurate
3799 // FIXME: Support XF and TF types
3800 if (!DestWidth) {
3801 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3802 return;
3803 }
3804
3805 QualType OldTy;
3806 if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
3807 OldTy = TD->getUnderlyingType();
3808 else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
3809 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
3810 // Try to get type from enum declaration, default to int.
3811 OldTy = ED->getIntegerType();
3812 if (OldTy.isNull())
3813 OldTy = Context.IntTy;
3814 } else
3815 OldTy = cast<ValueDecl>(D)->getType();
3816
3817 if (OldTy->isDependentType()) {
3818 D->addAttr(::new (Context)
3819 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3820 return;
3821 }
3822
3823 // Base type can also be a vector type (see PR17453).
3824 // Distinguish between base type and base element type.
3825 QualType OldElemTy = OldTy;
3826 if (const auto *VT = OldTy->getAs<VectorType>())
3827 OldElemTy = VT->getElementType();
3828
3829 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
3830 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
3831 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
3832 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
3833 VectorSize.getBoolValue()) {
3834 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
3835 return;
3836 }
3837 bool IntegralOrAnyEnumType =
3838 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
3839
3840 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
3841 !IntegralOrAnyEnumType)
3842 Diag(AttrLoc, diag::err_mode_not_primitive);
3843 else if (IntegerMode) {
3844 if (!IntegralOrAnyEnumType)
3845 Diag(AttrLoc, diag::err_mode_wrong_type);
3846 } else if (ComplexMode) {
3847 if (!OldElemTy->isComplexType())
3848 Diag(AttrLoc, diag::err_mode_wrong_type);
3849 } else {
3850 if (!OldElemTy->isFloatingType())
3851 Diag(AttrLoc, diag::err_mode_wrong_type);
3852 }
3853
3854 QualType NewElemTy;
3855
3856 if (IntegerMode)
3857 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
3858 OldElemTy->isSignedIntegerType());
3859 else
3860 NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
3861
3862 if (NewElemTy.isNull()) {
3863 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
3864 return;
3865 }
3866
3867 if (ComplexMode) {
3868 NewElemTy = Context.getComplexType(NewElemTy);
3869 }
3870
3871 QualType NewTy = NewElemTy;
3872 if (VectorSize.getBoolValue()) {
3873 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
3874 VectorType::GenericVector);
3875 } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
3876 // Complex machine mode does not support base vector types.
3877 if (ComplexMode) {
3878 Diag(AttrLoc, diag::err_complex_mode_vector_type);
3879 return;
3880 }
3881 unsigned NumElements = Context.getTypeSize(OldElemTy) *
3882 OldVT->getNumElements() /
3883 Context.getTypeSize(NewElemTy);
3884 NewTy =
3885 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
3886 }
3887
3888 if (NewTy.isNull()) {
3889 Diag(AttrLoc, diag::err_mode_wrong_type);
3890 return;
3891 }
3892
3893 // Install the new type.
3894 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
3895 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
3896 else if (auto *ED = dyn_cast<EnumDecl>(D))
3897 ED->setIntegerType(NewTy);
3898 else
3899 cast<ValueDecl>(D)->setType(NewTy);
3900
3901 D->addAttr(::new (Context)
3902 ModeAttr(AttrRange, Context, Name, SpellingListIndex));
3903}
3904
3905static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3906 D->addAttr(::new (S.Context)
3907 NoDebugAttr(AL.getRange(), S.Context,
3908 AL.getAttributeSpellingListIndex()));
3909}
3910
3911AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
3912 IdentifierInfo *Ident,
3913 unsigned AttrSpellingListIndex) {
3914 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3915 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
3916 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3917 return nullptr;
3918 }
3919
3920 if (D->hasAttr<AlwaysInlineAttr>())
3921 return nullptr;
3922
3923 return ::new (Context) AlwaysInlineAttr(Range, Context,
3924 AttrSpellingListIndex);
3925}
3926
3927CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range,
3928 IdentifierInfo *Ident,
3929 unsigned AttrSpellingListIndex) {
3930 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident))
3931 return nullptr;
3932
3933 return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex);
3934}
3935
3936InternalLinkageAttr *
3937Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range,
3938 IdentifierInfo *Ident,
3939 unsigned AttrSpellingListIndex) {
3940 if (const auto *VD = dyn_cast<VarDecl>(D)) {
3941 // Attribute applies to Var but not any subclass of it (like ParmVar,
3942 // ImplicitParm or VarTemplateSpecialization).
3943 if (VD->getKind() != Decl::Var) {
3944 Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type)
3945 << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
3946 : ExpectedVariableOrFunction);
3947 return nullptr;
3948 }
3949 // Attribute does not apply to non-static local variables.
3950 if (VD->hasLocalStorage()) {
3951 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
3952 return nullptr;
3953 }
3954 }
3955
3956 if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident))
3957 return nullptr;
3958
3959 return ::new (Context)
3960 InternalLinkageAttr(Range, Context, AttrSpellingListIndex);
3961}
3962
3963MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
3964 unsigned AttrSpellingListIndex) {
3965 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
3966 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
3967 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
3968 return nullptr;
3969 }
3970
3971 if (D->hasAttr<MinSizeAttr>())
3972 return nullptr;
3973
3974 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
3975}
3976
3977OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
3978 unsigned AttrSpellingListIndex) {
3979 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
3980 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
3981 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3982 D->dropAttr<AlwaysInlineAttr>();
3983 }
3984 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
3985 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
3986 Diag(Range.getBegin(), diag::note_conflicting_attribute);
3987 D->dropAttr<MinSizeAttr>();
3988 }
3989
3990 if (D->hasAttr<OptimizeNoneAttr>())
3991 return nullptr;
3992
3993 return ::new (Context) OptimizeNoneAttr(Range, Context,
3994 AttrSpellingListIndex);
3995}
3996
3997static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3998 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, AL.getRange(),
3999 AL.getName()))
4000 return;
4001
4002 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
4003 D, AL.getRange(), AL.getName(),
4004 AL.getAttributeSpellingListIndex()))
4005 D->addAttr(Inline);
4006}
4007
4008static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4009 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
4010 D, AL.getRange(), AL.getAttributeSpellingListIndex()))
4011 D->addAttr(MinSize);
4012}
4013
4014static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4015 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
4016 D, AL.getRange(), AL.getAttributeSpellingListIndex()))
4017 D->addAttr(Optnone);
4018}
4019
4020static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4021 if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, AL.getRange(),
4022 AL.getName()))
4023 return;
4024 const auto *VD = cast<VarDecl>(D);
4025 if (!VD->hasGlobalStorage()) {
4026 S.Diag(AL.getLoc(), diag::err_cuda_nonglobal_constant);
4027 return;
4028 }
4029 D->addAttr(::new (S.Context) CUDAConstantAttr(
4030 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4031}
4032
4033static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4034 if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, AL.getRange(),
4035 AL.getName()))
4036 return;
4037 const auto *VD = cast<VarDecl>(D);
4038 // extern __shared__ is only allowed on arrays with no length (e.g.
4039 // "int x[]").
4040 if (!S.getLangOpts().CUDARelocatableDeviceCode && VD->hasExternalStorage() &&
4041 !isa<IncompleteArrayType>(VD->getType())) {
4042 S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
4043 return;
4044 }
4045 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4046 S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
4047 << S.CurrentCUDATarget())
4048 return;
4049 D->addAttr(::new (S.Context) CUDASharedAttr(
4050 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4051}
4052
4053static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4054 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, AL.getRange(),
4055 AL.getName()) ||
4056 checkAttrMutualExclusion<CUDAHostAttr>(S, D, AL.getRange(),
4057 AL.getName())) {
4058 return;
4059 }
4060 const auto *FD = cast<FunctionDecl>(D);
4061 if (!FD->getReturnType()->isVoidType()) {
4062 SourceRange RTRange = FD->getReturnTypeSourceRange();
4063 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4064 << FD->getType()
4065 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4066 : FixItHint());
4067 return;
4068 }
4069 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4070 if (Method->isInstance()) {
4071 S.Diag(Method->getLocStart(), diag::err_kern_is_nonstatic_method)
4072 << Method;
4073 return;
4074 }
4075 S.Diag(Method->getLocStart(), diag::warn_kern_is_method) << Method;
4076 }
4077 // Only warn for "inline" when compiling for host, to cut down on noise.
4078 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4079 S.Diag(FD->getLocStart(), diag::warn_kern_is_inline) << FD;
4080
4081 D->addAttr(::new (S.Context)
4082 CUDAGlobalAttr(AL.getRange(), S.Context,
4083 AL.getAttributeSpellingListIndex()));
4084}
4085
4086static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4087 const auto *Fn = cast<FunctionDecl>(D);
4088 if (!Fn->isInlineSpecified()) {
4089 S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4090 return;
4091 }
4092
4093 D->addAttr(::new (S.Context)
4094 GNUInlineAttr(AL.getRange(), S.Context,
4095 AL.getAttributeSpellingListIndex()));
4096}
4097
4098static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4099 if (hasDeclarator(D)) return;
4100
4101 // Diagnostic is emitted elsewhere: here we store the (valid) AL
4102 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4103 CallingConv CC;
4104 if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr))
4105 return;
4106
4107 if (!isa<ObjCMethodDecl>(D)) {
4108 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4109 << AL.getName() << ExpectedFunctionOrMethod;
4110 return;
4111 }
4112
4113 switch (AL.getKind()) {
4114 case ParsedAttr::AT_FastCall:
4115 D->addAttr(::new (S.Context)
4116 FastCallAttr(AL.getRange(), S.Context,
4117 AL.getAttributeSpellingListIndex()));
4118 return;
4119 case ParsedAttr::AT_StdCall:
4120 D->addAttr(::new (S.Context)
4121 StdCallAttr(AL.getRange(), S.Context,
4122 AL.getAttributeSpellingListIndex()));
4123 return;
4124 case ParsedAttr::AT_ThisCall:
4125 D->addAttr(::new (S.Context)
4126 ThisCallAttr(AL.getRange(), S.Context,
4127 AL.getAttributeSpellingListIndex()));
4128 return;
4129 case ParsedAttr::AT_CDecl:
4130 D->addAttr(::new (S.Context)
4131 CDeclAttr(AL.getRange(), S.Context,
4132 AL.getAttributeSpellingListIndex()));
4133 return;
4134 case ParsedAttr::AT_Pascal:
4135 D->addAttr(::new (S.Context)
4136 PascalAttr(AL.getRange(), S.Context,
4137 AL.getAttributeSpellingListIndex()));
4138 return;
4139 case ParsedAttr::AT_SwiftCall:
4140 D->addAttr(::new (S.Context)
4141 SwiftCallAttr(AL.getRange(), S.Context,
4142 AL.getAttributeSpellingListIndex()));
4143 return;
4144 case ParsedAttr::AT_VectorCall:
4145 D->addAttr(::new (S.Context)
4146 VectorCallAttr(AL.getRange(), S.Context,
4147 AL.getAttributeSpellingListIndex()));
4148 return;
4149 case ParsedAttr::AT_MSABI:
4150 D->addAttr(::new (S.Context)
4151 MSABIAttr(AL.getRange(), S.Context,
4152 AL.getAttributeSpellingListIndex()));
4153 return;
4154 case ParsedAttr::AT_SysVABI:
4155 D->addAttr(::new (S.Context)
4156 SysVABIAttr(AL.getRange(), S.Context,
4157 AL.getAttributeSpellingListIndex()));
4158 return;
4159 case ParsedAttr::AT_RegCall:
4160 D->addAttr(::new (S.Context) RegCallAttr(
4161 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4162 return;
4163 case ParsedAttr::AT_Pcs: {
4164 PcsAttr::PCSType PCS;
4165 switch (CC) {
4166 case CC_AAPCS:
4167 PCS = PcsAttr::AAPCS;
4168 break;
4169 case CC_AAPCS_VFP:
4170 PCS = PcsAttr::AAPCS_VFP;
4171 break;
4172 default:
4173 llvm_unreachable("unexpected calling convention in pcs attribute")::llvm::llvm_unreachable_internal("unexpected calling convention in pcs attribute"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4173)
;
4174 }
4175
4176 D->addAttr(::new (S.Context)
4177 PcsAttr(AL.getRange(), S.Context, PCS,
4178 AL.getAttributeSpellingListIndex()));
4179 return;
4180 }
4181 case ParsedAttr::AT_IntelOclBicc:
4182 D->addAttr(::new (S.Context)
4183 IntelOclBiccAttr(AL.getRange(), S.Context,
4184 AL.getAttributeSpellingListIndex()));
4185 return;
4186 case ParsedAttr::AT_PreserveMost:
4187 D->addAttr(::new (S.Context) PreserveMostAttr(
4188 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4189 return;
4190 case ParsedAttr::AT_PreserveAll:
4191 D->addAttr(::new (S.Context) PreserveAllAttr(
4192 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4193 return;
4194 default:
4195 llvm_unreachable("unexpected attribute kind")::llvm::llvm_unreachable_internal("unexpected attribute kind"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4195)
;
4196 }
4197}
4198
4199static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4200 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
4201 return;
4202
4203 std::vector<StringRef> DiagnosticIdentifiers;
4204 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
4205 StringRef RuleName;
4206
4207 if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr))
4208 return;
4209
4210 // FIXME: Warn if the rule name is unknown. This is tricky because only
4211 // clang-tidy knows about available rules.
4212 DiagnosticIdentifiers.push_back(RuleName);
4213 }
4214 D->addAttr(::new (S.Context) SuppressAttr(
4215 AL.getRange(), S.Context, DiagnosticIdentifiers.data(),
4216 DiagnosticIdentifiers.size(), AL.getAttributeSpellingListIndex()));
4217}
4218
4219bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC,
4220 const FunctionDecl *FD) {
4221 if (Attrs.isInvalid())
4222 return true;
4223
4224 if (Attrs.hasProcessingCache()) {
4225 CC = (CallingConv) Attrs.getProcessingCache();
4226 return false;
4227 }
4228
4229 unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
4230 if (!checkAttributeNumArgs(*this, Attrs, ReqArgs)) {
4231 Attrs.setInvalid();
4232 return true;
4233 }
4234
4235 // TODO: diagnose uses of these conventions on the wrong target.
4236 switch (Attrs.getKind()) {
4237 case ParsedAttr::AT_CDecl:
4238 CC = CC_C;
4239 break;
4240 case ParsedAttr::AT_FastCall:
4241 CC = CC_X86FastCall;
4242 break;
4243 case ParsedAttr::AT_StdCall:
4244 CC = CC_X86StdCall;
4245 break;
4246 case ParsedAttr::AT_ThisCall:
4247 CC = CC_X86ThisCall;
4248 break;
4249 case ParsedAttr::AT_Pascal:
4250 CC = CC_X86Pascal;
4251 break;
4252 case ParsedAttr::AT_SwiftCall:
4253 CC = CC_Swift;
4254 break;
4255 case ParsedAttr::AT_VectorCall:
4256 CC = CC_X86VectorCall;
4257 break;
4258 case ParsedAttr::AT_RegCall:
4259 CC = CC_X86RegCall;
4260 break;
4261 case ParsedAttr::AT_MSABI:
4262 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4263 CC_Win64;
4264 break;
4265 case ParsedAttr::AT_SysVABI:
4266 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4267 CC_C;
4268 break;
4269 case ParsedAttr::AT_Pcs: {
4270 StringRef StrRef;
4271 if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
4272 Attrs.setInvalid();
4273 return true;
4274 }
4275 if (StrRef == "aapcs") {
4276 CC = CC_AAPCS;
4277 break;
4278 } else if (StrRef == "aapcs-vfp") {
4279 CC = CC_AAPCS_VFP;
4280 break;
4281 }
4282
4283 Attrs.setInvalid();
4284 Diag(Attrs.getLoc(), diag::err_invalid_pcs);
4285 return true;
4286 }
4287 case ParsedAttr::AT_IntelOclBicc:
4288 CC = CC_IntelOclBicc;
4289 break;
4290 case ParsedAttr::AT_PreserveMost:
4291 CC = CC_PreserveMost;
4292 break;
4293 case ParsedAttr::AT_PreserveAll:
4294 CC = CC_PreserveAll;
4295 break;
4296 default: llvm_unreachable("unexpected attribute kind")::llvm::llvm_unreachable_internal("unexpected attribute kind"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4296)
;
4297 }
4298
4299 const TargetInfo &TI = Context.getTargetInfo();
4300 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
4301 if (A != TargetInfo::CCCR_OK) {
4302 if (A == TargetInfo::CCCR_Warning)
4303 Diag(Attrs.getLoc(), diag::warn_cconv_ignored) << Attrs.getName();
4304
4305 // This convention is not valid for the target. Use the default function or
4306 // method calling convention.
4307 bool IsCXXMethod = false, IsVariadic = false;
4308 if (FD) {
4309 IsCXXMethod = FD->isCXXInstanceMember();
4310 IsVariadic = FD->isVariadic();
4311 }
4312 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
4313 }
4314
4315 Attrs.setProcessingCache((unsigned) CC);
4316 return false;
4317}
4318
4319/// Pointer-like types in the default address space.
4320static bool isValidSwiftContextType(QualType Ty) {
4321 if (!Ty->hasPointerRepresentation())
4322 return Ty->isDependentType();
4323 return Ty->getPointeeType().getAddressSpace() == LangAS::Default;
4324}
4325
4326/// Pointers and references in the default address space.
4327static bool isValidSwiftIndirectResultType(QualType Ty) {
4328 if (const auto *PtrType = Ty->getAs<PointerType>()) {
4329 Ty = PtrType->getPointeeType();
4330 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4331 Ty = RefType->getPointeeType();
4332 } else {
4333 return Ty->isDependentType();
4334 }
4335 return Ty.getAddressSpace() == LangAS::Default;
4336}
4337
4338/// Pointers and references to pointers in the default address space.
4339static bool isValidSwiftErrorResultType(QualType Ty) {
4340 if (const auto *PtrType = Ty->getAs<PointerType>()) {
4341 Ty = PtrType->getPointeeType();
4342 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4343 Ty = RefType->getPointeeType();
4344 } else {
4345 return Ty->isDependentType();
4346 }
4347 if (!Ty.getQualifiers().empty())
4348 return false;
4349 return isValidSwiftContextType(Ty);
4350}
4351
4352static void handleParameterABIAttr(Sema &S, Decl *D, const ParsedAttr &Attrs,
4353 ParameterABI Abi) {
4354 S.AddParameterABIAttr(Attrs.getRange(), D, Abi,
4355 Attrs.getAttributeSpellingListIndex());
4356}
4357
4358void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi,
4359 unsigned spellingIndex) {
4360
4361 QualType type = cast<ParmVarDecl>(D)->getType();
4362
4363 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4364 if (existingAttr->getABI() != abi) {
4365 Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
4366 << getParameterABISpelling(abi) << existingAttr;
4367 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4368 return;
4369 }
4370 }
4371
4372 switch (abi) {
4373 case ParameterABI::Ordinary:
4374 llvm_unreachable("explicit attribute for ordinary parameter ABI?")::llvm::llvm_unreachable_internal("explicit attribute for ordinary parameter ABI?"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4374)
;
4375
4376 case ParameterABI::SwiftContext:
4377 if (!isValidSwiftContextType(type)) {
4378 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4379 << getParameterABISpelling(abi)
4380 << /*pointer to pointer */ 0 << type;
4381 }
4382 D->addAttr(::new (Context)
4383 SwiftContextAttr(range, Context, spellingIndex));
4384 return;
4385
4386 case ParameterABI::SwiftErrorResult:
4387 if (!isValidSwiftErrorResultType(type)) {
4388 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4389 << getParameterABISpelling(abi)
4390 << /*pointer to pointer */ 1 << type;
4391 }
4392 D->addAttr(::new (Context)
4393 SwiftErrorResultAttr(range, Context, spellingIndex));
4394 return;
4395
4396 case ParameterABI::SwiftIndirectResult:
4397 if (!isValidSwiftIndirectResultType(type)) {
4398 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4399 << getParameterABISpelling(abi)
4400 << /*pointer*/ 0 << type;
4401 }
4402 D->addAttr(::new (Context)
4403 SwiftIndirectResultAttr(range, Context, spellingIndex));
4404 return;
4405 }
4406 llvm_unreachable("bad parameter ABI attribute")::llvm::llvm_unreachable_internal("bad parameter ABI attribute"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4406)
;
4407}
4408
4409/// Checks a regparm attribute, returning true if it is ill-formed and
4410/// otherwise setting numParams to the appropriate value.
4411bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) {
4412 if (AL.isInvalid())
4413 return true;
4414
4415 if (!checkAttributeNumArgs(*this, AL, 1)) {
4416 AL.setInvalid();
4417 return true;
4418 }
4419
4420 uint32_t NP;
4421 Expr *NumParamsExpr = AL.getArgAsExpr(0);
4422 if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) {
4423 AL.setInvalid();
4424 return true;
4425 }
4426
4427 if (Context.getTargetInfo().getRegParmMax() == 0) {
4428 Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform)
4429 << NumParamsExpr->getSourceRange();
4430 AL.setInvalid();
4431 return true;
4432 }
4433
4434 numParams = NP;
4435 if (numParams > Context.getTargetInfo().getRegParmMax()) {
4436 Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number)
4437 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
4438 AL.setInvalid();
4439 return true;
4440 }
4441
4442 return false;
4443}
4444
4445// Checks whether an argument of launch_bounds attribute is
4446// acceptable, performs implicit conversion to Rvalue, and returns
4447// non-nullptr Expr result on success. Otherwise, it returns nullptr
4448// and may output an error.
4449static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4450 const CUDALaunchBoundsAttr &AL,
4451 const unsigned Idx) {
4452 if (S.DiagnoseUnexpandedParameterPack(E))
4453 return nullptr;
4454
4455 // Accept template arguments for now as they depend on something else.
4456 // We'll get to check them when they eventually get instantiated.
4457 if (E->isValueDependent())
4458 return E;
4459
4460 llvm::APSInt I(64);
4461 if (!E->isIntegerConstantExpr(I, S.Context)) {
4462 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4463 << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
4464 return nullptr;
4465 }
4466 // Make sure we can fit it in 32 bits.
4467 if (!I.isIntN(32)) {
4468 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4469 << 32 << /* Unsigned */ 1;
4470 return nullptr;
4471 }
4472 if (I < 0)
4473 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4474 << &AL << Idx << E->getSourceRange();
4475
4476 // We may need to perform implicit conversion of the argument.
4477 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4478 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4479 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4480 assert(!ValArg.isInvalid() &&(static_cast <bool> (!ValArg.isInvalid() && "Unexpected PerformCopyInitialization() failure."
) ? void (0) : __assert_fail ("!ValArg.isInvalid() && \"Unexpected PerformCopyInitialization() failure.\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4481, __extension__ __PRETTY_FUNCTION__))
4481 "Unexpected PerformCopyInitialization() failure.")(static_cast <bool> (!ValArg.isInvalid() && "Unexpected PerformCopyInitialization() failure."
) ? void (0) : __assert_fail ("!ValArg.isInvalid() && \"Unexpected PerformCopyInitialization() failure.\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4481, __extension__ __PRETTY_FUNCTION__))
;
4482
4483 return ValArg.getAs<Expr>();
4484}
4485
4486void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4487 Expr *MinBlocks, unsigned SpellingListIndex) {
4488 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4489 SpellingListIndex);
4490 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4491 if (MaxThreads == nullptr)
4492 return;
4493
4494 if (MinBlocks) {
4495 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4496 if (MinBlocks == nullptr)
4497 return;
4498 }
4499
4500 D->addAttr(::new (Context) CUDALaunchBoundsAttr(
4501 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
4502}
4503
4504static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4505 if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
4506 !checkAttributeAtMostNumArgs(S, AL, 2))
4507 return;
4508
4509 S.AddLaunchBoundsAttr(AL.getRange(), D, AL.getArgAsExpr(0),
4510 AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr,
4511 AL.getAttributeSpellingListIndex());
4512}
4513
4514static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4515 const ParsedAttr &AL) {
4516 if (!AL.isArgIdent(0)) {
4517 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
4518 << AL.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
4519 return;
4520 }
4521
4522 ParamIdx ArgumentIdx;
4523 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1),
4524 ArgumentIdx))
4525 return;
4526
4527 ParamIdx TypeTagIdx;
4528 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2),
4529 TypeTagIdx))
4530 return;
4531
4532 bool IsPointer = AL.getName()->getName() == "pointer_with_type_tag";
4533 if (IsPointer) {
4534 // Ensure that buffer has a pointer type.
4535 unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex();
4536 if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) ||
4537 !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType())
4538 S.Diag(AL.getLoc(), diag::err_attribute_pointers_only)
4539 << AL.getName() << 0;
4540 }
4541
4542 D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr(
4543 AL.getRange(), S.Context, AL.getArgAsIdent(0)->Ident, ArgumentIdx,
4544 TypeTagIdx, IsPointer, AL.getAttributeSpellingListIndex()));
4545}
4546
4547static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4548 const ParsedAttr &AL) {
4549 if (!AL.isArgIdent(0)) {
4550 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
4551 << AL.getName() << 1 << AANT_ArgumentIdentifier;
4552 return;
4553 }
4554
4555 if (!checkAttributeNumArgs(S, AL, 1))
4556 return;
4557
4558 if (!isa<VarDecl>(D)) {
4559 S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type)
4560 << AL.getName() << ExpectedVariable;
4561 return;
4562 }
4563
4564 IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident;
4565 TypeSourceInfo *MatchingCTypeLoc = nullptr;
4566 S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc);
4567 assert(MatchingCTypeLoc && "no type source info for attribute argument")(static_cast <bool> (MatchingCTypeLoc && "no type source info for attribute argument"
) ? void (0) : __assert_fail ("MatchingCTypeLoc && \"no type source info for attribute argument\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4567, __extension__ __PRETTY_FUNCTION__))
;
4568
4569 D->addAttr(::new (S.Context)
4570 TypeTagForDatatypeAttr(AL.getRange(), S.Context, PointerKind,
4571 MatchingCTypeLoc,
4572 AL.getLayoutCompatible(),
4573 AL.getMustBeNull(),
4574 AL.getAttributeSpellingListIndex()));
4575}
4576
4577static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4578 ParamIdx ArgCount;
4579
4580 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0),
4581 ArgCount,
4582 true /* CanIndexImplicitThis */))
4583 return;
4584
4585 // ArgCount isn't a parameter index [0;n), it's a count [1;n]
4586 D->addAttr(::new (S.Context) XRayLogArgsAttr(
4587 AL.getRange(), S.Context, ArgCount.getSourceIndex(),
4588 AL.getAttributeSpellingListIndex()));
4589}
4590
4591//===----------------------------------------------------------------------===//
4592// Checker-specific attribute handlers.
4593//===----------------------------------------------------------------------===//
4594
4595static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) {
4596 return QT->isDependentType() || QT->isObjCRetainableType();
4597}
4598
4599static bool isValidSubjectOfNSAttribute(Sema &S, QualType QT) {
4600 return QT->isDependentType() || QT->isObjCObjectPointerType() ||
4601 S.Context.isObjCNSObjectType(QT);
4602}
4603
4604static bool isValidSubjectOfCFAttribute(Sema &S, QualType QT) {
4605 return QT->isDependentType() || QT->isPointerType() ||
4606 isValidSubjectOfNSAttribute(S, QT);
4607}
4608
4609static void handleNSConsumedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4610 S.AddNSConsumedAttr(AL.getRange(), D, AL.getAttributeSpellingListIndex(),
4611 AL.getKind() == ParsedAttr::AT_NSConsumed,
4612 /*template instantiation*/ false);
4613}
4614
4615void Sema::AddNSConsumedAttr(SourceRange AttrRange, Decl *D,
4616 unsigned SpellingIndex, bool IsNSConsumed,
4617 bool IsTemplateInstantiation) {
4618 const auto *Param = cast<ParmVarDecl>(D);
4619 bool TypeOK;
4620
4621 if (IsNSConsumed)
4622 TypeOK = isValidSubjectOfNSAttribute(*this, Param->getType());
4623 else
4624 TypeOK = isValidSubjectOfCFAttribute(*this, Param->getType());
4625
4626 if (!TypeOK) {
4627 // These attributes are normally just advisory, but in ARC, ns_consumed
4628 // is significant. Allow non-dependent code to contain inappropriate
4629 // attributes even in ARC, but require template instantiations to be
4630 // set up correctly.
4631 Diag(D->getLocStart(), (IsTemplateInstantiation && IsNSConsumed &&
4632 getLangOpts().ObjCAutoRefCount
4633 ? diag::err_ns_attribute_wrong_parameter_type
4634 : diag::warn_ns_attribute_wrong_parameter_type))
4635 << AttrRange << (IsNSConsumed ? "ns_consumed" : "cf_consumed")
4636 << (IsNSConsumed ? /*objc pointers*/ 0 : /*cf pointers*/ 1);
4637 return;
4638 }
4639
4640 if (IsNSConsumed)
4641 D->addAttr(::new (Context)
4642 NSConsumedAttr(AttrRange, Context, SpellingIndex));
4643 else
4644 D->addAttr(::new (Context)
4645 CFConsumedAttr(AttrRange, Context, SpellingIndex));
4646}
4647
4648bool Sema::checkNSReturnsRetainedReturnType(SourceLocation Loc, QualType QT) {
4649 if (isValidSubjectOfNSReturnsRetainedAttribute(QT))
4650 return false;
4651
4652 Diag(Loc, diag::warn_ns_attribute_wrong_return_type)
4653 << "'ns_returns_retained'" << 0 << 0;
4654 return true;
4655}
4656
4657static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
4658 const ParsedAttr &AL) {
4659 QualType ReturnType;
4660
4661 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
4662 ReturnType = MD->getReturnType();
4663 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
4664 (AL.getKind() == ParsedAttr::AT_NSReturnsRetained))
4665 return; // ignore: was handled as a type attribute
4666 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D))
4667 ReturnType = PD->getType();
4668 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
4669 ReturnType = FD->getReturnType();
4670 else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) {
4671 ReturnType = Param->getType()->getPointeeType();
4672 if (ReturnType.isNull()) {
4673 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4674 << AL.getName() << /*pointer-to-CF*/2
4675 << AL.getRange();
4676 return;
4677 }
4678 } else if (AL.isUsedAsTypeAttr()) {
4679 return;
4680 } else {
4681 AttributeDeclKind ExpectedDeclKind;
4682 switch (AL.getKind()) {
4683 default: llvm_unreachable("invalid ownership attribute")::llvm::llvm_unreachable_internal("invalid ownership attribute"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4683)
;
4684 case ParsedAttr::AT_NSReturnsRetained:
4685 case ParsedAttr::AT_NSReturnsAutoreleased:
4686 case ParsedAttr::AT_NSReturnsNotRetained:
4687 ExpectedDeclKind = ExpectedFunctionOrMethod;
4688 break;
4689
4690 case ParsedAttr::AT_CFReturnsRetained:
4691 case ParsedAttr::AT_CFReturnsNotRetained:
4692 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4693 break;
4694 }
4695 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
4696 << AL.getRange() << AL.getName() << ExpectedDeclKind;
4697 return;
4698 }
4699
4700 bool TypeOK;
4701 bool Cf;
4702 switch (AL.getKind()) {
4703 default: llvm_unreachable("invalid ownership attribute")::llvm::llvm_unreachable_internal("invalid ownership attribute"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4703)
;
4704 case ParsedAttr::AT_NSReturnsRetained:
4705 TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType);
4706 Cf = false;
4707 break;
4708
4709 case ParsedAttr::AT_NSReturnsAutoreleased:
4710 case ParsedAttr::AT_NSReturnsNotRetained:
4711 TypeOK = isValidSubjectOfNSAttribute(S, ReturnType);
4712 Cf = false;
4713 break;
4714
4715 case ParsedAttr::AT_CFReturnsRetained:
4716 case ParsedAttr::AT_CFReturnsNotRetained:
4717 TypeOK = isValidSubjectOfCFAttribute(S, ReturnType);
4718 Cf = true;
4719 break;
4720 }
4721
4722 if (!TypeOK) {
4723 if (AL.isUsedAsTypeAttr())
4724 return;
4725
4726 if (isa<ParmVarDecl>(D)) {
4727 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
4728 << AL.getName() << /*pointer-to-CF*/2
4729 << AL.getRange();
4730 } else {
4731 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
4732 enum : unsigned {
4733 Function,
4734 Method,
4735 Property
4736 } SubjectKind = Function;
4737 if (isa<ObjCMethodDecl>(D))
4738 SubjectKind = Method;
4739 else if (isa<ObjCPropertyDecl>(D))
4740 SubjectKind = Property;
4741 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4742 << AL.getName() << SubjectKind << Cf
4743 << AL.getRange();
4744 }
4745 return;
4746 }
4747
4748 switch (AL.getKind()) {
4749 default:
4750 llvm_unreachable("invalid ownership attribute")::llvm::llvm_unreachable_internal("invalid ownership attribute"
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4750)
;
4751 case ParsedAttr::AT_NSReturnsAutoreleased:
4752 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
4753 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4754 return;
4755 case ParsedAttr::AT_CFReturnsNotRetained:
4756 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
4757 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4758 return;
4759 case ParsedAttr::AT_NSReturnsNotRetained:
4760 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
4761 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4762 return;
4763 case ParsedAttr::AT_CFReturnsRetained:
4764 D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
4765 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4766 return;
4767 case ParsedAttr::AT_NSReturnsRetained:
4768 D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
4769 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
4770 return;
4771 };
4772}
4773
4774static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
4775 const ParsedAttr &Attrs) {
4776 const int EP_ObjCMethod = 1;
4777 const int EP_ObjCProperty = 2;
4778
4779 SourceLocation loc = Attrs.getLoc();
4780 QualType resultType;
4781 if (isa<ObjCMethodDecl>(D))
4782 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
4783 else
4784 resultType = cast<ObjCPropertyDecl>(D)->getType();
4785
4786 if (!resultType->isReferenceType() &&
4787 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
4788 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
4789 << SourceRange(loc)
4790 << Attrs.getName()
4791 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
4792 << /*non-retainable pointer*/ 2;
4793
4794 // Drop the attribute.
4795 return;
4796 }
4797
4798 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
4799 Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
4800}
4801
4802static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
4803 const ParsedAttr &Attrs) {
4804 const auto *Method = cast<ObjCMethodDecl>(D);
4805
4806 const DeclContext *DC = Method->getDeclContext();
4807 if (const auto *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
4808 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4809 << Attrs.getName() << 0;
4810 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
4811 return;
4812 }
4813 if (Method->getMethodFamily() == OMF_dealloc) {
4814 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
4815 << Attrs.getName() << 1;
4816 return;
4817 }
4818
4819 D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(
4820 Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
4821}
4822
4823static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4824 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
4825
4826 if (!Parm) {
4827 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << AL.getName() << 0;
4828 return;
4829 }
4830
4831 // Typedefs only allow objc_bridge(id) and have some additional checking.
4832 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
4833 if (!Parm->Ident->isStr("id")) {
4834 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id)
4835 << AL.getName();
4836 return;
4837 }
4838
4839 // Only allow 'cv void *'.
4840 QualType T = TD->getUnderlyingType();
4841 if (!T->isVoidPointerType()) {
4842 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
4843 return;
4844 }
4845 }
4846
4847 D->addAttr(::new (S.Context)
4848 ObjCBridgeAttr(AL.getRange(), S.Context, Parm->Ident,
4849 AL.getAttributeSpellingListIndex()));
4850}
4851
4852static void handleObjCBridgeMutableAttr(Sema &S, Decl *D,
4853 const ParsedAttr &AL) {
4854 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
4855
4856 if (!Parm) {
4857 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << AL.getName() << 0;
4858 return;
4859 }
4860
4861 D->addAttr(::new (S.Context)
4862 ObjCBridgeMutableAttr(AL.getRange(), S.Context, Parm->Ident,
4863 AL.getAttributeSpellingListIndex()));
4864}
4865
4866static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D,
4867 const ParsedAttr &AL) {
4868 IdentifierInfo *RelatedClass =
4869 AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr;
4870 if (!RelatedClass) {
4871 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << AL.getName() << 0;
4872 return;
4873 }
4874 IdentifierInfo *ClassMethod =
4875 AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr;
4876 IdentifierInfo *InstanceMethod =
4877 AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr;
4878 D->addAttr(::new (S.Context)
4879 ObjCBridgeRelatedAttr(AL.getRange(), S.Context, RelatedClass,
4880 ClassMethod, InstanceMethod,
4881 AL.getAttributeSpellingListIndex()));
4882}
4883
4884static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
4885 const ParsedAttr &AL) {
4886 ObjCInterfaceDecl *IFace;
4887 if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
4888 IFace = CatDecl->getClassInterface();
4889 else
4890 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
4891
4892 if (!IFace)
4893 return;
4894
4895 IFace->setHasDesignatedInitializers();
4896 D->addAttr(::new (S.Context)
4897 ObjCDesignatedInitializerAttr(AL.getRange(), S.Context,
4898 AL.getAttributeSpellingListIndex()));
4899}
4900
4901static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) {
4902 StringRef MetaDataName;
4903 if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName))
4904 return;
4905 D->addAttr(::new (S.Context)
4906 ObjCRuntimeNameAttr(AL.getRange(), S.Context,
4907 MetaDataName,
4908 AL.getAttributeSpellingListIndex()));
4909}
4910
4911// When a user wants to use objc_boxable with a union or struct
4912// but they don't have access to the declaration (legacy/third-party code)
4913// then they can 'enable' this feature with a typedef:
4914// typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
4915static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) {
4916 bool notify = false;
4917
4918 auto *RD = dyn_cast<RecordDecl>(D);
4919 if (RD && RD->getDefinition()) {
4920 RD = RD->getDefinition();
4921 notify = true;
4922 }
4923
4924 if (RD) {
4925 ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
4926 ObjCBoxableAttr(AL.getRange(), S.Context,
4927 AL.getAttributeSpellingListIndex());
4928 RD->addAttr(BoxableAttr);
4929 if (notify) {
4930 // we need to notify ASTReader/ASTWriter about
4931 // modification of existing declaration
4932 if (ASTMutationListener *L = S.getASTMutationListener())
4933 L->AddedAttributeToRecord(BoxableAttr, RD);
4934 }
4935 }
4936}
4937
4938static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4939 if (hasDeclarator(D)) return;
4940
4941 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
4942 << AL.getRange() << AL.getName() << ExpectedVariable;
4943}
4944
4945static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
4946 const ParsedAttr &AL) {
4947 const auto *VD = cast<ValueDecl>(D);
4948 QualType QT = VD->getType();
4949
4950 if (!QT->isDependentType() &&
4951 !QT->isObjCLifetimeType()) {
4952 S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type)
4953 << QT;
4954 return;
4955 }
4956
4957 Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime();
4958
4959 // If we have no lifetime yet, check the lifetime we're presumably
4960 // going to infer.
4961 if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType())
4962 Lifetime = QT->getObjCARCImplicitLifetime();
4963
4964 switch (Lifetime) {
4965 case Qualifiers::OCL_None:
4966 assert(QT->isDependentType() &&(static_cast <bool> (QT->isDependentType() &&
"didn't infer lifetime for non-dependent type?") ? void (0) :
__assert_fail ("QT->isDependentType() && \"didn't infer lifetime for non-dependent type?\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4967, __extension__ __PRETTY_FUNCTION__))
4967 "didn't infer lifetime for non-dependent type?")(static_cast <bool> (QT->isDependentType() &&
"didn't infer lifetime for non-dependent type?") ? void (0) :
__assert_fail ("QT->isDependentType() && \"didn't infer lifetime for non-dependent type?\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4967, __extension__ __PRETTY_FUNCTION__))
;
4968 break;
4969
4970 case Qualifiers::OCL_Weak: // meaningful
4971 case Qualifiers::OCL_Strong: // meaningful
4972 break;
4973
4974 case Qualifiers::OCL_ExplicitNone:
4975 case Qualifiers::OCL_Autoreleasing:
4976 S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
4977 << (Lifetime == Qualifiers::OCL_Autoreleasing);
4978 break;
4979 }
4980
4981 D->addAttr(::new (S.Context)
4982 ObjCPreciseLifetimeAttr(AL.getRange(), S.Context,
4983 AL.getAttributeSpellingListIndex()));
4984}
4985
4986//===----------------------------------------------------------------------===//
4987// Microsoft specific attribute handlers.
4988//===----------------------------------------------------------------------===//
4989
4990UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range,
4991 unsigned AttrSpellingListIndex, StringRef Uuid) {
4992 if (const auto *UA = D->getAttr<UuidAttr>()) {
4993 if (UA->getGuid().equals_lower(Uuid))
4994 return nullptr;
4995 Diag(UA->getLocation(), diag::err_mismatched_uuid);
4996 Diag(Range.getBegin(), diag::note_previous_uuid);
4997 D->dropAttr<UuidAttr>();
4998 }
4999
5000 return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex);
5001}
5002
5003static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5004 if (!S.LangOpts.CPlusPlus) {
5005 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
5006 << AL.getName() << AttributeLangSupport::C;
5007 return;
5008 }
5009
5010 StringRef StrRef;
5011 SourceLocation LiteralLoc;
5012 if (!S.checkStringLiteralArgumentAttr(AL, 0, StrRef, &LiteralLoc))
5013 return;
5014
5015 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
5016 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
5017 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
5018 StrRef = StrRef.drop_front().drop_back();
5019
5020 // Validate GUID length.
5021 if (StrRef.size() != 36) {
5022 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5023 return;
5024 }
5025
5026 for (unsigned i = 0; i < 36; ++i) {
5027 if (i == 8 || i == 13 || i == 18 || i == 23) {
5028 if (StrRef[i] != '-') {
5029 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5030 return;
5031 }
5032 } else if (!isHexDigit(StrRef[i])) {
5033 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5034 return;
5035 }
5036 }
5037
5038 // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
5039 // the only thing in the [] list, the [] too), and add an insertion of
5040 // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas
5041 // separating attributes nor of the [ and the ] are in the AST.
5042 // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
5043 // on cfe-dev.
5044 if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
5045 S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated);
5046
5047 UuidAttr *UA = S.mergeUuidAttr(D, AL.getRange(),
5048 AL.getAttributeSpellingListIndex(), StrRef);
5049 if (UA)
5050 D->addAttr(UA);
5051}
5052
5053static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5054 if (!S.LangOpts.CPlusPlus) {
5055 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
5056 << AL.getName() << AttributeLangSupport::C;
5057 return;
5058 }
5059 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
5060 D, AL.getRange(), /*BestCase=*/true,
5061 AL.getAttributeSpellingListIndex(),
5062 (MSInheritanceAttr::Spelling)AL.getSemanticSpelling());
5063 if (IA) {
5064 D->addAttr(IA);
5065 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
5066 }
5067}
5068
5069static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5070 const auto *VD = cast<VarDecl>(D);
5071 if (!S.Context.getTargetInfo().isTLSSupported()) {
5072 S.Diag(AL.getLoc(), diag::err_thread_unsupported);
5073 return;
5074 }
5075 if (VD->getTSCSpec() != TSCS_unspecified) {
5076 S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable);
5077 return;
5078 }
5079 if (VD->hasLocalStorage()) {
5080 S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
5081 return;
5082 }
5083 D->addAttr(::new (S.Context) ThreadAttr(AL.getRange(), S.Context,
5084 AL.getAttributeSpellingListIndex()));
5085}
5086
5087static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5088 SmallVector<StringRef, 4> Tags;
5089 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
5090 StringRef Tag;
5091 if (!S.checkStringLiteralArgumentAttr(AL, I, Tag))
5092 return;
5093 Tags.push_back(Tag);
5094 }
5095
5096 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
5097 if (!NS->isInline()) {
5098 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
5099 return;
5100 }
5101 if (NS->isAnonymousNamespace()) {
5102 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
5103 return;
5104 }
5105 if (AL.getNumArgs() == 0)
5106 Tags.push_back(NS->getName());
5107 } else if (!checkAttributeAtLeastNumArgs(S, AL, 1))
5108 return;
5109
5110 // Store tags sorted and without duplicates.
5111 llvm::sort(Tags.begin(), Tags.end());
5112 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
5113
5114 D->addAttr(::new (S.Context)
5115 AbiTagAttr(AL.getRange(), S.Context, Tags.data(), Tags.size(),
5116 AL.getAttributeSpellingListIndex()));
5117}
5118
5119static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5120 // Check the attribute arguments.
5121 if (AL.getNumArgs() > 1) {
5122 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
5123 << AL.getName() << 1;
5124 return;
5125 }
5126
5127 StringRef Str;
5128 SourceLocation ArgLoc;
5129
5130 if (AL.getNumArgs() == 0)
5131 Str = "";
5132 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5133 return;
5134
5135 ARMInterruptAttr::InterruptType Kind;
5136 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5137 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
5138 << AL.getName() << Str << ArgLoc;
5139 return;
5140 }
5141
5142 unsigned Index = AL.getAttributeSpellingListIndex();
5143 D->addAttr(::new (S.Context)
5144 ARMInterruptAttr(AL.getLoc(), S.Context, Kind, Index));
5145}
5146
5147static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5148 if (!checkAttributeNumArgs(S, AL, 1))
5149 return;
5150
5151 if (!AL.isArgExpr(0)) {
5152 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) << AL.getName()
5153 << AANT_ArgumentIntegerConstant;
5154 return;
5155 }
5156
5157 // FIXME: Check for decl - it should be void ()(void).
5158
5159 Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
5160 llvm::APSInt NumParams(32);
5161 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
5162 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
5163 << AL.getName() << AANT_ArgumentIntegerConstant
5164 << NumParamsExpr->getSourceRange();
5165 return;
5166 }
5167
5168 unsigned Num = NumParams.getLimitedValue(255);
5169 if ((Num & 1) || Num > 30) {
5170 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
5171 << AL.getName() << (int)NumParams.getSExtValue()
5172 << NumParamsExpr->getSourceRange();
5173 return;
5174 }
5175
5176 D->addAttr(::new (S.Context)
5177 MSP430InterruptAttr(AL.getLoc(), S.Context, Num,
5178 AL.getAttributeSpellingListIndex()));
5179 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5180}
5181
5182static void handleMipsInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5183 // Only one optional argument permitted.
5184 if (AL.getNumArgs() > 1) {
5185 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
5186 << AL.getName() << 1;
5187 return;
5188 }
5189
5190 StringRef Str;
5191 SourceLocation ArgLoc;
5192
5193 if (AL.getNumArgs() == 0)
5194 Str = "";
5195 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5196 return;
5197
5198 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
5199 // a) Must be a function.
5200 // b) Must have no parameters.
5201 // c) Must have the 'void' return type.
5202 // d) Cannot have the 'mips16' attribute, as that instruction set
5203 // lacks the 'eret' instruction.
5204 // e) The attribute itself must either have no argument or one of the
5205 // valid interrupt types, see [MipsInterruptDocs].
5206
5207 if (!isFunctionOrMethod(D)) {
5208 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5209 << "'interrupt'" << ExpectedFunctionOrMethod;
5210 return;
5211 }
5212
5213 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5214 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5215 << 0;
5216 return;
5217 }
5218
5219 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5220 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute)
5221 << 1;
5222 return;
5223 }
5224
5225 if (checkAttrMutualExclusion<Mips16Attr>(S, D, AL.getRange(),
5226 AL.getName()))
5227 return;
5228
5229 MipsInterruptAttr::InterruptType Kind;
5230 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5231 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
5232 << AL.getName() << "'" + std::string(Str) + "'";
5233 return;
5234 }
5235
5236 D->addAttr(::new (S.Context) MipsInterruptAttr(
5237 AL.getLoc(), S.Context, Kind, AL.getAttributeSpellingListIndex()));
5238}
5239
5240static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5241 // Semantic checks for a function with the 'interrupt' attribute.
5242 // a) Must be a function.
5243 // b) Must have the 'void' return type.
5244 // c) Must take 1 or 2 arguments.
5245 // d) The 1st argument must be a pointer.
5246 // e) The 2nd argument (if any) must be an unsigned integer.
5247 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
5248 CXXMethodDecl::isStaticOverloadedOperator(
5249 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
5250 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
5251 << AL.getName() << ExpectedFunctionWithProtoType;
5252 return;
5253 }
5254 // Interrupt handler must have void return type.
5255 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5256 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
5257 diag::err_anyx86_interrupt_attribute)
5258 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5259 ? 0
5260 : 1)
5261 << 0;
5262 return;
5263 }
5264 // Interrupt handler must have 1 or 2 parameters.
5265 unsigned NumParams = getFunctionOrMethodNumParams(D);
5266 if (NumParams < 1 || NumParams > 2) {
5267 S.Diag(D->getLocStart(), diag::err_anyx86_interrupt_attribute)
5268 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5269 ? 0
5270 : 1)
5271 << 1;
5272 return;
5273 }
5274 // The first argument must be a pointer.
5275 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
5276 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
5277 diag::err_anyx86_interrupt_attribute)
5278 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5279 ? 0
5280 : 1)
5281 << 2;
5282 return;
5283 }
5284 // The second argument, if present, must be an unsigned integer.
5285 unsigned TypeSize =
5286 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
5287 ? 64
5288 : 32;
5289 if (NumParams == 2 &&
5290 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
5291 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
5292 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
5293 diag::err_anyx86_interrupt_attribute)
5294 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5295 ? 0
5296 : 1)
5297 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
5298 return;
5299 }
5300 D->addAttr(::new (S.Context) AnyX86InterruptAttr(
5301 AL.getLoc(), S.Context, AL.getAttributeSpellingListIndex()));
5302 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5303}
5304
5305static void handleAVRInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5306 if (!isFunctionOrMethod(D)) {
5307 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5308 << "'interrupt'" << ExpectedFunction;
5309 return;
5310 }
5311
5312 if (!checkAttributeNumArgs(S, AL, 0))
5313 return;
5314
5315 handleSimpleAttribute<AVRInterruptAttr>(S, D, AL);
5316}
5317
5318static void handleAVRSignalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5319 if (!isFunctionOrMethod(D)) {
5320 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5321 << "'signal'" << ExpectedFunction;
5322 return;
5323 }
5324
5325 if (!checkAttributeNumArgs(S, AL, 0))
5326 return;
5327
5328 handleSimpleAttribute<AVRSignalAttr>(S, D, AL);
5329}
5330
5331static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5332 // Dispatch the interrupt attribute based on the current target.
5333 switch (S.Context.getTargetInfo().getTriple().getArch()) {
5334 case llvm::Triple::msp430:
5335 handleMSP430InterruptAttr(S, D, AL);
5336 break;
5337 case llvm::Triple::mipsel:
5338 case llvm::Triple::mips:
5339 handleMipsInterruptAttr(S, D, AL);
5340 break;
5341 case llvm::Triple::x86:
5342 case llvm::Triple::x86_64:
5343 handleAnyX86InterruptAttr(S, D, AL);
5344 break;
5345 case llvm::Triple::avr:
5346 handleAVRInterruptAttr(S, D, AL);
5347 break;
5348 default:
5349 handleARMInterruptAttr(S, D, AL);
5350 break;
5351 }
5352}
5353
5354static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
5355 const ParsedAttr &AL) {
5356 uint32_t Min = 0;
5357 Expr *MinExpr = AL.getArgAsExpr(0);
5358 if (!checkUInt32Argument(S, AL, MinExpr, Min))
5359 return;
5360
5361 uint32_t Max = 0;
5362 Expr *MaxExpr = AL.getArgAsExpr(1);
5363 if (!checkUInt32Argument(S, AL, MaxExpr, Max))
5364 return;
5365
5366 if (Min == 0 && Max != 0) {
5367 S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid)
5368 << AL.getName() << 0;
5369 return;
5370 }
5371 if (Min > Max) {
5372 S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid)
5373 << AL.getName() << 1;
5374 return;
5375 }
5376
5377 D->addAttr(::new (S.Context)
5378 AMDGPUFlatWorkGroupSizeAttr(AL.getLoc(), S.Context, Min, Max,
5379 AL.getAttributeSpellingListIndex()));
5380}
5381
5382static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5383 uint32_t Min = 0;
5384 Expr *MinExpr = AL.getArgAsExpr(0);
5385 if (!checkUInt32Argument(S, AL, MinExpr, Min))
5386 return;
5387
5388 uint32_t Max = 0;
5389 if (AL.getNumArgs() == 2) {
5390 Expr *MaxExpr = AL.getArgAsExpr(1);
5391 if (!checkUInt32Argument(S, AL, MaxExpr, Max))
5392 return;
5393 }
5394
5395 if (Min == 0 && Max != 0) {
5396 S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid)
5397 << AL.getName() << 0;
5398 return;
5399 }
5400 if (Max != 0 && Min > Max) {
5401 S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid)
5402 << AL.getName() << 1;
5403 return;
5404 }
5405
5406 D->addAttr(::new (S.Context)
5407 AMDGPUWavesPerEUAttr(AL.getLoc(), S.Context, Min, Max,
5408 AL.getAttributeSpellingListIndex()));
5409}
5410
5411static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5412 uint32_t NumSGPR = 0;
5413 Expr *NumSGPRExpr = AL.getArgAsExpr(0);
5414 if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR))
5415 return;
5416
5417 D->addAttr(::new (S.Context)
5418 AMDGPUNumSGPRAttr(AL.getLoc(), S.Context, NumSGPR,
5419 AL.getAttributeSpellingListIndex()));
5420}
5421
5422static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5423 uint32_t NumVGPR = 0;
5424 Expr *NumVGPRExpr = AL.getArgAsExpr(0);
5425 if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR))
5426 return;
5427
5428 D->addAttr(::new (S.Context)
5429 AMDGPUNumVGPRAttr(AL.getLoc(), S.Context, NumVGPR,
5430 AL.getAttributeSpellingListIndex()));
5431}
5432
5433static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
5434 const ParsedAttr &AL) {
5435 // If we try to apply it to a function pointer, don't warn, but don't
5436 // do anything, either. It doesn't matter anyway, because there's nothing
5437 // special about calling a force_align_arg_pointer function.
5438 const auto *VD = dyn_cast<ValueDecl>(D);
5439 if (VD && VD->getType()->isFunctionPointerType())
5440 return;
5441 // Also don't warn on function pointer typedefs.
5442 const auto *TD = dyn_cast<TypedefNameDecl>(D);
5443 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
5444 TD->getUnderlyingType()->isFunctionType()))
5445 return;
5446 // Attribute can only be applied to function types.
5447 if (!isa<FunctionDecl>(D)) {
5448 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
5449 << AL.getName() << ExpectedFunction;
5450 return;
5451 }
5452
5453 D->addAttr(::new (S.Context)
5454 X86ForceAlignArgPointerAttr(AL.getRange(), S.Context,
5455 AL.getAttributeSpellingListIndex()));
5456}
5457
5458static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) {
5459 uint32_t Version;
5460 Expr *VersionExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
5461 if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Version))
5462 return;
5463
5464 // TODO: Investigate what happens with the next major version of MSVC.
5465 if (Version != LangOptions::MSVC2015) {
5466 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
5467 << AL.getName() << Version << VersionExpr->getSourceRange();
5468 return;
5469 }
5470
5471 D->addAttr(::new (S.Context)
5472 LayoutVersionAttr(AL.getRange(), S.Context, Version,
5473 AL.getAttributeSpellingListIndex()));
5474}
5475
5476DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range,
5477 unsigned AttrSpellingListIndex) {
5478 if (D->hasAttr<DLLExportAttr>()) {
5479 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'";
5480 return nullptr;
5481 }
5482
5483 if (D->hasAttr<DLLImportAttr>())
5484 return nullptr;
5485
5486 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex);
5487}
5488
5489DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range,
5490 unsigned AttrSpellingListIndex) {
5491 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
5492 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
5493 D->dropAttr<DLLImportAttr>();
5494 }
5495
5496 if (D->hasAttr<DLLExportAttr>())
5497 return nullptr;
5498
5499 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex);
5500}
5501
5502static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) {
5503 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
5504 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5505 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored)
5506 << A.getName();
5507 return;
5508 }
5509
5510 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
5511 if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport &&
5512 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5513 // MinGW doesn't allow dllimport on inline functions.
5514 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
5515 << A.getName();
5516 return;
5517 }
5518 }
5519
5520 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
5521 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5522 MD->getParent()->isLambda()) {
5523 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName();
5524 return;
5525 }
5526 }
5527
5528 unsigned Index = A.getAttributeSpellingListIndex();
5529 Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport
5530 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index)
5531 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index);
5532 if (NewAttr)
5533 D->addAttr(NewAttr);
5534}
5535
5536MSInheritanceAttr *
5537Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
5538 unsigned AttrSpellingListIndex,
5539 MSInheritanceAttr::Spelling SemanticSpelling) {
5540 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
5541 if (IA->getSemanticSpelling() == SemanticSpelling)
5542 return nullptr;
5543 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
5544 << 1 /*previous declaration*/;
5545 Diag(Range.getBegin(), diag::note_previous_ms_inheritance);
5546 D->dropAttr<MSInheritanceAttr>();
5547 }
5548
5549 auto *RD = cast<CXXRecordDecl>(D);
5550 if (RD->hasDefinition()) {
5551 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase,
5552 SemanticSpelling)) {
5553 return nullptr;
5554 }
5555 } else {
5556 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
5557 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5558 << 1 /*partial specialization*/;
5559 return nullptr;
5560 }
5561 if (RD->getDescribedClassTemplate()) {
5562 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance)
5563 << 0 /*primary template*/;
5564 return nullptr;
5565 }
5566 }
5567
5568 return ::new (Context)
5569 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex);
5570}
5571
5572static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5573 // The capability attributes take a single string parameter for the name of
5574 // the capability they represent. The lockable attribute does not take any
5575 // parameters. However, semantically, both attributes represent the same
5576 // concept, and so they use the same semantic attribute. Eventually, the
5577 // lockable attribute will be removed.
5578 //
5579 // For backward compatibility, any capability which has no specified string
5580 // literal will be considered a "mutex."
5581 StringRef N("mutex");
5582 SourceLocation LiteralLoc;
5583 if (AL.getKind() == ParsedAttr::AT_Capability &&
5584 !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc))
5585 return;
5586
5587 // Currently, there are only two names allowed for a capability: role and
5588 // mutex (case insensitive). Diagnose other capability names.
5589 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
5590 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
5591
5592 D->addAttr(::new (S.Context) CapabilityAttr(AL.getRange(), S.Context, N,
5593 AL.getAttributeSpellingListIndex()));
5594}
5595
5596static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5597 SmallVector<Expr*, 1> Args;
5598 if (!checkLockFunAttrCommon(S, D, AL, Args))
5599 return;
5600
5601 D->addAttr(::new (S.Context) AssertCapabilityAttr(AL.getRange(), S.Context,
5602 Args.data(), Args.size(),
5603 AL.getAttributeSpellingListIndex()));
5604}
5605
5606static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
5607 const ParsedAttr &AL) {
5608 SmallVector<Expr*, 1> Args;
5609 if (!checkLockFunAttrCommon(S, D, AL, Args))
5610 return;
5611
5612 D->addAttr(::new (S.Context) AcquireCapabilityAttr(AL.getRange(),
5613 S.Context,
5614 Args.data(), Args.size(),
5615 AL.getAttributeSpellingListIndex()));
5616}
5617
5618static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
5619 const ParsedAttr &AL) {
5620 SmallVector<Expr*, 2> Args;
5621 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
5622 return;
5623
5624 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(AL.getRange(),
5625 S.Context,
5626 AL.getArgAsExpr(0),
5627 Args.data(),
5628 Args.size(),
5629 AL.getAttributeSpellingListIndex()));
5630}
5631
5632static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
5633 const ParsedAttr &AL) {
5634 // Check that all arguments are lockable objects.
5635 SmallVector<Expr *, 1> Args;
5636 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, true);
5637
5638 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(
5639 AL.getRange(), S.Context, Args.data(), Args.size(),
5640 AL.getAttributeSpellingListIndex()));
5641}
5642
5643static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
5644 const ParsedAttr &AL) {
5645 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
5646 return;
5647
5648 // check that all arguments are lockable objects
5649 SmallVector<Expr*, 1> Args;
5650 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
5651 if (Args.empty())
5652 return;
5653
5654 RequiresCapabilityAttr *RCA = ::new (S.Context)
5655 RequiresCapabilityAttr(AL.getRange(), S.Context, Args.data(),
5656 Args.size(), AL.getAttributeSpellingListIndex());
5657
5658 D->addAttr(RCA);
5659}
5660
5661static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5662 if (const auto *NSD = dyn_cast<NamespaceDecl>(D)) {
5663 if (NSD->isAnonymousNamespace()) {
5664 S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace);
5665 // Do not want to attach the attribute to the namespace because that will
5666 // cause confusing diagnostic reports for uses of declarations within the
5667 // namespace.
5668 return;
5669 }
5670 }
5671
5672 // Handle the cases where the attribute has a text message.
5673 StringRef Str, Replacement;
5674 if (AL.isArgExpr(0) && AL.getArgAsExpr(0) &&
5675 !S.checkStringLiteralArgumentAttr(AL, 0, Str))
5676 return;
5677
5678 // Only support a single optional message for Declspec and CXX11.
5679 if (AL.isDeclspecAttribute() || AL.isCXX11Attribute())
5680 checkAttributeAtMostNumArgs(S, AL, 1);
5681 else if (AL.isArgExpr(1) && AL.getArgAsExpr(1) &&
5682 !S.checkStringLiteralArgumentAttr(AL, 1, Replacement))
5683 return;
5684
5685 if (!S.getLangOpts().CPlusPlus14)
5686 if (AL.isCXX11Attribute() &&
5687 !(AL.hasScope() && AL.getScopeName()->isStr("gnu")))
5688 S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL.getName();
5689
5690 D->addAttr(::new (S.Context)
5691 DeprecatedAttr(AL.getRange(), S.Context, Str, Replacement,
5692 AL.getAttributeSpellingListIndex()));
5693}
5694
5695static bool isGlobalVar(const Decl *D) {
5696 if (const auto *S = dyn_cast<VarDecl>(D))
5697 return S->hasGlobalStorage();
5698 return false;
5699}
5700
5701static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5702 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
5703 return;
5704
5705 std::vector<StringRef> Sanitizers;
5706
5707 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
5708 StringRef SanitizerName;
5709 SourceLocation LiteralLoc;
5710
5711 if (!S.checkStringLiteralArgumentAttr(AL, I, SanitizerName, &LiteralLoc))
5712 return;
5713
5714 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0)
5715 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
5716 else if (isGlobalVar(D) && SanitizerName != "address")
5717 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5718 << AL.getName() << ExpectedFunctionOrMethod;
5719 Sanitizers.push_back(SanitizerName);
5720 }
5721
5722 D->addAttr(::new (S.Context) NoSanitizeAttr(
5723 AL.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(),
5724 AL.getAttributeSpellingListIndex()));
5725}
5726
5727static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
5728 const ParsedAttr &AL) {
5729 StringRef AttrName = AL.getName()->getName();
5730 normalizeName(AttrName);
5731 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
5732 .Case("no_address_safety_analysis", "address")
5733 .Case("no_sanitize_address", "address")
5734 .Case("no_sanitize_thread", "thread")
5735 .Case("no_sanitize_memory", "memory");
5736 if (isGlobalVar(D) && SanitizerName != "address")
5737 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
5738 << AL.getName() << ExpectedFunction;
5739 D->addAttr(::new (S.Context)
5740 NoSanitizeAttr(AL.getRange(), S.Context, &SanitizerName, 1,
5741 AL.getAttributeSpellingListIndex()));
5742}
5743
5744static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5745 if (InternalLinkageAttr *Internal =
5746 S.mergeInternalLinkageAttr(D, AL.getRange(), AL.getName(),
5747 AL.getAttributeSpellingListIndex()))
5748 D->addAttr(Internal);
5749}
5750
5751static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5752 if (S.LangOpts.OpenCLVersion != 200)
5753 S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version)
5754 << AL.getName() << "2.0" << 0;
5755 else
5756 S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored)
5757 << AL.getName() << "2.0";
5758}
5759
5760/// Handles semantic checking for features that are common to all attributes,
5761/// such as checking whether a parameter was properly specified, or the correct
5762/// number of arguments were passed, etc.
5763static bool handleCommonAttributeFeatures(Sema &S, Decl *D,
5764 const ParsedAttr &AL) {
5765 // Several attributes carry different semantics than the parsing requires, so
5766 // those are opted out of the common argument checks.
5767 //
5768 // We also bail on unknown and ignored attributes because those are handled
5769 // as part of the target-specific handling logic.
5770 if (AL.getKind() == ParsedAttr::UnknownAttribute)
5771 return false;
5772 // Check whether the attribute requires specific language extensions to be
5773 // enabled.
5774 if (!AL.diagnoseLangOpts(S))
5775 return true;
5776 // Check whether the attribute appertains to the given subject.
5777 if (!AL.diagnoseAppertainsTo(S, D))
5778 return true;
5779 if (AL.hasCustomParsing())
5780 return false;
5781
5782 if (AL.getMinArgs() == AL.getMaxArgs()) {
5783 // If there are no optional arguments, then checking for the argument count
5784 // is trivial.
5785 if (!checkAttributeNumArgs(S, AL, AL.getMinArgs()))
5786 return true;
5787 } else {
5788 // There are optional arguments, so checking is slightly more involved.
5789 if (AL.getMinArgs() &&
5790 !checkAttributeAtLeastNumArgs(S, AL, AL.getMinArgs()))
5791 return true;
5792 else if (!AL.hasVariadicArg() && AL.getMaxArgs() &&
5793 !checkAttributeAtMostNumArgs(S, AL, AL.getMaxArgs()))
5794 return true;
5795 }
5796
5797 if (S.CheckAttrTarget(AL))
5798 return true;
5799
5800 return false;
5801}
5802
5803static void handleOpenCLAccessAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5804 if (D->isInvalidDecl())
5805 return;
5806
5807 // Check if there is only one access qualifier.
5808 if (D->hasAttr<OpenCLAccessAttr>()) {
5809 S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers)
5810 << D->getSourceRange();
5811 D->setInvalidDecl(true);
5812 return;
5813 }
5814
5815 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
5816 // image object can be read and written.
5817 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
5818 // object. Using the read_write (or __read_write) qualifier with the pipe
5819 // qualifier is a compilation error.
5820 if (const auto *PDecl = dyn_cast<ParmVarDecl>(D)) {
5821 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
5822 if (AL.getName()->getName().find("read_write") != StringRef::npos) {
5823 if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) {
5824 S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write)
5825 << AL.getName() << PDecl->getType() << DeclTy->isImageType();
5826 D->setInvalidDecl(true);
5827 return;
5828 }
5829 }
5830 }
5831
5832 D->addAttr(::new (S.Context) OpenCLAccessAttr(
5833 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex()));
5834}
5835
5836//===----------------------------------------------------------------------===//
5837// Top Level Sema Entry Points
5838//===----------------------------------------------------------------------===//
5839
5840/// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
5841/// the attribute applies to decls. If the attribute is a type attribute, just
5842/// silently ignore it if a GNU attribute.
5843static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
5844 const ParsedAttr &AL,
5845 bool IncludeCXX11Attributes) {
5846 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
5847 return;
5848
5849 // Ignore C++11 attributes on declarator chunks: they appertain to the type
5850 // instead.
5851 if (AL.isCXX11Attribute() && !IncludeCXX11Attributes)
5852 return;
5853
5854 // Unknown attributes are automatically warned on. Target-specific attributes
5855 // which do not apply to the current target architecture are treated as
5856 // though they were unknown attributes.
5857 if (AL.getKind() == ParsedAttr::UnknownAttribute ||
5858 !AL.existsInTarget(S.Context.getTargetInfo())) {
5859 S.Diag(AL.getLoc(), AL.isDeclspecAttribute()
5860 ? diag::warn_unhandled_ms_attribute_ignored
5861 : diag::warn_unknown_attribute_ignored)
5862 << AL.getName();
5863 return;
5864 }
5865
5866 if (handleCommonAttributeFeatures(S, D, AL))
5867 return;
5868
5869 switch (AL.getKind()) {
5870 default:
5871 if (!AL.isStmtAttr()) {
5872 // Type attributes are handled elsewhere; silently move on.
5873 assert(AL.isTypeAttr() && "Non-type attribute not handled")(static_cast <bool> (AL.isTypeAttr() && "Non-type attribute not handled"
) ? void (0) : __assert_fail ("AL.isTypeAttr() && \"Non-type attribute not handled\""
, "/build/llvm-toolchain-snapshot-7~svn337490/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 5873, __extension__ __PRETTY_FUNCTION__))
;
5874 break;
5875 }
5876 S.Diag(AL.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
5877 << AL.getName() << D->getLocation();
5878 break;
5879 case ParsedAttr::AT_Interrupt:
5880 handleInterruptAttr(S, D, AL);
5881 break;
5882 case ParsedAttr::AT_X86ForceAlignArgPointer:
5883 handleX86ForceAlignArgPointerAttr(S, D, AL);
5884 break;
5885 case ParsedAttr::AT_DLLExport:
5886 case ParsedAttr::AT_DLLImport:
5887 handleDLLAttr(S, D, AL);
5888 break;
5889 case ParsedAttr::AT_Mips16:
5890 handleSimpleAttributeWithExclusions<Mips16Attr, MicroMipsAttr,
5891 MipsInterruptAttr>(S, D, AL);
5892 break;
5893 case ParsedAttr::AT_NoMips16:
5894 handleSimpleAttribute<NoMips16Attr>(S, D, AL);
5895 break;
5896 case ParsedAttr::AT_MicroMips:
5897 handleSimpleAttributeWithExclusions<MicroMipsAttr, Mips16Attr>(S, D, AL);
5898 break;
5899 case ParsedAttr::AT_NoMicroMips:
5900 handleSimpleAttribute<NoMicroMipsAttr>(S, D, AL);
5901 break;
5902 case ParsedAttr::AT_MipsLongCall:
5903 handleSimpleAttributeWithExclusions<MipsLongCallAttr, MipsShortCallAttr>(
5904 S, D, AL);
5905 break;
5906 case ParsedAttr::AT_MipsShortCall:
5907 handleSimpleAttributeWithExclusions<MipsShortCallAttr, MipsLongCallAttr>(
5908 S, D, AL);
5909 break;
5910 case ParsedAttr::AT_AMDGPUFlatWorkGroupSize:
5911 handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL);
5912 break;
5913 case ParsedAttr::AT_AMDGPUWavesPerEU:
5914 handleAMDGPUWavesPerEUAttr(S, D, AL);
5915 break;
5916 case ParsedAttr::AT_AMDGPUNumSGPR:
5917 handleAMDGPUNumSGPRAttr(S, D, AL);
5918 break;
5919 case ParsedAttr::AT_AMDGPUNumVGPR:
5920 handleAMDGPUNumVGPRAttr(S, D, AL);
5921 break;
5922 case ParsedAttr::AT_AVRSignal:
5923 handleAVRSignalAttr(S, D, AL);
5924 break;
5925 case ParsedAttr::AT_IBAction:
5926 handleSimpleAttribute<IBActionAttr>(S, D, AL);
5927 break;
5928 case ParsedAttr::AT_IBOutlet:
5929 handleIBOutlet(S, D, AL);
5930 break;
5931 case ParsedAttr::AT_IBOutletCollection:
5932 handleIBOutletCollection(S, D, AL);
5933 break;
5934 case ParsedAttr::AT_IFunc:
5935 handleIFuncAttr(S, D, AL);
5936 break;
5937 case ParsedAttr::AT_Alias:
5938 handleAliasAttr(S, D, AL);
5939 break;
5940 case ParsedAttr::AT_Aligned:
5941 handleAlignedAttr(S, D, AL);
5942 break;
5943 case ParsedAttr::AT_AlignValue:
5944 handleAlignValueAttr(S, D, AL);
5945 break;
5946 case ParsedAttr::AT_AllocSize:
5947 handleAllocSizeAttr(S, D, AL);
5948 break;
5949 case ParsedAttr::AT_AlwaysInline:
5950 handleAlwaysInlineAttr(S, D, AL);
5951 break;
5952 case ParsedAttr::AT_Artificial:
5953 handleSimpleAttribute<ArtificialAttr>(S, D, AL);
5954 break;
5955 case ParsedAttr::AT_AnalyzerNoReturn:
5956 handleAnalyzerNoReturnAttr(S, D, AL);
5957 break;
5958 case ParsedAttr::AT_TLSModel:
5959 handleTLSModelAttr(S, D, AL);
5960 break;
5961 case ParsedAttr::AT_Annotate:
5962 handleAnnotateAttr(S, D, AL);
5963 break;
5964 case ParsedAttr::AT_Availability:
5965 handleAvailabilityAttr(S, D, AL);
5966 break;
5967 case ParsedAttr::AT_CarriesDependency:
5968 handleDependencyAttr(S, scope, D, AL);
5969 break;
5970 case ParsedAttr::AT_Common:
5971 handleCommonAttr(S, D, AL);
5972 break;
5973 case ParsedAttr::AT_CUDAConstant:
5974 handleConstantAttr(S, D, AL);
5975 break;
5976 case ParsedAttr::AT_PassObjectSize:
5977 handlePassObjectSizeAttr(S, D, AL);
5978 break;
5979 case ParsedAttr::AT_Constructor:
5980 handleConstructorAttr(S, D, AL);
5981 break;
5982 case ParsedAttr::AT_CXX11NoReturn:
5983 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, AL);
5984 break;
5985 case ParsedAttr::AT_Deprecated:
5986 handleDeprecatedAttr(S, D, AL);
5987 break;
5988 case ParsedAttr::AT_Destructor:
5989 handleDestructorAttr(S, D, AL);
5990 break;
5991 case ParsedAttr::AT_EnableIf:
5992 handleEnableIfAttr(S, D, AL);
5993 break;
5994 case ParsedAttr::AT_DiagnoseIf:
5995 handleDiagnoseIfAttr(S, D, AL);
5996 break;
5997 case ParsedAttr::AT_ExtVectorType:
5998 handleExtVectorTypeAttr(S, D, AL);
5999 break;
6000 case ParsedAttr::AT_ExternalSourceSymbol:
6001 handleExternalSourceSymbolAttr(S, D, AL);
6002 break;
6003 case ParsedAttr::AT_MinSize:
6004 handleMinSizeAttr(S, D, AL);
6005 break;
6006 case ParsedAttr::AT_OptimizeNone:
6007 handleOptimizeNoneAttr(S, D, AL);
6008 break;
6009 case ParsedAttr::AT_FlagEnum:
6010 handleSimpleAttribute<FlagEnumAttr>(S, D, AL);
6011 break;
6012 case ParsedAttr::AT_EnumExtensibility:
6013 handleEnumExtensibilityAttr(S, D, AL);
6014 break;
6015 case ParsedAttr::AT_Flatten:
6016 handleSimpleAttribute<FlattenAttr>(S, D, AL);
6017 break;
6018 case ParsedAttr::AT_Format:
6019 handleFormatAttr(S, D, AL);
6020 break;
6021 case ParsedAttr::AT_FormatArg:
6022 handleFormatArgAttr(S, D, AL);
6023 break;
6024 case ParsedAttr::AT_CUDAGlobal:
6025 handleGlobalAttr(S, D, AL);
6026 break;
6027 case ParsedAttr::AT_CUDADevice:
6028 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
6029 AL);
6030 break;
6031 case ParsedAttr::AT_CUDAHost:
6032 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D, AL);
6033 break;
6034 case ParsedAttr::AT_GNUInline:
6035 handleGNUInlineAttr(S, D, AL);
6036 break;
6037 case ParsedAttr::AT_CUDALaunchBounds:
6038 handleLaunchBoundsAttr(S, D, AL);
6039 break;
6040 case ParsedAttr::AT_Restrict:
6041 handleRestrictAttr(S, D, AL);
6042 break;
6043 case ParsedAttr::AT_MayAlias:
6044 handleSimpleAttribute<MayAliasAttr>(S, D, AL);
6045 break;
6046 case ParsedAttr::AT_Mode:
6047 handleModeAttr(S, D, AL);
6048 break;
6049 case ParsedAttr::AT_NoAlias:
6050 handleSimpleAttribute<NoAliasAttr>(S, D, AL);
6051 break;
6052 case ParsedAttr::AT_NoCommon:
6053 handleSimpleAttribute<NoCommonAttr>(S, D, AL);
6054 break;
6055 case ParsedAttr::AT_NoSplitStack:
6056 handleSimpleAttribute<NoSplitStackAttr>(S, D, AL);
6057 break;
6058 case ParsedAttr::AT_NonNull:
6059 if (auto *PVD = dyn_cast<ParmVarDecl>(D))
6060 handleNonNullAttrParameter(S, PVD, AL);
6061 else
6062 handleNonNullAttr(S, D, AL);
6063 break;
6064 case ParsedAttr::AT_ReturnsNonNull:
6065 handleReturnsNonNullAttr(S, D, AL);
6066 break;
6067 case ParsedAttr::AT_NoEscape:
6068 handleNoEscapeAttr(S, D, AL);
6069 break;
6070 case ParsedAttr::AT_AssumeAligned:
6071 handleAssumeAlignedAttr(S, D, AL);
6072 break;
6073 case ParsedAttr::AT_AllocAlign:
6074 handleAllocAlignAttr(S, D, AL);
6075 break;
6076 case ParsedAttr::AT_Overloadable:
6077 handleSimpleAttribute<OverloadableAttr>(S, D, AL);
6078 break;
6079 case ParsedAttr::AT_Ownership:
6080 handleOwnershipAttr(S, D, AL);
6081 break;
6082 case ParsedAttr::AT_Cold:
6083 handleSimpleAttributeWithExclusions<ColdAttr, HotAttr>(S, D, AL);
6084 break;
6085 case ParsedAttr::AT_Hot:
6086 handleSimpleAttributeWithExclusions<HotAttr, ColdAttr>(S, D, AL);
6087 break;
6088 case ParsedAttr::AT_Naked:
6089 handleNakedAttr(S, D, AL);
6090 break;
6091 case ParsedAttr::AT_NoReturn:
6092 handleNoReturnAttr(S, D, AL);
6093 break;
6094 case ParsedAttr::AT_AnyX86NoCfCheck:
6095 handleNoCfCheckAttr(S, D, AL);
6096 break;
6097 case ParsedAttr::AT_NoThrow:
6098 handleSimpleAttribute<NoThrowAttr>(S, D, AL);
6099 break;
6100 case ParsedAttr::AT_CUDAShared:
6101 handleSharedAttr(S, D, AL);
6102 break;
6103 case ParsedAttr::AT_VecReturn:
6104 handleVecReturnAttr(S, D, AL);
6105 break;
6106 case ParsedAttr::AT_ObjCOwnership:
6107 handleObjCOwnershipAttr(S, D, AL);
6108 break;
6109 case ParsedAttr::AT_ObjCPreciseLifetime:
6110 handleObjCPreciseLifetimeAttr(S, D, AL);
6111 break;
6112 case ParsedAttr::AT_ObjCReturnsInnerPointer:
6113 handleObjCReturnsInnerPointerAttr(S, D, AL);
6114 break;
6115 case ParsedAttr::AT_ObjCRequiresSuper:
6116 handleObjCRequiresSuperAttr(S, D, AL);
6117 break;
6118 case ParsedAttr::AT_ObjCBridge:
6119 handleObjCBridgeAttr(S, D, AL);
6120 break;
6121 case ParsedAttr::AT_ObjCBridgeMutable:
6122 handleObjCBridgeMutableAttr(S, D, AL);
6123 break;
6124 case ParsedAttr::AT_ObjCBridgeRelated:
6125 handleObjCBridgeRelatedAttr(S, D, AL);
6126 break;
6127 case ParsedAttr::AT_ObjCDesignatedInitializer:
6128 handleObjCDesignatedInitializer(S, D, AL);
6129 break;
6130 case ParsedAttr::AT_ObjCRuntimeName:
6131 handleObjCRuntimeName(S, D, AL);
6132 break;
6133 case ParsedAttr::AT_ObjCRuntimeVisible:
6134 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, AL);
6135 break;
6136 case ParsedAttr::AT_ObjCBoxable:
6137 handleObjCBoxable(S, D, AL);
6138 break;
6139 case ParsedAttr::AT_CFAuditedTransfer:
6140 handleSimpleAttributeWithExclusions<CFAuditedTransferAttr,
6141 CFUnknownTransferAttr>(S, D, AL);
6142 break;
6143 case ParsedAttr::AT_CFUnknownTransfer:
6144 handleSimpleAttributeWithExclusions<CFUnknownTransferAttr,
6145 CFAuditedTransferAttr>(S, D, AL);
6146 break;
6147 case ParsedAttr::AT_CFConsumed:
6148 case ParsedAttr::AT_NSConsumed:
6149 handleNSConsumedAttr(S, D, AL);
6150 break;
6151 case ParsedAttr::AT_NSConsumesSelf:
6152 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, AL);
6153 break;
6154 case ParsedAttr::AT_NSReturnsAutoreleased:
6155 case ParsedAttr::AT_NSReturnsNotRetained:
6156 case ParsedAttr::AT_CFReturnsNotRetained:
6157 case ParsedAttr::AT_NSReturnsRetained:
6158 case ParsedAttr::AT_CFReturnsRetained:
6159 handleNSReturnsRetainedAttr(S, D, AL);
6160 break;
6161 case ParsedAttr::AT_WorkGroupSizeHint:
6162 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL);
6163 break;
6164 case ParsedAttr::AT_ReqdWorkGroupSize:
6165 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL);
6166 break;
6167 case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize:
6168 handleSubGroupSize(S, D, AL);
6169 break;
6170 case ParsedAttr::AT_VecTypeHint:
6171 handleVecTypeHint(S, D, AL);
6172 break;
6173 case ParsedAttr::AT_RequireConstantInit:
6174 handleSimpleAttribute<RequireConstantInitAttr>(S, D, AL);
6175 break;
6176 case ParsedAttr::AT_InitPriority:
6177 handleInitPriorityAttr(S, D, AL);
6178 break;
6179 case ParsedAttr::AT_Packed:
6180 handlePackedAttr(S, D, AL);
6181 break;
6182 case ParsedAttr::AT_Section:
6183 handleSectionAttr(S, D, AL);
6184 break;
6185 case ParsedAttr::AT_CodeSeg:
6186 handleCodeSegAttr(S, D, AL);
6187 break;
6188 case ParsedAttr::AT_Target:
6189 handleTargetAttr(S, D, AL);
6190 break;
6191 case ParsedAttr::AT_MinVectorWidth:
6192 handleMinVectorWidthAttr(S, D, AL);
6193 break;
6194 case ParsedAttr::AT_Unavailable:
6195 handleAttrWithMessage<UnavailableAttr>(S, D, AL);
6196 break;
6197 case ParsedAttr::AT_ArcWeakrefUnavailable:
6198 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, AL);
6199 break;
6200 case ParsedAttr::AT_ObjCRootClass:
6201 handleSimpleAttribute<ObjCRootClassAttr>(S, D, AL);
6202 break;
6203 case ParsedAttr::AT_ObjCSubclassingRestricted:
6204 handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, AL);
6205 break;
6206 case ParsedAttr::AT_ObjCExplicitProtocolImpl:
6207 handleObjCSuppresProtocolAttr(S, D, AL);
6208 break;
6209 case ParsedAttr::AT_ObjCRequiresPropertyDefs:
6210 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, AL);
6211 break;
6212 case ParsedAttr::AT_Unused:
6213 handleUnusedAttr(S, D, AL);
6214 break;
6215 case ParsedAttr::AT_ReturnsTwice:
6216 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, AL);
6217 break;
6218 case ParsedAttr::AT_NotTailCalled:
6219 handleSimpleAttributeWithExclusions<NotTailCalledAttr, AlwaysInlineAttr>(
6220 S, D, AL);
6221 break;
6222 case ParsedAttr::AT_DisableTailCalls:
6223 handleSimpleAttributeWithExclusions<DisableTailCallsAttr, NakedAttr>(S, D,
6224 AL);
6225 break;
6226 case ParsedAttr::AT_Used:
6227 handleSimpleAttribute<UsedAttr>(S, D, AL);
6228 break;
6229 case ParsedAttr::AT_Visibility:
6230 handleVisibilityAttr(S, D, AL, false);
6231 break;
6232 case ParsedAttr::AT_TypeVisibility:
6233 handleVisibilityAttr(S, D, AL, true);
6234 break;
6235 case ParsedAttr::AT_WarnUnused:
6236 handleSimpleAttribute<WarnUnusedAttr>(S, D, AL);
6237 break;
6238 case ParsedAttr::AT_WarnUnusedResult:
6239 handleWarnUnusedResult(S, D, AL);
6240 break;
6241 case ParsedAttr::AT_Weak:
6242 handleSimpleAttribute<WeakAttr>(S, D, AL);
6243 break;
6244 case ParsedAttr::AT_WeakRef:
6245 handleWeakRefAttr(S, D, AL);
6246 break;
6247 case ParsedAttr::AT_WeakImport:
6248 handleWeakImportAttr(S, D, AL);
6249 break;
6250 case ParsedAttr::AT_TransparentUnion:
6251 handleTransparentUnionAttr(S, D, AL);
6252 break;
6253 case ParsedAttr::AT_ObjCException:
6254 handleSimpleAttribute<ObjCExceptionAttr>(S, D, AL);
6255 break;
6256 case ParsedAttr::AT_ObjCMethodFamily:
6257 handleObjCMethodFamilyAttr(S, D, AL);
6258 break;
6259 case ParsedAttr::AT_ObjCNSObject:
6260 handleObjCNSObject(S, D, AL);
6261 break;
6262 case ParsedAttr::AT_ObjCIndependentClass:
6263 handleObjCIndependentClass(S, D, AL);
6264 break;
6265 case ParsedAttr::AT_Blocks:
6266 handleBlocksAttr(S, D, AL);
6267