Bug Summary

File:tools/clang/lib/Sema/SemaDeclAttr.cpp
Warning:line 3300, column 15
Called C++ object pointer is null

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-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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn373517/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/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++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn373517=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-02-234743-9763-1 -x c++ /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp

1//===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements decl-related attribute processing.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTMutationListener.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/Mangle.h"
23#include "clang/AST/RecursiveASTVisitor.h"
24#include "clang/Basic/CharInfo.h"
25#include "clang/Basic/SourceManager.h"
26#include "clang/Basic/TargetInfo.h"
27#include "clang/Lex/Preprocessor.h"
28#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/DelayedDiagnostic.h"
30#include "clang/Sema/Initialization.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Scope.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/SemaInternal.h"
35#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/StringExtras.h"
37#include "llvm/Support/MathExtras.h"
38
39using namespace clang;
40using namespace sema;
41
42namespace AttributeLangSupport {
43 enum LANG {
44 C,
45 Cpp,
46 ObjC
47 };
48} // end namespace AttributeLangSupport
49
50//===----------------------------------------------------------------------===//
51// Helper functions
52//===----------------------------------------------------------------------===//
53
54/// isFunctionOrMethod - Return true if the given decl has function
55/// type (function or function-typed variable) or an Objective-C
56/// method.
57static bool isFunctionOrMethod(const Decl *D) {
58 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
59}
60
61/// Return true if the given decl has function type (function or
62/// function-typed variable) or an Objective-C method or a block.
63static bool isFunctionOrMethodOrBlock(const Decl *D) {
64 return isFunctionOrMethod(D) || isa<BlockDecl>(D);
65}
66
67/// Return true if the given decl has a declarator that should have
68/// been processed by Sema::GetTypeForDeclarator.
69static bool hasDeclarator(const Decl *D) {
70 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
71 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
72 isa<ObjCPropertyDecl>(D);
73}
74
75/// hasFunctionProto - Return true if the given decl has a argument
76/// information. This decl should have already passed
77/// isFunctionOrMethod or isFunctionOrMethodOrBlock.
78static bool hasFunctionProto(const Decl *D) {
79 if (const FunctionType *FnTy = D->getFunctionType())
80 return isa<FunctionProtoType>(FnTy);
81 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
82}
83
84/// getFunctionOrMethodNumParams - Return number of function or method
85/// parameters. It is an error to call this on a K&R function (use
86/// hasFunctionProto first).
87static unsigned getFunctionOrMethodNumParams(const Decl *D) {
88 if (const FunctionType *FnTy = D->getFunctionType())
89 return cast<FunctionProtoType>(FnTy)->getNumParams();
90 if (const auto *BD = dyn_cast<BlockDecl>(D))
91 return BD->getNumParams();
92 return cast<ObjCMethodDecl>(D)->param_size();
93}
94
95static const ParmVarDecl *getFunctionOrMethodParam(const Decl *D,
96 unsigned Idx) {
97 if (const auto *FD = dyn_cast<FunctionDecl>(D))
98 return FD->getParamDecl(Idx);
99 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
100 return MD->getParamDecl(Idx);
101 if (const auto *BD = dyn_cast<BlockDecl>(D))
102 return BD->getParamDecl(Idx);
103 return nullptr;
104}
105
106static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
107 if (const FunctionType *FnTy = D->getFunctionType())
108 return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
109 if (const auto *BD = dyn_cast<BlockDecl>(D))
110 return BD->getParamDecl(Idx)->getType();
111
112 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
113}
114
115static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
116 if (auto *PVD = getFunctionOrMethodParam(D, Idx))
117 return PVD->getSourceRange();
118 return SourceRange();
119}
120
121static QualType getFunctionOrMethodResultType(const Decl *D) {
122 if (const FunctionType *FnTy = D->getFunctionType())
123 return FnTy->getReturnType();
124 return cast<ObjCMethodDecl>(D)->getReturnType();
125}
126
127static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
128 if (const auto *FD = dyn_cast<FunctionDecl>(D))
129 return FD->getReturnTypeSourceRange();
130 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
131 return MD->getReturnTypeSourceRange();
132 return SourceRange();
133}
134
135static bool isFunctionOrMethodVariadic(const Decl *D) {
136 if (const FunctionType *FnTy = D->getFunctionType())
137 return cast<FunctionProtoType>(FnTy)->isVariadic();
138 if (const auto *BD = dyn_cast<BlockDecl>(D))
139 return BD->isVariadic();
140 return cast<ObjCMethodDecl>(D)->isVariadic();
141}
142
143static bool isInstanceMethod(const Decl *D) {
144 if (const auto *MethodDecl
7.1
'MethodDecl' is null
7.1
'MethodDecl' is null
7.1
'MethodDecl' is null
= dyn_cast<CXXMethodDecl>(D))
7
Assuming 'D' is not a 'CXXMethodDecl'
8
Taking false branch
145 return MethodDecl->isInstance();
146 return false;
9
Returning zero, which participates in a condition later
147}
148
149static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
150 const auto *PT = T->getAs<ObjCObjectPointerType>();
151 if (!PT)
152 return false;
153
154 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
155 if (!Cls)
156 return false;
157
158 IdentifierInfo* ClsName = Cls->getIdentifier();
159
160 // FIXME: Should we walk the chain of classes?
161 return ClsName == &Ctx.Idents.get("NSString") ||
162 ClsName == &Ctx.Idents.get("NSMutableString");
163}
164
165static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
166 const auto *PT = T->getAs<PointerType>();
167 if (!PT)
168 return false;
169
170 const auto *RT = PT->getPointeeType()->getAs<RecordType>();
171 if (!RT)
172 return false;
173
174 const RecordDecl *RD = RT->getDecl();
175 if (RD->getTagKind() != TTK_Struct)
176 return false;
177
178 return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
179}
180
181static unsigned getNumAttributeArgs(const ParsedAttr &AL) {
182 // FIXME: Include the type in the argument list.
183 return AL.getNumArgs() + AL.hasParsedType();
184}
185
186template <typename Compare>
187static bool checkAttributeNumArgsImpl(Sema &S, const ParsedAttr &AL,
188 unsigned Num, unsigned Diag,
189 Compare Comp) {
190 if (Comp(getNumAttributeArgs(AL), Num)) {
191 S.Diag(AL.getLoc(), Diag) << AL << Num;
192 return false;
193 }
194
195 return true;
196}
197
198/// Check if the attribute has exactly as many args as Num. May
199/// output an error.
200static bool checkAttributeNumArgs(Sema &S, const ParsedAttr &AL, unsigned Num) {
201 return checkAttributeNumArgsImpl(S, AL, Num,
202 diag::err_attribute_wrong_number_arguments,
203 std::not_equal_to<unsigned>());
204}
205
206/// Check if the attribute has at least as many args as Num. May
207/// output an error.
208static bool checkAttributeAtLeastNumArgs(Sema &S, const ParsedAttr &AL,
209 unsigned Num) {
210 return checkAttributeNumArgsImpl(S, AL, Num,
211 diag::err_attribute_too_few_arguments,
212 std::less<unsigned>());
213}
214
215/// Check if the attribute has at most as many args as Num. May
216/// output an error.
217static bool checkAttributeAtMostNumArgs(Sema &S, const ParsedAttr &AL,
218 unsigned Num) {
219 return checkAttributeNumArgsImpl(S, AL, Num,
220 diag::err_attribute_too_many_arguments,
221 std::greater<unsigned>());
222}
223
224/// A helper function to provide Attribute Location for the Attr types
225/// AND the ParsedAttr.
226template <typename AttrInfo>
227static typename std::enable_if<std::is_base_of<Attr, AttrInfo>::value,
228 SourceLocation>::type
229getAttrLoc(const AttrInfo &AL) {
230 return AL.getLocation();
231}
232static SourceLocation getAttrLoc(const ParsedAttr &AL) { return AL.getLoc(); }
233
234/// If Expr is a valid integer constant, get the value of the integer
235/// expression and return success or failure. May output an error.
236///
237/// Negative argument is implicitly converted to unsigned, unless
238/// \p StrictlyUnsigned is true.
239template <typename AttrInfo>
240static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr,
241 uint32_t &Val, unsigned Idx = UINT_MAX(2147483647 *2U +1U),
242 bool StrictlyUnsigned = false) {
243 llvm::APSInt I(32);
244 if (Expr->isTypeDependent() || Expr->isValueDependent() ||
245 !Expr->isIntegerConstantExpr(I, S.Context)) {
246 if (Idx != UINT_MAX(2147483647 *2U +1U))
247 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
248 << &AI << Idx << AANT_ArgumentIntegerConstant
249 << Expr->getSourceRange();
250 else
251 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
252 << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
253 return false;
254 }
255
256 if (!I.isIntN(32)) {
257 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
258 << I.toString(10, false) << 32 << /* Unsigned */ 1;
259 return false;
260 }
261
262 if (StrictlyUnsigned && I.isSigned() && I.isNegative()) {
263 S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
264 << &AI << /*non-negative*/ 1;
265 return false;
266 }
267
268 Val = (uint32_t)I.getZExtValue();
269 return true;
270}
271
272/// Wrapper around checkUInt32Argument, with an extra check to be sure
273/// that the result will fit into a regular (signed) int. All args have the same
274/// purpose as they do in checkUInt32Argument.
275template <typename AttrInfo>
276static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr,
277 int &Val, unsigned Idx = UINT_MAX(2147483647 *2U +1U)) {
278 uint32_t UVal;
279 if (!checkUInt32Argument(S, AI, Expr, UVal, Idx))
280 return false;
281
282 if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
283 llvm::APSInt I(32); // for toString
284 I = UVal;
285 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
286 << I.toString(10, false) << 32 << /* Unsigned */ 0;
287 return false;
288 }
289
290 Val = UVal;
291 return true;
292}
293
294/// Diagnose mutually exclusive attributes when present on a given
295/// declaration. Returns true if diagnosed.
296template <typename AttrTy>
297static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL) {
298 if (const auto *A = D->getAttr<AttrTy>()) {
299 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << A;
300 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
301 return true;
302 }
303 return false;
304}
305
306template <typename AttrTy>
307static bool checkAttrMutualExclusion(Sema &S, Decl *D, const Attr &AL) {
308 if (const auto *A = D->getAttr<AttrTy>()) {
309 S.Diag(AL.getLocation(), diag::err_attributes_are_not_compatible) << &AL
310 << A;
311 S.Diag(A->getLocation(), diag::note_conflicting_attribute);
312 return true;
313 }
314 return false;
315}
316
317/// Check if IdxExpr is a valid parameter index for a function or
318/// instance method D. May output an error.
319///
320/// \returns true if IdxExpr is a valid index.
321template <typename AttrInfo>
322static bool checkFunctionOrMethodParameterIndex(
323 Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
324 const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) {
325 assert(isFunctionOrMethodOrBlock(D))((isFunctionOrMethodOrBlock(D)) ? static_cast<void> (0)
: __assert_fail ("isFunctionOrMethodOrBlock(D)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 325, __PRETTY_FUNCTION__))
;
326
327 // In C++ the implicit 'this' function parameter also counts.
328 // Parameters are counted from one.
329 bool HP = hasFunctionProto(D);
330 bool HasImplicitThisParam = isInstanceMethod(D);
331 bool IV = HP && isFunctionOrMethodVariadic(D);
332 unsigned NumParams =
333 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
334
335 llvm::APSInt IdxInt;
336 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
337 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
338 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
339 << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
340 << IdxExpr->getSourceRange();
341 return false;
342 }
343
344 unsigned IdxSource = IdxInt.getLimitedValue(UINT_MAX(2147483647 *2U +1U));
345 if (IdxSource < 1 || (!IV && IdxSource > NumParams)) {
346 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
347 << &AI << AttrArgNum << IdxExpr->getSourceRange();
348 return false;
349 }
350 if (HasImplicitThisParam && !CanIndexImplicitThis) {
351 if (IdxSource == 1) {
352 S.Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
353 << &AI << IdxExpr->getSourceRange();
354 return false;
355 }
356 }
357
358 Idx = ParamIdx(IdxSource, D);
359 return true;
360}
361
362/// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
363/// If not emit an error and return false. If the argument is an identifier it
364/// will emit an error with a fixit hint and treat it as if it was a string
365/// literal.
366bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum,
367 StringRef &Str,
368 SourceLocation *ArgLocation) {
369 // Look for identifiers. If we have one emit a hint to fix it to a literal.
370 if (AL.isArgIdent(ArgNum)) {
371 IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum);
372 Diag(Loc->Loc, diag::err_attribute_argument_type)
373 << AL << AANT_ArgumentString
374 << FixItHint::CreateInsertion(Loc->Loc, "\"")
375 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
376 Str = Loc->Ident->getName();
377 if (ArgLocation)
378 *ArgLocation = Loc->Loc;
379 return true;
380 }
381
382 // Now check for an actual string literal.
383 Expr *ArgExpr = AL.getArgAsExpr(ArgNum);
384 const auto *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
385 if (ArgLocation)
386 *ArgLocation = ArgExpr->getBeginLoc();
387
388 if (!Literal || !Literal->isAscii()) {
389 Diag(ArgExpr->getBeginLoc(), diag::err_attribute_argument_type)
390 << AL << AANT_ArgumentString;
391 return false;
392 }
393
394 Str = Literal->getString();
395 return true;
396}
397
398/// Applies the given attribute to the Decl without performing any
399/// additional semantic checking.
400template <typename AttrType>
401static void handleSimpleAttribute(Sema &S, Decl *D,
402 const AttributeCommonInfo &CI) {
403 D->addAttr(::new (S.Context) AttrType(S.Context, CI));
404}
405
406template <typename... DiagnosticArgs>
407static const Sema::SemaDiagnosticBuilder&
408appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr) {
409 return Bldr;
410}
411
412template <typename T, typename... DiagnosticArgs>
413static const Sema::SemaDiagnosticBuilder&
414appendDiagnostics(const Sema::SemaDiagnosticBuilder &Bldr, T &&ExtraArg,
415 DiagnosticArgs &&... ExtraArgs) {
416 return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
417 std::forward<DiagnosticArgs>(ExtraArgs)...);
418}
419
420/// Add an attribute {@code AttrType} to declaration {@code D}, provided that
421/// {@code PassesCheck} is true.
422/// Otherwise, emit diagnostic {@code DiagID}, passing in all parameters
423/// specified in {@code ExtraArgs}.
424template <typename AttrType, typename... DiagnosticArgs>
425static void handleSimpleAttributeOrDiagnose(Sema &S, Decl *D,
426 const AttributeCommonInfo &CI,
427 bool PassesCheck, unsigned DiagID,
428 DiagnosticArgs &&... ExtraArgs) {
429 if (!PassesCheck) {
430 Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID);
431 appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
432 return;
433 }
434 handleSimpleAttribute<AttrType>(S, D, CI);
435}
436
437template <typename AttrType>
438static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
439 const ParsedAttr &AL) {
440 handleSimpleAttribute<AttrType>(S, D, AL);
441}
442
443/// Applies the given attribute to the Decl so long as the Decl doesn't
444/// already have one of the given incompatible attributes.
445template <typename AttrType, typename IncompatibleAttrType,
446 typename... IncompatibleAttrTypes>
447static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
448 const ParsedAttr &AL) {
449 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, AL))
450 return;
451 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
452 AL);
453}
454
455/// Check if the passed-in expression is of type int or bool.
456static bool isIntOrBool(Expr *Exp) {
457 QualType QT = Exp->getType();
458 return QT->isBooleanType() || QT->isIntegerType();
459}
460
461
462// Check to see if the type is a smart pointer of some kind. We assume
463// it's a smart pointer if it defines both operator-> and operator*.
464static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
465 auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record,
466 OverloadedOperatorKind Op) {
467 DeclContextLookupResult Result =
468 Record->lookup(S.Context.DeclarationNames.getCXXOperatorName(Op));
469 return !Result.empty();
470 };
471
472 const RecordDecl *Record = RT->getDecl();
473 bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star);
474 bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow);
475 if (foundStarOperator && foundArrowOperator)
476 return true;
477
478 const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record);
479 if (!CXXRecord)
480 return false;
481
482 for (auto BaseSpecifier : CXXRecord->bases()) {
483 if (!foundStarOperator)
484 foundStarOperator = IsOverloadedOperatorPresent(
485 BaseSpecifier.getType()->getAsRecordDecl(), OO_Star);
486 if (!foundArrowOperator)
487 foundArrowOperator = IsOverloadedOperatorPresent(
488 BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow);
489 }
490
491 if (foundStarOperator && foundArrowOperator)
492 return true;
493
494 return false;
495}
496
497/// Check if passed in Decl is a pointer type.
498/// Note that this function may produce an error message.
499/// \return true if the Decl is a pointer type; false otherwise
500static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
501 const ParsedAttr &AL) {
502 const auto *VD = cast<ValueDecl>(D);
503 QualType QT = VD->getType();
504 if (QT->isAnyPointerType())
505 return true;
506
507 if (const auto *RT = QT->getAs<RecordType>()) {
508 // If it's an incomplete type, it could be a smart pointer; skip it.
509 // (We don't want to force template instantiation if we can avoid it,
510 // since that would alter the order in which templates are instantiated.)
511 if (RT->isIncompleteType())
512 return true;
513
514 if (threadSafetyCheckIsSmartPointer(S, RT))
515 return true;
516 }
517
518 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << AL << QT;
519 return false;
520}
521
522/// Checks that the passed in QualType either is of RecordType or points
523/// to RecordType. Returns the relevant RecordType, null if it does not exit.
524static const RecordType *getRecordType(QualType QT) {
525 if (const auto *RT = QT->getAs<RecordType>())
526 return RT;
527
528 // Now check if we point to record type.
529 if (const auto *PT = QT->getAs<PointerType>())
530 return PT->getPointeeType()->getAs<RecordType>();
531
532 return nullptr;
533}
534
535template <typename AttrType>
536static bool checkRecordDeclForAttr(const RecordDecl *RD) {
537 // Check if the record itself has the attribute.
538 if (RD->hasAttr<AttrType>())
539 return true;
540
541 // Else check if any base classes have the attribute.
542 if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
543 CXXBasePaths BPaths(false, false);
544 if (CRD->lookupInBases(
545 [](const CXXBaseSpecifier *BS, CXXBasePath &) {
546 const auto &Ty = *BS->getType();
547 // If it's type-dependent, we assume it could have the attribute.
548 if (Ty.isDependentType())
549 return true;
550 return Ty.getAs<RecordType>()->getDecl()->hasAttr<AttrType>();
551 },
552 BPaths, true))
553 return true;
554 }
555 return false;
556}
557
558static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
559 const RecordType *RT = getRecordType(Ty);
560
561 if (!RT)
562 return false;
563
564 // Don't check for the capability if the class hasn't been defined yet.
565 if (RT->isIncompleteType())
566 return true;
567
568 // Allow smart pointers to be used as capability objects.
569 // FIXME -- Check the type that the smart pointer points to.
570 if (threadSafetyCheckIsSmartPointer(S, RT))
571 return true;
572
573 return checkRecordDeclForAttr<CapabilityAttr>(RT->getDecl());
574}
575
576static bool checkTypedefTypeForCapability(QualType Ty) {
577 const auto *TD = Ty->getAs<TypedefType>();
578 if (!TD)
579 return false;
580
581 TypedefNameDecl *TN = TD->getDecl();
582 if (!TN)
583 return false;
584
585 return TN->hasAttr<CapabilityAttr>();
586}
587
588static bool typeHasCapability(Sema &S, QualType Ty) {
589 if (checkTypedefTypeForCapability(Ty))
590 return true;
591
592 if (checkRecordTypeForCapability(S, Ty))
593 return true;
594
595 return false;
596}
597
598static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
599 // Capability expressions are simple expressions involving the boolean logic
600 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
601 // a DeclRefExpr is found, its type should be checked to determine whether it
602 // is a capability or not.
603
604 if (const auto *E = dyn_cast<CastExpr>(Ex))
605 return isCapabilityExpr(S, E->getSubExpr());
606 else if (const auto *E = dyn_cast<ParenExpr>(Ex))
607 return isCapabilityExpr(S, E->getSubExpr());
608 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
609 if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
610 E->getOpcode() == UO_Deref)
611 return isCapabilityExpr(S, E->getSubExpr());
612 return false;
613 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
614 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
615 return isCapabilityExpr(S, E->getLHS()) &&
616 isCapabilityExpr(S, E->getRHS());
617 return false;
618 }
619
620 return typeHasCapability(S, Ex->getType());
621}
622
623/// Checks that all attribute arguments, starting from Sidx, resolve to
624/// a capability object.
625/// \param Sidx The attribute argument index to start checking with.
626/// \param ParamIdxOk Whether an argument can be indexing into a function
627/// parameter list.
628static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
629 const ParsedAttr &AL,
630 SmallVectorImpl<Expr *> &Args,
631 unsigned Sidx = 0,
632 bool ParamIdxOk = false) {
633 if (Sidx == AL.getNumArgs()) {
634 // If we don't have any capability arguments, the attribute implicitly
635 // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're
636 // a non-static method, and that the class is a (scoped) capability.
637 const auto *MD = dyn_cast<const CXXMethodDecl>(D);
638 if (MD && !MD->isStatic()) {
639 const CXXRecordDecl *RD = MD->getParent();
640 // FIXME -- need to check this again on template instantiation
641 if (!checkRecordDeclForAttr<CapabilityAttr>(RD) &&
642 !checkRecordDeclForAttr<ScopedLockableAttr>(RD))
643 S.Diag(AL.getLoc(),
644 diag::warn_thread_attribute_not_on_capability_member)
645 << AL << MD->getParent();
646 } else {
647 S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member)
648 << AL;
649 }
650 }
651
652 for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) {
653 Expr *ArgExp = AL.getArgAsExpr(Idx);
654
655 if (ArgExp->isTypeDependent()) {
656 // FIXME -- need to check this again on template instantiation
657 Args.push_back(ArgExp);
658 continue;
659 }
660
661 if (const auto *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
662 if (StrLit->getLength() == 0 ||
663 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
664 // Pass empty strings to the analyzer without warnings.
665 // Treat "*" as the universal lock.
666 Args.push_back(ArgExp);
667 continue;
668 }
669
670 // We allow constant strings to be used as a placeholder for expressions
671 // that are not valid C++ syntax, but warn that they are ignored.
672 S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL;
673 Args.push_back(ArgExp);
674 continue;
675 }
676
677 QualType ArgTy = ArgExp->getType();
678
679 // A pointer to member expression of the form &MyClass::mu is treated
680 // specially -- we need to look at the type of the member.
681 if (const auto *UOp = dyn_cast<UnaryOperator>(ArgExp))
682 if (UOp->getOpcode() == UO_AddrOf)
683 if (const auto *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
684 if (DRE->getDecl()->isCXXInstanceMember())
685 ArgTy = DRE->getDecl()->getType();
686
687 // First see if we can just cast to record type, or pointer to record type.
688 const RecordType *RT = getRecordType(ArgTy);
689
690 // Now check if we index into a record type function param.
691 if(!RT && ParamIdxOk) {
692 const auto *FD = dyn_cast<FunctionDecl>(D);
693 const auto *IL = dyn_cast<IntegerLiteral>(ArgExp);
694 if(FD && IL) {
695 unsigned int NumParams = FD->getNumParams();
696 llvm::APInt ArgValue = IL->getValue();
697 uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
698 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
699 if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
700 S.Diag(AL.getLoc(),
701 diag::err_attribute_argument_out_of_bounds_extra_info)
702 << AL << Idx + 1 << NumParams;
703 continue;
704 }
705 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
706 }
707 }
708
709 // If the type does not have a capability, see if the components of the
710 // expression have capabilities. This allows for writing C code where the
711 // capability may be on the type, and the expression is a capability
712 // boolean logic expression. Eg) requires_capability(A || B && !C)
713 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
714 S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
715 << AL << ArgTy;
716
717 Args.push_back(ArgExp);
718 }
719}
720
721//===----------------------------------------------------------------------===//
722// Attribute Implementations
723//===----------------------------------------------------------------------===//
724
725static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
726 if (!threadSafetyCheckIsPointer(S, D, AL))
727 return;
728
729 D->addAttr(::new (S.Context) PtGuardedVarAttr(S.Context, AL));
730}
731
732static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
733 Expr *&Arg) {
734 SmallVector<Expr *, 1> Args;
735 // check that all arguments are lockable objects
736 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
737 unsigned Size = Args.size();
738 if (Size != 1)
739 return false;
740
741 Arg = Args[0];
742
743 return true;
744}
745
746static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
747 Expr *Arg = nullptr;
748 if (!checkGuardedByAttrCommon(S, D, AL, Arg))
749 return;
750
751 D->addAttr(::new (S.Context) GuardedByAttr(S.Context, AL, Arg));
752}
753
754static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
755 Expr *Arg = nullptr;
756 if (!checkGuardedByAttrCommon(S, D, AL, Arg))
757 return;
758
759 if (!threadSafetyCheckIsPointer(S, D, AL))
760 return;
761
762 D->addAttr(::new (S.Context) PtGuardedByAttr(S.Context, AL, Arg));
763}
764
765static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
766 SmallVectorImpl<Expr *> &Args) {
767 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
768 return false;
769
770 // Check that this attribute only applies to lockable types.
771 QualType QT = cast<ValueDecl>(D)->getType();
772 if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
773 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable) << AL;
774 return false;
775 }
776
777 // Check that all arguments are lockable objects.
778 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
779 if (Args.empty())
780 return false;
781
782 return true;
783}
784
785static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
786 SmallVector<Expr *, 1> Args;
787 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
788 return;
789
790 Expr **StartArg = &Args[0];
791 D->addAttr(::new (S.Context)
792 AcquiredAfterAttr(S.Context, AL, StartArg, Args.size()));
793}
794
795static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
796 SmallVector<Expr *, 1> Args;
797 if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
798 return;
799
800 Expr **StartArg = &Args[0];
801 D->addAttr(::new (S.Context)
802 AcquiredBeforeAttr(S.Context, AL, StartArg, Args.size()));
803}
804
805static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
806 SmallVectorImpl<Expr *> &Args) {
807 // zero or more arguments ok
808 // check that all arguments are lockable objects
809 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, /*ParamIdxOk=*/true);
810
811 return true;
812}
813
814static void handleAssertSharedLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
815 SmallVector<Expr *, 1> Args;
816 if (!checkLockFunAttrCommon(S, D, AL, Args))
817 return;
818
819 unsigned Size = Args.size();
820 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
821 D->addAttr(::new (S.Context)
822 AssertSharedLockAttr(S.Context, AL, StartArg, Size));
823}
824
825static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
826 const ParsedAttr &AL) {
827 SmallVector<Expr *, 1> Args;
828 if (!checkLockFunAttrCommon(S, D, AL, Args))
829 return;
830
831 unsigned Size = Args.size();
832 Expr **StartArg = Size == 0 ? nullptr : &Args[0];
833 D->addAttr(::new (S.Context)
834 AssertExclusiveLockAttr(S.Context, AL, StartArg, Size));
835}
836
837/// Checks to be sure that the given parameter number is in bounds, and
838/// is an integral type. Will emit appropriate diagnostics if this returns
839/// false.
840///
841/// AttrArgNo is used to actually retrieve the argument, so it's base-0.
842template <typename AttrInfo>
843static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD,
844 const AttrInfo &AI, unsigned AttrArgNo) {
845 assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument")((AI.isArgExpr(AttrArgNo) && "Expected expression argument"
) ? static_cast<void> (0) : __assert_fail ("AI.isArgExpr(AttrArgNo) && \"Expected expression argument\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 845, __PRETTY_FUNCTION__))
;
846 Expr *AttrArg = AI.getArgAsExpr(AttrArgNo);
847 ParamIdx Idx;
848 if (!checkFunctionOrMethodParameterIndex(S, FD, AI, AttrArgNo + 1, AttrArg,
849 Idx))
850 return false;
851
852 const ParmVarDecl *Param = FD->getParamDecl(Idx.getASTIndex());
853 if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) {
854 SourceLocation SrcLoc = AttrArg->getBeginLoc();
855 S.Diag(SrcLoc, diag::err_attribute_integers_only)
856 << AI << Param->getSourceRange();
857 return false;
858 }
859 return true;
860}
861
862static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
863 if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
864 !checkAttributeAtMostNumArgs(S, AL, 2))
865 return;
866
867 const auto *FD = cast<FunctionDecl>(D);
868 if (!FD->getReturnType()->isPointerType()) {
869 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL;
870 return;
871 }
872
873 const Expr *SizeExpr = AL.getArgAsExpr(0);
874 int SizeArgNoVal;
875 // Parameter indices are 1-indexed, hence Index=1
876 if (!checkPositiveIntArgument(S, AL, SizeExpr, SizeArgNoVal, /*Idx=*/1))
877 return;
878 if (!checkParamIsIntegerType(S, FD, AL, /*AttrArgNo=*/0))
879 return;
880 ParamIdx SizeArgNo(SizeArgNoVal, D);
881
882 ParamIdx NumberArgNo;
883 if (AL.getNumArgs() == 2) {
884 const Expr *NumberExpr = AL.getArgAsExpr(1);
885 int Val;
886 // Parameter indices are 1-based, hence Index=2
887 if (!checkPositiveIntArgument(S, AL, NumberExpr, Val, /*Idx=*/2))
888 return;
889 if (!checkParamIsIntegerType(S, FD, AL, /*AttrArgNo=*/1))
890 return;
891 NumberArgNo = ParamIdx(Val, D);
892 }
893
894 D->addAttr(::new (S.Context)
895 AllocSizeAttr(S.Context, AL, SizeArgNo, NumberArgNo));
896}
897
898static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
899 SmallVectorImpl<Expr *> &Args) {
900 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
901 return false;
902
903 if (!isIntOrBool(AL.getArgAsExpr(0))) {
904 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
905 << AL << 1 << AANT_ArgumentIntOrBool;
906 return false;
907 }
908
909 // check that all arguments are lockable objects
910 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 1);
911
912 return true;
913}
914
915static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
916 const ParsedAttr &AL) {
917 SmallVector<Expr*, 2> Args;
918 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
919 return;
920
921 D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(
922 S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
923}
924
925static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
926 const ParsedAttr &AL) {
927 SmallVector<Expr*, 2> Args;
928 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
929 return;
930
931 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
932 S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
933}
934
935static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
936 // check that the argument is lockable object
937 SmallVector<Expr*, 1> Args;
938 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
939 unsigned Size = Args.size();
940 if (Size == 0)
941 return;
942
943 D->addAttr(::new (S.Context) LockReturnedAttr(S.Context, AL, Args[0]));
944}
945
946static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
947 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
948 return;
949
950 // check that all arguments are lockable objects
951 SmallVector<Expr*, 1> Args;
952 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
953 unsigned Size = Args.size();
954 if (Size == 0)
955 return;
956 Expr **StartArg = &Args[0];
957
958 D->addAttr(::new (S.Context)
959 LocksExcludedAttr(S.Context, AL, StartArg, Size));
960}
961
962static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL,
963 Expr *&Cond, StringRef &Msg) {
964 Cond = AL.getArgAsExpr(0);
965 if (!Cond->isTypeDependent()) {
966 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
967 if (Converted.isInvalid())
968 return false;
969 Cond = Converted.get();
970 }
971
972 if (!S.checkStringLiteralArgumentAttr(AL, 1, Msg))
973 return false;
974
975 if (Msg.empty())
976 Msg = "<no message provided>";
977
978 SmallVector<PartialDiagnosticAt, 8> Diags;
979 if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
980 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
981 Diags)) {
982 S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr) << AL;
983 for (const PartialDiagnosticAt &PDiag : Diags)
984 S.Diag(PDiag.first, PDiag.second);
985 return false;
986 }
987 return true;
988}
989
990static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
991 S.Diag(AL.getLoc(), diag::ext_clang_enable_if);
992
993 Expr *Cond;
994 StringRef Msg;
995 if (checkFunctionConditionAttr(S, D, AL, Cond, Msg))
996 D->addAttr(::new (S.Context) EnableIfAttr(S.Context, AL, Cond, Msg));
997}
998
999namespace {
1000/// Determines if a given Expr references any of the given function's
1001/// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
1002class ArgumentDependenceChecker
1003 : public RecursiveASTVisitor<ArgumentDependenceChecker> {
1004#ifndef NDEBUG
1005 const CXXRecordDecl *ClassType;
1006#endif
1007 llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms;
1008 bool Result;
1009
1010public:
1011 ArgumentDependenceChecker(const FunctionDecl *FD) {
1012#ifndef NDEBUG
1013 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1014 ClassType = MD->getParent();
1015 else
1016 ClassType = nullptr;
1017#endif
1018 Parms.insert(FD->param_begin(), FD->param_end());
1019 }
1020
1021 bool referencesArgs(Expr *E) {
1022 Result = false;
1023 TraverseStmt(E);
1024 return Result;
1025 }
1026
1027 bool VisitCXXThisExpr(CXXThisExpr *E) {
1028 assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&((E->getType()->getPointeeCXXRecordDecl() == ClassType &&
"`this` doesn't refer to the enclosing class?") ? static_cast
<void> (0) : __assert_fail ("E->getType()->getPointeeCXXRecordDecl() == ClassType && \"`this` doesn't refer to the enclosing class?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 1029, __PRETTY_FUNCTION__))
1029 "`this` doesn't refer to the enclosing class?")((E->getType()->getPointeeCXXRecordDecl() == ClassType &&
"`this` doesn't refer to the enclosing class?") ? static_cast
<void> (0) : __assert_fail ("E->getType()->getPointeeCXXRecordDecl() == ClassType && \"`this` doesn't refer to the enclosing class?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 1029, __PRETTY_FUNCTION__))
;
1030 Result = true;
1031 return false;
1032 }
1033
1034 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
1035 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
1036 if (Parms.count(PVD)) {
1037 Result = true;
1038 return false;
1039 }
1040 return true;
1041 }
1042};
1043}
1044
1045static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1046 S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if);
1047
1048 Expr *Cond;
1049 StringRef Msg;
1050 if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg))
1051 return;
1052
1053 StringRef DiagTypeStr;
1054 if (!S.checkStringLiteralArgumentAttr(AL, 2, DiagTypeStr))
1055 return;
1056
1057 DiagnoseIfAttr::DiagnosticType DiagType;
1058 if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
1059 S.Diag(AL.getArgAsExpr(2)->getBeginLoc(),
1060 diag::err_diagnose_if_invalid_diagnostic_type);
1061 return;
1062 }
1063
1064 bool ArgDependent = false;
1065 if (const auto *FD = dyn_cast<FunctionDecl>(D))
1066 ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
1067 D->addAttr(::new (S.Context) DiagnoseIfAttr(
1068 S.Context, AL, Cond, Msg, DiagType, ArgDependent, cast<NamedDecl>(D)));
1069}
1070
1071static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1072 if (D->hasAttr<PassObjectSizeAttr>()) {
1073 S.Diag(D->getBeginLoc(), diag::err_attribute_only_once_per_parameter) << AL;
1074 return;
1075 }
1076
1077 Expr *E = AL.getArgAsExpr(0);
1078 uint32_t Type;
1079 if (!checkUInt32Argument(S, AL, E, Type, /*Idx=*/1))
1080 return;
1081
1082 // pass_object_size's argument is passed in as the second argument of
1083 // __builtin_object_size. So, it has the same constraints as that second
1084 // argument; namely, it must be in the range [0, 3].
1085 if (Type > 3) {
1086 S.Diag(E->getBeginLoc(), diag::err_attribute_argument_out_of_range)
1087 << AL << 0 << 3 << E->getSourceRange();
1088 return;
1089 }
1090
1091 // pass_object_size is only supported on constant pointer parameters; as a
1092 // kindness to users, we allow the parameter to be non-const for declarations.
1093 // At this point, we have no clue if `D` belongs to a function declaration or
1094 // definition, so we defer the constness check until later.
1095 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1096 S.Diag(D->getBeginLoc(), diag::err_attribute_pointers_only) << AL << 1;
1097 return;
1098 }
1099
1100 D->addAttr(::new (S.Context) PassObjectSizeAttr(S.Context, AL, (int)Type));
1101}
1102
1103static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1104 ConsumableAttr::ConsumedState DefaultState;
1105
1106 if (AL.isArgIdent(0)) {
1107 IdentifierLoc *IL = AL.getArgAsIdent(0);
1108 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1109 DefaultState)) {
1110 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1111 << IL->Ident;
1112 return;
1113 }
1114 } else {
1115 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1116 << AL << AANT_ArgumentIdentifier;
1117 return;
1118 }
1119
1120 D->addAttr(::new (S.Context) ConsumableAttr(S.Context, AL, DefaultState));
1121}
1122
1123static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1124 const ParsedAttr &AL) {
1125 QualType ThisType = MD->getThisType()->getPointeeType();
1126
1127 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1128 if (!RD->hasAttr<ConsumableAttr>()) {
1129 S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) <<
1130 RD->getNameAsString();
1131
1132 return false;
1133 }
1134 }
1135
1136 return true;
1137}
1138
1139static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1140 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
1141 return;
1142
1143 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1144 return;
1145
1146 SmallVector<CallableWhenAttr::ConsumedState, 3> States;
1147 for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
1148 CallableWhenAttr::ConsumedState CallableState;
1149
1150 StringRef StateString;
1151 SourceLocation Loc;
1152 if (AL.isArgIdent(ArgIndex)) {
1153 IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
1154 StateString = Ident->Ident->getName();
1155 Loc = Ident->Loc;
1156 } else {
1157 if (!S.checkStringLiteralArgumentAttr(AL, ArgIndex, StateString, &Loc))
1158 return;
1159 }
1160
1161 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1162 CallableState)) {
1163 S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << StateString;
1164 return;
1165 }
1166
1167 States.push_back(CallableState);
1168 }
1169
1170 D->addAttr(::new (S.Context)
1171 CallableWhenAttr(S.Context, AL, States.data(), States.size()));
1172}
1173
1174static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1175 ParamTypestateAttr::ConsumedState ParamState;
1176
1177 if (AL.isArgIdent(0)) {
1178 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1179 StringRef StateString = Ident->Ident->getName();
1180
1181 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1182 ParamState)) {
1183 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1184 << AL << StateString;
1185 return;
1186 }
1187 } else {
1188 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1189 << AL << AANT_ArgumentIdentifier;
1190 return;
1191 }
1192
1193 // FIXME: This check is currently being done in the analysis. It can be
1194 // enabled here only after the parser propagates attributes at
1195 // template specialization definition, not declaration.
1196 //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1197 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1198 //
1199 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1200 // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1201 // ReturnType.getAsString();
1202 // return;
1203 //}
1204
1205 D->addAttr(::new (S.Context) ParamTypestateAttr(S.Context, AL, ParamState));
1206}
1207
1208static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1209 ReturnTypestateAttr::ConsumedState ReturnState;
1210
1211 if (AL.isArgIdent(0)) {
1212 IdentifierLoc *IL = AL.getArgAsIdent(0);
1213 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1214 ReturnState)) {
1215 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1216 << IL->Ident;
1217 return;
1218 }
1219 } else {
1220 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1221 << AL << AANT_ArgumentIdentifier;
1222 return;
1223 }
1224
1225 // FIXME: This check is currently being done in the analysis. It can be
1226 // enabled here only after the parser propagates attributes at
1227 // template specialization definition, not declaration.
1228 //QualType ReturnType;
1229 //
1230 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1231 // ReturnType = Param->getType();
1232 //
1233 //} else if (const CXXConstructorDecl *Constructor =
1234 // dyn_cast<CXXConstructorDecl>(D)) {
1235 // ReturnType = Constructor->getThisType()->getPointeeType();
1236 //
1237 //} else {
1238 //
1239 // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1240 //}
1241 //
1242 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1243 //
1244 //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1245 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1246 // ReturnType.getAsString();
1247 // return;
1248 //}
1249
1250 D->addAttr(::new (S.Context) ReturnTypestateAttr(S.Context, AL, ReturnState));
1251}
1252
1253static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1254 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1255 return;
1256
1257 SetTypestateAttr::ConsumedState NewState;
1258 if (AL.isArgIdent(0)) {
1259 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1260 StringRef Param = Ident->Ident->getName();
1261 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1262 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1263 << Param;
1264 return;
1265 }
1266 } else {
1267 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1268 << AL << AANT_ArgumentIdentifier;
1269 return;
1270 }
1271
1272 D->addAttr(::new (S.Context) SetTypestateAttr(S.Context, AL, NewState));
1273}
1274
1275static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1276 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1277 return;
1278
1279 TestTypestateAttr::ConsumedState TestState;
1280 if (AL.isArgIdent(0)) {
1281 IdentifierLoc *Ident = AL.getArgAsIdent(0);
1282 StringRef Param = Ident->Ident->getName();
1283 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1284 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1285 << Param;
1286 return;
1287 }
1288 } else {
1289 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1290 << AL << AANT_ArgumentIdentifier;
1291 return;
1292 }
1293
1294 D->addAttr(::new (S.Context) TestTypestateAttr(S.Context, AL, TestState));
1295}
1296
1297static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1298 // Remember this typedef decl, we will need it later for diagnostics.
1299 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1300}
1301
1302static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1303 if (auto *TD = dyn_cast<TagDecl>(D))
1304 TD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1305 else if (auto *FD = dyn_cast<FieldDecl>(D)) {
1306 bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
1307 !FD->getType()->isIncompleteType() &&
1308 FD->isBitField() &&
1309 S.Context.getTypeAlign(FD->getType()) <= 8);
1310
1311 if (S.getASTContext().getTargetInfo().getTriple().isPS4()) {
1312 if (BitfieldByteAligned)
1313 // The PS4 target needs to maintain ABI backwards compatibility.
1314 S.Diag(AL.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1315 << AL << FD->getType();
1316 else
1317 FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1318 } else {
1319 // Report warning about changed offset in the newer compiler versions.
1320 if (BitfieldByteAligned)
1321 S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield);
1322
1323 FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1324 }
1325
1326 } else
1327 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
1328}
1329
1330static bool checkIBOutletCommon(Sema &S, Decl *D, const ParsedAttr &AL) {
1331 // The IBOutlet/IBOutletCollection attributes only apply to instance
1332 // variables or properties of Objective-C classes. The outlet must also
1333 // have an object reference type.
1334 if (const auto *VD = dyn_cast<ObjCIvarDecl>(D)) {
1335 if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1336 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1337 << AL << VD->getType() << 0;
1338 return false;
1339 }
1340 }
1341 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1342 if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1343 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1344 << AL << PD->getType() << 1;
1345 return false;
1346 }
1347 }
1348 else {
1349 S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL;
1350 return false;
1351 }
1352
1353 return true;
1354}
1355
1356static void handleIBOutlet(Sema &S, Decl *D, const ParsedAttr &AL) {
1357 if (!checkIBOutletCommon(S, D, AL))
1358 return;
1359
1360 D->addAttr(::new (S.Context) IBOutletAttr(S.Context, AL));
1361}
1362
1363static void handleIBOutletCollection(Sema &S, Decl *D, const ParsedAttr &AL) {
1364
1365 // The iboutletcollection attribute can have zero or one arguments.
1366 if (AL.getNumArgs() > 1) {
1367 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1368 return;
1369 }
1370
1371 if (!checkIBOutletCommon(S, D, AL))
1372 return;
1373
1374 ParsedType PT;
1375
1376 if (AL.hasParsedType())
1377 PT = AL.getTypeArg();
1378 else {
1379 PT = S.getTypeName(S.Context.Idents.get("NSObject"), AL.getLoc(),
1380 S.getScopeForContext(D->getDeclContext()->getParent()));
1381 if (!PT) {
1382 S.Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1383 return;
1384 }
1385 }
1386
1387 TypeSourceInfo *QTLoc = nullptr;
1388 QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1389 if (!QTLoc)
1390 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, AL.getLoc());
1391
1392 // Diagnose use of non-object type in iboutletcollection attribute.
1393 // FIXME. Gnu attribute extension ignores use of builtin types in
1394 // attributes. So, __attribute__((iboutletcollection(char))) will be
1395 // treated as __attribute__((iboutletcollection())).
1396 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1397 S.Diag(AL.getLoc(),
1398 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1399 : diag::err_iboutletcollection_type) << QT;
1400 return;
1401 }
1402
1403 D->addAttr(::new (S.Context) IBOutletCollectionAttr(S.Context, AL, QTLoc));
1404}
1405
1406bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
1407 if (RefOkay) {
1408 if (T->isReferenceType())
1409 return true;
1410 } else {
1411 T = T.getNonReferenceType();
1412 }
1413
1414 // The nonnull attribute, and other similar attributes, can be applied to a
1415 // transparent union that contains a pointer type.
1416 if (const RecordType *UT = T->getAsUnionType()) {
1417 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1418 RecordDecl *UD = UT->getDecl();
1419 for (const auto *I : UD->fields()) {
1420 QualType QT = I->getType();
1421 if (QT->isAnyPointerType() || QT->isBlockPointerType())
1422 return true;
1423 }
1424 }
1425 }
1426
1427 return T->isAnyPointerType() || T->isBlockPointerType();
1428}
1429
1430static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL,
1431 SourceRange AttrParmRange,
1432 SourceRange TypeRange,
1433 bool isReturnValue = false) {
1434 if (!S.isValidPointerAttrType(T)) {
1435 if (isReturnValue)
1436 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1437 << AL << AttrParmRange << TypeRange;
1438 else
1439 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1440 << AL << AttrParmRange << TypeRange << 0;
1441 return false;
1442 }
1443 return true;
1444}
1445
1446static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1447 SmallVector<ParamIdx, 8> NonNullArgs;
1448 for (unsigned I = 0; I < AL.getNumArgs(); ++I) {
1449 Expr *Ex = AL.getArgAsExpr(I);
1450 ParamIdx Idx;
1451 if (!checkFunctionOrMethodParameterIndex(S, D, AL, I + 1, Ex, Idx))
1452 return;
1453
1454 // Is the function argument a pointer type?
1455 if (Idx.getASTIndex() < getFunctionOrMethodNumParams(D) &&
1456 !attrNonNullArgCheck(
1457 S, getFunctionOrMethodParamType(D, Idx.getASTIndex()), AL,
1458 Ex->getSourceRange(),
1459 getFunctionOrMethodParamRange(D, Idx.getASTIndex())))
1460 continue;
1461
1462 NonNullArgs.push_back(Idx);
1463 }
1464
1465 // If no arguments were specified to __attribute__((nonnull)) then all pointer
1466 // arguments have a nonnull attribute; warn if there aren't any. Skip this
1467 // check if the attribute came from a macro expansion or a template
1468 // instantiation.
1469 if (NonNullArgs.empty() && AL.getLoc().isFileID() &&
1470 !S.inTemplateInstantiation()) {
1471 bool AnyPointers = isFunctionOrMethodVariadic(D);
1472 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1473 I != E && !AnyPointers; ++I) {
1474 QualType T = getFunctionOrMethodParamType(D, I);
1475 if (T->isDependentType() || S.isValidPointerAttrType(T))
1476 AnyPointers = true;
1477 }
1478
1479 if (!AnyPointers)
1480 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1481 }
1482
1483 ParamIdx *Start = NonNullArgs.data();
1484 unsigned Size = NonNullArgs.size();
1485 llvm::array_pod_sort(Start, Start + Size);
1486 D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, Start, Size));
1487}
1488
1489static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
1490 const ParsedAttr &AL) {
1491 if (AL.getNumArgs() > 0) {
1492 if (D->getFunctionType()) {
1493 handleNonNullAttr(S, D, AL);
1494 } else {
1495 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1496 << D->getSourceRange();
1497 }
1498 return;
1499 }
1500
1501 // Is the argument a pointer type?
1502 if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(),
1503 D->getSourceRange()))
1504 return;
1505
1506 D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, nullptr, 0));
1507}
1508
1509static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1510 QualType ResultType = getFunctionOrMethodResultType(D);
1511 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1512 if (!attrNonNullArgCheck(S, ResultType, AL, SourceRange(), SR,
1513 /* isReturnValue */ true))
1514 return;
1515
1516 D->addAttr(::new (S.Context) ReturnsNonNullAttr(S.Context, AL));
1517}
1518
1519static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1520 if (D->isInvalidDecl())
1521 return;
1522
1523 // noescape only applies to pointer types.
1524 QualType T = cast<ParmVarDecl>(D)->getType();
1525 if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
1526 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1527 << AL << AL.getRange() << 0;
1528 return;
1529 }
1530
1531 D->addAttr(::new (S.Context) NoEscapeAttr(S.Context, AL));
1532}
1533
1534static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1535 Expr *E = AL.getArgAsExpr(0),
1536 *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr;
1537 S.AddAssumeAlignedAttr(D, AL, E, OE);
1538}
1539
1540static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1541 S.AddAllocAlignAttr(D, AL, AL.getArgAsExpr(0));
1542}
1543
1544void Sema::AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
1545 Expr *OE) {
1546 QualType ResultType = getFunctionOrMethodResultType(D);
1547 SourceRange SR = getFunctionOrMethodResultSourceRange(D);
1548
1549 AssumeAlignedAttr TmpAttr(Context, CI, E, OE);
1550 SourceLocation AttrLoc = TmpAttr.getLocation();
1551
1552 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1553 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1554 << &TmpAttr << TmpAttr.getRange() << SR;
1555 return;
1556 }
1557
1558 if (!E->isValueDependent()) {
1559 llvm::APSInt I(64);
1560 if (!E->isIntegerConstantExpr(I, Context)) {
1561 if (OE)
1562 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1563 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1564 << E->getSourceRange();
1565 else
1566 Diag(AttrLoc, diag::err_attribute_argument_type)
1567 << &TmpAttr << AANT_ArgumentIntegerConstant
1568 << E->getSourceRange();
1569 return;
1570 }
1571
1572 if (!I.isPowerOf2()) {
1573 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1574 << E->getSourceRange();
1575 return;
1576 }
1577 }
1578
1579 if (OE) {
1580 if (!OE->isValueDependent()) {
1581 llvm::APSInt I(64);
1582 if (!OE->isIntegerConstantExpr(I, Context)) {
1583 Diag(AttrLoc, diag::err_attribute_argument_n_type)
1584 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1585 << OE->getSourceRange();
1586 return;
1587 }
1588 }
1589 }
1590
1591 D->addAttr(::new (Context) AssumeAlignedAttr(Context, CI, E, OE));
1592}
1593
1594void Sema::AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
1595 Expr *ParamExpr) {
1596 QualType ResultType = getFunctionOrMethodResultType(D);
1597
1598 AllocAlignAttr TmpAttr(Context, CI, ParamIdx());
1599 SourceLocation AttrLoc = CI.getLoc();
1600
1601 if (!ResultType->isDependentType() &&
1602 !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1603 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1604 << &TmpAttr << CI.getRange() << getFunctionOrMethodResultSourceRange(D);
1605 return;
1606 }
1607
1608 ParamIdx Idx;
1609 const auto *FuncDecl = cast<FunctionDecl>(D);
1610 if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
1611 /*AttrArgNum=*/1, ParamExpr, Idx))
1612 return;
1613
1614 QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
1615 if (!Ty->isDependentType() && !Ty->isIntegralType(Context)) {
1616 Diag(ParamExpr->getBeginLoc(), diag::err_attribute_integers_only)
1617 << &TmpAttr
1618 << FuncDecl->getParamDecl(Idx.getASTIndex())->getSourceRange();
1619 return;
1620 }
1621
1622 D->addAttr(::new (Context) AllocAlignAttr(Context, CI, Idx));
1623}
1624
1625/// Normalize the attribute, __foo__ becomes foo.
1626/// Returns true if normalization was applied.
1627static bool normalizeName(StringRef &AttrName) {
1628 if (AttrName.size() > 4 && AttrName.startswith("__") &&
1629 AttrName.endswith("__")) {
1630 AttrName = AttrName.drop_front(2).drop_back(2);
1631 return true;
1632 }
1633 return false;
1634}
1635
1636static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1637 // This attribute must be applied to a function declaration. The first
1638 // argument to the attribute must be an identifier, the name of the resource,
1639 // for example: malloc. The following arguments must be argument indexes, the
1640 // arguments must be of integer type for Returns, otherwise of pointer type.
1641 // The difference between Holds and Takes is that a pointer may still be used
1642 // after being held. free() should be __attribute((ownership_takes)), whereas
1643 // a list append function may well be __attribute((ownership_holds)).
1644
1645 if (!AL.isArgIdent(0)) {
1646 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1647 << AL << 1 << AANT_ArgumentIdentifier;
1648 return;
1649 }
1650
1651 // Figure out our Kind.
1652 OwnershipAttr::OwnershipKind K =
1653 OwnershipAttr(S.Context, AL, nullptr, nullptr, 0).getOwnKind();
1654
1655 // Check arguments.
1656 switch (K) {
1657 case OwnershipAttr::Takes:
1658 case OwnershipAttr::Holds:
1659 if (AL.getNumArgs() < 2) {
1660 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << AL << 2;
1661 return;
1662 }
1663 break;
1664 case OwnershipAttr::Returns:
1665 if (AL.getNumArgs() > 2) {
1666 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
1667 return;
1668 }
1669 break;
1670 }
1671
1672 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
1673
1674 StringRef ModuleName = Module->getName();
1675 if (normalizeName(ModuleName)) {
1676 Module = &S.PP.getIdentifierTable().get(ModuleName);
1677 }
1678
1679 SmallVector<ParamIdx, 8> OwnershipArgs;
1680 for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1681 Expr *Ex = AL.getArgAsExpr(i);
1682 ParamIdx Idx;
1683 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1684 return;
1685
1686 // Is the function argument a pointer type?
1687 QualType T = getFunctionOrMethodParamType(D, Idx.getASTIndex());
1688 int Err = -1; // No error
1689 switch (K) {
1690 case OwnershipAttr::Takes:
1691 case OwnershipAttr::Holds:
1692 if (!T->isAnyPointerType() && !T->isBlockPointerType())
1693 Err = 0;
1694 break;
1695 case OwnershipAttr::Returns:
1696 if (!T->isIntegerType())
1697 Err = 1;
1698 break;
1699 }
1700 if (-1 != Err) {
1701 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL << Err
1702 << Ex->getSourceRange();
1703 return;
1704 }
1705
1706 // Check we don't have a conflict with another ownership attribute.
1707 for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1708 // Cannot have two ownership attributes of different kinds for the same
1709 // index.
1710 if (I->getOwnKind() != K && I->args_end() !=
1711 std::find(I->args_begin(), I->args_end(), Idx)) {
1712 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << I;
1713 return;
1714 } else if (K == OwnershipAttr::Returns &&
1715 I->getOwnKind() == OwnershipAttr::Returns) {
1716 // A returns attribute conflicts with any other returns attribute using
1717 // a different index.
1718 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
1719 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1720 << I->args_begin()->getSourceIndex();
1721 if (I->args_size())
1722 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1723 << Idx.getSourceIndex() << Ex->getSourceRange();
1724 return;
1725 }
1726 }
1727 }
1728 OwnershipArgs.push_back(Idx);
1729 }
1730
1731 ParamIdx *Start = OwnershipArgs.data();
1732 unsigned Size = OwnershipArgs.size();
1733 llvm::array_pod_sort(Start, Start + Size);
1734 D->addAttr(::new (S.Context)
1735 OwnershipAttr(S.Context, AL, Module, Start, Size));
1736}
1737
1738static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1739 // Check the attribute arguments.
1740 if (AL.getNumArgs() > 1) {
1741 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1742 return;
1743 }
1744
1745 // gcc rejects
1746 // class c {
1747 // static int a __attribute__((weakref ("v2")));
1748 // static int b() __attribute__((weakref ("f3")));
1749 // };
1750 // and ignores the attributes of
1751 // void f(void) {
1752 // static int a __attribute__((weakref ("v2")));
1753 // }
1754 // we reject them
1755 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1756 if (!Ctx->isFileContext()) {
1757 S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context)
1758 << cast<NamedDecl>(D);
1759 return;
1760 }
1761
1762 // The GCC manual says
1763 //
1764 // At present, a declaration to which `weakref' is attached can only
1765 // be `static'.
1766 //
1767 // It also says
1768 //
1769 // Without a TARGET,
1770 // given as an argument to `weakref' or to `alias', `weakref' is
1771 // equivalent to `weak'.
1772 //
1773 // gcc 4.4.1 will accept
1774 // int a7 __attribute__((weakref));
1775 // as
1776 // int a7 __attribute__((weak));
1777 // This looks like a bug in gcc. We reject that for now. We should revisit
1778 // it if this behaviour is actually used.
1779
1780 // GCC rejects
1781 // static ((alias ("y"), weakref)).
1782 // Should we? How to check that weakref is before or after alias?
1783
1784 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1785 // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1786 // StringRef parameter it was given anyway.
1787 StringRef Str;
1788 if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, 0, Str))
1789 // GCC will accept anything as the argument of weakref. Should we
1790 // check for an existing decl?
1791 D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
1792
1793 D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
1794}
1795
1796static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1797 StringRef Str;
1798 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1799 return;
1800
1801 // Aliases should be on declarations, not definitions.
1802 const auto *FD = cast<FunctionDecl>(D);
1803 if (FD->isThisDeclarationADefinition()) {
1804 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1;
1805 return;
1806 }
1807
1808 D->addAttr(::new (S.Context) IFuncAttr(S.Context, AL, Str));
1809}
1810
1811static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1812 StringRef Str;
1813 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1814 return;
1815
1816 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1817 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin);
1818 return;
1819 }
1820 if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1821 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx);
1822 }
1823
1824 // Aliases should be on declarations, not definitions.
1825 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1826 if (FD->isThisDeclarationADefinition()) {
1827 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0;
1828 return;
1829 }
1830 } else {
1831 const auto *VD = cast<VarDecl>(D);
1832 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
1833 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0;
1834 return;
1835 }
1836 }
1837
1838 // Mark target used to prevent unneeded-internal-declaration warnings.
1839 if (!S.LangOpts.CPlusPlus) {
1840 // FIXME: demangle Str for C++, as the attribute refers to the mangled
1841 // linkage name, not the pre-mangled identifier.
1842 const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
1843 LookupResult LR(S, target, Sema::LookupOrdinaryName);
1844 if (S.LookupQualifiedName(LR, S.getCurLexicalContext()))
1845 for (NamedDecl *ND : LR)
1846 ND->markUsed(S.Context);
1847 }
1848
1849 D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
1850}
1851
1852static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1853 StringRef Model;
1854 SourceLocation LiteralLoc;
1855 // Check that it is a string.
1856 if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc))
1857 return;
1858
1859 // Check that the value.
1860 if (Model != "global-dynamic" && Model != "local-dynamic"
1861 && Model != "initial-exec" && Model != "local-exec") {
1862 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
1863 return;
1864 }
1865
1866 D->addAttr(::new (S.Context) TLSModelAttr(S.Context, AL, Model));
1867}
1868
1869static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1870 QualType ResultType = getFunctionOrMethodResultType(D);
1871 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
1872 D->addAttr(::new (S.Context) RestrictAttr(S.Context, AL));
1873 return;
1874 }
1875
1876 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1877 << AL << getFunctionOrMethodResultSourceRange(D);
1878}
1879
1880static void handleCPUSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1881 FunctionDecl *FD = cast<FunctionDecl>(D);
1882
1883 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
1884 if (MD->getParent()->isLambda()) {
1885 S.Diag(AL.getLoc(), diag::err_attribute_dll_lambda) << AL;
1886 return;
1887 }
1888 }
1889
1890 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
1891 return;
1892
1893 SmallVector<IdentifierInfo *, 8> CPUs;
1894 for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); ++ArgNo) {
1895 if (!AL.isArgIdent(ArgNo)) {
1896 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1897 << AL << AANT_ArgumentIdentifier;
1898 return;
1899 }
1900
1901 IdentifierLoc *CPUArg = AL.getArgAsIdent(ArgNo);
1902 StringRef CPUName = CPUArg->Ident->getName().trim();
1903
1904 if (!S.Context.getTargetInfo().validateCPUSpecificCPUDispatch(CPUName)) {
1905 S.Diag(CPUArg->Loc, diag::err_invalid_cpu_specific_dispatch_value)
1906 << CPUName << (AL.getKind() == ParsedAttr::AT_CPUDispatch);
1907 return;
1908 }
1909
1910 const TargetInfo &Target = S.Context.getTargetInfo();
1911 if (llvm::any_of(CPUs, [CPUName, &Target](const IdentifierInfo *Cur) {
1912 return Target.CPUSpecificManglingCharacter(CPUName) ==
1913 Target.CPUSpecificManglingCharacter(Cur->getName());
1914 })) {
1915 S.Diag(AL.getLoc(), diag::warn_multiversion_duplicate_entries);
1916 return;
1917 }
1918 CPUs.push_back(CPUArg->Ident);
1919 }
1920
1921 FD->setIsMultiVersion(true);
1922 if (AL.getKind() == ParsedAttr::AT_CPUSpecific)
1923 D->addAttr(::new (S.Context)
1924 CPUSpecificAttr(S.Context, AL, CPUs.data(), CPUs.size()));
1925 else
1926 D->addAttr(::new (S.Context)
1927 CPUDispatchAttr(S.Context, AL, CPUs.data(), CPUs.size()));
1928}
1929
1930static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1931 if (S.LangOpts.CPlusPlus) {
1932 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
1933 << AL << AttributeLangSupport::Cpp;
1934 return;
1935 }
1936
1937 if (CommonAttr *CA = S.mergeCommonAttr(D, AL))
1938 D->addAttr(CA);
1939}
1940
1941static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1942 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, AL))
1943 return;
1944
1945 if (AL.isDeclspecAttribute()) {
1946 const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
1947 const auto &Arch = Triple.getArch();
1948 if (Arch != llvm::Triple::x86 &&
1949 (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
1950 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch)
1951 << AL << Triple.getArchName();
1952 return;
1953 }
1954 }
1955
1956 D->addAttr(::new (S.Context) NakedAttr(S.Context, AL));
1957}
1958
1959static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
1960 if (hasDeclarator(D)) return;
1961
1962 if (!isa<ObjCMethodDecl>(D)) {
1963 S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
1964 << Attrs << ExpectedFunctionOrMethod;
1965 return;
1966 }
1967
1968 D->addAttr(::new (S.Context) NoReturnAttr(S.Context, Attrs));
1969}
1970
1971static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
1972 if (!S.getLangOpts().CFProtectionBranch)
1973 S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored);
1974 else
1975 handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs);
1976}
1977
1978bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) {
1979 if (!checkAttributeNumArgs(*this, Attrs, 0)) {
1980 Attrs.setInvalid();
1981 return true;
1982 }
1983
1984 return false;
1985}
1986
1987bool Sema::CheckAttrTarget(const ParsedAttr &AL) {
1988 // Check whether the attribute is valid on the current target.
1989 if (!AL.existsInTarget(Context.getTargetInfo())) {
1990 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL;
1991 AL.setInvalid();
1992 return true;
1993 }
1994
1995 return false;
1996}
1997
1998static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1999
2000 // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2001 // because 'analyzer_noreturn' does not impact the type.
2002 if (!isFunctionOrMethodOrBlock(D)) {
2003 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2004 if (!VD || (!VD->getType()->isBlockPointerType() &&
2005 !VD->getType()->isFunctionPointerType())) {
2006 S.Diag(AL.getLoc(), AL.isCXX11Attribute()
2007 ? diag::err_attribute_wrong_decl_type
2008 : diag::warn_attribute_wrong_decl_type)
2009 << AL << ExpectedFunctionMethodOrBlock;
2010 return;
2011 }
2012 }
2013
2014 D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(S.Context, AL));
2015}
2016
2017// PS3 PPU-specific.
2018static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2019 /*
2020 Returning a Vector Class in Registers
2021
2022 According to the PPU ABI specifications, a class with a single member of
2023 vector type is returned in memory when used as the return value of a
2024 function.
2025 This results in inefficient code when implementing vector classes. To return
2026 the value in a single vector register, add the vecreturn attribute to the
2027 class definition. This attribute is also applicable to struct types.
2028
2029 Example:
2030
2031 struct Vector
2032 {
2033 __vector float xyzw;
2034 } __attribute__((vecreturn));
2035
2036 Vector Add(Vector lhs, Vector rhs)
2037 {
2038 Vector result;
2039 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2040 return result; // This will be returned in a register
2041 }
2042 */
2043 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2044 S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A;
2045 return;
2046 }
2047
2048 const auto *R = cast<RecordDecl>(D);
2049 int count = 0;
2050
2051 if (!isa<CXXRecordDecl>(R)) {
2052 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2053 return;
2054 }
2055
2056 if (!cast<CXXRecordDecl>(R)->isPOD()) {
2057 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2058 return;
2059 }
2060
2061 for (const auto *I : R->fields()) {
2062 if ((count == 1) || !I->getType()->isVectorType()) {
2063 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2064 return;
2065 }
2066 count++;
2067 }
2068
2069 D->addAttr(::new (S.Context) VecReturnAttr(S.Context, AL));
2070}
2071
2072static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
2073 const ParsedAttr &AL) {
2074 if (isa<ParmVarDecl>(D)) {
2075 // [[carries_dependency]] can only be applied to a parameter if it is a
2076 // parameter of a function declaration or lambda.
2077 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
2078 S.Diag(AL.getLoc(),
2079 diag::err_carries_dependency_param_not_function_decl);
2080 return;
2081 }
2082 }
2083
2084 D->addAttr(::new (S.Context) CarriesDependencyAttr(S.Context, AL));
2085}
2086
2087static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2088 bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName();
2089
2090 // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2091 // about using it as an extension.
2092 if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
2093 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2094
2095 D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL));
2096}
2097
2098static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2099 uint32_t priority = ConstructorAttr::DefaultPriority;
2100 if (AL.getNumArgs() &&
2101 !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2102 return;
2103
2104 D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority));
2105}
2106
2107static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2108 uint32_t priority = DestructorAttr::DefaultPriority;
2109 if (AL.getNumArgs() &&
2110 !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2111 return;
2112
2113 D->addAttr(::new (S.Context) DestructorAttr(S.Context, AL, priority));
2114}
2115
2116template <typename AttrTy>
2117static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) {
2118 // Handle the case where the attribute has a text message.
2119 StringRef Str;
2120 if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str))
2121 return;
2122
2123 D->addAttr(::new (S.Context) AttrTy(S.Context, AL, Str));
2124}
2125
2126static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
2127 const ParsedAttr &AL) {
2128 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
2129 S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2130 << AL << AL.getRange();
2131 return;
2132 }
2133
2134 D->addAttr(::new (S.Context) ObjCExplicitProtocolImplAttr(S.Context, AL));
2135}
2136
2137static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
2138 IdentifierInfo *Platform,
2139 VersionTuple Introduced,
2140 VersionTuple Deprecated,
2141 VersionTuple Obsoleted) {
2142 StringRef PlatformName
2143 = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2144 if (PlatformName.empty())
2145 PlatformName = Platform->getName();
2146
2147 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2148 // of these steps are needed).
2149 if (!Introduced.empty() && !Deprecated.empty() &&
2150 !(Introduced <= Deprecated)) {
2151 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2152 << 1 << PlatformName << Deprecated.getAsString()
2153 << 0 << Introduced.getAsString();
2154 return true;
2155 }
2156
2157 if (!Introduced.empty() && !Obsoleted.empty() &&
2158 !(Introduced <= Obsoleted)) {
2159 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2160 << 2 << PlatformName << Obsoleted.getAsString()
2161 << 0 << Introduced.getAsString();
2162 return true;
2163 }
2164
2165 if (!Deprecated.empty() && !Obsoleted.empty() &&
2166 !(Deprecated <= Obsoleted)) {
2167 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2168 << 2 << PlatformName << Obsoleted.getAsString()
2169 << 1 << Deprecated.getAsString();
2170 return true;
2171 }
2172
2173 return false;
2174}
2175
2176/// Check whether the two versions match.
2177///
2178/// If either version tuple is empty, then they are assumed to match. If
2179/// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2180static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2181 bool BeforeIsOkay) {
2182 if (X.empty() || Y.empty())
2183 return true;
2184
2185 if (X == Y)
2186 return true;
2187
2188 if (BeforeIsOkay && X < Y)
2189 return true;
2190
2191 return false;
2192}
2193
2194AvailabilityAttr *Sema::mergeAvailabilityAttr(
2195 NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform,
2196 bool Implicit, VersionTuple Introduced, VersionTuple Deprecated,
2197 VersionTuple Obsoleted, bool IsUnavailable, StringRef Message,
2198 bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK,
2199 int Priority) {
2200 VersionTuple MergedIntroduced = Introduced;
2201 VersionTuple MergedDeprecated = Deprecated;
2202 VersionTuple MergedObsoleted = Obsoleted;
2203 bool FoundAny = false;
2204 bool OverrideOrImpl = false;
2205 switch (AMK) {
2206 case AMK_None:
2207 case AMK_Redeclaration:
2208 OverrideOrImpl = false;
2209 break;
2210
2211 case AMK_Override:
2212 case AMK_ProtocolImplementation:
2213 OverrideOrImpl = true;
2214 break;
2215 }
2216
2217 if (D->hasAttrs()) {
2218 AttrVec &Attrs = D->getAttrs();
2219 for (unsigned i = 0, e = Attrs.size(); i != e;) {
2220 const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2221 if (!OldAA) {
2222 ++i;
2223 continue;
2224 }
2225
2226 IdentifierInfo *OldPlatform = OldAA->getPlatform();
2227 if (OldPlatform != Platform) {
2228 ++i;
2229 continue;
2230 }
2231
2232 // If there is an existing availability attribute for this platform that
2233 // has a lower priority use the existing one and discard the new
2234 // attribute.
2235 if (OldAA->getPriority() < Priority)
2236 return nullptr;
2237
2238 // If there is an existing attribute for this platform that has a higher
2239 // priority than the new attribute then erase the old one and continue
2240 // processing the attributes.
2241 if (OldAA->getPriority() > Priority) {
2242 Attrs.erase(Attrs.begin() + i);
2243 --e;
2244 continue;
2245 }
2246
2247 FoundAny = true;
2248 VersionTuple OldIntroduced = OldAA->getIntroduced();
2249 VersionTuple OldDeprecated = OldAA->getDeprecated();
2250 VersionTuple OldObsoleted = OldAA->getObsoleted();
2251 bool OldIsUnavailable = OldAA->getUnavailable();
2252
2253 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2254 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2255 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2256 !(OldIsUnavailable == IsUnavailable ||
2257 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2258 if (OverrideOrImpl) {
2259 int Which = -1;
2260 VersionTuple FirstVersion;
2261 VersionTuple SecondVersion;
2262 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2263 Which = 0;
2264 FirstVersion = OldIntroduced;
2265 SecondVersion = Introduced;
2266 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2267 Which = 1;
2268 FirstVersion = Deprecated;
2269 SecondVersion = OldDeprecated;
2270 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2271 Which = 2;
2272 FirstVersion = Obsoleted;
2273 SecondVersion = OldObsoleted;
2274 }
2275
2276 if (Which == -1) {
2277 Diag(OldAA->getLocation(),
2278 diag::warn_mismatched_availability_override_unavail)
2279 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2280 << (AMK == AMK_Override);
2281 } else {
2282 Diag(OldAA->getLocation(),
2283 diag::warn_mismatched_availability_override)
2284 << Which
2285 << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2286 << FirstVersion.getAsString() << SecondVersion.getAsString()
2287 << (AMK == AMK_Override);
2288 }
2289 if (AMK == AMK_Override)
2290 Diag(CI.getLoc(), diag::note_overridden_method);
2291 else
2292 Diag(CI.getLoc(), diag::note_protocol_method);
2293 } else {
2294 Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2295 Diag(CI.getLoc(), diag::note_previous_attribute);
2296 }
2297
2298 Attrs.erase(Attrs.begin() + i);
2299 --e;
2300 continue;
2301 }
2302
2303 VersionTuple MergedIntroduced2 = MergedIntroduced;
2304 VersionTuple MergedDeprecated2 = MergedDeprecated;
2305 VersionTuple MergedObsoleted2 = MergedObsoleted;
2306
2307 if (MergedIntroduced2.empty())
2308 MergedIntroduced2 = OldIntroduced;
2309 if (MergedDeprecated2.empty())
2310 MergedDeprecated2 = OldDeprecated;
2311 if (MergedObsoleted2.empty())
2312 MergedObsoleted2 = OldObsoleted;
2313
2314 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2315 MergedIntroduced2, MergedDeprecated2,
2316 MergedObsoleted2)) {
2317 Attrs.erase(Attrs.begin() + i);
2318 --e;
2319 continue;
2320 }
2321
2322 MergedIntroduced = MergedIntroduced2;
2323 MergedDeprecated = MergedDeprecated2;
2324 MergedObsoleted = MergedObsoleted2;
2325 ++i;
2326 }
2327 }
2328
2329 if (FoundAny &&
2330 MergedIntroduced == Introduced &&
2331 MergedDeprecated == Deprecated &&
2332 MergedObsoleted == Obsoleted)
2333 return nullptr;
2334
2335 // Only create a new attribute if !OverrideOrImpl, but we want to do
2336 // the checking.
2337 if (!checkAvailabilityAttr(*this, CI.getRange(), Platform, MergedIntroduced,
2338 MergedDeprecated, MergedObsoleted) &&
2339 !OverrideOrImpl) {
2340 auto *Avail = ::new (Context) AvailabilityAttr(
2341 Context, CI, Platform, Introduced, Deprecated, Obsoleted, IsUnavailable,
2342 Message, IsStrict, Replacement, Priority);
2343 Avail->setImplicit(Implicit);
2344 return Avail;
2345 }
2346 return nullptr;
2347}
2348
2349static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2350 if (!checkAttributeNumArgs(S, AL, 1))
2351 return;
2352 IdentifierLoc *Platform = AL.getArgAsIdent(0);
2353
2354 IdentifierInfo *II = Platform->Ident;
2355 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2356 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2357 << Platform->Ident;
2358
2359 auto *ND = dyn_cast<NamedDecl>(D);
2360 if (!ND) // We warned about this already, so just return.
2361 return;
2362
2363 AvailabilityChange Introduced = AL.getAvailabilityIntroduced();
2364 AvailabilityChange Deprecated = AL.getAvailabilityDeprecated();
2365 AvailabilityChange Obsoleted = AL.getAvailabilityObsoleted();
2366 bool IsUnavailable = AL.getUnavailableLoc().isValid();
2367 bool IsStrict = AL.getStrictLoc().isValid();
2368 StringRef Str;
2369 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getMessageExpr()))
2370 Str = SE->getString();
2371 StringRef Replacement;
2372 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getReplacementExpr()))
2373 Replacement = SE->getString();
2374
2375 if (II->isStr("swift")) {
2376 if (Introduced.isValid() || Obsoleted.isValid() ||
2377 (!IsUnavailable && !Deprecated.isValid())) {
2378 S.Diag(AL.getLoc(),
2379 diag::warn_availability_swift_unavailable_deprecated_only);
2380 return;
2381 }
2382 }
2383
2384 int PriorityModifier = AL.isPragmaClangAttribute()
2385 ? Sema::AP_PragmaClangAttribute
2386 : Sema::AP_Explicit;
2387 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2388 ND, AL, II, false /*Implicit*/, Introduced.Version, Deprecated.Version,
2389 Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement,
2390 Sema::AMK_None, PriorityModifier);
2391 if (NewAttr)
2392 D->addAttr(NewAttr);
2393
2394 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2395 // matches before the start of the watchOS platform.
2396 if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2397 IdentifierInfo *NewII = nullptr;
2398 if (II->getName() == "ios")
2399 NewII = &S.Context.Idents.get("watchos");
2400 else if (II->getName() == "ios_app_extension")
2401 NewII = &S.Context.Idents.get("watchos_app_extension");
2402
2403 if (NewII) {
2404 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2405 if (Version.empty())
2406 return Version;
2407 auto Major = Version.getMajor();
2408 auto NewMajor = Major >= 9 ? Major - 7 : 0;
2409 if (NewMajor >= 2) {
2410 if (Version.getMinor().hasValue()) {
2411 if (Version.getSubminor().hasValue())
2412 return VersionTuple(NewMajor, Version.getMinor().getValue(),
2413 Version.getSubminor().getValue());
2414 else
2415 return VersionTuple(NewMajor, Version.getMinor().getValue());
2416 }
2417 return VersionTuple(NewMajor);
2418 }
2419
2420 return VersionTuple(2, 0);
2421 };
2422
2423 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2424 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2425 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2426
2427 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2428 ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
2429 NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
2430 Sema::AMK_None,
2431 PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2432 if (NewAttr)
2433 D->addAttr(NewAttr);
2434 }
2435 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2436 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2437 // matches before the start of the tvOS platform.
2438 IdentifierInfo *NewII = nullptr;
2439 if (II->getName() == "ios")
2440 NewII = &S.Context.Idents.get("tvos");
2441 else if (II->getName() == "ios_app_extension")
2442 NewII = &S.Context.Idents.get("tvos_app_extension");
2443
2444 if (NewII) {
2445 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2446 ND, AL, NewII, true /*Implicit*/, Introduced.Version,
2447 Deprecated.Version, Obsoleted.Version, IsUnavailable, Str, IsStrict,
2448 Replacement, Sema::AMK_None,
2449 PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2450 if (NewAttr)
2451 D->addAttr(NewAttr);
2452 }
2453 }
2454}
2455
2456static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2457 const ParsedAttr &AL) {
2458 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
2459 return;
2460 assert(checkAttributeAtMostNumArgs(S, AL, 3) &&((checkAttributeAtMostNumArgs(S, AL, 3) && "Invalid number of arguments in an external_source_symbol attribute"
) ? static_cast<void> (0) : __assert_fail ("checkAttributeAtMostNumArgs(S, AL, 3) && \"Invalid number of arguments in an external_source_symbol attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 2461, __PRETTY_FUNCTION__))
2461 "Invalid number of arguments in an external_source_symbol attribute")((checkAttributeAtMostNumArgs(S, AL, 3) && "Invalid number of arguments in an external_source_symbol attribute"
) ? static_cast<void> (0) : __assert_fail ("checkAttributeAtMostNumArgs(S, AL, 3) && \"Invalid number of arguments in an external_source_symbol attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 2461, __PRETTY_FUNCTION__))
;
2462
2463 StringRef Language;
2464 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(0)))
2465 Language = SE->getString();
2466 StringRef DefinedIn;
2467 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(1)))
2468 DefinedIn = SE->getString();
2469 bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
2470
2471 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2472 S.Context, AL, Language, DefinedIn, IsGeneratedDeclaration));
2473}
2474
2475template <class T>
2476static T *mergeVisibilityAttr(Sema &S, Decl *D, const AttributeCommonInfo &CI,
2477 typename T::VisibilityType value) {
2478 T *existingAttr = D->getAttr<T>();
2479 if (existingAttr) {
2480 typename T::VisibilityType existingValue = existingAttr->getVisibility();
2481 if (existingValue == value)
2482 return nullptr;
2483 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2484 S.Diag(CI.getLoc(), diag::note_previous_attribute);
2485 D->dropAttr<T>();
2486 }
2487 return ::new (S.Context) T(S.Context, CI, value);
2488}
2489
2490VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D,
2491 const AttributeCommonInfo &CI,
2492 VisibilityAttr::VisibilityType Vis) {
2493 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, CI, Vis);
2494}
2495
2496TypeVisibilityAttr *
2497Sema::mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
2498 TypeVisibilityAttr::VisibilityType Vis) {
2499 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, CI, Vis);
2500}
2501
2502static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
2503 bool isTypeVisibility) {
2504 // Visibility attributes don't mean anything on a typedef.
2505 if (isa<TypedefNameDecl>(D)) {
2506 S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
2507 return;
2508 }
2509
2510 // 'type_visibility' can only go on a type or namespace.
2511 if (isTypeVisibility &&
2512 !(isa<TagDecl>(D) ||
2513 isa<ObjCInterfaceDecl>(D) ||
2514 isa<NamespaceDecl>(D))) {
2515 S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2516 << AL << ExpectedTypeOrNamespace;
2517 return;
2518 }
2519
2520 // Check that the argument is a string literal.
2521 StringRef TypeStr;
2522 SourceLocation LiteralLoc;
2523 if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc))
2524 return;
2525
2526 VisibilityAttr::VisibilityType type;
2527 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2528 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL
2529 << TypeStr;
2530 return;
2531 }
2532
2533 // Complain about attempts to use protected visibility on targets
2534 // (like Darwin) that don't support it.
2535 if (type == VisibilityAttr::Protected &&
2536 !S.Context.getTargetInfo().hasProtectedVisibility()) {
2537 S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
2538 type = VisibilityAttr::Default;
2539 }
2540
2541 Attr *newAttr;
2542 if (isTypeVisibility) {
2543 newAttr = S.mergeTypeVisibilityAttr(
2544 D, AL, (TypeVisibilityAttr::VisibilityType)type);
2545 } else {
2546 newAttr = S.mergeVisibilityAttr(D, AL, type);
2547 }
2548 if (newAttr)
2549 D->addAttr(newAttr);
2550}
2551
2552static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2553 const auto *M = cast<ObjCMethodDecl>(D);
2554 if (!AL.isArgIdent(0)) {
2555 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2556 << AL << 1 << AANT_ArgumentIdentifier;
2557 return;
2558 }
2559
2560 IdentifierLoc *IL = AL.getArgAsIdent(0);
2561 ObjCMethodFamilyAttr::FamilyKind F;
2562 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2563 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident;
2564 return;
2565 }
2566
2567 if (F == ObjCMethodFamilyAttr::OMF_init &&
2568 !M->getReturnType()->isObjCObjectPointerType()) {
2569 S.Diag(M->getLocation(), diag::err_init_method_bad_return_type)
2570 << M->getReturnType();
2571 // Ignore the attribute.
2572 return;
2573 }
2574
2575 D->addAttr(new (S.Context) ObjCMethodFamilyAttr(S.Context, AL, F));
2576}
2577
2578static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) {
2579 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2580 QualType T = TD->getUnderlyingType();
2581 if (!T->isCARCBridgableType()) {
2582 S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2583 return;
2584 }
2585 }
2586 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2587 QualType T = PD->getType();
2588 if (!T->isCARCBridgableType()) {
2589 S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2590 return;
2591 }
2592 }
2593 else {
2594 // It is okay to include this attribute on properties, e.g.:
2595 //
2596 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2597 //
2598 // In this case it follows tradition and suppresses an error in the above
2599 // case.
2600 S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2601 }
2602 D->addAttr(::new (S.Context) ObjCNSObjectAttr(S.Context, AL));
2603}
2604
2605static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) {
2606 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2607 QualType T = TD->getUnderlyingType();
2608 if (!T->isObjCObjectPointerType()) {
2609 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2610 return;
2611 }
2612 } else {
2613 S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2614 return;
2615 }
2616 D->addAttr(::new (S.Context) ObjCIndependentClassAttr(S.Context, AL));
2617}
2618
2619static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2620 if (!AL.isArgIdent(0)) {
2621 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2622 << AL << 1 << AANT_ArgumentIdentifier;
2623 return;
2624 }
2625
2626 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
2627 BlocksAttr::BlockType type;
2628 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2629 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
2630 return;
2631 }
2632
2633 D->addAttr(::new (S.Context) BlocksAttr(S.Context, AL, type));
2634}
2635
2636static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2637 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2638 if (AL.getNumArgs() > 0) {
2639 Expr *E = AL.getArgAsExpr(0);
2640 llvm::APSInt Idx(32);
2641 if (E->isTypeDependent() || E->isValueDependent() ||
2642 !E->isIntegerConstantExpr(Idx, S.Context)) {
2643 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2644 << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2645 return;
2646 }
2647
2648 if (Idx.isSigned() && Idx.isNegative()) {
2649 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2650 << E->getSourceRange();
2651 return;
2652 }
2653
2654 sentinel = Idx.getZExtValue();
2655 }
2656
2657 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2658 if (AL.getNumArgs() > 1) {
2659 Expr *E = AL.getArgAsExpr(1);
2660 llvm::APSInt Idx(32);
2661 if (E->isTypeDependent() || E->isValueDependent() ||
2662 !E->isIntegerConstantExpr(Idx, S.Context)) {
2663 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2664 << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2665 return;
2666 }
2667 nullPos = Idx.getZExtValue();
2668
2669 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2670 // FIXME: This error message could be improved, it would be nice
2671 // to say what the bounds actually are.
2672 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2673 << E->getSourceRange();
2674 return;
2675 }
2676 }
2677
2678 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2679 const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2680 if (isa<FunctionNoProtoType>(FT)) {
2681 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2682 return;
2683 }
2684
2685 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2686 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2687 return;
2688 }
2689 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
2690 if (!MD->isVariadic()) {
2691 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2692 return;
2693 }
2694 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
2695 if (!BD->isVariadic()) {
2696 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2697 return;
2698 }
2699 } else if (const auto *V = dyn_cast<VarDecl>(D)) {
2700 QualType Ty = V->getType();
2701 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2702 const FunctionType *FT = Ty->isFunctionPointerType()
2703 ? D->getFunctionType()
2704 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2705 if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2706 int m = Ty->isFunctionPointerType() ? 0 : 1;
2707 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2708 return;
2709 }
2710 } else {
2711 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2712 << AL << ExpectedFunctionMethodOrBlock;
2713 return;
2714 }
2715 } else {
2716 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2717 << AL << ExpectedFunctionMethodOrBlock;
2718 return;
2719 }
2720 D->addAttr(::new (S.Context) SentinelAttr(S.Context, AL, sentinel, nullPos));
2721}
2722
2723static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
2724 if (D->getFunctionType() &&
2725 D->getFunctionType()->getReturnType()->isVoidType() &&
2726 !isa<CXXConstructorDecl>(D)) {
2727 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0;
2728 return;
2729 }
2730 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
2731 if (MD->getReturnType()->isVoidType()) {
2732 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1;
2733 return;
2734 }
2735
2736 StringRef Str;
2737 if ((AL.isCXX11Attribute() || AL.isC2xAttribute()) && !AL.getScopeName()) {
2738 // If this is spelled as the standard C++17 attribute, but not in C++17,
2739 // warn about using it as an extension. If there are attribute arguments,
2740 // then claim it's a C++2a extension instead.
2741 // FIXME: If WG14 does not seem likely to adopt the same feature, add an
2742 // extension warning for C2x mode.
2743 const LangOptions &LO = S.getLangOpts();
2744 if (AL.getNumArgs() == 1) {
2745 if (LO.CPlusPlus && !LO.CPlusPlus2a)
2746 S.Diag(AL.getLoc(), diag::ext_cxx2a_attr) << AL;
2747
2748 // Since this this is spelled [[nodiscard]], get the optional string
2749 // literal. If in C++ mode, but not in C++2a mode, diagnose as an
2750 // extension.
2751 // FIXME: C2x should support this feature as well, even as an extension.
2752 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, nullptr))
2753 return;
2754 } else if (LO.CPlusPlus && !LO.CPlusPlus17)
2755 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2756 }
2757
2758 D->addAttr(::new (S.Context) WarnUnusedResultAttr(S.Context, AL, Str));
2759}
2760
2761static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2762 // weak_import only applies to variable & function declarations.
2763 bool isDef = false;
2764 if (!D->canBeWeakImported(isDef)) {
2765 if (isDef)
2766 S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
2767 << "weak_import";
2768 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2769 (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2770 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2771 // Nothing to warn about here.
2772 } else
2773 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2774 << AL << ExpectedVariableOrFunction;
2775
2776 return;
2777 }
2778
2779 D->addAttr(::new (S.Context) WeakImportAttr(S.Context, AL));
2780}
2781
2782// Handles reqd_work_group_size and work_group_size_hint.
2783template <typename WorkGroupAttr>
2784static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2785 uint32_t WGSize[3];
2786 for (unsigned i = 0; i < 3; ++i) {
2787 const Expr *E = AL.getArgAsExpr(i);
2788 if (!checkUInt32Argument(S, AL, E, WGSize[i], i,
2789 /*StrictlyUnsigned=*/true))
2790 return;
2791 if (WGSize[i] == 0) {
2792 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2793 << AL << E->getSourceRange();
2794 return;
2795 }
2796 }
2797
2798 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2799 if (Existing && !(Existing->getXDim() == WGSize[0] &&
2800 Existing->getYDim() == WGSize[1] &&
2801 Existing->getZDim() == WGSize[2]))
2802 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2803
2804 D->addAttr(::new (S.Context)
2805 WorkGroupAttr(S.Context, AL, WGSize[0], WGSize[1], WGSize[2]));
2806}
2807
2808// Handles intel_reqd_sub_group_size.
2809static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2810 uint32_t SGSize;
2811 const Expr *E = AL.getArgAsExpr(0);
2812 if (!checkUInt32Argument(S, AL, E, SGSize))
2813 return;
2814 if (SGSize == 0) {
2815 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2816 << AL << E->getSourceRange();
2817 return;
2818 }
2819
2820 OpenCLIntelReqdSubGroupSizeAttr *Existing =
2821 D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
2822 if (Existing && Existing->getSubGroupSize() != SGSize)
2823 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2824
2825 D->addAttr(::new (S.Context)
2826 OpenCLIntelReqdSubGroupSizeAttr(S.Context, AL, SGSize));
2827}
2828
2829static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
2830 if (!AL.hasParsedType()) {
2831 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
2832 return;
2833 }
2834
2835 TypeSourceInfo *ParmTSI = nullptr;
2836 QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
2837 assert(ParmTSI && "no type source info for attribute argument")((ParmTSI && "no type source info for attribute argument"
) ? static_cast<void> (0) : __assert_fail ("ParmTSI && \"no type source info for attribute argument\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 2837, __PRETTY_FUNCTION__))
;
2838
2839 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2840 (ParmType->isBooleanType() ||
2841 !ParmType->isIntegralType(S.getASTContext()))) {
2842 S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) << 3 << AL;
2843 return;
2844 }
2845
2846 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2847 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2848 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2849 return;
2850 }
2851 }
2852
2853 D->addAttr(::new (S.Context) VecTypeHintAttr(S.Context, AL, ParmTSI));
2854}
2855
2856SectionAttr *Sema::mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
2857 StringRef Name) {
2858 // Explicit or partial specializations do not inherit
2859 // the section attribute from the primary template.
2860 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2861 if (CI.getAttributeSpellingListIndex() == SectionAttr::Declspec_allocate &&
2862 FD->isFunctionTemplateSpecialization())
2863 return nullptr;
2864 }
2865 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2866 if (ExistingAttr->getName() == Name)
2867 return nullptr;
2868 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
2869 << 1 /*section*/;
2870 Diag(CI.getLoc(), diag::note_previous_attribute);
2871 return nullptr;
2872 }
2873 return ::new (Context) SectionAttr(Context, CI, Name);
2874}
2875
2876bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2877 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2878 if (!Error.empty()) {
2879 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error
2880 << 1 /*'section'*/;
2881 return false;
2882 }
2883 return true;
2884}
2885
2886static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2887 // Make sure that there is a string literal as the sections's single
2888 // argument.
2889 StringRef Str;
2890 SourceLocation LiteralLoc;
2891 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
2892 return;
2893
2894 if (!S.checkSectionName(LiteralLoc, Str))
2895 return;
2896
2897 // If the target wants to validate the section specifier, make it happen.
2898 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
2899 if (!Error.empty()) {
2900 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2901 << Error;
2902 return;
2903 }
2904
2905 SectionAttr *NewAttr = S.mergeSectionAttr(D, AL, Str);
2906 if (NewAttr)
2907 D->addAttr(NewAttr);
2908}
2909
2910// This is used for `__declspec(code_seg("segname"))` on a decl.
2911// `#pragma code_seg("segname")` uses checkSectionName() instead.
2912static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc,
2913 StringRef CodeSegName) {
2914 std::string Error =
2915 S.Context.getTargetInfo().isValidSectionSpecifier(CodeSegName);
2916 if (!Error.empty()) {
2917 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
2918 << Error << 0 /*'code-seg'*/;
2919 return false;
2920 }
2921
2922 return true;
2923}
2924
2925CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
2926 StringRef Name) {
2927 // Explicit or partial specializations do not inherit
2928 // the code_seg attribute from the primary template.
2929 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2930 if (FD->isFunctionTemplateSpecialization())
2931 return nullptr;
2932 }
2933 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
2934 if (ExistingAttr->getName() == Name)
2935 return nullptr;
2936 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
2937 << 0 /*codeseg*/;
2938 Diag(CI.getLoc(), diag::note_previous_attribute);
2939 return nullptr;
2940 }
2941 return ::new (Context) CodeSegAttr(Context, CI, Name);
2942}
2943
2944static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2945 StringRef Str;
2946 SourceLocation LiteralLoc;
2947 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
2948 return;
2949 if (!checkCodeSegName(S, LiteralLoc, Str))
2950 return;
2951 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
2952 if (!ExistingAttr->isImplicit()) {
2953 S.Diag(AL.getLoc(),
2954 ExistingAttr->getName() == Str
2955 ? diag::warn_duplicate_codeseg_attribute
2956 : diag::err_conflicting_codeseg_attribute);
2957 return;
2958 }
2959 D->dropAttr<CodeSegAttr>();
2960 }
2961 if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL, Str))
2962 D->addAttr(CSA);
2963}
2964
2965// Check for things we'd like to warn about. Multiversioning issues are
2966// handled later in the process, once we know how many exist.
2967bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
2968 enum FirstParam { Unsupported, Duplicate };
2969 enum SecondParam { None, Architecture };
2970 for (auto Str : {"tune=", "fpmath="})
2971 if (AttrStr.find(Str) != StringRef::npos)
2972 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
2973 << Unsupported << None << Str;
2974
2975 TargetAttr::ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr);
2976
2977 if (!ParsedAttrs.Architecture.empty() &&
2978 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture))
2979 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
2980 << Unsupported << Architecture << ParsedAttrs.Architecture;
2981
2982 if (ParsedAttrs.DuplicateArchitecture)
2983 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
2984 << Duplicate << None << "arch=";
2985
2986 for (const auto &Feature : ParsedAttrs.Features) {
2987 auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
2988 if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
2989 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
2990 << Unsupported << None << CurFeature;
2991 }
2992
2993 return false;
2994}
2995
2996static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2997 StringRef Str;
2998 SourceLocation LiteralLoc;
2999 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
3000 S.checkTargetAttr(LiteralLoc, Str))
3001 return;
3002
3003 TargetAttr *NewAttr = ::new (S.Context) TargetAttr(S.Context, AL, Str);
3004 D->addAttr(NewAttr);
3005}
3006
3007static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3008 Expr *E = AL.getArgAsExpr(0);
3009 uint32_t VecWidth;
3010 if (!checkUInt32Argument(S, AL, E, VecWidth)) {
3011 AL.setInvalid();
3012 return;
3013 }
3014
3015 MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
3016 if (Existing && Existing->getVectorWidth() != VecWidth) {
3017 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3018 return;
3019 }
3020
3021 D->addAttr(::new (S.Context) MinVectorWidthAttr(S.Context, AL, VecWidth));
3022}
3023
3024static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3025 Expr *E = AL.getArgAsExpr(0);
3026 SourceLocation Loc = E->getExprLoc();
3027 FunctionDecl *FD = nullptr;
3028 DeclarationNameInfo NI;
3029
3030 // gcc only allows for simple identifiers. Since we support more than gcc, we
3031 // will warn the user.
3032 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3033 if (DRE->hasQualifier())
3034 S.Diag(Loc, diag::warn_cleanup_ext);
3035 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3036 NI = DRE->getNameInfo();
3037 if (!FD) {
3038 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3039 << NI.getName();
3040 return;
3041 }
3042 } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3043 if (ULE->hasExplicitTemplateArgs())
3044 S.Diag(Loc, diag::warn_cleanup_ext);
3045 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
3046 NI = ULE->getNameInfo();
3047 if (!FD) {
3048 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3049 << NI.getName();
3050 if (ULE->getType() == S.Context.OverloadTy)
3051 S.NoteAllOverloadCandidates(ULE);
3052 return;
3053 }
3054 } else {
3055 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3056 return;
3057 }
3058
3059 if (FD->getNumParams() != 1) {
3060 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3061 << NI.getName();
3062 return;
3063 }
3064
3065 // We're currently more strict than GCC about what function types we accept.
3066 // If this ever proves to be a problem it should be easy to fix.
3067 QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
3068 QualType ParamTy = FD->getParamDecl(0)->getType();
3069 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
3070 ParamTy, Ty) != Sema::Compatible) {
3071 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3072 << NI.getName() << ParamTy << Ty;
3073 return;
3074 }
3075
3076 D->addAttr(::new (S.Context) CleanupAttr(S.Context, AL, FD));
3077}
3078
3079static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3080 const ParsedAttr &AL) {
3081 if (!AL.isArgIdent(0)) {
3082 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3083 << AL << 0 << AANT_ArgumentIdentifier;
3084 return;
3085 }
3086
3087 EnumExtensibilityAttr::Kind ExtensibilityKind;
3088 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3089 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3090 ExtensibilityKind)) {
3091 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3092 return;
3093 }
3094
3095 D->addAttr(::new (S.Context)
3096 EnumExtensibilityAttr(S.Context, AL, ExtensibilityKind));
3097}
3098
3099/// Handle __attribute__((format_arg((idx)))) attribute based on
3100/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3101static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3102 Expr *IdxExpr = AL.getArgAsExpr(0);
3103 ParamIdx Idx;
3104 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx))
3105 return;
3106
3107 // Make sure the format string is really a string.
3108 QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex());
3109
3110 bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3111 if (NotNSStringTy &&
3112 !isCFStringType(Ty, S.Context) &&
3113 (!Ty->isPointerType() ||
3114 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3115 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3116 << "a string type" << IdxExpr->getSourceRange()
3117 << getFunctionOrMethodParamRange(D, 0);
3118 return;
3119 }
3120 Ty = getFunctionOrMethodResultType(D);
3121 if (!isNSStringType(Ty, S.Context) &&
3122 !isCFStringType(Ty, S.Context) &&
3123 (!Ty->isPointerType() ||
3124 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3125 S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
3126 << (NotNSStringTy ? "string type" : "NSString")
3127 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3128 return;
3129 }
3130
3131 D->addAttr(::new (S.Context) FormatArgAttr(S.Context, AL, Idx));
3132}
3133
3134enum FormatAttrKind {
3135 CFStringFormat,
3136 NSStringFormat,
3137 StrftimeFormat,
3138 SupportedFormat,
3139 IgnoredFormat,
3140 InvalidFormat
3141};
3142
3143/// getFormatAttrKind - Map from format attribute names to supported format
3144/// types.
3145static FormatAttrKind getFormatAttrKind(StringRef Format) {
3146 return llvm::StringSwitch<FormatAttrKind>(Format)
3147 // Check for formats that get handled specially.
3148 .Case("NSString", NSStringFormat)
3149 .Case("CFString", CFStringFormat)
3150 .Case("strftime", StrftimeFormat)
3151
3152 // Otherwise, check for supported formats.
3153 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3154 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3155 .Case("kprintf", SupportedFormat) // OpenBSD.
3156 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3157 .Case("os_trace", SupportedFormat)
3158 .Case("os_log", SupportedFormat)
3159
3160 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3161 .Default(InvalidFormat);
3162}
3163
3164/// Handle __attribute__((init_priority(priority))) attributes based on
3165/// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3166static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3167 if (!S.getLangOpts().CPlusPlus) {
3168 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
3169 return;
3170 }
3171
3172 if (S.getCurFunctionOrMethodDecl()) {
3173 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3174 AL.setInvalid();
3175 return;
3176 }
3177 QualType T = cast<VarDecl>(D)->getType();
3178 if (S.Context.getAsArrayType(T))
3179 T = S.Context.getBaseElementType(T);
3180 if (!T->getAs<RecordType>()) {
3181 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3182 AL.setInvalid();
3183 return;
3184 }
3185
3186 Expr *E = AL.getArgAsExpr(0);
3187 uint32_t prioritynum;
3188 if (!checkUInt32Argument(S, AL, E, prioritynum)) {
3189 AL.setInvalid();
3190 return;
3191 }
3192
3193 if (prioritynum < 101 || prioritynum > 65535) {
3194 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
3195 << E->getSourceRange() << AL << 101 << 65535;
3196 AL.setInvalid();
3197 return;
3198 }
3199 D->addAttr(::new (S.Context) InitPriorityAttr(S.Context, AL, prioritynum));
3200}
3201
3202FormatAttr *Sema::mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3203 IdentifierInfo *Format, int FormatIdx,
3204 int FirstArg) {
3205 // Check whether we already have an equivalent format attribute.
3206 for (auto *F : D->specific_attrs<FormatAttr>()) {
3207 if (F->getType() == Format &&
3208 F->getFormatIdx() == FormatIdx &&
3209 F->getFirstArg() == FirstArg) {
3210 // If we don't have a valid location for this attribute, adopt the
3211 // location.
3212 if (F->getLocation().isInvalid())
3213 F->setRange(CI.getRange());
3214 return nullptr;
3215 }
3216 }
3217
3218 return ::new (Context) FormatAttr(Context, CI, Format, FormatIdx, FirstArg);
3219}
3220
3221/// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3222/// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3223static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3224 if (!AL.isArgIdent(0)) {
1
Calling 'ParsedAttr::isArgIdent'
4
Returning from 'ParsedAttr::isArgIdent'
5
Taking false branch
3225 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3226 << AL << 1 << AANT_ArgumentIdentifier;
3227 return;
3228 }
3229
3230 // In C++ the implicit 'this' function parameter also counts, and they are
3231 // counted from one.
3232 bool HasImplicitThisParam = isInstanceMethod(D);
6
Calling 'isInstanceMethod'
10
Returning from 'isInstanceMethod'
3233 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3234
3235 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3236 StringRef Format = II->getName();
3237
3238 if (normalizeName(Format)) {
11
Taking false branch
3239 // If we've modified the string name, we need a new identifier for it.
3240 II = &S.Context.Idents.get(Format);
3241 }
3242
3243 // Check for supported formats.
3244 FormatAttrKind Kind = getFormatAttrKind(Format);
3245
3246 if (Kind
11.1
'Kind' is not equal to IgnoredFormat
11.1
'Kind' is not equal to IgnoredFormat
11.1
'Kind' is not equal to IgnoredFormat
== IgnoredFormat)
12
Taking false branch
3247 return;
3248
3249 if (Kind
12.1
'Kind' is not equal to InvalidFormat
12.1
'Kind' is not equal to InvalidFormat
12.1
'Kind' is not equal to InvalidFormat
== InvalidFormat) {
13
Taking false branch
3250 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
3251 << AL << II->getName();
3252 return;
3253 }
3254
3255 // checks for the 2nd argument
3256 Expr *IdxExpr = AL.getArgAsExpr(1);
3257 uint32_t Idx;
3258 if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2))
14
Assuming the condition is false
15
Taking false branch
3259 return;
3260
3261 if (Idx < 1 || Idx > NumArgs) {
16
Assuming 'Idx' is >= 1
17
Assuming 'Idx' is <= 'NumArgs'
18
Taking false branch
3262 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3263 << AL << 2 << IdxExpr->getSourceRange();
3264 return;
3265 }
3266
3267 // FIXME: Do we need to bounds check?
3268 unsigned ArgIdx = Idx - 1;
3269
3270 if (HasImplicitThisParam
18.1
'HasImplicitThisParam' is false
18.1
'HasImplicitThisParam' is false
18.1
'HasImplicitThisParam' is false
) {
19
Taking false branch
3271 if (ArgIdx == 0) {
3272 S.Diag(AL.getLoc(),
3273 diag::err_format_attribute_implicit_this_format_string)
3274 << IdxExpr->getSourceRange();
3275 return;
3276 }
3277 ArgIdx--;
3278 }
3279
3280 // make sure the format string is really a string
3281 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3282
3283 if (Kind
19.1
'Kind' is not equal to CFStringFormat
19.1
'Kind' is not equal to CFStringFormat
19.1
'Kind' is not equal to CFStringFormat
== CFStringFormat) {
20
Taking false branch
3284 if (!isCFStringType(Ty, S.Context)) {
3285 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3286 << "a CFString" << IdxExpr->getSourceRange()
3287 << getFunctionOrMethodParamRange(D, ArgIdx);
3288 return;
3289 }
3290 } else if (Kind
20.1
'Kind' is not equal to NSStringFormat
20.1
'Kind' is not equal to NSStringFormat
20.1
'Kind' is not equal to NSStringFormat
== NSStringFormat) {
21
Taking false branch
3291 // FIXME: do we need to check if the type is NSString*? What are the
3292 // semantics?
3293 if (!isNSStringType(Ty, S.Context)) {
3294 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3295 << "an NSString" << IdxExpr->getSourceRange()
3296 << getFunctionOrMethodParamRange(D, ArgIdx);
3297 return;
3298 }
3299 } else if (!Ty->isPointerType() ||
22
Calling 'Type::isPointerType'
25
Returning from 'Type::isPointerType'
3300 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
26
Assuming the object is not a 'PointerType'
27
Called C++ object pointer is null
3301 S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3302 << "a string type" << IdxExpr->getSourceRange()
3303 << getFunctionOrMethodParamRange(D, ArgIdx);
3304 return;
3305 }
3306
3307 // check the 3rd argument
3308 Expr *FirstArgExpr = AL.getArgAsExpr(2);
3309 uint32_t FirstArg;
3310 if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3))
3311 return;
3312
3313 // check if the function is variadic if the 3rd argument non-zero
3314 if (FirstArg != 0) {
3315 if (isFunctionOrMethodVariadic(D)) {
3316 ++NumArgs; // +1 for ...
3317 } else {
3318 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3319 return;
3320 }
3321 }
3322
3323 // strftime requires FirstArg to be 0 because it doesn't read from any
3324 // variable the input is just the current time + the format string.
3325 if (Kind == StrftimeFormat) {
3326 if (FirstArg != 0) {
3327 S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
3328 << FirstArgExpr->getSourceRange();
3329 return;
3330 }
3331 // if 0 it disables parameter checking (to use with e.g. va_list)
3332 } else if (FirstArg != 0 && FirstArg != NumArgs) {
3333 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3334 << AL << 3 << FirstArgExpr->getSourceRange();
3335 return;
3336 }
3337
3338 FormatAttr *NewAttr = S.mergeFormatAttr(D, AL, II, Idx, FirstArg);
3339 if (NewAttr)
3340 D->addAttr(NewAttr);
3341}
3342
3343/// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
3344static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3345 // The index that identifies the callback callee is mandatory.
3346 if (AL.getNumArgs() == 0) {
3347 S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee)
3348 << AL.getRange();
3349 return;
3350 }
3351
3352 bool HasImplicitThisParam = isInstanceMethod(D);
3353 int32_t NumArgs = getFunctionOrMethodNumParams(D);
3354
3355 FunctionDecl *FD = D->getAsFunction();
3356 assert(FD && "Expected a function declaration!")((FD && "Expected a function declaration!") ? static_cast
<void> (0) : __assert_fail ("FD && \"Expected a function declaration!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 3356, __PRETTY_FUNCTION__))
;
3357
3358 llvm::StringMap<int> NameIdxMapping;
3359 NameIdxMapping["__"] = -1;
3360
3361 NameIdxMapping["this"] = 0;
3362
3363 int Idx = 1;
3364 for (const ParmVarDecl *PVD : FD->parameters())
3365 NameIdxMapping[PVD->getName()] = Idx++;
3366
3367 auto UnknownName = NameIdxMapping.end();
3368
3369 SmallVector<int, 8> EncodingIndices;
3370 for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) {
3371 SourceRange SR;
3372 int32_t ArgIdx;
3373
3374 if (AL.isArgIdent(I)) {
3375 IdentifierLoc *IdLoc = AL.getArgAsIdent(I);
3376 auto It = NameIdxMapping.find(IdLoc->Ident->getName());
3377 if (It == UnknownName) {
3378 S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown)
3379 << IdLoc->Ident << IdLoc->Loc;
3380 return;
3381 }
3382
3383 SR = SourceRange(IdLoc->Loc);
3384 ArgIdx = It->second;
3385 } else if (AL.isArgExpr(I)) {
3386 Expr *IdxExpr = AL.getArgAsExpr(I);
3387
3388 // If the expression is not parseable as an int32_t we have a problem.
3389 if (!checkUInt32Argument(S, AL, IdxExpr, (uint32_t &)ArgIdx, I + 1,
3390 false)) {
3391 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3392 << AL << (I + 1) << IdxExpr->getSourceRange();
3393 return;
3394 }
3395
3396 // Check oob, excluding the special values, 0 and -1.
3397 if (ArgIdx < -1 || ArgIdx > NumArgs) {
3398 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3399 << AL << (I + 1) << IdxExpr->getSourceRange();
3400 return;
3401 }
3402
3403 SR = IdxExpr->getSourceRange();
3404 } else {
3405 llvm_unreachable("Unexpected ParsedAttr argument type!")::llvm::llvm_unreachable_internal("Unexpected ParsedAttr argument type!"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 3405)
;
3406 }
3407
3408 if (ArgIdx == 0 && !HasImplicitThisParam) {
3409 S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available)
3410 << (I + 1) << SR;
3411 return;
3412 }
3413
3414 // Adjust for the case we do not have an implicit "this" parameter. In this
3415 // case we decrease all positive values by 1 to get LLVM argument indices.
3416 if (!HasImplicitThisParam && ArgIdx > 0)
3417 ArgIdx -= 1;
3418
3419 EncodingIndices.push_back(ArgIdx);
3420 }
3421
3422 int CalleeIdx = EncodingIndices.front();
3423 // Check if the callee index is proper, thus not "this" and not "unknown".
3424 // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam"
3425 // is false and positive if "HasImplicitThisParam" is true.
3426 if (CalleeIdx < (int)HasImplicitThisParam) {
3427 S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee)
3428 << AL.getRange();
3429 return;
3430 }
3431
3432 // Get the callee type, note the index adjustment as the AST doesn't contain
3433 // the this type (which the callee cannot reference anyway!).
3434 const Type *CalleeType =
3435 getFunctionOrMethodParamType(D, CalleeIdx - HasImplicitThisParam)
3436 .getTypePtr();
3437 if (!CalleeType || !CalleeType->isFunctionPointerType()) {
3438 S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3439 << AL.getRange();
3440 return;
3441 }
3442
3443 const Type *CalleeFnType =
3444 CalleeType->getPointeeType()->getUnqualifiedDesugaredType();
3445
3446 // TODO: Check the type of the callee arguments.
3447
3448 const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(CalleeFnType);
3449 if (!CalleeFnProtoType) {
3450 S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3451 << AL.getRange();
3452 return;
3453 }
3454
3455 if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) {
3456 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3457 << AL << (unsigned)(EncodingIndices.size() - 1);
3458 return;
3459 }
3460
3461 if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) {
3462 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3463 << AL << (unsigned)(EncodingIndices.size() - 1);
3464 return;
3465 }
3466
3467 if (CalleeFnProtoType->isVariadic()) {
3468 S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange();
3469 return;
3470 }
3471
3472 // Do not allow multiple callback attributes.
3473 if (D->hasAttr<CallbackAttr>()) {
3474 S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange();
3475 return;
3476 }
3477
3478 D->addAttr(::new (S.Context) CallbackAttr(
3479 S.Context, AL, EncodingIndices.data(), EncodingIndices.size()));
3480}
3481
3482static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3483 // Try to find the underlying union declaration.
3484 RecordDecl *RD = nullptr;
3485 const auto *TD = dyn_cast<TypedefNameDecl>(D);
3486 if (TD && TD->getUnderlyingType()->isUnionType())
3487 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3488 else
3489 RD = dyn_cast<RecordDecl>(D);
3490
3491 if (!RD || !RD->isUnion()) {
3492 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL
3493 << ExpectedUnion;
3494 return;
3495 }
3496
3497 if (!RD->isCompleteDefinition()) {
3498 if (!RD->isBeingDefined())
3499 S.Diag(AL.getLoc(),
3500 diag::warn_transparent_union_attribute_not_definition);
3501 return;
3502 }
3503
3504 RecordDecl::field_iterator Field = RD->field_begin(),
3505 FieldEnd = RD->field_end();
3506 if (Field == FieldEnd) {
3507 S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3508 return;
3509 }
3510
3511 FieldDecl *FirstField = *Field;
3512 QualType FirstType = FirstField->getType();
3513 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3514 S.Diag(FirstField->getLocation(),
3515 diag::warn_transparent_union_attribute_floating)
3516 << FirstType->isVectorType() << FirstType;
3517 return;
3518 }
3519
3520 if (FirstType->isIncompleteType())
3521 return;
3522 uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3523 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3524 for (; Field != FieldEnd; ++Field) {
3525 QualType FieldType = Field->getType();
3526 if (FieldType->isIncompleteType())
3527 return;
3528 // FIXME: this isn't fully correct; we also need to test whether the
3529 // members of the union would all have the same calling convention as the
3530 // first member of the union. Checking just the size and alignment isn't
3531 // sufficient (consider structs passed on the stack instead of in registers
3532 // as an example).
3533 if (S.Context.getTypeSize(FieldType) != FirstSize ||
3534 S.Context.getTypeAlign(FieldType) > FirstAlign) {
3535 // Warn if we drop the attribute.
3536 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3537 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3538 : S.Context.getTypeAlign(FieldType);
3539 S.Diag(Field->getLocation(),
3540 diag::warn_transparent_union_attribute_field_size_align)
3541 << isSize << Field->getDeclName() << FieldBits;
3542 unsigned FirstBits = isSize? FirstSize : FirstAlign;
3543 S.Diag(FirstField->getLocation(),
3544 diag::note_transparent_union_first_field_size_align)
3545 << isSize << FirstBits;
3546 return;
3547 }
3548 }
3549
3550 RD->addAttr(::new (S.Context) TransparentUnionAttr(S.Context, AL));
3551}
3552
3553static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3554 // Make sure that there is a string literal as the annotation's single
3555 // argument.
3556 StringRef Str;
3557 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
3558 return;
3559
3560 // Don't duplicate annotations that are already set.
3561 for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3562 if (I->getAnnotation() == Str)
3563 return;
3564 }
3565
3566 D->addAttr(::new (S.Context) AnnotateAttr(S.Context, AL, Str));
3567}
3568
3569static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3570 S.AddAlignValueAttr(D, AL, AL.getArgAsExpr(0));
3571}
3572
3573void Sema::AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E) {
3574 AlignValueAttr TmpAttr(Context, CI, E);
3575 SourceLocation AttrLoc = CI.getLoc();
3576
3577 QualType T;
3578 if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
3579 T = TD->getUnderlyingType();
3580 else if (const auto *VD = dyn_cast<ValueDecl>(D))
3581 T = VD->getType();
3582 else
3583 llvm_unreachable("Unknown decl type for align_value")::llvm::llvm_unreachable_internal("Unknown decl type for align_value"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 3583)
;
3584
3585 if (!T->isDependentType() && !T->isAnyPointerType() &&
3586 !T->isReferenceType() && !T->isMemberPointerType()) {
3587 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3588 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3589 return;
3590 }
3591
3592 if (!E->isValueDependent()) {
3593 llvm::APSInt Alignment;
3594 ExprResult ICE
3595 = VerifyIntegerConstantExpression(E, &Alignment,
3596 diag::err_align_value_attribute_argument_not_int,
3597 /*AllowFold*/ false);
3598 if (ICE.isInvalid())
3599 return;
3600
3601 if (!Alignment.isPowerOf2()) {
3602 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3603 << E->getSourceRange();
3604 return;
3605 }
3606
3607 D->addAttr(::new (Context) AlignValueAttr(Context, CI, ICE.get()));
3608 return;
3609 }
3610
3611 // Save dependent expressions in the AST to be instantiated.
3612 D->addAttr(::new (Context) AlignValueAttr(Context, CI, E));
3613}
3614
3615static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3616 // check the attribute arguments.
3617 if (AL.getNumArgs() > 1) {
3618 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3619 return;
3620 }
3621
3622 if (AL.getNumArgs() == 0) {
3623 D->addAttr(::new (S.Context) AlignedAttr(S.Context, AL, true, nullptr));
3624 return;
3625 }
3626
3627 Expr *E = AL.getArgAsExpr(0);
3628 if (AL.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
3629 S.Diag(AL.getEllipsisLoc(),
3630 diag::err_pack_expansion_without_parameter_packs);
3631 return;
3632 }
3633
3634 if (!AL.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
3635 return;
3636
3637 S.AddAlignedAttr(D, AL, E, AL.isPackExpansion());
3638}
3639
3640void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
3641 bool IsPackExpansion) {
3642 AlignedAttr TmpAttr(Context, CI, true, E);
3643 SourceLocation AttrLoc = CI.getLoc();
3644
3645 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3646 if (TmpAttr.isAlignas()) {
3647 // C++11 [dcl.align]p1:
3648 // An alignment-specifier may be applied to a variable or to a class
3649 // data member, but it shall not be applied to a bit-field, a function
3650 // parameter, the formal parameter of a catch clause, or a variable
3651 // declared with the register storage class specifier. An
3652 // alignment-specifier may also be applied to the declaration of a class
3653 // or enumeration type.
3654 // C11 6.7.5/2:
3655 // An alignment attribute shall not be specified in a declaration of
3656 // a typedef, or a bit-field, or a function, or a parameter, or an
3657 // object declared with the register storage-class specifier.
3658 int DiagKind = -1;
3659 if (isa<ParmVarDecl>(D)) {
3660 DiagKind = 0;
3661 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
3662 if (VD->getStorageClass() == SC_Register)
3663 DiagKind = 1;
3664 if (VD->isExceptionVariable())
3665 DiagKind = 2;
3666 } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
3667 if (FD->isBitField())
3668 DiagKind = 3;
3669 } else if (!isa<TagDecl>(D)) {
3670 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3671 << (TmpAttr.isC11() ? ExpectedVariableOrField
3672 : ExpectedVariableFieldOrTag);
3673 return;
3674 }
3675 if (DiagKind != -1) {
3676 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3677 << &TmpAttr << DiagKind;
3678 return;
3679 }
3680 }
3681
3682 if (E->isValueDependent()) {
3683 // We can't support a dependent alignment on a non-dependent type,
3684 // because we have no way to model that a type is "alignment-dependent"
3685 // but not dependent in any other way.
3686 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3687 if (!TND->getUnderlyingType()->isDependentType()) {
3688 Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
3689 << E->getSourceRange();
3690 return;
3691 }
3692 }
3693
3694 // Save dependent expressions in the AST to be instantiated.
3695 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, E);
3696 AA->setPackExpansion(IsPackExpansion);
3697 D->addAttr(AA);
3698 return;
3699 }
3700
3701 // FIXME: Cache the number on the AL object?
3702 llvm::APSInt Alignment;
3703 ExprResult ICE
3704 = VerifyIntegerConstantExpression(E, &Alignment,
3705 diag::err_aligned_attribute_argument_not_int,
3706 /*AllowFold*/ false);
3707 if (ICE.isInvalid())
3708 return;
3709
3710 uint64_t AlignVal = Alignment.getZExtValue();
3711
3712 // C++11 [dcl.align]p2:
3713 // -- if the constant expression evaluates to zero, the alignment
3714 // specifier shall have no effect
3715 // C11 6.7.5p6:
3716 // An alignment specification of zero has no effect.
3717 if (!(TmpAttr.isAlignas() && !Alignment)) {
3718 if (!llvm::isPowerOf2_64(AlignVal)) {
3719 Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3720 << E->getSourceRange();
3721 return;
3722 }
3723 }
3724
3725 // Alignment calculations can wrap around if it's greater than 2**28.
3726 unsigned MaxValidAlignment =
3727 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3728 : 268435456;
3729 if (AlignVal > MaxValidAlignment) {
3730 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3731 << E->getSourceRange();
3732 return;
3733 }
3734
3735 if (Context.getTargetInfo().isTLSSupported()) {
3736 unsigned MaxTLSAlign =
3737 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3738 .getQuantity();
3739 const auto *VD = dyn_cast<VarDecl>(D);
3740 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3741 VD->getTLSKind() != VarDecl::TLS_None) {
3742 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3743 << (unsigned)AlignVal << VD << MaxTLSAlign;
3744 return;
3745 }
3746 }
3747
3748 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, ICE.get());
3749 AA->setPackExpansion(IsPackExpansion);
3750 D->addAttr(AA);
3751}
3752
3753void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI,
3754 TypeSourceInfo *TS, bool IsPackExpansion) {
3755 // FIXME: Cache the number on the AL object if non-dependent?
3756 // FIXME: Perform checking of type validity
3757 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
3758 AA->setPackExpansion(IsPackExpansion);
3759 D->addAttr(AA);
3760}
3761
3762void Sema::CheckAlignasUnderalignment(Decl *D) {
3763 assert(D->hasAttrs() && "no attributes on decl")((D->hasAttrs() && "no attributes on decl") ? static_cast
<void> (0) : __assert_fail ("D->hasAttrs() && \"no attributes on decl\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 3763, __PRETTY_FUNCTION__))
;
3764
3765 QualType UnderlyingTy, DiagTy;
3766 if (const auto *VD = dyn_cast<ValueDecl>(D)) {
3767 UnderlyingTy = DiagTy = VD->getType();
3768 } else {
3769 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3770 if (const auto *ED = dyn_cast<EnumDecl>(D))
3771 UnderlyingTy = ED->getIntegerType();
3772 }
3773 if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3774 return;
3775
3776 // C++11 [dcl.align]p5, C11 6.7.5/4:
3777 // The combined effect of all alignment attributes in a declaration shall
3778 // not specify an alignment that is less strict than the alignment that
3779 // would otherwise be required for the entity being declared.
3780 AlignedAttr *AlignasAttr = nullptr;
3781 unsigned Align = 0;
3782 for (auto *I : D->specific_attrs<AlignedAttr>()) {
3783 if (I->isAlignmentDependent())
3784 return;
3785 if (I->isAlignas())
3786 AlignasAttr = I;
3787 Align = std::max(Align, I->getAlignment(Context));
3788 }
3789
3790 if (AlignasAttr && Align) {
3791 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3792 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3793 if (NaturalAlign > RequestedAlign)
3794 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3795 << DiagTy << (unsigned)NaturalAlign.getQuantity();
3796 }
3797}
3798
3799bool Sema::checkMSInheritanceAttrOnDefinition(
3800 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3801 MSInheritanceAttr::Spelling SemanticSpelling) {
3802 assert(RD->hasDefinition() && "RD has no definition!")((RD->hasDefinition() && "RD has no definition!") ?
static_cast<void> (0) : __assert_fail ("RD->hasDefinition() && \"RD has no definition!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 3802, __PRETTY_FUNCTION__))
;
3803
3804 // We may not have seen base specifiers or any virtual methods yet. We will
3805 // have to wait until the record is defined to catch any mismatches.
3806 if (!RD->getDefinition()->isCompleteDefinition())
3807 return false;
3808
3809 // The unspecified model never matches what a definition could need.
3810 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3811 return false;
3812
3813 if (BestCase) {
3814 if (RD->calculateInheritanceModel() == SemanticSpelling)
3815 return false;
3816 } else {
3817 if (RD->calculateInheritanceModel() <= SemanticSpelling)
3818 return false;
3819 }
3820
3821 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3822 << 0 /*definition*/;
3823 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3824 << RD->getNameAsString();
3825 return true;
3826}
3827
3828/// parseModeAttrArg - Parses attribute mode string and returns parsed type
3829/// attribute.
3830static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3831 bool &IntegerMode, bool &ComplexMode) {
3832 IntegerMode = true;
3833 ComplexMode = false;
3834 switch (Str.size()) {
3835 case 2:
3836 switch (Str[0]) {
3837 case 'Q':
3838 DestWidth = 8;
3839 break;
3840 case 'H':
3841 DestWidth = 16;
3842 break;
3843 case 'S':
3844 DestWidth = 32;
3845 break;
3846 case 'D':
3847 DestWidth = 64;
3848 break;
3849 case 'X':
3850 DestWidth = 96;
3851 break;
3852 case 'T':
3853 DestWidth = 128;
3854 break;
3855 }
3856 if (Str[1] == 'F') {
3857 IntegerMode = false;
3858 } else if (Str[1] == 'C') {
3859 IntegerMode = false;
3860 ComplexMode = true;
3861 } else if (Str[1] != 'I') {
3862 DestWidth = 0;
3863 }
3864 break;
3865 case 4:
3866 // FIXME: glibc uses 'word' to define register_t; this is narrower than a
3867 // pointer on PIC16 and other embedded platforms.
3868 if (Str == "word")
3869 DestWidth = S.Context.getTargetInfo().getRegisterWidth();
3870 else if (Str == "byte")
3871 DestWidth = S.Context.getTargetInfo().getCharWidth();
3872 break;
3873 case 7:
3874 if (Str == "pointer")
3875 DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
3876 break;
3877 case 11:
3878 if (Str == "unwind_word")
3879 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
3880 break;
3881 }
3882}
3883
3884/// handleModeAttr - This attribute modifies the width of a decl with primitive
3885/// type.
3886///
3887/// Despite what would be logical, the mode attribute is a decl attribute, not a
3888/// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
3889/// HImode, not an intermediate pointer.
3890static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3891 // This attribute isn't documented, but glibc uses it. It changes
3892 // the width of an int or unsigned int to the specified size.
3893 if (!AL.isArgIdent(0)) {
3894 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
3895 << AL << AANT_ArgumentIdentifier;
3896 return;
3897 }
3898
3899 IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
3900
3901 S.AddModeAttr(D, AL, Name);
3902}
3903
3904void Sema::AddModeAttr(Decl *D, const AttributeCommonInfo &CI,
3905 IdentifierInfo *Name, bool InInstantiation) {
3906 StringRef Str = Name->getName();
3907 normalizeName(Str);
3908 SourceLocation AttrLoc = CI.getLoc();
3909
3910 unsigned DestWidth = 0;
3911 bool IntegerMode = true;
3912 bool ComplexMode = false;
3913 llvm::APInt VectorSize(64, 0);
3914 if (Str.size() >= 4 && Str[0] == 'V') {
3915 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
3916 size_t StrSize = Str.size();
3917 size_t VectorStringLength = 0;
3918 while ((VectorStringLength + 1) < StrSize &&
3919 isdigit(Str[VectorStringLength + 1]))
3920 ++VectorStringLength;
3921 if (VectorStringLength &&
3922 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
3923 VectorSize.isPowerOf2()) {
3924 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
3925 IntegerMode, ComplexMode);
3926 // Avoid duplicate warning from template instantiation.
3927 if (!InInstantiation)
3928 Diag(AttrLoc, diag::warn_vector_mode_deprecated);
3929 } else {
3930 VectorSize = 0;
3931 }
3932 }
3933
3934 if (!VectorSize)
3935 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
3936
3937 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
3938 // and friends, at least with glibc.
3939 // FIXME: Make sure floating-point mappings are accurate
3940 // FIXME: Support XF and TF types
3941 if (!DestWidth) {
3942 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
3943 return;
3944 }
3945
3946 QualType OldTy;
3947 if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
3948 OldTy = TD->getUnderlyingType();
3949 else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
3950 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
3951 // Try to get type from enum declaration, default to int.
3952 OldTy = ED->getIntegerType();
3953 if (OldTy.isNull())
3954 OldTy = Context.IntTy;
3955 } else
3956 OldTy = cast<ValueDecl>(D)->getType();
3957
3958 if (OldTy->isDependentType()) {
3959 D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
3960 return;
3961 }
3962
3963 // Base type can also be a vector type (see PR17453).
3964 // Distinguish between base type and base element type.
3965 QualType OldElemTy = OldTy;
3966 if (const auto *VT = OldTy->getAs<VectorType>())
3967 OldElemTy = VT->getElementType();
3968
3969 // GCC allows 'mode' attribute on enumeration types (even incomplete), except
3970 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
3971 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
3972 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
3973 VectorSize.getBoolValue()) {
3974 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << CI.getRange();
3975 return;
3976 }
3977 bool IntegralOrAnyEnumType =
3978 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
3979
3980 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
3981 !IntegralOrAnyEnumType)
3982 Diag(AttrLoc, diag::err_mode_not_primitive);
3983 else if (IntegerMode) {
3984 if (!IntegralOrAnyEnumType)
3985 Diag(AttrLoc, diag::err_mode_wrong_type);
3986 } else if (ComplexMode) {
3987 if (!OldElemTy->isComplexType())
3988 Diag(AttrLoc, diag::err_mode_wrong_type);
3989 } else {
3990 if (!OldElemTy->isFloatingType())
3991 Diag(AttrLoc, diag::err_mode_wrong_type);
3992 }
3993
3994 QualType NewElemTy;
3995
3996 if (IntegerMode)
3997 NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
3998 OldElemTy->isSignedIntegerType());
3999 else
4000 NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
4001
4002 if (NewElemTy.isNull()) {
4003 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
4004 return;
4005 }
4006
4007 if (ComplexMode) {
4008 NewElemTy = Context.getComplexType(NewElemTy);
4009 }
4010
4011 QualType NewTy = NewElemTy;
4012 if (VectorSize.getBoolValue()) {
4013 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
4014 VectorType::GenericVector);
4015 } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
4016 // Complex machine mode does not support base vector types.
4017 if (ComplexMode) {
4018 Diag(AttrLoc, diag::err_complex_mode_vector_type);
4019 return;
4020 }
4021 unsigned NumElements = Context.getTypeSize(OldElemTy) *
4022 OldVT->getNumElements() /
4023 Context.getTypeSize(NewElemTy);
4024 NewTy =
4025 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
4026 }
4027
4028 if (NewTy.isNull()) {
4029 Diag(AttrLoc, diag::err_mode_wrong_type);
4030 return;
4031 }
4032
4033 // Install the new type.
4034 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
4035 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
4036 else if (auto *ED = dyn_cast<EnumDecl>(D))
4037 ED->setIntegerType(NewTy);
4038 else
4039 cast<ValueDecl>(D)->setType(NewTy);
4040
4041 D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4042}
4043
4044static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4045 D->addAttr(::new (S.Context) NoDebugAttr(S.Context, AL));
4046}
4047
4048AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D,
4049 const AttributeCommonInfo &CI,
4050 const IdentifierInfo *Ident) {
4051 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4052 Diag(CI.getLoc(), diag::warn_attribute_ignored) << Ident;
4053 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4054 return nullptr;
4055 }
4056
4057 if (D->hasAttr<AlwaysInlineAttr>())
4058 return nullptr;
4059
4060 return ::new (Context) AlwaysInlineAttr(Context, CI);
4061}
4062
4063CommonAttr *Sema::mergeCommonAttr(Decl *D, const ParsedAttr &AL) {
4064 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, AL))
4065 return nullptr;
4066
4067 return ::new (Context) CommonAttr(Context, AL);
4068}
4069
4070CommonAttr *Sema::mergeCommonAttr(Decl *D, const CommonAttr &AL) {
4071 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, AL))
4072 return nullptr;
4073
4074 return ::new (Context) CommonAttr(Context, AL);
4075}
4076
4077InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
4078 const ParsedAttr &AL) {
4079 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4080 // Attribute applies to Var but not any subclass of it (like ParmVar,
4081 // ImplicitParm or VarTemplateSpecialization).
4082 if (VD->getKind() != Decl::Var) {
4083 Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4084 << AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4085 : ExpectedVariableOrFunction);
4086 return nullptr;
4087 }
4088 // Attribute does not apply to non-static local variables.
4089 if (VD->hasLocalStorage()) {
4090 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4091 return nullptr;
4092 }
4093 }
4094
4095 if (checkAttrMutualExclusion<CommonAttr>(*this, D, AL))
4096 return nullptr;
4097
4098 return ::new (Context) InternalLinkageAttr(Context, AL);
4099}
4100InternalLinkageAttr *
4101Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
4102 if (const auto *VD = dyn_cast<VarDecl>(D)) {
4103 // Attribute applies to Var but not any subclass of it (like ParmVar,
4104 // ImplicitParm or VarTemplateSpecialization).
4105 if (VD->getKind() != Decl::Var) {
4106 Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
4107 << &AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4108 : ExpectedVariableOrFunction);
4109 return nullptr;
4110 }
4111 // Attribute does not apply to non-static local variables.
4112 if (VD->hasLocalStorage()) {
4113 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4114 return nullptr;
4115 }
4116 }
4117
4118 if (checkAttrMutualExclusion<CommonAttr>(*this, D, AL))
4119 return nullptr;
4120
4121 return ::new (Context) InternalLinkageAttr(Context, AL);
4122}
4123
4124MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI) {
4125 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4126 Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'minsize'";
4127 Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4128 return nullptr;
4129 }
4130
4131 if (D->hasAttr<MinSizeAttr>())
4132 return nullptr;
4133
4134 return ::new (Context) MinSizeAttr(Context, CI);
4135}
4136
4137NoSpeculativeLoadHardeningAttr *Sema::mergeNoSpeculativeLoadHardeningAttr(
4138 Decl *D, const NoSpeculativeLoadHardeningAttr &AL) {
4139 if (checkAttrMutualExclusion<SpeculativeLoadHardeningAttr>(*this, D, AL))
4140 return nullptr;
4141
4142 return ::new (Context) NoSpeculativeLoadHardeningAttr(Context, AL);
4143}
4144
4145OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D,
4146 const AttributeCommonInfo &CI) {
4147 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4148 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4149 Diag(CI.getLoc(), diag::note_conflicting_attribute);
4150 D->dropAttr<AlwaysInlineAttr>();
4151 }
4152 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4153 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4154 Diag(CI.getLoc(), diag::note_conflicting_attribute);
4155 D->dropAttr<MinSizeAttr>();
4156 }
4157
4158 if (D->hasAttr<OptimizeNoneAttr>())
4159 return nullptr;
4160
4161 return ::new (Context) OptimizeNoneAttr(Context, CI);
4162}
4163
4164SpeculativeLoadHardeningAttr *Sema::mergeSpeculativeLoadHardeningAttr(
4165 Decl *D, const SpeculativeLoadHardeningAttr &AL) {
4166 if (checkAttrMutualExclusion<NoSpeculativeLoadHardeningAttr>(*this, D, AL))
4167 return nullptr;
4168
4169 return ::new (Context) SpeculativeLoadHardeningAttr(Context, AL);
4170}
4171
4172static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4173 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, AL))
4174 return;
4175
4176 if (AlwaysInlineAttr *Inline =
4177 S.mergeAlwaysInlineAttr(D, AL, AL.getAttrName()))
4178 D->addAttr(Inline);
4179}
4180
4181static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4182 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(D, AL))
4183 D->addAttr(MinSize);
4184}
4185
4186static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4187 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(D, AL))
4188 D->addAttr(Optnone);
4189}
4190
4191static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4192 if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, AL))
4193 return;
4194 const auto *VD = cast<VarDecl>(D);
4195 if (!VD->hasGlobalStorage()) {
4196 S.Diag(AL.getLoc(), diag::err_cuda_nonglobal_constant);
4197 return;
4198 }
4199 D->addAttr(::new (S.Context) CUDAConstantAttr(S.Context, AL));
4200}
4201
4202static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4203 if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, AL))
4204 return;
4205 const auto *VD = cast<VarDecl>(D);
4206 // extern __shared__ is only allowed on arrays with no length (e.g.
4207 // "int x[]").
4208 if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
4209 !isa<IncompleteArrayType>(VD->getType())) {
4210 S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
4211 return;
4212 }
4213 if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4214 S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
4215 << S.CurrentCUDATarget())
4216 return;
4217 D->addAttr(::new (S.Context) CUDASharedAttr(S.Context, AL));
4218}
4219
4220static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4221 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, AL) ||
4222 checkAttrMutualExclusion<CUDAHostAttr>(S, D, AL)) {
4223 return;
4224 }
4225 const auto *FD = cast<FunctionDecl>(D);
4226 if (!FD->getReturnType()->isVoidType() &&
4227 !FD->getReturnType()->getAs<AutoType>() &&
4228 !FD->getReturnType()->isInstantiationDependentType()) {
4229 SourceRange RTRange = FD->getReturnTypeSourceRange();
4230 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4231 << FD->getType()
4232 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4233 : FixItHint());
4234 return;
4235 }
4236 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4237 if (Method->isInstance()) {
4238 S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
4239 << Method;
4240 return;
4241 }
4242 S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
4243 }
4244 // Only warn for "inline" when compiling for host, to cut down on noise.
4245 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4246 S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
4247
4248 D->addAttr(::new (S.Context) CUDAGlobalAttr(S.Context, AL));
4249}
4250
4251static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4252 const auto *Fn = cast<FunctionDecl>(D);
4253 if (!Fn->isInlineSpecified()) {
4254 S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4255 return;
4256 }
4257
4258 if (S.LangOpts.CPlusPlus && Fn->getStorageClass() != SC_Extern)
4259 S.Diag(AL.getLoc(), diag::warn_gnu_inline_cplusplus_without_extern);
4260
4261 D->addAttr(::new (S.Context) GNUInlineAttr(S.Context, AL));
4262}
4263
4264static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4265 if (hasDeclarator(D)) return;
4266
4267 // Diagnostic is emitted elsewhere: here we store the (valid) AL
4268 // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4269 CallingConv CC;
4270 if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr))
4271 return;
4272
4273 if (!isa<ObjCMethodDecl>(D)) {
4274 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4275 << AL << ExpectedFunctionOrMethod;
4276 return;
4277 }
4278
4279 switch (AL.getKind()) {
4280 case ParsedAttr::AT_FastCall:
4281 D->addAttr(::new (S.Context) FastCallAttr(S.Context, AL));
4282 return;
4283 case ParsedAttr::AT_StdCall:
4284 D->addAttr(::new (S.Context) StdCallAttr(S.Context, AL));
4285 return;
4286 case ParsedAttr::AT_ThisCall:
4287 D->addAttr(::new (S.Context) ThisCallAttr(S.Context, AL));
4288 return;
4289 case ParsedAttr::AT_CDecl:
4290 D->addAttr(::new (S.Context) CDeclAttr(S.Context, AL));
4291 return;
4292 case ParsedAttr::AT_Pascal:
4293 D->addAttr(::new (S.Context) PascalAttr(S.Context, AL));
4294 return;
4295 case ParsedAttr::AT_SwiftCall:
4296 D->addAttr(::new (S.Context) SwiftCallAttr(S.Context, AL));
4297 return;
4298 case ParsedAttr::AT_VectorCall:
4299 D->addAttr(::new (S.Context) VectorCallAttr(S.Context, AL));
4300 return;
4301 case ParsedAttr::AT_MSABI:
4302 D->addAttr(::new (S.Context) MSABIAttr(S.Context, AL));
4303 return;
4304 case ParsedAttr::AT_SysVABI:
4305 D->addAttr(::new (S.Context) SysVABIAttr(S.Context, AL));
4306 return;
4307 case ParsedAttr::AT_RegCall:
4308 D->addAttr(::new (S.Context) RegCallAttr(S.Context, AL));
4309 return;
4310 case ParsedAttr::AT_Pcs: {
4311 PcsAttr::PCSType PCS;
4312 switch (CC) {
4313 case CC_AAPCS:
4314 PCS = PcsAttr::AAPCS;
4315 break;
4316 case CC_AAPCS_VFP:
4317 PCS = PcsAttr::AAPCS_VFP;
4318 break;
4319 default:
4320 llvm_unreachable("unexpected calling convention in pcs attribute")::llvm::llvm_unreachable_internal("unexpected calling convention in pcs attribute"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4320)
;
4321 }
4322
4323 D->addAttr(::new (S.Context) PcsAttr(S.Context, AL, PCS));
4324 return;
4325 }
4326 case ParsedAttr::AT_AArch64VectorPcs:
4327 D->addAttr(::new (S.Context) AArch64VectorPcsAttr(S.Context, AL));
4328 return;
4329 case ParsedAttr::AT_IntelOclBicc:
4330 D->addAttr(::new (S.Context) IntelOclBiccAttr(S.Context, AL));
4331 return;
4332 case ParsedAttr::AT_PreserveMost:
4333 D->addAttr(::new (S.Context) PreserveMostAttr(S.Context, AL));
4334 return;
4335 case ParsedAttr::AT_PreserveAll:
4336 D->addAttr(::new (S.Context) PreserveAllAttr(S.Context, AL));
4337 return;
4338 default:
4339 llvm_unreachable("unexpected attribute kind")::llvm::llvm_unreachable_internal("unexpected attribute kind"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4339)
;
4340 }
4341}
4342
4343static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4344 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
4345 return;
4346
4347 std::vector<StringRef> DiagnosticIdentifiers;
4348 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
4349 StringRef RuleName;
4350
4351 if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr))
4352 return;
4353
4354 // FIXME: Warn if the rule name is unknown. This is tricky because only
4355 // clang-tidy knows about available rules.
4356 DiagnosticIdentifiers.push_back(RuleName);
4357 }
4358 D->addAttr(::new (S.Context)
4359 SuppressAttr(S.Context, AL, DiagnosticIdentifiers.data(),
4360 DiagnosticIdentifiers.size()));
4361}
4362
4363static void handleLifetimeCategoryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4364 TypeSourceInfo *DerefTypeLoc = nullptr;
4365 QualType ParmType;
4366 if (AL.hasParsedType()) {
4367 ParmType = S.GetTypeFromParser(AL.getTypeArg(), &DerefTypeLoc);
4368
4369 unsigned SelectIdx = ~0U;
4370 if (ParmType->isVoidType())
4371 SelectIdx = 0;
4372 else if (ParmType->isReferenceType())
4373 SelectIdx = 1;
4374 else if (ParmType->isArrayType())
4375 SelectIdx = 2;
4376
4377 if (SelectIdx != ~0U) {
4378 S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument)
4379 << SelectIdx << AL;
4380 return;
4381 }
4382 }
4383
4384 // To check if earlier decl attributes do not conflict the newly parsed ones
4385 // we always add (and check) the attribute to the cannonical decl.
4386 D = D->getCanonicalDecl();
4387 if (AL.getKind() == ParsedAttr::AT_Owner) {
4388 if (checkAttrMutualExclusion<PointerAttr>(S, D, AL))
4389 return;
4390 if (const auto *OAttr = D->getAttr<OwnerAttr>()) {
4391 const Type *ExistingDerefType = OAttr->getDerefTypeLoc()
4392 ? OAttr->getDerefType().getTypePtr()
4393 : nullptr;
4394 if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
4395 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
4396 << AL << OAttr;
4397 S.Diag(OAttr->getLocation(), diag::note_conflicting_attribute);
4398 }
4399 return;
4400 }
4401 for (Decl *Redecl : D->redecls()) {
4402 Redecl->addAttr(::new (S.Context) OwnerAttr(S.Context, AL, DerefTypeLoc));
4403 }
4404 } else {
4405 if (checkAttrMutualExclusion<OwnerAttr>(S, D, AL))
4406 return;
4407 if (const auto *PAttr = D->getAttr<PointerAttr>()) {
4408 const Type *ExistingDerefType = PAttr->getDerefTypeLoc()
4409 ? PAttr->getDerefType().getTypePtr()
4410 : nullptr;
4411 if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
4412 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
4413 << AL << PAttr;
4414 S.Diag(PAttr->getLocation(), diag::note_conflicting_attribute);
4415 }
4416 return;
4417 }
4418 for (Decl *Redecl : D->redecls()) {
4419 Redecl->addAttr(::new (S.Context)
4420 PointerAttr(S.Context, AL, DerefTypeLoc));
4421 }
4422 }
4423}
4424
4425bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC,
4426 const FunctionDecl *FD) {
4427 if (Attrs.isInvalid())
4428 return true;
4429
4430 if (Attrs.hasProcessingCache()) {
4431 CC = (CallingConv) Attrs.getProcessingCache();
4432 return false;
4433 }
4434
4435 unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
4436 if (!checkAttributeNumArgs(*this, Attrs, ReqArgs)) {
4437 Attrs.setInvalid();
4438 return true;
4439 }
4440
4441 // TODO: diagnose uses of these conventions on the wrong target.
4442 switch (Attrs.getKind()) {
4443 case ParsedAttr::AT_CDecl:
4444 CC = CC_C;
4445 break;
4446 case ParsedAttr::AT_FastCall:
4447 CC = CC_X86FastCall;
4448 break;
4449 case ParsedAttr::AT_StdCall:
4450 CC = CC_X86StdCall;
4451 break;
4452 case ParsedAttr::AT_ThisCall:
4453 CC = CC_X86ThisCall;
4454 break;
4455 case ParsedAttr::AT_Pascal:
4456 CC = CC_X86Pascal;
4457 break;
4458 case ParsedAttr::AT_SwiftCall:
4459 CC = CC_Swift;
4460 break;
4461 case ParsedAttr::AT_VectorCall:
4462 CC = CC_X86VectorCall;
4463 break;
4464 case ParsedAttr::AT_AArch64VectorPcs:
4465 CC = CC_AArch64VectorCall;
4466 break;
4467 case ParsedAttr::AT_RegCall:
4468 CC = CC_X86RegCall;
4469 break;
4470 case ParsedAttr::AT_MSABI:
4471 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4472 CC_Win64;
4473 break;
4474 case ParsedAttr::AT_SysVABI:
4475 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4476 CC_C;
4477 break;
4478 case ParsedAttr::AT_Pcs: {
4479 StringRef StrRef;
4480 if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
4481 Attrs.setInvalid();
4482 return true;
4483 }
4484 if (StrRef == "aapcs") {
4485 CC = CC_AAPCS;
4486 break;
4487 } else if (StrRef == "aapcs-vfp") {
4488 CC = CC_AAPCS_VFP;
4489 break;
4490 }
4491
4492 Attrs.setInvalid();
4493 Diag(Attrs.getLoc(), diag::err_invalid_pcs);
4494 return true;
4495 }
4496 case ParsedAttr::AT_IntelOclBicc:
4497 CC = CC_IntelOclBicc;
4498 break;
4499 case ParsedAttr::AT_PreserveMost:
4500 CC = CC_PreserveMost;
4501 break;
4502 case ParsedAttr::AT_PreserveAll:
4503 CC = CC_PreserveAll;
4504 break;
4505 default: llvm_unreachable("unexpected attribute kind")::llvm::llvm_unreachable_internal("unexpected attribute kind"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4505)
;
4506 }
4507
4508 TargetInfo::CallingConvCheckResult A = TargetInfo::CCCR_OK;
4509 const TargetInfo &TI = Context.getTargetInfo();
4510 // CUDA functions may have host and/or device attributes which indicate
4511 // their targeted execution environment, therefore the calling convention
4512 // of functions in CUDA should be checked against the target deduced based
4513 // on their host/device attributes.
4514 if (LangOpts.CUDA) {
4515 auto *Aux = Context.getAuxTargetInfo();
4516 auto CudaTarget = IdentifyCUDATarget(FD);
4517 bool CheckHost = false, CheckDevice = false;
4518 switch (CudaTarget) {
4519 case CFT_HostDevice:
4520 CheckHost = true;
4521 CheckDevice = true;
4522 break;
4523 case CFT_Host:
4524 CheckHost = true;
4525 break;
4526 case CFT_Device:
4527 case CFT_Global:
4528 CheckDevice = true;
4529 break;
4530 case CFT_InvalidTarget:
4531 llvm_unreachable("unexpected cuda target")::llvm::llvm_unreachable_internal("unexpected cuda target", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4531)
;
4532 }
4533 auto *HostTI = LangOpts.CUDAIsDevice ? Aux : &TI;
4534 auto *DeviceTI = LangOpts.CUDAIsDevice ? &TI : Aux;
4535 if (CheckHost && HostTI)
4536 A = HostTI->checkCallingConvention(CC);
4537 if (A == TargetInfo::CCCR_OK && CheckDevice && DeviceTI)
4538 A = DeviceTI->checkCallingConvention(CC);
4539 } else {
4540 A = TI.checkCallingConvention(CC);
4541 }
4542
4543 switch (A) {
4544 case TargetInfo::CCCR_OK:
4545 break;
4546
4547 case TargetInfo::CCCR_Ignore:
4548 // Treat an ignored convention as if it was an explicit C calling convention
4549 // attribute. For example, __stdcall on Win x64 functions as __cdecl, so
4550 // that command line flags that change the default convention to
4551 // __vectorcall don't affect declarations marked __stdcall.
4552 CC = CC_C;
4553 break;
4554
4555 case TargetInfo::CCCR_Error:
4556 Diag(Attrs.getLoc(), diag::error_cconv_unsupported)
4557 << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
4558 break;
4559
4560 case TargetInfo::CCCR_Warning: {
4561 Diag(Attrs.getLoc(), diag::warn_cconv_unsupported)
4562 << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
4563
4564 // This convention is not valid for the target. Use the default function or
4565 // method calling convention.
4566 bool IsCXXMethod = false, IsVariadic = false;
4567 if (FD) {
4568 IsCXXMethod = FD->isCXXInstanceMember();
4569 IsVariadic = FD->isVariadic();
4570 }
4571 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
4572 break;
4573 }
4574 }
4575
4576 Attrs.setProcessingCache((unsigned) CC);
4577 return false;
4578}
4579
4580/// Pointer-like types in the default address space.
4581static bool isValidSwiftContextType(QualType Ty) {
4582 if (!Ty->hasPointerRepresentation())
4583 return Ty->isDependentType();
4584 return Ty->getPointeeType().getAddressSpace() == LangAS::Default;
4585}
4586
4587/// Pointers and references in the default address space.
4588static bool isValidSwiftIndirectResultType(QualType Ty) {
4589 if (const auto *PtrType = Ty->getAs<PointerType>()) {
4590 Ty = PtrType->getPointeeType();
4591 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4592 Ty = RefType->getPointeeType();
4593 } else {
4594 return Ty->isDependentType();
4595 }
4596 return Ty.getAddressSpace() == LangAS::Default;
4597}
4598
4599/// Pointers and references to pointers in the default address space.
4600static bool isValidSwiftErrorResultType(QualType Ty) {
4601 if (const auto *PtrType = Ty->getAs<PointerType>()) {
4602 Ty = PtrType->getPointeeType();
4603 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4604 Ty = RefType->getPointeeType();
4605 } else {
4606 return Ty->isDependentType();
4607 }
4608 if (!Ty.getQualifiers().empty())
4609 return false;
4610 return isValidSwiftContextType(Ty);
4611}
4612
4613void Sema::AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
4614 ParameterABI abi) {
4615
4616 QualType type = cast<ParmVarDecl>(D)->getType();
4617
4618 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4619 if (existingAttr->getABI() != abi) {
4620 Diag(CI.getLoc(), diag::err_attributes_are_not_compatible)
4621 << getParameterABISpelling(abi) << existingAttr;
4622 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4623 return;
4624 }
4625 }
4626
4627 switch (abi) {
4628 case ParameterABI::Ordinary:
4629 llvm_unreachable("explicit attribute for ordinary parameter ABI?")::llvm::llvm_unreachable_internal("explicit attribute for ordinary parameter ABI?"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4629)
;
4630
4631 case ParameterABI::SwiftContext:
4632 if (!isValidSwiftContextType(type)) {
4633 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
4634 << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
4635 }
4636 D->addAttr(::new (Context) SwiftContextAttr(Context, CI));
4637 return;
4638
4639 case ParameterABI::SwiftErrorResult:
4640 if (!isValidSwiftErrorResultType(type)) {
4641 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
4642 << getParameterABISpelling(abi) << /*pointer to pointer */ 1 << type;
4643 }
4644 D->addAttr(::new (Context) SwiftErrorResultAttr(Context, CI));
4645 return;
4646
4647 case ParameterABI::SwiftIndirectResult:
4648 if (!isValidSwiftIndirectResultType(type)) {
4649 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
4650 << getParameterABISpelling(abi) << /*pointer*/ 0 << type;
4651 }
4652 D->addAttr(::new (Context) SwiftIndirectResultAttr(Context, CI));
4653 return;
4654 }
4655 llvm_unreachable("bad parameter ABI attribute")::llvm::llvm_unreachable_internal("bad parameter ABI attribute"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4655)
;
4656}
4657
4658/// Checks a regparm attribute, returning true if it is ill-formed and
4659/// otherwise setting numParams to the appropriate value.
4660bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) {
4661 if (AL.isInvalid())
4662 return true;
4663
4664 if (!checkAttributeNumArgs(*this, AL, 1)) {
4665 AL.setInvalid();
4666 return true;
4667 }
4668
4669 uint32_t NP;
4670 Expr *NumParamsExpr = AL.getArgAsExpr(0);
4671 if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) {
4672 AL.setInvalid();
4673 return true;
4674 }
4675
4676 if (Context.getTargetInfo().getRegParmMax() == 0) {
4677 Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform)
4678 << NumParamsExpr->getSourceRange();
4679 AL.setInvalid();
4680 return true;
4681 }
4682
4683 numParams = NP;
4684 if (numParams > Context.getTargetInfo().getRegParmMax()) {
4685 Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number)
4686 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
4687 AL.setInvalid();
4688 return true;
4689 }
4690
4691 return false;
4692}
4693
4694// Checks whether an argument of launch_bounds attribute is
4695// acceptable, performs implicit conversion to Rvalue, and returns
4696// non-nullptr Expr result on success. Otherwise, it returns nullptr
4697// and may output an error.
4698static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4699 const CUDALaunchBoundsAttr &AL,
4700 const unsigned Idx) {
4701 if (S.DiagnoseUnexpandedParameterPack(E))
4702 return nullptr;
4703
4704 // Accept template arguments for now as they depend on something else.
4705 // We'll get to check them when they eventually get instantiated.
4706 if (E->isValueDependent())
4707 return E;
4708
4709 llvm::APSInt I(64);
4710 if (!E->isIntegerConstantExpr(I, S.Context)) {
4711 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4712 << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
4713 return nullptr;
4714 }
4715 // Make sure we can fit it in 32 bits.
4716 if (!I.isIntN(32)) {
4717 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4718 << 32 << /* Unsigned */ 1;
4719 return nullptr;
4720 }
4721 if (I < 0)
4722 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4723 << &AL << Idx << E->getSourceRange();
4724
4725 // We may need to perform implicit conversion of the argument.
4726 InitializedEntity Entity = InitializedEntity::InitializeParameter(
4727 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4728 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4729 assert(!ValArg.isInvalid() &&((!ValArg.isInvalid() && "Unexpected PerformCopyInitialization() failure."
) ? static_cast<void> (0) : __assert_fail ("!ValArg.isInvalid() && \"Unexpected PerformCopyInitialization() failure.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4730, __PRETTY_FUNCTION__))
4730 "Unexpected PerformCopyInitialization() failure.")((!ValArg.isInvalid() && "Unexpected PerformCopyInitialization() failure."
) ? static_cast<void> (0) : __assert_fail ("!ValArg.isInvalid() && \"Unexpected PerformCopyInitialization() failure.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4730, __PRETTY_FUNCTION__))
;
4731
4732 return ValArg.getAs<Expr>();
4733}
4734
4735void Sema::AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
4736 Expr *MaxThreads, Expr *MinBlocks) {
4737 CUDALaunchBoundsAttr TmpAttr(Context, CI, MaxThreads, MinBlocks);
4738 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4739 if (MaxThreads == nullptr)
4740 return;
4741
4742 if (MinBlocks) {
4743 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4744 if (MinBlocks == nullptr)
4745 return;
4746 }
4747
4748 D->addAttr(::new (Context)
4749 CUDALaunchBoundsAttr(Context, CI, MaxThreads, MinBlocks));
4750}
4751
4752static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4753 if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
4754 !checkAttributeAtMostNumArgs(S, AL, 2))
4755 return;
4756
4757 S.AddLaunchBoundsAttr(D, AL, AL.getArgAsExpr(0),
4758 AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr);
4759}
4760
4761static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4762 const ParsedAttr &AL) {
4763 if (!AL.isArgIdent(0)) {
4764 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
4765 << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier;
4766 return;
4767 }
4768
4769 ParamIdx ArgumentIdx;
4770 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1),
4771 ArgumentIdx))
4772 return;
4773
4774 ParamIdx TypeTagIdx;
4775 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2),
4776 TypeTagIdx))
4777 return;
4778
4779 bool IsPointer = AL.getAttrName()->getName() == "pointer_with_type_tag";
4780 if (IsPointer) {
4781 // Ensure that buffer has a pointer type.
4782 unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex();
4783 if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) ||
4784 !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType())
4785 S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0;
4786 }
4787
4788 D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr(
4789 S.Context, AL, AL.getArgAsIdent(0)->Ident, ArgumentIdx, TypeTagIdx,
4790 IsPointer));
4791}
4792
4793static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4794 const ParsedAttr &AL) {
4795 if (!AL.isArgIdent(0)) {
4796 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
4797 << AL << 1 << AANT_ArgumentIdentifier;
4798 return;
4799 }
4800
4801 if (!checkAttributeNumArgs(S, AL, 1))
4802 return;
4803
4804 if (!isa<VarDecl>(D)) {
4805 S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type)
4806 << AL << ExpectedVariable;
4807 return;
4808 }
4809
4810 IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident;
4811 TypeSourceInfo *MatchingCTypeLoc = nullptr;
4812 S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc);
4813 assert(MatchingCTypeLoc && "no type source info for attribute argument")((MatchingCTypeLoc && "no type source info for attribute argument"
) ? static_cast<void> (0) : __assert_fail ("MatchingCTypeLoc && \"no type source info for attribute argument\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4813, __PRETTY_FUNCTION__))
;
4814
4815 D->addAttr(::new (S.Context) TypeTagForDatatypeAttr(
4816 S.Context, AL, PointerKind, MatchingCTypeLoc, AL.getLayoutCompatible(),
4817 AL.getMustBeNull()));
4818}
4819
4820static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4821 ParamIdx ArgCount;
4822
4823 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0),
4824 ArgCount,
4825 true /* CanIndexImplicitThis */))
4826 return;
4827
4828 // ArgCount isn't a parameter index [0;n), it's a count [1;n]
4829 D->addAttr(::new (S.Context)
4830 XRayLogArgsAttr(S.Context, AL, ArgCount.getSourceIndex()));
4831}
4832
4833//===----------------------------------------------------------------------===//
4834// Checker-specific attribute handlers.
4835//===----------------------------------------------------------------------===//
4836static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) {
4837 return QT->isDependentType() || QT->isObjCRetainableType();
4838}
4839
4840static bool isValidSubjectOfNSAttribute(QualType QT) {
4841 return QT->isDependentType() || QT->isObjCObjectPointerType() ||
4842 QT->isObjCNSObjectType();
4843}
4844
4845static bool isValidSubjectOfCFAttribute(QualType QT) {
4846 return QT->isDependentType() || QT->isPointerType() ||
4847 isValidSubjectOfNSAttribute(QT);
4848}
4849
4850static bool isValidSubjectOfOSAttribute(QualType QT) {
4851 if (QT->isDependentType())
4852 return true;
4853 QualType PT = QT->getPointeeType();
4854 return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr;
4855}
4856
4857void Sema::AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
4858 RetainOwnershipKind K,
4859 bool IsTemplateInstantiation) {
4860 ValueDecl *VD = cast<ValueDecl>(D);
4861 switch (K) {
4862 case RetainOwnershipKind::OS:
4863 handleSimpleAttributeOrDiagnose<OSConsumedAttr>(
4864 *this, VD, CI, isValidSubjectOfOSAttribute(VD->getType()),
4865 diag::warn_ns_attribute_wrong_parameter_type,
4866 /*ExtraArgs=*/CI.getRange(), "os_consumed", /*pointers*/ 1);
4867 return;
4868 case RetainOwnershipKind::NS:
4869 handleSimpleAttributeOrDiagnose<NSConsumedAttr>(
4870 *this, VD, CI, isValidSubjectOfNSAttribute(VD->getType()),
4871
4872 // These attributes are normally just advisory, but in ARC, ns_consumed
4873 // is significant. Allow non-dependent code to contain inappropriate
4874 // attributes even in ARC, but require template instantiations to be
4875 // set up correctly.
4876 ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount)
4877 ? diag::err_ns_attribute_wrong_parameter_type
4878 : diag::warn_ns_attribute_wrong_parameter_type),
4879 /*ExtraArgs=*/CI.getRange(), "ns_consumed", /*objc pointers*/ 0);
4880 return;
4881 case RetainOwnershipKind::CF:
4882 handleSimpleAttributeOrDiagnose<CFConsumedAttr>(
4883 *this, VD, CI, isValidSubjectOfCFAttribute(VD->getType()),
4884 diag::warn_ns_attribute_wrong_parameter_type,
4885 /*ExtraArgs=*/CI.getRange(), "cf_consumed", /*pointers*/ 1);
4886 return;
4887 }
4888}
4889
4890static Sema::RetainOwnershipKind
4891parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) {
4892 switch (AL.getKind()) {
4893 case ParsedAttr::AT_CFConsumed:
4894 case ParsedAttr::AT_CFReturnsRetained:
4895 case ParsedAttr::AT_CFReturnsNotRetained:
4896 return Sema::RetainOwnershipKind::CF;
4897 case ParsedAttr::AT_OSConsumesThis:
4898 case ParsedAttr::AT_OSConsumed:
4899 case ParsedAttr::AT_OSReturnsRetained:
4900 case ParsedAttr::AT_OSReturnsNotRetained:
4901 case ParsedAttr::AT_OSReturnsRetainedOnZero:
4902 case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
4903 return Sema::RetainOwnershipKind::OS;
4904 case ParsedAttr::AT_NSConsumesSelf:
4905 case ParsedAttr::AT_NSConsumed:
4906 case ParsedAttr::AT_NSReturnsRetained:
4907 case ParsedAttr::AT_NSReturnsNotRetained:
4908 case ParsedAttr::AT_NSReturnsAutoreleased:
4909 return Sema::RetainOwnershipKind::NS;
4910 default:
4911 llvm_unreachable("Wrong argument supplied")::llvm::llvm_unreachable_internal("Wrong argument supplied", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4911)
;
4912 }
4913}
4914
4915bool Sema::checkNSReturnsRetainedReturnType(SourceLocation Loc, QualType QT) {
4916 if (isValidSubjectOfNSReturnsRetainedAttribute(QT))
4917 return false;
4918
4919 Diag(Loc, diag::warn_ns_attribute_wrong_return_type)
4920 << "'ns_returns_retained'" << 0 << 0;
4921 return true;
4922}
4923
4924/// \return whether the parameter is a pointer to OSObject pointer.
4925static bool isValidOSObjectOutParameter(const Decl *D) {
4926 const auto *PVD = dyn_cast<ParmVarDecl>(D);
4927 if (!PVD)
4928 return false;
4929 QualType QT = PVD->getType();
4930 QualType PT = QT->getPointeeType();
4931 return !PT.isNull() && isValidSubjectOfOSAttribute(PT);
4932}
4933
4934static void handleXReturnsXRetainedAttr(Sema &S, Decl *D,
4935 const ParsedAttr &AL) {
4936 QualType ReturnType;
4937 Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL);
4938
4939 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
4940 ReturnType = MD->getReturnType();
4941 } else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
4942 (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) {
4943 return; // ignore: was handled as a type attribute
4944 } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
4945 ReturnType = PD->getType();
4946 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4947 ReturnType = FD->getReturnType();
4948 } else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) {
4949 // Attributes on parameters are used for out-parameters,
4950 // passed as pointers-to-pointers.
4951 unsigned DiagID = K == Sema::RetainOwnershipKind::CF
4952 ? /*pointer-to-CF-pointer*/2
4953 : /*pointer-to-OSObject-pointer*/3;
4954 ReturnType = Param->getType()->getPointeeType();
4955 if (ReturnType.isNull()) {
4956 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
4957 << AL << DiagID << AL.getRange();
4958 return;
4959 }
4960 } else if (AL.isUsedAsTypeAttr()) {
4961 return;
4962 } else {
4963 AttributeDeclKind ExpectedDeclKind;
4964 switch (AL.getKind()) {
4965 default: llvm_unreachable("invalid ownership attribute")::llvm::llvm_unreachable_internal("invalid ownership attribute"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4965)
;
4966 case ParsedAttr::AT_NSReturnsRetained:
4967 case ParsedAttr::AT_NSReturnsAutoreleased:
4968 case ParsedAttr::AT_NSReturnsNotRetained:
4969 ExpectedDeclKind = ExpectedFunctionOrMethod;
4970 break;
4971
4972 case ParsedAttr::AT_OSReturnsRetained:
4973 case ParsedAttr::AT_OSReturnsNotRetained:
4974 case ParsedAttr::AT_CFReturnsRetained:
4975 case ParsedAttr::AT_CFReturnsNotRetained:
4976 ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
4977 break;
4978 }
4979 S.Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type)
4980 << AL.getRange() << AL << ExpectedDeclKind;
4981 return;
4982 }
4983
4984 bool TypeOK;
4985 bool Cf;
4986 unsigned ParmDiagID = 2; // Pointer-to-CF-pointer
4987 switch (AL.getKind()) {
4988 default: llvm_unreachable("invalid ownership attribute")::llvm::llvm_unreachable_internal("invalid ownership attribute"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 4988)
;
4989 case ParsedAttr::AT_NSReturnsRetained:
4990 TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType);
4991 Cf = false;
4992 break;
4993
4994 case ParsedAttr::AT_NSReturnsAutoreleased:
4995 case ParsedAttr::AT_NSReturnsNotRetained:
4996 TypeOK = isValidSubjectOfNSAttribute(ReturnType);
4997 Cf = false;
4998 break;
4999
5000 case ParsedAttr::AT_CFReturnsRetained:
5001 case ParsedAttr::AT_CFReturnsNotRetained:
5002 TypeOK = isValidSubjectOfCFAttribute(ReturnType);
5003 Cf = true;
5004 break;
5005
5006 case ParsedAttr::AT_OSReturnsRetained:
5007 case ParsedAttr::AT_OSReturnsNotRetained:
5008 TypeOK = isValidSubjectOfOSAttribute(ReturnType);
5009 Cf = true;
5010 ParmDiagID = 3; // Pointer-to-OSObject-pointer
5011 break;
5012 }
5013
5014 if (!TypeOK) {
5015 if (AL.isUsedAsTypeAttr())
5016 return;
5017
5018 if (isa<ParmVarDecl>(D)) {
5019 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
5020 << AL << ParmDiagID << AL.getRange();
5021 } else {
5022 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
5023 enum : unsigned {
5024 Function,
5025 Method,
5026 Property
5027 } SubjectKind = Function;
5028 if (isa<ObjCMethodDecl>(D))
5029 SubjectKind = Method;
5030 else if (isa<ObjCPropertyDecl>(D))
5031 SubjectKind = Property;
5032 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
5033 << AL << SubjectKind << Cf << AL.getRange();
5034 }
5035 return;
5036 }
5037
5038 switch (AL.getKind()) {
5039 default:
5040 llvm_unreachable("invalid ownership attribute")::llvm::llvm_unreachable_internal("invalid ownership attribute"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 5040)
;
5041 case ParsedAttr::AT_NSReturnsAutoreleased:
5042 handleSimpleAttribute<NSReturnsAutoreleasedAttr>(S, D, AL);
5043 return;
5044 case ParsedAttr::AT_CFReturnsNotRetained:
5045 handleSimpleAttribute<CFReturnsNotRetainedAttr>(S, D, AL);
5046 return;
5047 case ParsedAttr::AT_NSReturnsNotRetained:
5048 handleSimpleAttribute<NSReturnsNotRetainedAttr>(S, D, AL);
5049 return;
5050 case ParsedAttr::AT_CFReturnsRetained:
5051 handleSimpleAttribute<CFReturnsRetainedAttr>(S, D, AL);
5052 return;
5053 case ParsedAttr::AT_NSReturnsRetained:
5054 handleSimpleAttribute<NSReturnsRetainedAttr>(S, D, AL);
5055 return;
5056 case ParsedAttr::AT_OSReturnsRetained:
5057 handleSimpleAttribute<OSReturnsRetainedAttr>(S, D, AL);
5058 return;
5059 case ParsedAttr::AT_OSReturnsNotRetained:
5060 handleSimpleAttribute<OSReturnsNotRetainedAttr>(S, D, AL);
5061 return;
5062 };
5063}
5064
5065static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
5066 const ParsedAttr &Attrs) {
5067 const int EP_ObjCMethod = 1;
5068 const int EP_ObjCProperty = 2;
5069
5070 SourceLocation loc = Attrs.getLoc();
5071 QualType resultType;
5072 if (isa<ObjCMethodDecl>(D))
5073 resultType = cast<ObjCMethodDecl>(D)->getReturnType();
5074 else
5075 resultType = cast<ObjCPropertyDecl>(D)->getType();
5076
5077 if (!resultType->isReferenceType() &&
5078 (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
5079 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
5080 << SourceRange(loc) << Attrs
5081 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
5082 << /*non-retainable pointer*/ 2;
5083
5084 // Drop the attribute.
5085 return;
5086 }
5087
5088 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(S.Context, Attrs));
5089}
5090
5091static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
5092 const ParsedAttr &Attrs) {
5093 const auto *Method = cast<ObjCMethodDecl>(D);
5094
5095 const DeclContext *DC = Method->getDeclContext();
5096 if (const auto *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
5097 S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5098 << 0;
5099 S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
5100 return;
5101 }
5102 if (Method->getMethodFamily() == OMF_dealloc) {
5103 S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5104 << 1;
5105 return;
5106 }
5107
5108 D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(S.Context, Attrs));
5109}
5110
5111static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5112 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5113
5114 if (!Parm) {
5115 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5116 return;
5117 }
5118
5119 // Typedefs only allow objc_bridge(id) and have some additional checking.
5120 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
5121 if (!Parm->Ident->isStr("id")) {
5122 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL;
5123 return;
5124 }
5125
5126 // Only allow 'cv void *'.
5127 QualType T = TD->getUnderlyingType();
5128 if (!T->isVoidPointerType()) {
5129 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
5130 return;
5131 }
5132 }
5133
5134 D->addAttr(::new (S.Context) ObjCBridgeAttr(S.Context, AL, Parm->Ident));
5135}
5136
5137static void handleObjCBridgeMutableAttr(Sema &S, Decl *D,
5138 const ParsedAttr &AL) {
5139 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5140
5141 if (!Parm) {
5142 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5143 return;
5144 }
5145
5146 D->addAttr(::new (S.Context)
5147 ObjCBridgeMutableAttr(S.Context, AL, Parm->Ident));
5148}
5149
5150static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D,
5151 const ParsedAttr &AL) {
5152 IdentifierInfo *RelatedClass =
5153 AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr;
5154 if (!RelatedClass) {
5155 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5156 return;
5157 }
5158 IdentifierInfo *ClassMethod =
5159 AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr;
5160 IdentifierInfo *InstanceMethod =
5161 AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr;
5162 D->addAttr(::new (S.Context) ObjCBridgeRelatedAttr(
5163 S.Context, AL, RelatedClass, ClassMethod, InstanceMethod));
5164}
5165
5166static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
5167 const ParsedAttr &AL) {
5168 DeclContext *Ctx = D->getDeclContext();
5169
5170 // This attribute can only be applied to methods in interfaces or class
5171 // extensions.
5172 if (!isa<ObjCInterfaceDecl>(Ctx) &&
5173 !(isa<ObjCCategoryDecl>(Ctx) &&
5174 cast<ObjCCategoryDecl>(Ctx)->IsClassExtension())) {
5175 S.Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
5176 return;
5177 }
5178
5179 ObjCInterfaceDecl *IFace;
5180 if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Ctx))
5181 IFace = CatDecl->getClassInterface();
5182 else
5183 IFace = cast<ObjCInterfaceDecl>(Ctx);
5184
5185 if (!IFace)
5186 return;
5187
5188 IFace->setHasDesignatedInitializers();
5189 D->addAttr(::new (S.Context) ObjCDesignatedInitializerAttr(S.Context, AL));
5190}
5191
5192static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) {
5193 StringRef MetaDataName;
5194 if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName))
5195 return;
5196 D->addAttr(::new (S.Context)
5197 ObjCRuntimeNameAttr(S.Context, AL, MetaDataName));
5198}
5199
5200// When a user wants to use objc_boxable with a union or struct
5201// but they don't have access to the declaration (legacy/third-party code)
5202// then they can 'enable' this feature with a typedef:
5203// typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
5204static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) {
5205 bool notify = false;
5206
5207 auto *RD = dyn_cast<RecordDecl>(D);
5208 if (RD && RD->getDefinition()) {
5209 RD = RD->getDefinition();
5210 notify = true;
5211 }
5212
5213 if (RD) {
5214 ObjCBoxableAttr *BoxableAttr =
5215 ::new (S.Context) ObjCBoxableAttr(S.Context, AL);
5216 RD->addAttr(BoxableAttr);
5217 if (notify) {
5218 // we need to notify ASTReader/ASTWriter about
5219 // modification of existing declaration
5220 if (ASTMutationListener *L = S.getASTMutationListener())
5221 L->AddedAttributeToRecord(BoxableAttr, RD);
5222 }
5223 }
5224}
5225
5226static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5227 if (hasDeclarator(D)) return;
5228
5229 S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type)
5230 << AL.getRange() << AL << ExpectedVariable;
5231}
5232
5233static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
5234 const ParsedAttr &AL) {
5235 const auto *VD = cast<ValueDecl>(D);
5236 QualType QT = VD->getType();
5237
5238 if (!QT->isDependentType() &&
5239 !QT->isObjCLifetimeType()) {
5240 S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type)
5241 << QT;
5242 return;
5243 }
5244
5245 Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime();
5246
5247 // If we have no lifetime yet, check the lifetime we're presumably
5248 // going to infer.
5249 if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType())
5250 Lifetime = QT->getObjCARCImplicitLifetime();
5251
5252 switch (Lifetime) {
5253 case Qualifiers::OCL_None:
5254 assert(QT->isDependentType() &&((QT->isDependentType() && "didn't infer lifetime for non-dependent type?"
) ? static_cast<void> (0) : __assert_fail ("QT->isDependentType() && \"didn't infer lifetime for non-dependent type?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 5255, __PRETTY_FUNCTION__))
5255 "didn't infer lifetime for non-dependent type?")((QT->isDependentType() && "didn't infer lifetime for non-dependent type?"
) ? static_cast<void> (0) : __assert_fail ("QT->isDependentType() && \"didn't infer lifetime for non-dependent type?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 5255, __PRETTY_FUNCTION__))
;
5256 break;
5257
5258 case Qualifiers::OCL_Weak: // meaningful
5259 case Qualifiers::OCL_Strong: // meaningful
5260 break;
5261
5262 case Qualifiers::OCL_ExplicitNone:
5263 case Qualifiers::OCL_Autoreleasing:
5264 S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
5265 << (Lifetime == Qualifiers::OCL_Autoreleasing);
5266 break;
5267 }
5268
5269 D->addAttr(::new (S.Context) ObjCPreciseLifetimeAttr(S.Context, AL));
5270}
5271
5272//===----------------------------------------------------------------------===//
5273// Microsoft specific attribute handlers.
5274//===----------------------------------------------------------------------===//
5275
5276UuidAttr *Sema::mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
5277 StringRef Uuid) {
5278 if (const auto *UA = D->getAttr<UuidAttr>()) {
5279 if (UA->getGuid().equals_lower(Uuid))
5280 return nullptr;
5281 Diag(UA->getLocation(), diag::err_mismatched_uuid);
5282 Diag(CI.getLoc(), diag::note_previous_uuid);
5283 D->dropAttr<UuidAttr>();
5284 }
5285
5286 return ::new (Context) UuidAttr(Context, CI, Uuid);
5287}
5288
5289static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5290 if (!S.LangOpts.CPlusPlus) {
5291 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
5292 << AL << AttributeLangSupport::C;
5293 return;
5294 }
5295
5296 StringRef StrRef;
5297 SourceLocation LiteralLoc;
5298 if (!S.checkStringLiteralArgumentAttr(AL, 0, StrRef, &LiteralLoc))
5299 return;
5300
5301 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
5302 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
5303 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
5304 StrRef = StrRef.drop_front().drop_back();
5305
5306 // Validate GUID length.
5307 if (StrRef.size() != 36) {
5308 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5309 return;
5310 }
5311
5312 for (unsigned i = 0; i < 36; ++i) {
5313 if (i == 8 || i == 13 || i == 18 || i == 23) {
5314 if (StrRef[i] != '-') {
5315 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5316 return;
5317 }
5318 } else if (!isHexDigit(StrRef[i])) {
5319 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5320 return;
5321 }
5322 }
5323
5324 // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
5325 // the only thing in the [] list, the [] too), and add an insertion of
5326 // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas
5327 // separating attributes nor of the [ and the ] are in the AST.
5328 // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
5329 // on cfe-dev.
5330 if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
5331 S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated);
5332
5333 UuidAttr *UA = S.mergeUuidAttr(D, AL, StrRef);
5334 if (UA)
5335 D->addAttr(UA);
5336}
5337
5338static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5339 if (!S.LangOpts.CPlusPlus) {
5340 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
5341 << AL << AttributeLangSupport::C;
5342 return;
5343 }
5344 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
5345 D, AL, /*BestCase=*/true,
5346 (MSInheritanceAttr::Spelling)AL.getSemanticSpelling());
5347 if (IA) {
5348 D->addAttr(IA);
5349 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
5350 }
5351}
5352
5353static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5354 const auto *VD = cast<VarDecl>(D);
5355 if (!S.Context.getTargetInfo().isTLSSupported()) {
5356 S.Diag(AL.getLoc(), diag::err_thread_unsupported);
5357 return;
5358 }
5359 if (VD->getTSCSpec() != TSCS_unspecified) {
5360 S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable);
5361 return;
5362 }
5363 if (VD->hasLocalStorage()) {
5364 S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
5365 return;
5366 }
5367 D->addAttr(::new (S.Context) ThreadAttr(S.Context, AL));
5368}
5369
5370static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5371 SmallVector<StringRef, 4> Tags;
5372 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
5373 StringRef Tag;
5374 if (!S.checkStringLiteralArgumentAttr(AL, I, Tag))
5375 return;
5376 Tags.push_back(Tag);
5377 }
5378
5379 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) {
5380 if (!NS->isInline()) {
5381 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0;
5382 return;
5383 }
5384 if (NS->isAnonymousNamespace()) {
5385 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1;
5386 return;
5387 }
5388 if (AL.getNumArgs() == 0)
5389 Tags.push_back(NS->getName());
5390 } else if (!checkAttributeAtLeastNumArgs(S, AL, 1))
5391 return;
5392
5393 // Store tags sorted and without duplicates.
5394 llvm::sort(Tags);
5395 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end());
5396
5397 D->addAttr(::new (S.Context)
5398 AbiTagAttr(S.Context, AL, Tags.data(), Tags.size()));
5399}
5400
5401static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5402 // Check the attribute arguments.
5403 if (AL.getNumArgs() > 1) {
5404 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
5405 return;
5406 }
5407
5408 StringRef Str;
5409 SourceLocation ArgLoc;
5410
5411 if (AL.getNumArgs() == 0)
5412 Str = "";
5413 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5414 return;
5415
5416 ARMInterruptAttr::InterruptType Kind;
5417 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5418 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
5419 << ArgLoc;
5420 return;
5421 }
5422
5423 D->addAttr(::new (S.Context) ARMInterruptAttr(S.Context, AL, Kind));
5424}
5425
5426static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5427 // MSP430 'interrupt' attribute is applied to
5428 // a function with no parameters and void return type.
5429 if (!isFunctionOrMethod(D)) {
5430 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5431 << "'interrupt'" << ExpectedFunctionOrMethod;
5432 return;
5433 }
5434
5435 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5436 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5437 << /*MSP430*/ 1 << 0;
5438 return;
5439 }
5440
5441 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5442 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5443 << /*MSP430*/ 1 << 1;
5444 return;
5445 }
5446
5447 // The attribute takes one integer argument.
5448 if (!checkAttributeNumArgs(S, AL, 1))
5449 return;
5450
5451 if (!AL.isArgExpr(0)) {
5452 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
5453 << AL << AANT_ArgumentIntegerConstant;
5454 return;
5455 }
5456
5457 Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
5458 llvm::APSInt NumParams(32);
5459 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
5460 S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
5461 << AL << AANT_ArgumentIntegerConstant
5462 << NumParamsExpr->getSourceRange();
5463 return;
5464 }
5465 // The argument should be in range 0..63.
5466 unsigned Num = NumParams.getLimitedValue(255);
5467 if (Num > 63) {
5468 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
5469 << AL << (int)NumParams.getSExtValue()
5470 << NumParamsExpr->getSourceRange();
5471 return;
5472 }
5473
5474 D->addAttr(::new (S.Context) MSP430InterruptAttr(S.Context, AL, Num));
5475 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5476}
5477
5478static void handleMipsInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5479 // Only one optional argument permitted.
5480 if (AL.getNumArgs() > 1) {
5481 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
5482 return;
5483 }
5484
5485 StringRef Str;
5486 SourceLocation ArgLoc;
5487
5488 if (AL.getNumArgs() == 0)
5489 Str = "";
5490 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5491 return;
5492
5493 // Semantic checks for a function with the 'interrupt' attribute for MIPS:
5494 // a) Must be a function.
5495 // b) Must have no parameters.
5496 // c) Must have the 'void' return type.
5497 // d) Cannot have the 'mips16' attribute, as that instruction set
5498 // lacks the 'eret' instruction.
5499 // e) The attribute itself must either have no argument or one of the
5500 // valid interrupt types, see [MipsInterruptDocs].
5501
5502 if (!isFunctionOrMethod(D)) {
5503 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5504 << "'interrupt'" << ExpectedFunctionOrMethod;
5505 return;
5506 }
5507
5508 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5509 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5510 << /*MIPS*/ 0 << 0;
5511 return;
5512 }
5513
5514 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5515 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5516 << /*MIPS*/ 0 << 1;
5517 return;
5518 }
5519
5520 if (checkAttrMutualExclusion<Mips16Attr>(S, D, AL))
5521 return;
5522
5523 MipsInterruptAttr::InterruptType Kind;
5524 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5525 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
5526 << AL << "'" + std::string(Str) + "'";
5527 return;
5528 }
5529
5530 D->addAttr(::new (S.Context) MipsInterruptAttr(S.Context, AL, Kind));
5531}
5532
5533static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5534 // Semantic checks for a function with the 'interrupt' attribute.
5535 // a) Must be a function.
5536 // b) Must have the 'void' return type.
5537 // c) Must take 1 or 2 arguments.
5538 // d) The 1st argument must be a pointer.
5539 // e) The 2nd argument (if any) must be an unsigned integer.
5540 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) ||
5541 CXXMethodDecl::isStaticOverloadedOperator(
5542 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) {
5543 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
5544 << AL << ExpectedFunctionWithProtoType;
5545 return;
5546 }
5547 // Interrupt handler must have void return type.
5548 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5549 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(),
5550 diag::err_anyx86_interrupt_attribute)
5551 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5552 ? 0
5553 : 1)
5554 << 0;
5555 return;
5556 }
5557 // Interrupt handler must have 1 or 2 parameters.
5558 unsigned NumParams = getFunctionOrMethodNumParams(D);
5559 if (NumParams < 1 || NumParams > 2) {
5560 S.Diag(D->getBeginLoc(), diag::err_anyx86_interrupt_attribute)
5561 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5562 ? 0
5563 : 1)
5564 << 1;
5565 return;
5566 }
5567 // The first argument must be a pointer.
5568 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) {
5569 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(),
5570 diag::err_anyx86_interrupt_attribute)
5571 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5572 ? 0
5573 : 1)
5574 << 2;
5575 return;
5576 }
5577 // The second argument, if present, must be an unsigned integer.
5578 unsigned TypeSize =
5579 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64
5580 ? 64
5581 : 32;
5582 if (NumParams == 2 &&
5583 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() ||
5584 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) {
5585 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(),
5586 diag::err_anyx86_interrupt_attribute)
5587 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86
5588 ? 0
5589 : 1)
5590 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false);
5591 return;
5592 }
5593 D->addAttr(::new (S.Context) AnyX86InterruptAttr(S.Context, AL));
5594 D->addAttr(UsedAttr::CreateImplicit(S.Context));
5595}
5596
5597static void handleAVRInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5598 if (!isFunctionOrMethod(D)) {
5599 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5600 << "'interrupt'" << ExpectedFunction;
5601 return;
5602 }
5603
5604 if (!checkAttributeNumArgs(S, AL, 0))
5605 return;
5606
5607 handleSimpleAttribute<AVRInterruptAttr>(S, D, AL);
5608}
5609
5610static void handleAVRSignalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5611 if (!isFunctionOrMethod(D)) {
5612 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5613 << "'signal'" << ExpectedFunction;
5614 return;
5615 }
5616
5617 if (!checkAttributeNumArgs(S, AL, 0))
5618 return;
5619
5620 handleSimpleAttribute<AVRSignalAttr>(S, D, AL);
5621}
5622
5623static void handleWebAssemblyImportModuleAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5624 if (!isFunctionOrMethod(D)) {
5625 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5626 << "'import_module'" << ExpectedFunction;
5627 return;
5628 }
5629
5630 auto *FD = cast<FunctionDecl>(D);
5631 if (FD->isThisDeclarationADefinition()) {
5632 S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
5633 return;
5634 }
5635
5636 StringRef Str;
5637 SourceLocation ArgLoc;
5638 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5639 return;
5640
5641 FD->addAttr(::new (S.Context)
5642 WebAssemblyImportModuleAttr(S.Context, AL, Str));
5643}
5644
5645static void handleWebAssemblyImportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5646 if (!isFunctionOrMethod(D)) {
5647 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5648 << "'import_name'" << ExpectedFunction;
5649 return;
5650 }
5651
5652 auto *FD = cast<FunctionDecl>(D);
5653 if (FD->isThisDeclarationADefinition()) {
5654 S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0;
5655 return;
5656 }
5657
5658 StringRef Str;
5659 SourceLocation ArgLoc;
5660 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5661 return;
5662
5663 FD->addAttr(::new (S.Context) WebAssemblyImportNameAttr(S.Context, AL, Str));
5664}
5665
5666static void handleRISCVInterruptAttr(Sema &S, Decl *D,
5667 const ParsedAttr &AL) {
5668 // Warn about repeated attributes.
5669 if (const auto *A = D->getAttr<RISCVInterruptAttr>()) {
5670 S.Diag(AL.getRange().getBegin(),
5671 diag::warn_riscv_repeated_interrupt_attribute);
5672 S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute);
5673 return;
5674 }
5675
5676 // Check the attribute argument. Argument is optional.
5677 if (!checkAttributeAtMostNumArgs(S, AL, 1))
5678 return;
5679
5680 StringRef Str;
5681 SourceLocation ArgLoc;
5682
5683 // 'machine'is the default interrupt mode.
5684 if (AL.getNumArgs() == 0)
5685 Str = "machine";
5686 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc))
5687 return;
5688
5689 // Semantic checks for a function with the 'interrupt' attribute:
5690 // - Must be a function.
5691 // - Must have no parameters.
5692 // - Must have the 'void' return type.
5693 // - The attribute itself must either have no argument or one of the
5694 // valid interrupt types, see [RISCVInterruptDocs].
5695
5696 if (D->getFunctionType() == nullptr) {
5697 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type)
5698 << "'interrupt'" << ExpectedFunction;
5699 return;
5700 }
5701
5702 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) {
5703 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5704 << /*RISC-V*/ 2 << 0;
5705 return;
5706 }
5707
5708 if (!getFunctionOrMethodResultType(D)->isVoidType()) {
5709 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid)
5710 << /*RISC-V*/ 2 << 1;
5711 return;
5712 }
5713
5714 RISCVInterruptAttr::InterruptType Kind;
5715 if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
5716 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str
5717 << ArgLoc;
5718 return;
5719 }
5720
5721 D->addAttr(::new (S.Context) RISCVInterruptAttr(S.Context, AL, Kind));
5722}
5723
5724static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5725 // Dispatch the interrupt attribute based on the current target.
5726 switch (S.Context.getTargetInfo().getTriple().getArch()) {
5727 case llvm::Triple::msp430:
5728 handleMSP430InterruptAttr(S, D, AL);
5729 break;
5730 case llvm::Triple::mipsel:
5731 case llvm::Triple::mips:
5732 handleMipsInterruptAttr(S, D, AL);
5733 break;
5734 case llvm::Triple::x86:
5735 case llvm::Triple::x86_64:
5736 handleAnyX86InterruptAttr(S, D, AL);
5737 break;
5738 case llvm::Triple::avr:
5739 handleAVRInterruptAttr(S, D, AL);
5740 break;
5741 case llvm::Triple::riscv32:
5742 case llvm::Triple::riscv64:
5743 handleRISCVInterruptAttr(S, D, AL);
5744 break;
5745 default:
5746 handleARMInterruptAttr(S, D, AL);
5747 break;
5748 }
5749}
5750
5751static bool
5752checkAMDGPUFlatWorkGroupSizeArguments(Sema &S, Expr *MinExpr, Expr *MaxExpr,
5753 const AMDGPUFlatWorkGroupSizeAttr &Attr) {
5754 // Accept template arguments for now as they depend on something else.
5755 // We'll get to check them when they eventually get instantiated.
5756 if (MinExpr->isValueDependent() || MaxExpr->isValueDependent())
5757 return false;
5758
5759 uint32_t Min = 0;
5760 if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
5761 return true;
5762
5763 uint32_t Max = 0;
5764 if (!checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
5765 return true;
5766
5767 if (Min == 0 && Max != 0) {
5768 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
5769 << &Attr << 0;
5770 return true;
5771 }
5772 if (Min > Max) {
5773 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
5774 << &Attr << 1;
5775 return true;
5776 }
5777
5778 return false;
5779}
5780
5781void Sema::addAMDGPUFlatWorkGroupSizeAttr(Decl *D,
5782 const AttributeCommonInfo &CI,
5783 Expr *MinExpr, Expr *MaxExpr) {
5784 AMDGPUFlatWorkGroupSizeAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
5785
5786 if (checkAMDGPUFlatWorkGroupSizeArguments(*this, MinExpr, MaxExpr, TmpAttr))
5787 return;
5788
5789 D->addAttr(::new (Context)
5790 AMDGPUFlatWorkGroupSizeAttr(Context, CI, MinExpr, MaxExpr));
5791}
5792
5793static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D,
5794 const ParsedAttr &AL) {
5795 Expr *MinExpr = AL.getArgAsExpr(0);
5796 Expr *MaxExpr = AL.getArgAsExpr(1);
5797
5798 S.addAMDGPUFlatWorkGroupSizeAttr(D, AL, MinExpr, MaxExpr);
5799}
5800
5801static bool checkAMDGPUWavesPerEUArguments(Sema &S, Expr *MinExpr,
5802 Expr *MaxExpr,
5803 const AMDGPUWavesPerEUAttr &Attr) {
5804 if (S.DiagnoseUnexpandedParameterPack(MinExpr) ||
5805 (MaxExpr && S.DiagnoseUnexpandedParameterPack(MaxExpr)))
5806 return true;
5807
5808 // Accept template arguments for now as they depend on something else.
5809 // We'll get to check them when they eventually get instantiated.
5810 if (MinExpr->isValueDependent() || (MaxExpr && MaxExpr->isValueDependent()))
5811 return false;
5812
5813 uint32_t Min = 0;
5814 if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0))
5815 return true;
5816
5817 uint32_t Max = 0;
5818 if (MaxExpr && !checkUInt32Argument(S, Attr, MaxExpr, Max, 1))
5819 return true;
5820
5821 if (Min == 0 && Max != 0) {
5822 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
5823 << &Attr << 0;
5824 return true;
5825 }
5826 if (Max != 0 && Min > Max) {
5827 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid)
5828 << &Attr << 1;
5829 return true;
5830 }
5831
5832 return false;
5833}
5834
5835void Sema::addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
5836 Expr *MinExpr, Expr *MaxExpr) {
5837 AMDGPUWavesPerEUAttr TmpAttr(Context, CI, MinExpr, MaxExpr);
5838
5839 if (checkAMDGPUWavesPerEUArguments(*this, MinExpr, MaxExpr, TmpAttr))
5840 return;
5841
5842 D->addAttr(::new (Context)
5843 AMDGPUWavesPerEUAttr(Context, CI, MinExpr, MaxExpr));
5844}
5845
5846static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5847 if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
5848 !checkAttributeAtMostNumArgs(S, AL, 2))
5849 return;
5850
5851 Expr *MinExpr = AL.getArgAsExpr(0);
5852 Expr *MaxExpr = (AL.getNumArgs() > 1) ? AL.getArgAsExpr(1) : nullptr;
5853
5854 S.addAMDGPUWavesPerEUAttr(D, AL, MinExpr, MaxExpr);
5855}
5856
5857static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5858 uint32_t NumSGPR = 0;
5859 Expr *NumSGPRExpr = AL.getArgAsExpr(0);
5860 if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR))
5861 return;
5862
5863 D->addAttr(::new (S.Context) AMDGPUNumSGPRAttr(S.Context, AL, NumSGPR));
5864}
5865
5866static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5867 uint32_t NumVGPR = 0;
5868 Expr *NumVGPRExpr = AL.getArgAsExpr(0);
5869 if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR))
5870 return;
5871
5872 D->addAttr(::new (S.Context) AMDGPUNumVGPRAttr(S.Context, AL, NumVGPR));
5873}
5874
5875static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D,
5876 const ParsedAttr &AL) {
5877 // If we try to apply it to a function pointer, don't warn, but don't
5878 // do anything, either. It doesn't matter anyway, because there's nothing
5879 // special about calling a force_align_arg_pointer function.
5880 const auto *VD = dyn_cast<ValueDecl>(D);
5881 if (VD && VD->getType()->isFunctionPointerType())
5882 return;
5883 // Also don't warn on function pointer typedefs.
5884 const auto *TD = dyn_cast<TypedefNameDecl>(D);
5885 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() ||
5886 TD->getUnderlyingType()->isFunctionType()))
5887 return;
5888 // Attribute can only be applied to function types.
5889 if (!isa<FunctionDecl>(D)) {
5890 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
5891 << AL << ExpectedFunction;
5892 return;
5893 }
5894
5895 D->addAttr(::new (S.Context) X86ForceAlignArgPointerAttr(S.Context, AL));
5896}
5897
5898static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) {
5899 uint32_t Version;
5900 Expr *VersionExpr = static_cast<Expr *>(AL.getArgAsExpr(0));
5901 if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Version))
5902 return;
5903
5904 // TODO: Investigate what happens with the next major version of MSVC.
5905 if (Version != LangOptions::MSVC2015 / 100) {
5906 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
5907 << AL << Version << VersionExpr->getSourceRange();
5908 return;
5909 }
5910
5911 // The attribute expects a "major" version number like 19, but new versions of
5912 // MSVC have moved to updating the "minor", or less significant numbers, so we
5913 // have to multiply by 100 now.
5914 Version *= 100;
5915
5916 D->addAttr(::new (S.Context) LayoutVersionAttr(S.Context, AL, Version));
5917}
5918
5919DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D,
5920 const AttributeCommonInfo &CI) {
5921 if (D->hasAttr<DLLExportAttr>()) {
5922 Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'dllimport'";
5923 return nullptr;
5924 }
5925
5926 if (D->hasAttr<DLLImportAttr>())
5927 return nullptr;
5928
5929 return ::new (Context) DLLImportAttr(Context, CI);
5930}
5931
5932DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D,
5933 const AttributeCommonInfo &CI) {
5934 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) {
5935 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import;
5936 D->dropAttr<DLLImportAttr>();
5937 }
5938
5939 if (D->hasAttr<DLLExportAttr>())
5940 return nullptr;
5941
5942 return ::new (Context) DLLExportAttr(Context, CI);
5943}
5944
5945static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) {
5946 if (isa<ClassTemplatePartialSpecializationDecl>(D) &&
5947 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5948 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) << A;
5949 return;
5950 }
5951
5952 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
5953 if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport &&
5954 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5955 // MinGW doesn't allow dllimport on inline functions.
5956 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline)
5957 << A;
5958 return;
5959 }
5960 }
5961
5962 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
5963 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5964 MD->getParent()->isLambda()) {
5965 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A;
5966 return;
5967 }
5968 }
5969
5970 Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport
5971 ? (Attr *)S.mergeDLLExportAttr(D, A)
5972 : (Attr *)S.mergeDLLImportAttr(D, A);
5973 if (NewAttr)
5974 D->addAttr(NewAttr);
5975}
5976
5977MSInheritanceAttr *
5978Sema::mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI,
5979 bool BestCase,
5980 MSInheritanceAttr::Spelling SemanticSpelling) {
5981 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) {
5982 if (IA->getSemanticSpelling() == SemanticSpelling)
5983 return nullptr;
5984 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance)
5985 << 1 /*previous declaration*/;
5986 Diag(CI.getLoc(), diag::note_previous_ms_inheritance);
5987 D->dropAttr<MSInheritanceAttr>();
5988 }
5989
5990 auto *RD = cast<CXXRecordDecl>(D);
5991 if (RD->hasDefinition()) {
5992 if (checkMSInheritanceAttrOnDefinition(RD, CI.getRange(), BestCase,
5993 SemanticSpelling)) {
5994 return nullptr;
5995 }
5996 } else {
5997 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) {
5998 Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
5999 << 1 /*partial specialization*/;
6000 return nullptr;
6001 }
6002 if (RD->getDescribedClassTemplate()) {
6003 Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance)
6004 << 0 /*primary template*/;
6005 return nullptr;
6006 }
6007 }
6008
6009 return ::new (Context) MSInheritanceAttr(Context, CI, BestCase);
6010}
6011
6012static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6013 // The capability attributes take a single string parameter for the name of
6014 // the capability they represent. The lockable attribute does not take any
6015 // parameters. However, semantically, both attributes represent the same
6016 // concept, and so they use the same semantic attribute. Eventually, the
6017 // lockable attribute will be removed.
6018 //
6019 // For backward compatibility, any capability which has no specified string
6020 // literal will be considered a "mutex."
6021 StringRef N("mutex");
6022 SourceLocation LiteralLoc;
6023 if (AL.getKind() == ParsedAttr::AT_Capability &&
6024 !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc))
6025 return;
6026
6027 // Currently, there are only two names allowed for a capability: role and
6028 // mutex (case insensitive). Diagnose other capability names.
6029 if (!N.equals_lower("mutex") && !N.equals_lower("role"))
6030 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N;
6031
6032 D->addAttr(::new (S.Context) CapabilityAttr(S.Context, AL, N));
6033}
6034
6035static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6036 SmallVector<Expr*, 1> Args;
6037 if (!checkLockFunAttrCommon(S, D, AL, Args))
6038 return;
6039
6040 D->addAttr(::new (S.Context)
6041 AssertCapabilityAttr(S.Context, AL, Args.data(), Args.size()));
6042}
6043
6044static void handleAcquireCapabilityAttr(Sema &S, Decl *D,
6045 const ParsedAttr &AL) {
6046 SmallVector<Expr*, 1> Args;
6047 if (!checkLockFunAttrCommon(S, D, AL, Args))
6048 return;
6049
6050 D->addAttr(::new (S.Context) AcquireCapabilityAttr(S.Context, AL, Args.data(),
6051 Args.size()));
6052}
6053
6054static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D,
6055 const ParsedAttr &AL) {
6056 SmallVector<Expr*, 2> Args;
6057 if (!checkTryLockFunAttrCommon(S, D, AL, Args))
6058 return;
6059
6060 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(
6061 S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
6062}
6063
6064static void handleReleaseCapabilityAttr(Sema &S, Decl *D,
6065 const ParsedAttr &AL) {
6066 // Check that all arguments are lockable objects.
6067 SmallVector<Expr *, 1> Args;
6068 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, true);
6069
6070 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(S.Context, AL, Args.data(),
6071 Args.size()));
6072}
6073
6074static void handleRequiresCapabilityAttr(Sema &S, Decl *D,
6075 const ParsedAttr &AL) {
6076 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
6077 return;
6078
6079 // check that all arguments are lockable objects
6080 SmallVector<Expr*, 1> Args;
6081 checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
6082 if (Args.empty())
6083 return;
6084
6085 RequiresCapabilityAttr *RCA = ::new (S.Context)
6086 RequiresCapabilityAttr(S.Context, AL, Args.data(), Args.size());
6087
6088 D->addAttr(RCA);
6089}
6090
6091static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6092 if (const auto *NSD = dyn_cast<NamespaceDecl>(D)) {
6093 if (NSD->isAnonymousNamespace()) {
6094 S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace);
6095 // Do not want to attach the attribute to the namespace because that will
6096 // cause confusing diagnostic reports for uses of declarations within the
6097 // namespace.
6098 return;
6099 }
6100 }
6101
6102 // Handle the cases where the attribute has a text message.
6103 StringRef Str, Replacement;
6104 if (AL.isArgExpr(0) && AL.getArgAsExpr(0) &&
6105 !S.checkStringLiteralArgumentAttr(AL, 0, Str))
6106 return;
6107
6108 // Only support a single optional message for Declspec and CXX11.
6109 if (AL.isDeclspecAttribute() || AL.isCXX11Attribute())
6110 checkAttributeAtMostNumArgs(S, AL, 1);
6111 else if (AL.isArgExpr(1) && AL.getArgAsExpr(1) &&
6112 !S.checkStringLiteralArgumentAttr(AL, 1, Replacement))
6113 return;
6114
6115 if (!S.getLangOpts().CPlusPlus14 && AL.isCXX11Attribute() && !AL.isGNUScope())
6116 S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL;
6117
6118 D->addAttr(::new (S.Context) DeprecatedAttr(S.Context, AL, Str, Replacement));
6119}
6120
6121static bool isGlobalVar(const Decl *D) {
6122 if (const auto *S = dyn_cast<VarDecl>(D))
6123 return S->hasGlobalStorage();
6124 return false;
6125}
6126
6127static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6128 if (!checkAttributeAtLeastNumArgs(S, AL, 1))
6129 return;
6130
6131 std::vector<StringRef> Sanitizers;
6132
6133 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
6134 StringRef SanitizerName;
6135 SourceLocation LiteralLoc;
6136
6137 if (!S.checkStringLiteralArgumentAttr(AL, I, SanitizerName, &LiteralLoc))
6138 return;
6139
6140 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) ==
6141 SanitizerMask())
6142 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName;
6143 else if (isGlobalVar(D) && SanitizerName != "address")
6144 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6145 << AL << ExpectedFunctionOrMethod;
6146 Sanitizers.push_back(SanitizerName);
6147 }
6148
6149 D->addAttr(::new (S.Context) NoSanitizeAttr(S.Context, AL, Sanitizers.data(),
6150 Sanitizers.size()));
6151}
6152
6153static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D,
6154 const ParsedAttr &AL) {
6155 StringRef AttrName = AL.getAttrName()->getName();
6156 normalizeName(AttrName);
6157 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName)
6158 .Case("no_address_safety_analysis", "address")
6159 .Case("no_sanitize_address", "address")
6160 .Case("no_sanitize_thread", "thread")
6161 .Case("no_sanitize_memory", "memory");
6162 if (isGlobalVar(D) && SanitizerName != "address")
6163 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
6164 << AL << ExpectedFunction;
6165
6166 // FIXME: Rather than create a NoSanitizeSpecificAttr, this creates a
6167 // NoSanitizeAttr object; but we need to calculate the correct spelling list
6168 // index rather than incorrectly assume the index for NoSanitizeSpecificAttr
6169 // has the same spellings as the index for NoSanitizeAttr. We don't have a
6170 // general way to "translate" between the two, so this hack attempts to work
6171 // around the issue with hard-coded indicies. This is critical for calling
6172 // getSpelling() or prettyPrint() on the resulting semantic attribute object
6173 // without failing assertions.
6174 unsigned TranslatedSpellingIndex = 0;
6175 if (AL.isC2xAttribute() || AL.isCXX11Attribute())
6176 TranslatedSpellingIndex = 1;
6177
6178 AttributeCommonInfo Info = AL;
6179 Info.setAttributeSpellingListIndex(TranslatedSpellingIndex);
6180 D->addAttr(::new (S.Context)
6181 NoSanitizeAttr(S.Context, Info, &SanitizerName, 1));
6182}
6183
6184static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6185 if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, AL))
6186 D->addAttr(Internal);
6187}
6188
6189static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6190 if (S.LangOpts.OpenCLVersion != 200)
6191 S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version)
6192 << AL << "2.0" << 0;
6193 else
6194 S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored) << AL
6195 << "2.0";
6196}
6197
6198/// Handles semantic checking for features that are common to all attributes,
6199/// such as checking whether a parameter was properly specified, or the correct
6200/// number of arguments were passed, etc.
6201static bool handleCommonAttributeFeatures(Sema &S, Decl *D,
6202 const ParsedAttr &AL) {
6203 // Several attributes carry different semantics than the parsing requires, so
6204 // those are opted out of the common argument checks.
6205 //
6206 // We also bail on unknown and ignored attributes because those are handled
6207 // as part of the target-specific handling logic.
6208 if (AL.getKind() == ParsedAttr::UnknownAttribute)
6209 return false;
6210 // Check whether the attribute requires specific language extensions to be
6211 // enabled.
6212 if (!AL.diagnoseLangOpts(S))
6213 return true;
6214 // Check whether the attribute appertains to the given subject.
6215 if (!AL.diagnoseAppertainsTo(S, D))
6216 return true;
6217 if (AL.hasCustomParsing())
6218 return false;
6219
6220 if (AL.getMinArgs() == AL.getMaxArgs()) {
6221 // If there are no optional arguments, then checking for the argument count
6222 // is trivial.
6223 if (!checkAttributeNumArgs(S, AL, AL.getMinArgs()))
6224 return true;
6225 } else {
6226 // There are optional arguments, so checking is slightly more involved.
6227 if (AL.getMinArgs() &&
6228 !checkAttributeAtLeastNumArgs(S, AL, AL.getMinArgs()))
6229 return true;
6230 else if (!AL.hasVariadicArg() && AL.getMaxArgs() &&
6231 !checkAttributeAtMostNumArgs(S, AL, AL.getMaxArgs()))
6232 return true;
6233 }
6234
6235 if (S.CheckAttrTarget(AL))
6236 return true;
6237
6238 return false;
6239}
6240
6241static void handleOpenCLAccessAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6242 if (D->isInvalidDecl())
6243 return;
6244
6245 // Check if there is only one access qualifier.
6246 if (D->hasAttr<OpenCLAccessAttr>()) {
6247 if (D->getAttr<OpenCLAccessAttr>()->getSemanticSpelling() ==
6248 AL.getSemanticSpelling()) {
6249 S.Diag(AL.getLoc(), diag::warn_duplicate_declspec)
6250 << AL.getAttrName()->getName() << AL.getRange();
6251 } else {
6252 S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers)
6253 << D->getSourceRange();
6254 D->setInvalidDecl(true);
6255 return;
6256 }
6257 }
6258
6259 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an
6260 // image object can be read and written.
6261 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe
6262 // object. Using the read_write (or __read_write) qualifier with the pipe
6263 // qualifier is a compilation error.
6264 if (const auto *PDecl = dyn_cast<ParmVarDecl>(D)) {
6265 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr();
6266 if (AL.getAttrName()->getName().find("read_write") != StringRef::npos) {
6267 if ((!S.getLangOpts().OpenCLCPlusPlus &&
6268 S.getLangOpts().OpenCLVersion < 200) ||
6269 DeclTy->isPipeType()) {
6270 S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write)
6271 << AL << PDecl->getType() << DeclTy->isImageType();
6272 D->setInvalidDecl(true);
6273 return;
6274 }
6275 }
6276 }
6277
6278 D->addAttr(::new (S.Context) OpenCLAccessAttr(S.Context, AL));
6279}
6280
6281static void handleDestroyAttr(Sema &S, Decl *D, const ParsedAttr &A) {
6282 if (!cast<VarDecl>(D)->hasGlobalStorage()) {
6283 S.Diag(D->getLocation(), diag::err_destroy_attr_on_non_static_var)
6284 << (A.getKind() == ParsedAttr::AT_AlwaysDestroy);
6285 return;
6286 }
6287
6288 if (A.getKind() == ParsedAttr::AT_AlwaysDestroy)
6289 handleSimpleAttributeWithExclusions<AlwaysDestroyAttr, NoDestroyAttr>(S, D, A);
6290 else
6291 handleSimpleAttributeWithExclusions<NoDestroyAttr, AlwaysDestroyAttr>(S, D, A);
6292}
6293
6294static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6295 assert(cast<VarDecl>(D)->getStorageDuration() == SD_Automatic &&((cast<VarDecl>(D)->getStorageDuration() == SD_Automatic
&& "uninitialized is only valid on automatic duration variables"
) ? static_cast<void> (0) : __assert_fail ("cast<VarDecl>(D)->getStorageDuration() == SD_Automatic && \"uninitialized is only valid on automatic duration variables\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 6296, __PRETTY_FUNCTION__))
6296 "uninitialized is only valid on automatic duration variables")((cast<VarDecl>(D)->getStorageDuration() == SD_Automatic
&& "uninitialized is only valid on automatic duration variables"
) ? static_cast<void> (0) : __assert_fail ("cast<VarDecl>(D)->getStorageDuration() == SD_Automatic && \"uninitialized is only valid on automatic duration variables\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 6296, __PRETTY_FUNCTION__))
;
6297 D->addAttr(::new (S.Context) UninitializedAttr(S.Context, AL));
6298}
6299
6300static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD,
6301 bool DiagnoseFailure) {
6302 QualType Ty = VD->getType();
6303 if (!Ty->isObjCRetainableType()) {
6304 if (DiagnoseFailure) {
6305 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
6306 << 0;
6307 }
6308 return false;
6309 }
6310
6311 Qualifiers::ObjCLifetime LifetimeQual = Ty.getQualifiers().getObjCLifetime();
6312
6313 // Sema::inferObjCARCLifetime must run after processing decl attributes
6314 // (because __block lowers to an attribute), so if the lifetime hasn't been
6315 // explicitly specified, infer it locally now.
6316 if (LifetimeQual == Qualifiers::OCL_None)
6317 LifetimeQual = Ty->getObjCARCImplicitLifetime();
6318
6319 // The attributes only really makes sense for __strong variables; ignore any
6320 // attempts to annotate a parameter with any other lifetime qualifier.
6321 if (LifetimeQual != Qualifiers::OCL_Strong) {
6322 if (DiagnoseFailure) {
6323 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
6324 << 1;
6325 }
6326 return false;
6327 }
6328
6329 // Tampering with the type of a VarDecl here is a bit of a hack, but we need
6330 // to ensure that the variable is 'const' so that we can error on
6331 // modification, which can otherwise over-release.
6332 VD->setType(Ty.withConst());
6333 VD->setARCPseudoStrong(true);
6334 return true;
6335}
6336
6337static void handleObjCExternallyRetainedAttr(Sema &S, Decl *D,
6338 const ParsedAttr &AL) {
6339 if (auto *VD = dyn_cast<VarDecl>(D)) {
6340 assert(!isa<ParmVarDecl>(VD) && "should be diagnosed automatically")((!isa<ParmVarDecl>(VD) && "should be diagnosed automatically"
) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(VD) && \"should be diagnosed automatically\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 6340, __PRETTY_FUNCTION__))
;
6341 if (!VD->hasLocalStorage()) {
6342 S.Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained)
6343 << 0;
6344 return;
6345 }
6346
6347 if (!tryMakeVariablePseudoStrong(S, VD, /*DiagnoseFailure=*/true))
6348 return;
6349
6350 handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
6351 return;
6352 }
6353
6354 // If D is a function-like declaration (method, block, or function), then we
6355 // make every parameter psuedo-strong.
6356 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); I != E; ++I) {
6357 auto *PVD = const_cast<ParmVarDecl *>(getFunctionOrMethodParam(D, I));
6358 QualType Ty = PVD->getType();
6359
6360 // If a user wrote a parameter with __strong explicitly, then assume they
6361 // want "real" strong semantics for that parameter. This works because if
6362 // the parameter was written with __strong, then the strong qualifier will
6363 // be non-local.
6364 if (Ty.getLocalUnqualifiedType().getQualifiers().getObjCLifetime() ==
6365 Qualifiers::OCL_Strong)
6366 continue;
6367
6368 tryMakeVariablePseudoStrong(S, PVD, /*DiagnoseFailure=*/false);
6369 }
6370 handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL);
6371}
6372
6373static void handleMIGServerRoutineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6374 // Check that the return type is a `typedef int kern_return_t` or a typedef
6375 // around it, because otherwise MIG convention checks make no sense.
6376 // BlockDecl doesn't store a return type, so it's annoying to check,
6377 // so let's skip it for now.
6378 if (!isa<BlockDecl>(D)) {
6379 QualType T = getFunctionOrMethodResultType(D);
6380 bool IsKernReturnT = false;
6381 while (const auto *TT = T->getAs<TypedefType>()) {
6382 IsKernReturnT = (TT->getDecl()->getName() == "kern_return_t");
6383 T = TT->desugar();
6384 }
6385 if (!IsKernReturnT || T.getCanonicalType() != S.getASTContext().IntTy) {
6386 S.Diag(D->getBeginLoc(),
6387 diag::warn_mig_server_routine_does_not_return_kern_return_t);
6388 return;
6389 }
6390 }
6391
6392 handleSimpleAttribute<MIGServerRoutineAttr>(S, D, AL);
6393}
6394
6395static void handleMSAllocatorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
6396 // Warn if the return type is not a pointer or reference type.
6397 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6398 QualType RetTy = FD->getReturnType();
6399 if (!RetTy->isPointerType() && !RetTy->isReferenceType()) {
6400 S.Diag(AL.getLoc(), diag::warn_declspec_allocator_nonpointer)
6401 << AL.getRange() << RetTy;
6402 return;
6403 }
6404 }
6405
6406 handleSimpleAttribute<MSAllocatorAttr>(S, D, AL);
6407}
6408
6409//===----------------------------------------------------------------------===//
6410// Top Level Sema Entry Points
6411//===----------------------------------------------------------------------===//
6412
6413/// ProcessDeclAttribute - Apply the specific attribute to the specified decl if
6414/// the attribute applies to decls. If the attribute is a type attribute, just
6415/// silently ignore it if a GNU attribute.
6416static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D,
6417 const ParsedAttr &AL,
6418 bool IncludeCXX11Attributes) {
6419 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
6420 return;
6421
6422 // Ignore C++11 attributes on declarator chunks: they appertain to the type
6423 // instead.
6424 if (AL.isCXX11Attribute() && !IncludeCXX11Attributes)
6425 return;
6426
6427 // Unknown attributes are automatically warned on. Target-specific attributes
6428 // which do not apply to the current target architecture are treated as
6429 // though they were unknown attributes.
6430 if (AL.getKind() == ParsedAttr::UnknownAttribute ||
6431 !AL.existsInTarget(S.Context.getTargetInfo())) {
6432 S.Diag(AL.getLoc(),
6433 AL.isDeclspecAttribute()
6434 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored
6435 : (unsigned)diag::warn_unknown_attribute_ignored)
6436 << AL;
6437 return;
6438 }
6439
6440 if (handleCommonAttributeFeatures(S, D, AL))
6441 return;
6442
6443 switch (AL.getKind()) {
6444 default:
6445 if (!AL.isStmtAttr()) {
6446 // Type attributes are handled elsewhere; silently move on.
6447 assert(AL.isTypeAttr() && "Non-type attribute not handled")((AL.isTypeAttr() && "Non-type attribute not handled"
) ? static_cast<void> (0) : __assert_fail ("AL.isTypeAttr() && \"Non-type attribute not handled\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 6447, __PRETTY_FUNCTION__))
;
6448 break;
6449 }
6450 S.Diag(AL.getLoc(), diag::err_stmt_attribute_invalid_on_decl)
6451 << AL << D->getLocation();
6452 break;
6453 case ParsedAttr::AT_Interrupt:
6454 handleInterruptAttr(S, D, AL);
6455 break;
6456 case ParsedAttr::AT_X86ForceAlignArgPointer:
6457 handleX86ForceAlignArgPointerAttr(S, D, AL);
6458 break;
6459 case ParsedAttr::AT_DLLExport:
6460 case ParsedAttr::AT_DLLImport:
6461 handleDLLAttr(S, D, AL);
6462 break;
6463 case ParsedAttr::AT_Mips16:
6464 handleSimpleAttributeWithExclusions<Mips16Attr, MicroMipsAttr,
6465 MipsInterruptAttr>(S, D, AL);
6466 break;
6467 case ParsedAttr::AT_NoMips16:
6468 handleSimpleAttribute<NoMips16Attr>(S, D, AL);
6469 break;
6470 case ParsedAttr::AT_MicroMips:
6471 handleSimpleAttributeWithExclusions<MicroMipsAttr, Mips16Attr>(S, D, AL);
6472 break;
6473 case ParsedAttr::AT_NoMicroMips:
6474 handleSimpleAttribute<NoMicroMipsAttr>(S, D, AL);
6475 break;
6476 case ParsedAttr::AT_MipsLongCall:
6477 handleSimpleAttributeWithExclusions<MipsLongCallAttr, MipsShortCallAttr>(
6478 S, D, AL);
6479 break;
6480 case ParsedAttr::AT_MipsShortCall:
6481 handleSimpleAttributeWithExclusions<MipsShortCallAttr, MipsLongCallAttr>(
6482 S, D, AL);
6483 break;
6484 case ParsedAttr::AT_AMDGPUFlatWorkGroupSize:
6485 handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL);
6486 break;
6487 case ParsedAttr::AT_AMDGPUWavesPerEU:
6488 handleAMDGPUWavesPerEUAttr(S, D, AL);
6489 break;
6490 case ParsedAttr::AT_AMDGPUNumSGPR:
6491 handleAMDGPUNumSGPRAttr(S, D, AL);
6492 break;
6493 case ParsedAttr::AT_AMDGPUNumVGPR:
6494 handleAMDGPUNumVGPRAttr(S, D, AL);
6495 break;
6496 case ParsedAttr::AT_AVRSignal:
6497 handleAVRSignalAttr(S, D, AL);
6498 break;
6499 case ParsedAttr::AT_WebAssemblyImportModule:
6500 handleWebAssemblyImportModuleAttr(S, D, AL);
6501 break;
6502 case ParsedAttr::AT_WebAssemblyImportName:
6503 handleWebAssemblyImportNameAttr(S, D, AL);
6504 break;
6505 case ParsedAttr::AT_IBAction:
6506 handleSimpleAttribute<IBActionAttr>(S, D, AL);
6507 break;
6508 case ParsedAttr::AT_IBOutlet:
6509 handleIBOutlet(S, D, AL);
6510 break;
6511 case ParsedAttr::AT_IBOutletCollection:
6512 handleIBOutletCollection(S, D, AL);
6513 break;
6514 case ParsedAttr::AT_IFunc:
6515 handleIFuncAttr(S, D, AL);
6516 break;
6517 case ParsedAttr::AT_Alias:
6518 handleAliasAttr(S, D, AL);
6519 break;
6520 case ParsedAttr::AT_Aligned:
6521 handleAlignedAttr(S, D, AL);
6522 break;
6523 case ParsedAttr::AT_AlignValue:
6524 handleAlignValueAttr(S, D, AL);
6525 break;
6526 case ParsedAttr::AT_AllocSize:
6527 handleAllocSizeAttr(S, D, AL);
6528 break;
6529 case ParsedAttr::AT_AlwaysInline:
6530 handleAlwaysInlineAttr(S, D, AL);
6531 break;
6532 case ParsedAttr::AT_Artificial:
6533 handleSimpleAttribute<ArtificialAttr>(S, D, AL);
6534 break;
6535 case ParsedAttr::AT_AnalyzerNoReturn:
6536 handleAnalyzerNoReturnAttr(S, D, AL);
6537 break;
6538 case ParsedAttr::AT_TLSModel:
6539 handleTLSModelAttr(S, D, AL);
6540 break;
6541 case ParsedAttr::AT_Annotate:
6542 handleAnnotateAttr(S, D, AL);
6543 break;
6544 case ParsedAttr::AT_Availability:
6545 handleAvailabilityAttr(S, D, AL);
6546 break;
6547 case ParsedAttr::AT_CarriesDependency:
6548 handleDependencyAttr(S, scope, D, AL);
6549 break;
6550 case ParsedAttr::AT_CPUDispatch:
6551 case ParsedAttr::AT_CPUSpecific:
6552 handleCPUSpecificAttr(S, D, AL);
6553 break;
6554 case ParsedAttr::AT_Common:
6555 handleCommonAttr(S, D, AL);
6556 break;
6557 case ParsedAttr::AT_CUDAConstant:
6558 handleConstantAttr(S, D, AL);
6559 break;
6560 case ParsedAttr::AT_PassObjectSize:
6561 handlePassObjectSizeAttr(S, D, AL);
6562 break;
6563 case ParsedAttr::AT_Constructor:
6564 handleConstructorAttr(S, D, AL);
6565 break;
6566 case ParsedAttr::AT_CXX11NoReturn:
6567 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, AL);
6568 break;
6569 case ParsedAttr::AT_Deprecated:
6570 handleDeprecatedAttr(S, D, AL);
6571 break;
6572 case ParsedAttr::AT_Destructor:
6573 handleDestructorAttr(S, D, AL);
6574 break;
6575 case ParsedAttr::AT_EnableIf:
6576 handleEnableIfAttr(S, D, AL);
6577 break;
6578 case ParsedAttr::AT_DiagnoseIf:
6579 handleDiagnoseIfAttr(S, D, AL);
6580 break;
6581 case ParsedAttr::AT_ExtVectorType:
6582 handleExtVectorTypeAttr(S, D, AL);
6583 break;
6584 case ParsedAttr::AT_ExternalSourceSymbol:
6585 handleExternalSourceSymbolAttr(S, D, AL);
6586 break;
6587 case ParsedAttr::AT_MinSize:
6588 handleMinSizeAttr(S, D, AL);
6589 break;
6590 case ParsedAttr::AT_OptimizeNone:
6591 handleOptimizeNoneAttr(S, D, AL);
6592 break;
6593 case ParsedAttr::AT_FlagEnum:
6594 handleSimpleAttribute<FlagEnumAttr>(S, D, AL);
6595 break;
6596 case ParsedAttr::AT_EnumExtensibility:
6597 handleEnumExtensibilityAttr(S, D, AL);
6598 break;
6599 case ParsedAttr::AT_Flatten:
6600 handleSimpleAttribute<FlattenAttr>(S, D, AL);
6601 break;
6602 case ParsedAttr::AT_Format:
6603 handleFormatAttr(S, D, AL);
6604 break;
6605 case ParsedAttr::AT_FormatArg:
6606 handleFormatArgAttr(S, D, AL);
6607 break;
6608 case ParsedAttr::AT_Callback:
6609 handleCallbackAttr(S, D, AL);
6610 break;
6611 case ParsedAttr::AT_CUDAGlobal:
6612 handleGlobalAttr(S, D, AL);
6613 break;
6614 case ParsedAttr::AT_CUDADevice:
6615 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D,
6616 AL);
6617 break;
6618 case ParsedAttr::AT_CUDAHost:
6619 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D, AL);
6620 break;
6621 case ParsedAttr::AT_HIPPinnedShadow:
6622 handleSimpleAttributeWithExclusions<HIPPinnedShadowAttr, CUDADeviceAttr,
6623 CUDAConstantAttr>(S, D, AL);
6624 break;
6625 case ParsedAttr::AT_GNUInline:
6626 handleGNUInlineAttr(S, D, AL);
6627 break;
6628 case ParsedAttr::AT_CUDALaunchBounds:
6629 handleLaunchBoundsAttr(S, D, AL);
6630 break;
6631 case ParsedAttr::AT_Restrict:
6632 handleRestrictAttr(S, D, AL);
6633 break;
6634 case ParsedAttr::AT_LifetimeBound:
6635 handleSimpleAttribute<LifetimeBoundAttr>(S, D, AL);
6636 break;
6637 case ParsedAttr::AT_MayAlias:
6638 handleSimpleAttribute<MayAliasAttr>(S, D, AL);
6639 break;
6640 case ParsedAttr::AT_Mode:
6641 handleModeAttr(S, D, AL);
6642 break;
6643 case ParsedAttr::AT_NoAlias:
6644 handleSimpleAttribute<NoAliasAttr>(S, D, AL);
6645 break;
6646 case ParsedAttr::AT_NoCommon:
6647 handleSimpleAttribute<NoCommonAttr>(S, D, AL);
6648 break;
6649 case ParsedAttr::AT_NoSplitStack:
6650 handleSimpleAttribute<NoSplitStackAttr>(S, D, AL);
6651 break;
6652 case ParsedAttr::AT_NoUniqueAddress:
6653 handleSimpleAttribute<NoUniqueAddressAttr>(S, D, AL);
6654 break;
6655 case ParsedAttr::AT_NonNull:
6656 if (auto *PVD = dyn_cast<ParmVarDecl>(D))
6657 handleNonNullAttrParameter(S, PVD, AL);
6658 else
6659 handleNonNullAttr(S, D, AL);
6660 break;
6661 case ParsedAttr::AT_ReturnsNonNull:
6662 handleReturnsNonNullAttr(S, D, AL);
6663 break;
6664 case ParsedAttr::AT_NoEscape:
6665 handleNoEscapeAttr(S, D, AL);
6666 break;
6667 case ParsedAttr::AT_AssumeAligned:
6668 handleAssumeAlignedAttr(S, D, AL);
6669 break;
6670 case ParsedAttr::AT_AllocAlign:
6671 handleAllocAlignAttr(S, D, AL);
6672 break;
6673 case ParsedAttr::AT_Overloadable:
6674 handleSimpleAttribute<OverloadableAttr>(S, D, AL);
6675 break;
6676 case ParsedAttr::AT_Ownership:
6677 handleOwnershipAttr(S, D, AL);
6678 break;
6679 case ParsedAttr::AT_Cold:
6680 handleSimpleAttributeWithExclusions<ColdAttr, HotAttr>(S, D, AL);
6681 break;
6682 case ParsedAttr::AT_Hot:
6683 handleSimpleAttributeWithExclusions<HotAttr, ColdAttr>(S, D, AL);
6684 break;
6685 case ParsedAttr::AT_Naked:
6686 handleNakedAttr(S, D, AL);
6687 break;
6688 case ParsedAttr::AT_NoReturn:
6689 handleNoReturnAttr(S, D, AL);
6690 break;
6691 case ParsedAttr::AT_AnyX86NoCfCheck:
6692 handleNoCfCheckAttr(S, D, AL);
6693 break;
6694 case ParsedAttr::AT_NoThrow:
6695 if (!AL.isUsedAsTypeAttr())
6696 handleSimpleAttribute<NoThrowAttr>(S, D, AL);
6697 break;
6698 case ParsedAttr::AT_CUDAShared:
6699 handleSharedAttr(S, D, AL);
6700 break;
6701 case ParsedAttr::AT_VecReturn:
6702 handleVecReturnAttr(S, D, AL);
6703 break;
6704 case ParsedAttr::AT_ObjCOwnership:
6705 handleObjCOwnershipAttr(S, D, AL);
6706 break;
6707 case ParsedAttr::AT_ObjCPreciseLifetime:
6708 handleObjCPreciseLifetimeAttr(S, D, AL);
6709 break;
6710 case ParsedAttr::AT_ObjCReturnsInnerPointer:
6711 handleObjCReturnsInnerPointerAttr(S, D, AL);
6712 break;
6713 case ParsedAttr::AT_ObjCRequiresSuper:
6714 handleObjCRequiresSuperAttr(S, D, AL);
6715 break;
6716 case ParsedAttr::AT_ObjCBridge:
6717 handleObjCBridgeAttr(S, D, AL);
6718 break;
6719 case ParsedAttr::AT_ObjCBridgeMutable:
6720 handleObjCBridgeMutableAttr(S, D, AL);
6721 break;
6722 case ParsedAttr::AT_ObjCBridgeRelated:
6723 handleObjCBridgeRelatedAttr(S, D, AL);
6724 break;
6725 case ParsedAttr::AT_ObjCDesignatedInitializer:
6726 handleObjCDesignatedInitializer(S, D, AL);
6727 break;
6728 case ParsedAttr::AT_ObjCRuntimeName:
6729 handleObjCRuntimeName(S, D, AL);
6730 break;
6731 case ParsedAttr::AT_ObjCRuntimeVisible:
6732 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, AL);
6733 break;
6734 case ParsedAttr::AT_ObjCBoxable:
6735 handleObjCBoxable(S, D, AL);
6736 break;
6737 case ParsedAttr::AT_CFAuditedTransfer:
6738 handleSimpleAttributeWithExclusions<CFAuditedTransferAttr,
6739 CFUnknownTransferAttr>(S, D, AL);
6740 break;
6741 case ParsedAttr::AT_CFUnknownTransfer:
6742 handleSimpleAttributeWithExclusions<CFUnknownTransferAttr,
6743 CFAuditedTransferAttr>(S, D, AL);
6744 break;
6745 case ParsedAttr::AT_CFConsumed:
6746 case ParsedAttr::AT_NSConsumed:
6747 case ParsedAttr::AT_OSConsumed:
6748 S.AddXConsumedAttr(D, AL, parsedAttrToRetainOwnershipKind(AL),
6749 /*IsTemplateInstantiation=*/false);
6750 break;
6751 case ParsedAttr::AT_NSConsumesSelf:
6752 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, AL);
6753 break;
6754 case ParsedAttr::AT_OSConsumesThis:
6755 handleSimpleAttribute<OSConsumesThisAttr>(S, D, AL);
6756 break;
6757 case ParsedAttr::AT_OSReturnsRetainedOnZero:
6758 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnZeroAttr>(
6759 S, D, AL, isValidOSObjectOutParameter(D),
6760 diag::warn_ns_attribute_wrong_parameter_type,
6761 /*Extra Args=*/AL, /*pointer-to-OSObject-pointer*/ 3, AL.getRange());
6762 break;
6763 case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
6764 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnNonZeroAttr>(
6765 S, D, AL, isValidOSObjectOutParameter(D),
6766 diag::warn_ns_attribute_wrong_parameter_type,
6767 /*Extra Args=*/AL, /*pointer-to-OSObject-poointer*/ 3, AL.getRange());
6768 break;
6769 case ParsedAttr::AT_NSReturnsAutoreleased:
6770 case ParsedAttr::AT_NSReturnsNotRetained:
6771 case ParsedAttr::AT_NSReturnsRetained:
6772 case ParsedAttr::AT_CFReturnsNotRetained:
6773 case ParsedAttr::AT_CFReturnsRetained:
6774 case ParsedAttr::AT_OSReturnsNotRetained:
6775 case ParsedAttr::AT_OSReturnsRetained:
6776 handleXReturnsXRetainedAttr(S, D, AL);
6777 break;
6778 case ParsedAttr::AT_WorkGroupSizeHint:
6779 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL);
6780 break;
6781 case ParsedAttr::AT_ReqdWorkGroupSize:
6782 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL);
6783 break;
6784 case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize:
6785 handleSubGroupSize(S, D, AL);
6786 break;
6787 case ParsedAttr::AT_VecTypeHint:
6788 handleVecTypeHint(S, D, AL);
6789 break;
6790 case ParsedAttr::AT_ConstInit:
6791 handleSimpleAttribute<ConstInitAttr>(S, D, AL);
6792 break;
6793 case ParsedAttr::AT_InitPriority:
6794 handleInitPriorityAttr(S, D, AL);
6795 break;
6796 case ParsedAttr::AT_Packed:
6797 handlePackedAttr(S, D, AL);
6798 break;
6799 case ParsedAttr::AT_Section:
6800 handleSectionAttr(S, D, AL);
6801 break;
6802 case ParsedAttr::AT_SpeculativeLoadHardening:
6803 handleSimpleAttributeWithExclusions<SpeculativeLoadHardeningAttr,
6804 NoSpeculativeLoadHardeningAttr>(S, D,
6805 AL);
6806 break;
6807 case ParsedAttr::AT_NoSpeculativeLoadHardening:
6808 handleSimpleAttributeWithExclusions<NoSpeculativeLoadHardeningAttr,
6809 SpeculativeLoadHardeningAttr>(S, D, AL);
6810 break;
6811 case ParsedAttr::AT_CodeSeg:
6812 handleCodeSegAttr(S, D, AL);
6813 break;
6814 case ParsedAttr::AT_Target:
6815 handleTargetAttr(S, D, AL);
6816 break;
6817 case ParsedAttr::AT_MinVectorWidth:
6818 handleMinVectorWidthAttr(S, D, AL);
6819 break;
6820 case ParsedAttr::AT_Unavailable:
6821 handleAttrWithMessage<UnavailableAttr>(S, D, AL);
6822 break;
6823 case ParsedAttr::AT_ArcWeakrefUnavailable:
6824 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, AL);
6825 break;
6826 case ParsedAttr::AT_ObjCRootClass:
6827 handleSimpleAttribute<ObjCRootClassAttr>(S, D, AL);
6828 break;
6829 case ParsedAttr::AT_ObjCNonLazyClass:
6830 handleSimpleAttribute<ObjCNonLazyClassAttr>(S, D, AL);
6831 break;
6832 case ParsedAttr::AT_ObjCSubclassingRestricted:
6833 handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, AL);
6834 break;
6835 case ParsedAttr::AT_ObjCClassStub:
6836 handleSimpleAttribute<ObjCClassStubAttr>(S, D, AL);
6837 break;
6838 case ParsedAttr::AT_ObjCExplicitProtocolImpl:
6839 handleObjCSuppresProtocolAttr(S, D, AL);
6840 break;
6841 case ParsedAttr::AT_ObjCRequiresPropertyDefs:
6842 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, AL);
6843 break;
6844 case ParsedAttr::AT_Unused:
6845 handleUnusedAttr(S, D, AL);
6846 break;
6847 case ParsedAttr::AT_ReturnsTwice:
6848 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, AL);
6849 break;
6850 case ParsedAttr::AT_NotTailCalled:
6851 handleSimpleAttributeWithExclusions<NotTailCalledAttr, AlwaysInlineAttr>(
6852 S, D, AL);
6853 break;
6854 case ParsedAttr::AT_DisableTailCalls:
6855 handleSimpleAttributeWithExclusions<DisableTailCallsAttr, NakedAttr>(S, D,
6856 AL);
6857 break;
6858 case ParsedAttr::AT_Used:
6859 handleSimpleAttribute<UsedAttr>(S, D, AL);
6860 break;
6861 case ParsedAttr::AT_Visibility:
6862 handleVisibilityAttr(S, D, AL, false);
6863 break;
6864 case ParsedAttr::AT_TypeVisibility:
6865 handleVisibilityAttr(S, D, AL, true);
6866 break;
6867 case ParsedAttr::AT_WarnUnused:
6868 handleSimpleAttribute<WarnUnusedAttr>(S, D, AL);
6869 break;
6870 case ParsedAttr::AT_WarnUnusedResult:
6871 handleWarnUnusedResult(S, D, AL);
6872 break;
6873 case ParsedAttr::AT_Weak:
6874 handleSimpleAttribute<WeakAttr>(S, D, AL);
6875 break;
6876 case ParsedAttr::AT_WeakRef:
6877 handleWeakRefAttr(S, D, AL);
6878 break;
6879 case ParsedAttr::AT_WeakImport:
6880 handleWeakImportAttr(S, D, AL);
6881 break;
6882 case ParsedAttr::AT_TransparentUnion:
6883 handleTransparentUnionAttr(S, D, AL);
6884 break;
6885 case ParsedAttr::AT_ObjCException:
6886 handleSimpleAttribute<ObjCExceptionAttr>(S, D, AL);
6887 break;
6888 case ParsedAttr::AT_ObjCMethodFamily:
6889 handleObjCMethodFamilyAttr(S, D, AL);
6890 break;
6891 case ParsedAttr::AT_ObjCNSObject:
6892 handleObjCNSObject(S, D, AL);
6893 break;
6894 case ParsedAttr::AT_ObjCIndependentClass:
6895 handleObjCIndependentClass(S, D, AL);
6896 break;
6897 case ParsedAttr::AT_Blocks:
6898 handleBlocksAttr(S, D, AL);
6899 break;
6900 case ParsedAttr::AT_Sentinel:
6901 handleSentinelAttr(S, D, AL);
6902 break;
6903 case ParsedAttr::AT_Const:
6904 handleSimpleAttribute<ConstAttr>(S, D, AL);
6905 break;
6906 case ParsedAttr::AT_Pure:
6907 handleSimpleAttribute<PureAttr>(S, D, AL);
6908 break;
6909 case ParsedAttr::AT_Cleanup:
6910 handleCleanupAttr(S, D, AL);
6911 break;
6912 case ParsedAttr::AT_NoDebug:
6913 handleNoDebugAttr(S, D, AL);
6914 break;
6915 case ParsedAttr::AT_NoDuplicate:
6916 handleSimpleAttribute<NoDuplicateAttr>(S, D, AL);
6917 break;
6918 case ParsedAttr::AT_Convergent:
6919 handleSimpleAttribute<ConvergentAttr>(S, D, AL);
6920 break;
6921 case ParsedAttr::AT_NoInline:
6922 handleSimpleAttribute<NoInlineAttr>(S, D, AL);
6923 break;
6924 case ParsedAttr::AT_NoInstrumentFunction: // Interacts with -pg.
6925 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, AL);
6926 break;
6927 case ParsedAttr::AT_NoStackProtector:
6928 // Interacts with -fstack-protector options.
6929 handleSimpleAttribute<NoStackProtectorAttr>(S, D, AL);
6930 break;
6931 case ParsedAttr::AT_CFICanonicalJumpTable:
6932 handleSimpleAttribute<CFICanonicalJumpTableAttr>(S, D, AL);
6933 break;
6934 case ParsedAttr::AT_StdCall:
6935 case ParsedAttr::AT_CDecl:
6936 case ParsedAttr::AT_FastCall:
6937 case ParsedAttr::AT_ThisCall:
6938 case ParsedAttr::AT_Pascal:
6939 case ParsedAttr::AT_RegCall:
6940 case ParsedAttr::AT_SwiftCall:
6941 case ParsedAttr::AT_VectorCall:
6942 case ParsedAttr::AT_MSABI:
6943 case ParsedAttr::AT_SysVABI:
6944 case ParsedAttr::AT_Pcs:
6945 case ParsedAttr::AT_IntelOclBicc:
6946 case ParsedAttr::AT_PreserveMost:
6947 case ParsedAttr::AT_PreserveAll:
6948 case ParsedAttr::AT_AArch64VectorPcs:
6949 handleCallConvAttr(S, D, AL);
6950 break;
6951 case ParsedAttr::AT_Suppress:
6952 handleSuppressAttr(S, D, AL);
6953 break;
6954 case ParsedAttr::AT_Owner:
6955 case ParsedAttr::AT_Pointer:
6956 handleLifetimeCategoryAttr(S, D, AL);
6957 break;
6958 case ParsedAttr::AT_OpenCLKernel:
6959 handleSimpleAttribute<OpenCLKernelAttr>(S, D, AL);
6960 break;
6961 case ParsedAttr::AT_OpenCLAccess:
6962 handleOpenCLAccessAttr(S, D, AL);
6963 break;
6964 case ParsedAttr::AT_OpenCLNoSVM:
6965 handleOpenCLNoSVMAttr(S, D, AL);
6966 break;
6967 case ParsedAttr::AT_SwiftContext:
6968 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftContext);
6969 break;
6970 case ParsedAttr::AT_SwiftErrorResult:
6971 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftErrorResult);
6972 break;
6973 case ParsedAttr::AT_SwiftIndirectResult:
6974 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftIndirectResult);
6975 break;
6976 case ParsedAttr::AT_InternalLinkage:
6977 handleInternalLinkageAttr(S, D, AL);
6978 break;
6979 case ParsedAttr::AT_ExcludeFromExplicitInstantiation:
6980 handleSimpleAttribute<ExcludeFromExplicitInstantiationAttr>(S, D, AL);
6981 break;
6982 case ParsedAttr::AT_LTOVisibilityPublic:
6983 handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, AL);
6984 break;
6985
6986 // Microsoft attributes:
6987 case ParsedAttr::AT_EmptyBases:
6988 handleSimpleAttribute<EmptyBasesAttr>(S, D, AL);
6989 break;
6990 case ParsedAttr::AT_LayoutVersion:
6991 handleLayoutVersion(S, D, AL);
6992 break;
6993 case ParsedAttr::AT_TrivialABI:
6994 handleSimpleAttribute<TrivialABIAttr>(S, D, AL);
6995 break;
6996 case ParsedAttr::AT_MSNoVTable:
6997 handleSimpleAttribute<MSNoVTableAttr>(S, D, AL);
6998 break;
6999 case ParsedAttr::AT_MSStruct:
7000 handleSimpleAttribute<MSStructAttr>(S, D, AL);
7001 break;
7002 case ParsedAttr::AT_Uuid:
7003 handleUuidAttr(S, D, AL);
7004 break;
7005 case ParsedAttr::AT_MSInheritance:
7006 handleMSInheritanceAttr(S, D, AL);
7007 break;
7008 case ParsedAttr::AT_SelectAny:
7009 handleSimpleAttribute<SelectAnyAttr>(S, D, AL);
7010 break;
7011 case ParsedAttr::AT_Thread:
7012 handleDeclspecThreadAttr(S, D, AL);
7013 break;
7014
7015 case ParsedAttr::AT_AbiTag:
7016 handleAbiTagAttr(S, D, AL);
7017 break;
7018
7019 // Thread safety attributes:
7020 case ParsedAttr::AT_AssertExclusiveLock:
7021 handleAssertExclusiveLockAttr(S, D, AL);
7022 break;
7023 case ParsedAttr::AT_AssertSharedLock:
7024 handleAssertSharedLockAttr(S, D, AL);
7025 break;
7026 case ParsedAttr::AT_GuardedVar:
7027 handleSimpleAttribute<GuardedVarAttr>(S, D, AL);
7028 break;
7029 case ParsedAttr::AT_PtGuardedVar:
7030 handlePtGuardedVarAttr(S, D, AL);
7031 break;
7032 case ParsedAttr::AT_ScopedLockable:
7033 handleSimpleAttribute<ScopedLockableAttr>(S, D, AL);
7034 break;
7035 case ParsedAttr::AT_NoSanitize:
7036 handleNoSanitizeAttr(S, D, AL);
7037 break;
7038 case ParsedAttr::AT_NoSanitizeSpecific:
7039 handleNoSanitizeSpecificAttr(S, D, AL);
7040 break;
7041 case ParsedAttr::AT_NoThreadSafetyAnalysis:
7042 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, AL);
7043 break;
7044 case ParsedAttr::AT_GuardedBy:
7045 handleGuardedByAttr(S, D, AL);
7046 break;
7047 case ParsedAttr::AT_PtGuardedBy:
7048 handlePtGuardedByAttr(S, D, AL);
7049 break;
7050 case ParsedAttr::AT_ExclusiveTrylockFunction:
7051 handleExclusiveTrylockFunctionAttr(S, D, AL);
7052 break;
7053 case ParsedAttr::AT_LockReturned:
7054 handleLockReturnedAttr(S, D, AL);
7055 break;
7056 case ParsedAttr::AT_LocksExcluded:
7057 handleLocksExcludedAttr(S, D, AL);
7058 break;
7059 case ParsedAttr::AT_SharedTrylockFunction:
7060 handleSharedTrylockFunctionAttr(S, D, AL);
7061 break;
7062 case ParsedAttr::AT_AcquiredBefore:
7063 handleAcquiredBeforeAttr(S, D, AL);
7064 break;
7065 case ParsedAttr::AT_AcquiredAfter:
7066 handleAcquiredAfterAttr(S, D, AL);
7067 break;
7068
7069 // Capability analysis attributes.
7070 case ParsedAttr::AT_Capability:
7071 case ParsedAttr::AT_Lockable:
7072 handleCapabilityAttr(S, D, AL);
7073 break;
7074 case ParsedAttr::AT_RequiresCapability:
7075 handleRequiresCapabilityAttr(S, D, AL);
7076 break;
7077
7078 case ParsedAttr::AT_AssertCapability:
7079 handleAssertCapabilityAttr(S, D, AL);
7080 break;
7081 case ParsedAttr::AT_AcquireCapability:
7082 handleAcquireCapabilityAttr(S, D, AL);
7083 break;
7084 case ParsedAttr::AT_ReleaseCapability:
7085 handleReleaseCapabilityAttr(S, D, AL);
7086 break;
7087 case ParsedAttr::AT_TryAcquireCapability:
7088 handleTryAcquireCapabilityAttr(S, D, AL);
7089 break;
7090
7091 // Consumed analysis attributes.
7092 case ParsedAttr::AT_Consumable:
7093 handleConsumableAttr(S, D, AL);
7094 break;
7095 case ParsedAttr::AT_ConsumableAutoCast:
7096 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, AL);
7097 break;
7098 case ParsedAttr::AT_ConsumableSetOnRead:
7099 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, AL);
7100 break;
7101 case ParsedAttr::AT_CallableWhen:
7102 handleCallableWhenAttr(S, D, AL);
7103 break;
7104 case ParsedAttr::AT_ParamTypestate:
7105 handleParamTypestateAttr(S, D, AL);
7106 break;
7107 case ParsedAttr::AT_ReturnTypestate:
7108 handleReturnTypestateAttr(S, D, AL);
7109 break;
7110 case ParsedAttr::AT_SetTypestate:
7111 handleSetTypestateAttr(S, D, AL);
7112 break;
7113 case ParsedAttr::AT_TestTypestate:
7114 handleTestTypestateAttr(S, D, AL);
7115 break;
7116
7117 // Type safety attributes.
7118 case ParsedAttr::AT_ArgumentWithTypeTag:
7119 handleArgumentWithTypeTagAttr(S, D, AL);
7120 break;
7121 case ParsedAttr::AT_TypeTagForDatatype:
7122 handleTypeTagForDatatypeAttr(S, D, AL);
7123 break;
7124 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters:
7125 handleSimpleAttribute<AnyX86NoCallerSavedRegistersAttr>(S, D, AL);
7126 break;
7127 case ParsedAttr::AT_RenderScriptKernel:
7128 handleSimpleAttribute<RenderScriptKernelAttr>(S, D, AL);
7129 break;
7130 // XRay attributes.
7131 case ParsedAttr::AT_XRayInstrument:
7132 handleSimpleAttribute<XRayInstrumentAttr>(S, D, AL);
7133 break;
7134 case ParsedAttr::AT_XRayLogArgs:
7135 handleXRayLogArgsAttr(S, D, AL);
7136 break;
7137
7138 // Move semantics attribute.
7139 case ParsedAttr::AT_Reinitializes:
7140 handleSimpleAttribute<ReinitializesAttr>(S, D, AL);
7141 break;
7142
7143 case ParsedAttr::AT_AlwaysDestroy:
7144 case ParsedAttr::AT_NoDestroy:
7145 handleDestroyAttr(S, D, AL);
7146 break;
7147
7148 case ParsedAttr::AT_Uninitialized:
7149 handleUninitializedAttr(S, D, AL);
7150 break;
7151
7152 case ParsedAttr::AT_ObjCExternallyRetained:
7153 handleObjCExternallyRetainedAttr(S, D, AL);
7154 break;
7155
7156 case ParsedAttr::AT_MIGServerRoutine:
7157 handleMIGServerRoutineAttr(S, D, AL);
7158 break;
7159
7160 case ParsedAttr::AT_MSAllocator:
7161 handleMSAllocatorAttr(S, D, AL);
7162 break;
7163 }
7164}
7165
7166/// ProcessDeclAttributeList - Apply all the decl attributes in the specified
7167/// attribute list to the specified decl, ignoring any type attributes.
7168void Sema::ProcessDeclAttributeList(Scope *S, Decl *D,
7169 const ParsedAttributesView &AttrList,
7170 bool IncludeCXX11Attributes) {
7171 if (AttrList.empty())
7172 return;
7173
7174 for (const ParsedAttr &AL : AttrList)
7175 ProcessDeclAttribute(*this, S, D, AL, IncludeCXX11Attributes);
7176
7177 // FIXME: We should be able to handle these cases in TableGen.
7178 // GCC accepts
7179 // static int a9 __attribute__((weakref));
7180 // but that looks really pointless. We reject it.
7181 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) {
7182 Diag(AttrList.begin()->getLoc(), diag::err_attribute_weakref_without_alias)
7183 << cast<NamedDecl>(D);
7184 D->dropAttr<WeakRefAttr>();
7185 return;
7186 }
7187
7188 // FIXME: We should be able to handle this in TableGen as well. It would be
7189 // good to have a way to specify "these attributes must appear as a group",
7190 // for these. Additionally, it would be good to have a way to specify "these
7191 // attribute must never appear as a group" for attributes like cold and hot.
7192 if (!D->hasAttr<OpenCLKernelAttr>()) {
7193 // These attributes cannot be applied to a non-kernel function.
7194 if (const auto *A = D->getAttr<ReqdWorkGroupSizeAttr>()) {
7195 // FIXME: This emits a different error message than
7196 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction.
7197 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7198 D->setInvalidDecl();
7199 } else if (const auto *A = D->getAttr<WorkGroupSizeHintAttr>()) {
7200 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7201 D->setInvalidDecl();
7202 } else if (const auto *A = D->getAttr<VecTypeHintAttr>()) {
7203 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7204 D->setInvalidDecl();
7205 } else if (const auto *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
7206 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A;
7207 D->setInvalidDecl();
7208 } else if (!D->hasAttr<CUDAGlobalAttr>()) {
7209 if (const auto *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
7210 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7211 << A << ExpectedKernelFunction;
7212 D->setInvalidDecl();
7213 } else if (const auto *A = D->getAttr<AMDGPUWavesPerEUAttr>()) {
7214 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7215 << A << ExpectedKernelFunction;
7216 D->setInvalidDecl();
7217 } else if (const auto *A = D->getAttr<AMDGPUNumSGPRAttr>()) {
7218 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7219 << A << ExpectedKernelFunction;
7220 D->setInvalidDecl();
7221 } else if (const auto *A = D->getAttr<AMDGPUNumVGPRAttr>()) {
7222 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type)
7223 << A << ExpectedKernelFunction;
7224 D->setInvalidDecl();
7225 }
7226 }
7227 }
7228
7229 // Do this check after processing D's attributes because the attribute
7230 // objc_method_family can change whether the given method is in the init
7231 // family, and it can be applied after objc_designated_initializer. This is a
7232 // bit of a hack, but we need it to be compatible with versions of clang that
7233 // processed the attribute list in the wrong order.
7234 if (D->hasAttr<ObjCDesignatedInitializerAttr>() &&
7235 cast<ObjCMethodDecl>(D)->getMethodFamily() != OMF_init) {
7236 Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
7237 D->dropAttr<ObjCDesignatedInitializerAttr>();
7238 }
7239}
7240
7241// Helper for delayed processing TransparentUnion attribute.
7242void Sema::ProcessDeclAttributeDelayed(Decl *D,
7243 const ParsedAttributesView &AttrList) {
7244 for (const ParsedAttr &AL : AttrList)
7245 if (AL.getKind() == ParsedAttr::AT_TransparentUnion) {
7246 handleTransparentUnionAttr(*this, D, AL);
7247 break;
7248 }
7249}
7250
7251// Annotation attributes are the only attributes allowed after an access
7252// specifier.
7253bool Sema::ProcessAccessDeclAttributeList(
7254 AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList) {
7255 for (const ParsedAttr &AL : AttrList) {
7256 if (AL.getKind() == ParsedAttr::AT_Annotate) {
7257 ProcessDeclAttribute(*this, nullptr, ASDecl, AL, AL.isCXX11Attribute());
7258 } else {
7259 Diag(AL.getLoc(), diag::err_only_annotate_after_access_spec);
7260 return true;
7261 }
7262 }
7263 return false;
7264}
7265
7266/// checkUnusedDeclAttributes - Check a list of attributes to see if it
7267/// contains any decl attributes that we should warn about.
7268static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A) {
7269 for (const ParsedAttr &AL : A) {
7270 // Only warn if the attribute is an unignored, non-type attribute.
7271 if (AL.isUsedAsTypeAttr() || AL.isInvalid())
7272 continue;
7273 if (AL.getKind() == ParsedAttr::IgnoredAttribute)
7274 continue;
7275
7276 if (AL.getKind() == ParsedAttr::UnknownAttribute) {
7277 S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
7278 << AL << AL.getRange();
7279 } else {
7280 S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) << AL
7281 << AL.getRange();
7282 }
7283 }
7284}
7285
7286/// checkUnusedDeclAttributes - Given a declarator which is not being
7287/// used to build a declaration, complain about any decl attributes
7288/// which might be lying around on it.
7289void Sema::checkUnusedDeclAttributes(Declarator &D) {
7290 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes());
7291 ::checkUnusedDeclAttributes(*this, D.getAttributes());
7292 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i)
7293 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs());
7294}
7295
7296/// DeclClonePragmaWeak - clone existing decl (maybe definition),
7297/// \#pragma weak needs a non-definition decl and source may not have one.
7298NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
7299 SourceLocation Loc) {
7300 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND))((isa<FunctionDecl>(ND) || isa<VarDecl>(ND)) ? static_cast
<void> (0) : __assert_fail ("isa<FunctionDecl>(ND) || isa<VarDecl>(ND)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 7300, __PRETTY_FUNCTION__))
;
7301 NamedDecl *NewD = nullptr;
7302 if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
7303 FunctionDecl *NewFD;
7304 // FIXME: Missing call to CheckFunctionDeclaration().
7305 // FIXME: Mangling?
7306 // FIXME: Is the qualifier info correct?
7307 // FIXME: Is the DeclContext correct?
7308 NewFD = FunctionDecl::Create(
7309 FD->getASTContext(), FD->getDeclContext(), Loc, Loc,
7310 DeclarationName(II), FD->getType(), FD->getTypeSourceInfo(), SC_None,
7311 false /*isInlineSpecified*/, FD->hasPrototype(), CSK_unspecified);
7312 NewD = NewFD;
7313
7314 if (FD->getQualifier())
7315 NewFD->setQualifierInfo(FD->getQualifierLoc());
7316
7317 // Fake up parameter variables; they are declared as if this were
7318 // a typedef.
7319 QualType FDTy = FD->getType();
7320 if (const auto *FT = FDTy->getAs<FunctionProtoType>()) {
7321 SmallVector<ParmVarDecl*, 16> Params;
7322 for (const auto &AI : FT->param_types()) {
7323 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI);
7324 Param->setScopeInfo(0, Params.size());
7325 Params.push_back(Param);
7326 }
7327 NewFD->setParams(Params);
7328 }
7329 } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
7330 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(),
7331 VD->getInnerLocStart(), VD->getLocation(), II,
7332 VD->getType(), VD->getTypeSourceInfo(),
7333 VD->getStorageClass());
7334 if (VD->getQualifier())
7335 cast<VarDecl>(NewD)->setQualifierInfo(VD->getQualifierLoc());
7336 }
7337 return NewD;
7338}
7339
7340/// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak
7341/// applied to it, possibly with an alias.
7342void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) {
7343 if (W.getUsed()) return; // only do this once
7344 W.setUsed(true);
7345 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...))
7346 IdentifierInfo *NDId = ND->getIdentifier();
7347 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation());
7348 NewD->addAttr(
7349 AliasAttr::CreateImplicit(Context, NDId->getName(), W.getLocation()));
7350 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation(),
7351 AttributeCommonInfo::AS_Pragma));
7352 WeakTopLevelDecl.push_back(NewD);
7353 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin
7354 // to insert Decl at TU scope, sorry.
7355 DeclContext *SavedContext = CurContext;
7356 CurContext = Context.getTranslationUnitDecl();
7357 NewD->setDeclContext(CurContext);
7358 NewD->setLexicalDeclContext(CurContext);
7359 PushOnScopeChains(NewD, S);
7360 CurContext = SavedContext;
7361 } else { // just add weak to existing
7362 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation(),
7363 AttributeCommonInfo::AS_Pragma));
7364 }
7365}
7366
7367void Sema::ProcessPragmaWeak(Scope *S, Decl *D) {
7368 // It's valid to "forward-declare" #pragma weak, in which case we
7369 // have to do this.
7370 LoadExternalWeakUndeclaredIdentifiers();
7371 if (!WeakUndeclaredIdentifiers.empty()) {
7372 NamedDecl *ND = nullptr;
7373 if (auto *VD = dyn_cast<VarDecl>(D))
7374 if (VD->isExternC())
7375 ND = VD;
7376 if (auto *FD = dyn_cast<FunctionDecl>(D))
7377 if (FD->isExternC())
7378 ND = FD;
7379 if (ND) {
7380 if (IdentifierInfo *Id = ND->getIdentifier()) {
7381 auto I = WeakUndeclaredIdentifiers.find(Id);
7382 if (I != WeakUndeclaredIdentifiers.end()) {
7383 WeakInfo W = I->second;
7384 DeclApplyPragmaWeak(S, ND, W);
7385 WeakUndeclaredIdentifiers[Id] = W;
7386 }
7387 }
7388 }
7389 }
7390}
7391
7392/// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in
7393/// it, apply them to D. This is a bit tricky because PD can have attributes
7394/// specified in many different places, and we need to find and apply them all.
7395void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) {
7396 // Apply decl attributes from the DeclSpec if present.
7397 if (!PD.getDeclSpec().getAttributes().empty())
7398 ProcessDeclAttributeList(S, D, PD.getDeclSpec().getAttributes());
7399
7400 // Walk the declarator structure, applying decl attributes that were in a type
7401 // position to the decl itself. This handles cases like:
7402 // int *__attr__(x)** D;
7403 // when X is a decl attribute.
7404 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i)
7405 ProcessDeclAttributeList(S, D, PD.getTypeObject(i).getAttrs(),
7406 /*IncludeCXX11Attributes=*/false);
7407
7408 // Finally, apply any attributes on the decl itself.
7409 ProcessDeclAttributeList(S, D, PD.getAttributes());
7410
7411 // Apply additional attributes specified by '#pragma clang attribute'.
7412 AddPragmaAttributes(S, D);
7413}
7414
7415/// Is the given declaration allowed to use a forbidden type?
7416/// If so, it'll still be annotated with an attribute that makes it
7417/// illegal to actually use.
7418static bool isForbiddenTypeAllowed(Sema &S, Decl *D,
7419 const DelayedDiagnostic &diag,
7420 UnavailableAttr::ImplicitReason &reason) {
7421 // Private ivars are always okay. Unfortunately, people don't
7422 // always properly make their ivars private, even in system headers.
7423 // Plus we need to make fields okay, too.
7424 if (!isa<FieldDecl>(D) && !isa<ObjCPropertyDecl>(D) &&
7425 !isa<FunctionDecl>(D))
7426 return false;
7427
7428 // Silently accept unsupported uses of __weak in both user and system
7429 // declarations when it's been disabled, for ease of integration with
7430 // -fno-objc-arc files. We do have to take some care against attempts
7431 // to define such things; for now, we've only done that for ivars
7432 // and properties.
7433 if ((isa<ObjCIvarDecl>(D) || isa<ObjCPropertyDecl>(D))) {
7434 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled ||
7435 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) {
7436 reason = UnavailableAttr::IR_ForbiddenWeak;
7437 return true;
7438 }
7439 }
7440
7441 // Allow all sorts of things in system headers.
7442 if (S.Context.getSourceManager().isInSystemHeader(D->getLocation())) {
7443 // Currently, all the failures dealt with this way are due to ARC
7444 // restrictions.
7445 reason = UnavailableAttr::IR_ARCForbiddenType;
7446 return true;
7447 }
7448
7449 return false;
7450}
7451
7452/// Handle a delayed forbidden-type diagnostic.
7453static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD,
7454 Decl *D) {
7455 auto Reason = UnavailableAttr::IR_None;
7456 if (D && isForbiddenTypeAllowed(S, D, DD, Reason)) {
7457 assert(Reason && "didn't set reason?")((Reason && "didn't set reason?") ? static_cast<void
> (0) : __assert_fail ("Reason && \"didn't set reason?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 7457, __PRETTY_FUNCTION__))
;
7458 D->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", Reason, DD.Loc));
7459 return;
7460 }
7461 if (S.getLangOpts().ObjCAutoRefCount)
7462 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
7463 // FIXME: we may want to suppress diagnostics for all
7464 // kind of forbidden type messages on unavailable functions.
7465 if (FD->hasAttr<UnavailableAttr>() &&
7466 DD.getForbiddenTypeDiagnostic() ==
7467 diag::err_arc_array_param_no_ownership) {
7468 DD.Triggered = true;
7469 return;
7470 }
7471 }
7472
7473 S.Diag(DD.Loc, DD.getForbiddenTypeDiagnostic())
7474 << DD.getForbiddenTypeOperand() << DD.getForbiddenTypeArgument();
7475 DD.Triggered = true;
7476}
7477
7478static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context,
7479 const Decl *D) {
7480 // Check each AvailabilityAttr to find the one for this platform.
7481 for (const auto *A : D->attrs()) {
7482 if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) {
7483 // FIXME: this is copied from CheckAvailability. We should try to
7484 // de-duplicate.
7485
7486 // Check if this is an App Extension "platform", and if so chop off
7487 // the suffix for matching with the actual platform.
7488 StringRef ActualPlatform = Avail->getPlatform()->getName();
7489 StringRef RealizedPlatform = ActualPlatform;
7490 if (Context.getLangOpts().AppExt) {
7491 size_t suffix = RealizedPlatform.rfind("_app_extension");
7492 if (suffix != StringRef::npos)
7493 RealizedPlatform = RealizedPlatform.slice(0, suffix);
7494 }
7495
7496 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
7497
7498 // Match the platform name.
7499 if (RealizedPlatform == TargetPlatform)
7500 return Avail;
7501 }
7502 }
7503 return nullptr;
7504}
7505
7506/// The diagnostic we should emit for \c D, and the declaration that
7507/// originated it, or \c AR_Available.
7508///
7509/// \param D The declaration to check.
7510/// \param Message If non-null, this will be populated with the message from
7511/// the availability attribute that is selected.
7512/// \param ClassReceiver If we're checking the the method of a class message
7513/// send, the class. Otherwise nullptr.
7514static std::pair<AvailabilityResult, const NamedDecl *>
7515ShouldDiagnoseAvailabilityOfDecl(Sema &S, const NamedDecl *D,
7516 std::string *Message,
7517 ObjCInterfaceDecl *ClassReceiver) {
7518 AvailabilityResult Result = D->getAvailability(Message);
7519
7520 // For typedefs, if the typedef declaration appears available look
7521 // to the underlying type to see if it is more restrictive.
7522 while (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
7523 if (Result == AR_Available) {
7524 if (const auto *TT = TD->getUnderlyingType()->getAs<TagType>()) {
7525 D = TT->getDecl();
7526 Result = D->getAvailability(Message);
7527 continue;
7528 }
7529 }
7530 break;
7531 }
7532
7533 // Forward class declarations get their attributes from their definition.
7534 if (const auto *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
7535 if (IDecl->getDefinition()) {
7536 D = IDecl->getDefinition();
7537 Result = D->getAvailability(Message);
7538 }
7539 }
7540
7541 if (const auto *ECD = dyn_cast<EnumConstantDecl>(D))
7542 if (Result == AR_Available) {
7543 const DeclContext *DC = ECD->getDeclContext();
7544 if (const auto *TheEnumDecl = dyn_cast<EnumDecl>(DC)) {
7545 Result = TheEnumDecl->getAvailability(Message);
7546 D = TheEnumDecl;
7547 }
7548 }
7549
7550 // For +new, infer availability from -init.
7551 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
7552 if (S.NSAPIObj && ClassReceiver) {
7553 ObjCMethodDecl *Init = ClassReceiver->lookupInstanceMethod(
7554 S.NSAPIObj->getInitSelector());
7555 if (Init && Result == AR_Available && MD->isClassMethod() &&
7556 MD->getSelector() == S.NSAPIObj->getNewSelector() &&
7557 MD->definedInNSObject(S.getASTContext())) {
7558 Result = Init->getAvailability(Message);
7559 D = Init;
7560 }
7561 }
7562 }
7563
7564 return {Result, D};
7565}
7566
7567
7568/// whether we should emit a diagnostic for \c K and \c DeclVersion in
7569/// the context of \c Ctx. For example, we should emit an unavailable diagnostic
7570/// in a deprecated context, but not the other way around.
7571static bool
7572ShouldDiagnoseAvailabilityInContext(Sema &S, AvailabilityResult K,
7573 VersionTuple DeclVersion, Decl *Ctx,
7574 const NamedDecl *OffendingDecl) {
7575 assert(K != AR_Available && "Expected an unavailable declaration here!")((K != AR_Available && "Expected an unavailable declaration here!"
) ? static_cast<void> (0) : __assert_fail ("K != AR_Available && \"Expected an unavailable declaration here!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 7575, __PRETTY_FUNCTION__))
;
7576
7577 // Checks if we should emit the availability diagnostic in the context of C.
7578 auto CheckContext = [&](const Decl *C) {
7579 if (K == AR_NotYetIntroduced) {
7580 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C))
7581 if (AA->getIntroduced() >= DeclVersion)
7582 return true;
7583 } else if (K == AR_Deprecated) {
7584 if (C->isDeprecated())
7585 return true;
7586 } else if (K == AR_Unavailable) {
7587 // It is perfectly fine to refer to an 'unavailable' Objective-C method
7588 // when it is referenced from within the @implementation itself. In this
7589 // context, we interpret unavailable as a form of access control.
7590 if (const auto *MD = dyn_cast<ObjCMethodDecl>(OffendingDecl)) {
7591 if (const auto *Impl = dyn_cast<ObjCImplDecl>(C)) {
7592 if (MD->getClassInterface() == Impl->getClassInterface())
7593 return true;
7594 }
7595 }
7596 }
7597
7598 if (C->isUnavailable())
7599 return true;
7600 return false;
7601 };
7602
7603 do {
7604 if (CheckContext(Ctx))
7605 return false;
7606
7607 // An implementation implicitly has the availability of the interface.
7608 // Unless it is "+load" method.
7609 if (const auto *MethodD = dyn_cast<ObjCMethodDecl>(Ctx))
7610 if (MethodD->isClassMethod() &&
7611 MethodD->getSelector().getAsString() == "load")
7612 return true;
7613
7614 if (const auto *CatOrImpl = dyn_cast<ObjCImplDecl>(Ctx)) {
7615 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface())
7616 if (CheckContext(Interface))
7617 return false;
7618 }
7619 // A category implicitly has the availability of the interface.
7620 else if (const auto *CatD = dyn_cast<ObjCCategoryDecl>(Ctx))
7621 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface())
7622 if (CheckContext(Interface))
7623 return false;
7624 } while ((Ctx = cast_or_null<Decl>(Ctx->getDeclContext())));
7625
7626 return true;
7627}
7628
7629static bool
7630shouldDiagnoseAvailabilityByDefault(const ASTContext &Context,
7631 const VersionTuple &DeploymentVersion,
7632 const VersionTuple &DeclVersion) {
7633 const auto &Triple = Context.getTargetInfo().getTriple();
7634 VersionTuple ForceAvailabilityFromVersion;
7635 switch (Triple.getOS()) {
7636 case llvm::Triple::IOS:
7637 case llvm::Triple::TvOS:
7638 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/11);
7639 break;
7640 case llvm::Triple::WatchOS:
7641 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/4);
7642 break;
7643 case llvm::Triple::Darwin:
7644 case llvm::Triple::MacOSX:
7645 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/10, /*Minor=*/13);
7646 break;
7647 default:
7648 // New targets should always warn about availability.
7649 return Triple.getVendor() == llvm::Triple::Apple;
7650 }
7651 return DeploymentVersion >= ForceAvailabilityFromVersion ||
7652 DeclVersion >= ForceAvailabilityFromVersion;
7653}
7654
7655static NamedDecl *findEnclosingDeclToAnnotate(Decl *OrigCtx) {
7656 for (Decl *Ctx = OrigCtx; Ctx;
7657 Ctx = cast_or_null<Decl>(Ctx->getDeclContext())) {
7658 if (isa<TagDecl>(Ctx) || isa<FunctionDecl>(Ctx) || isa<ObjCMethodDecl>(Ctx))
7659 return cast<NamedDecl>(Ctx);
7660 if (auto *CD = dyn_cast<ObjCContainerDecl>(Ctx)) {
7661 if (auto *Imp = dyn_cast<ObjCImplDecl>(Ctx))
7662 return Imp->getClassInterface();
7663 return CD;
7664 }
7665 }
7666
7667 return dyn_cast<NamedDecl>(OrigCtx);
7668}
7669
7670namespace {
7671
7672struct AttributeInsertion {
7673 StringRef Prefix;
7674 SourceLocation Loc;
7675 StringRef Suffix;
7676
7677 static AttributeInsertion createInsertionAfter(const NamedDecl *D) {
7678 return {" ", D->getEndLoc(), ""};
7679 }
7680 static AttributeInsertion createInsertionAfter(SourceLocation Loc) {
7681 return {" ", Loc, ""};
7682 }
7683 static AttributeInsertion createInsertionBefore(const NamedDecl *D) {
7684 return {"", D->getBeginLoc(), "\n"};
7685 }
7686};
7687
7688} // end anonymous namespace
7689
7690/// Tries to parse a string as ObjC method name.
7691///
7692/// \param Name The string to parse. Expected to originate from availability
7693/// attribute argument.
7694/// \param SlotNames The vector that will be populated with slot names. In case
7695/// of unsuccessful parsing can contain invalid data.
7696/// \returns A number of method parameters if parsing was successful, None
7697/// otherwise.
7698static Optional<unsigned>
7699tryParseObjCMethodName(StringRef Name, SmallVectorImpl<StringRef> &SlotNames,
7700 const LangOptions &LangOpts) {
7701 // Accept replacements starting with - or + as valid ObjC method names.
7702 if (!Name.empty() && (Name.front() == '-' || Name.front() == '+'))
7703 Name = Name.drop_front(1);
7704 if (Name.empty())
7705 return None;
7706 Name.split(SlotNames, ':');
7707 unsigned NumParams;
7708 if (Name.back() == ':') {
7709 // Remove an empty string at the end that doesn't represent any slot.
7710 SlotNames.pop_back();
7711 NumParams = SlotNames.size();
7712 } else {
7713 if (SlotNames.size() != 1)
7714 // Not a valid method name, just a colon-separated string.
7715 return None;
7716 NumParams = 0;
7717 }
7718 // Verify all slot names are valid.
7719 bool AllowDollar = LangOpts.DollarIdents;
7720 for (StringRef S : SlotNames) {
7721 if (S.empty())
7722 continue;
7723 if (!isValidIdentifier(S, AllowDollar))
7724 return None;
7725 }
7726 return NumParams;
7727}
7728
7729/// Returns a source location in which it's appropriate to insert a new
7730/// attribute for the given declaration \D.
7731static Optional<AttributeInsertion>
7732createAttributeInsertion(const NamedDecl *D, const SourceManager &SM,
7733 const LangOptions &LangOpts) {
7734 if (isa<ObjCPropertyDecl>(D))
7735 return AttributeInsertion::createInsertionAfter(D);
7736 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
7737 if (MD->hasBody())
7738 return None;
7739 return AttributeInsertion::createInsertionAfter(D);
7740 }
7741 if (const auto *TD = dyn_cast<TagDecl>(D)) {
7742 SourceLocation Loc =
7743 Lexer::getLocForEndOfToken(TD->getInnerLocStart(), 0, SM, LangOpts);
7744 if (Loc.isInvalid())
7745 return None;
7746 // Insert after the 'struct'/whatever keyword.
7747 return AttributeInsertion::createInsertionAfter(Loc);
7748 }
7749 return AttributeInsertion::createInsertionBefore(D);
7750}
7751
7752/// Actually emit an availability diagnostic for a reference to an unavailable
7753/// decl.
7754///
7755/// \param Ctx The context that the reference occurred in
7756/// \param ReferringDecl The exact declaration that was referenced.
7757/// \param OffendingDecl A related decl to \c ReferringDecl that has an
7758/// availability attribute corresponding to \c K attached to it. Note that this
7759/// may not be the same as ReferringDecl, i.e. if an EnumDecl is annotated and
7760/// we refer to a member EnumConstantDecl, ReferringDecl is the EnumConstantDecl
7761/// and OffendingDecl is the EnumDecl.
7762static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K,
7763 Decl *Ctx, const NamedDecl *ReferringDecl,
7764 const NamedDecl *OffendingDecl,
7765 StringRef Message,
7766 ArrayRef<SourceLocation> Locs,
7767 const ObjCInterfaceDecl *UnknownObjCClass,
7768 const ObjCPropertyDecl *ObjCProperty,
7769 bool ObjCPropertyAccess) {
7770 // Diagnostics for deprecated or unavailable.
7771 unsigned diag, diag_message, diag_fwdclass_message;
7772 unsigned diag_available_here = diag::note_availability_specified_here;
7773 SourceLocation NoteLocation = OffendingDecl->getLocation();
7774
7775 // Matches 'diag::note_property_attribute' options.
7776 unsigned property_note_select;
7777
7778 // Matches diag::note_availability_specified_here.
7779 unsigned available_here_select_kind;
7780
7781 VersionTuple DeclVersion;
7782 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, OffendingDecl))
7783 DeclVersion = AA->getIntroduced();
7784
7785 if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx,
7786 OffendingDecl))
7787 return;
7788
7789 SourceLocation Loc = Locs.front();
7790
7791 // The declaration can have multiple availability attributes, we are looking
7792 // at one of them.
7793 const AvailabilityAttr *A = getAttrForPlatform(S.Context, OffendingDecl);
7794 if (A && A->isInherited()) {
7795 for (const Decl *Redecl = OffendingDecl->getMostRecentDecl(); Redecl;
7796 Redecl = Redecl->getPreviousDecl()) {
7797 const AvailabilityAttr *AForRedecl =
7798 getAttrForPlatform(S.Context, Redecl);
7799 if (AForRedecl && !AForRedecl->isInherited()) {
7800 // If D is a declaration with inherited attributes, the note should
7801 // point to the declaration with actual attributes.
7802 NoteLocation = Redecl->getLocation();
7803 break;
7804 }
7805 }
7806 }
7807
7808 switch (K) {
7809 case AR_NotYetIntroduced: {
7810 // We would like to emit the diagnostic even if -Wunguarded-availability is
7811 // not specified for deployment targets >= to iOS 11 or equivalent or
7812 // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or
7813 // later.
7814 const AvailabilityAttr *AA =
7815 getAttrForPlatform(S.getASTContext(), OffendingDecl);
7816 VersionTuple Introduced = AA->getIntroduced();
7817
7818 bool UseNewWarning = shouldDiagnoseAvailabilityByDefault(
7819 S.Context, S.Context.getTargetInfo().getPlatformMinVersion(),
7820 Introduced);
7821 unsigned Warning = UseNewWarning ? diag::warn_unguarded_availability_new
7822 : diag::warn_unguarded_availability;
7823
7824 std::string PlatformName = AvailabilityAttr::getPrettyPlatformName(
7825 S.getASTContext().getTargetInfo().getPlatformName());
7826
7827 S.Diag(Loc, Warning) << OffendingDecl << PlatformName
7828 << Introduced.getAsString();
7829
7830 S.Diag(OffendingDecl->getLocation(),
7831 diag::note_partial_availability_specified_here)
7832 << OffendingDecl << PlatformName << Introduced.getAsString()
7833 << S.Context.getTargetInfo().getPlatformMinVersion().getAsString();
7834
7835 if (const auto *Enclosing = findEnclosingDeclToAnnotate(Ctx)) {
7836 if (const auto *TD = dyn_cast<TagDecl>(Enclosing))
7837 if (TD->getDeclName().isEmpty()) {
7838 S.Diag(TD->getLocation(),
7839 diag::note_decl_unguarded_availability_silence)
7840 << /*Anonymous*/ 1 << TD->getKindName();
7841 return;
7842 }
7843 auto FixitNoteDiag =
7844 S.Diag(Enclosing->getLocation(),
7845 diag::note_decl_unguarded_availability_silence)
7846 << /*Named*/ 0 << Enclosing;
7847 // Don't offer a fixit for declarations with availability attributes.
7848 if (Enclosing->hasAttr<AvailabilityAttr>())
7849 return;
7850 if (!S.getPreprocessor().isMacroDefined("API_AVAILABLE"))
7851 return;
7852 Optional<AttributeInsertion> Insertion = createAttributeInsertion(
7853 Enclosing, S.getSourceManager(), S.getLangOpts());
7854 if (!Insertion)
7855 return;
7856 std::string PlatformName =
7857 AvailabilityAttr::getPlatformNameSourceSpelling(
7858 S.getASTContext().getTargetInfo().getPlatformName())
7859 .lower();
7860 std::string Introduced =
7861 OffendingDecl->getVersionIntroduced().getAsString();
7862 FixitNoteDiag << FixItHint::CreateInsertion(
7863 Insertion->Loc,
7864 (llvm::Twine(Insertion->Prefix) + "API_AVAILABLE(" + PlatformName +
7865 "(" + Introduced + "))" + Insertion->Suffix)
7866 .str());
7867 }
7868 return;
7869 }
7870 case AR_Deprecated:
7871 diag = !ObjCPropertyAccess ? diag::warn_deprecated
7872 : diag::warn_property_method_deprecated;
7873 diag_message = diag::warn_deprecated_message;
7874 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message;
7875 property_note_select = /* deprecated */ 0;
7876 available_here_select_kind = /* deprecated */ 2;
7877 if (const auto *AL = OffendingDecl->getAttr<DeprecatedAttr>())
7878 NoteLocation = AL->getLocation();
7879 break;
7880
7881 case AR_Unavailable:
7882 diag = !ObjCPropertyAccess ? diag::err_unavailable
7883 : diag::err_property_method_unavailable;
7884 diag_message = diag::err_unavailable_message;
7885 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message;
7886 property_note_select = /* unavailable */ 1;
7887 available_here_select_kind = /* unavailable */ 0;
7888
7889 if (auto AL = OffendingDecl->getAttr<UnavailableAttr>()) {
7890 if (AL->isImplicit() && AL->getImplicitReason()) {
7891 // Most of these failures are due to extra restrictions in ARC;
7892 // reflect that in the primary diagnostic when applicable.
7893 auto flagARCError = [&] {
7894 if (S.getLangOpts().ObjCAutoRefCount &&
7895 S.getSourceManager().isInSystemHeader(
7896 OffendingDecl->getLocation()))
7897 diag = diag::err_unavailable_in_arc;
7898 };
7899
7900 switch (AL->getImplicitReason()) {
7901 case UnavailableAttr::IR_None: break;
7902
7903 case UnavailableAttr::IR_ARCForbiddenType:
7904 flagARCError();
7905 diag_available_here = diag::note_arc_forbidden_type;
7906 break;
7907
7908 case UnavailableAttr::IR_ForbiddenWeak:
7909 if (S.getLangOpts().ObjCWeakRuntime)
7910 diag_available_here = diag::note_arc_weak_disabled;
7911 else
7912 diag_available_here = diag::note_arc_weak_no_runtime;
7913 break;
7914
7915 case UnavailableAttr::IR_ARCForbiddenConversion:
7916 flagARCError();
7917 diag_available_here = diag::note_performs_forbidden_arc_conversion;
7918 break;
7919
7920 case UnavailableAttr::IR_ARCInitReturnsUnrelated:
7921 flagARCError();
7922 diag_available_here = diag::note_arc_init_returns_unrelated;
7923 break;
7924
7925 case UnavailableAttr::IR_ARCFieldWithOwnership:
7926 flagARCError();
7927 diag_available_here = diag::note_arc_field_with_ownership;
7928 break;
7929 }
7930 }
7931 }
7932 break;
7933
7934 case AR_Available:
7935 llvm_unreachable("Warning for availability of available declaration?")::llvm::llvm_unreachable_internal("Warning for availability of available declaration?"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 7935)
;
7936 }
7937
7938 SmallVector<FixItHint, 12> FixIts;
7939 if (K == AR_Deprecated) {
7940 StringRef Replacement;
7941 if (auto AL = OffendingDecl->getAttr<DeprecatedAttr>())
7942 Replacement = AL->getReplacement();
7943 if (auto AL = getAttrForPlatform(S.Context, OffendingDecl))
7944 Replacement = AL->getReplacement();
7945
7946 CharSourceRange UseRange;
7947 if (!Replacement.empty())
7948 UseRange =
7949 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
7950 if (UseRange.isValid()) {
7951 if (const auto *MethodDecl = dyn_cast<ObjCMethodDecl>(ReferringDecl)) {
7952 Selector Sel = MethodDecl->getSelector();
7953 SmallVector<StringRef, 12> SelectorSlotNames;
7954 Optional<unsigned> NumParams = tryParseObjCMethodName(
7955 Replacement, SelectorSlotNames, S.getLangOpts());
7956 if (NumParams && NumParams.getValue() == Sel.getNumArgs()) {
7957 assert(SelectorSlotNames.size() == Locs.size())((SelectorSlotNames.size() == Locs.size()) ? static_cast<void
> (0) : __assert_fail ("SelectorSlotNames.size() == Locs.size()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 7957, __PRETTY_FUNCTION__))
;
7958 for (unsigned I = 0; I < Locs.size(); ++I) {
7959 if (!Sel.getNameForSlot(I).empty()) {
7960 CharSourceRange NameRange = CharSourceRange::getCharRange(
7961 Locs[I], S.getLocForEndOfToken(Locs[I]));
7962 FixIts.push_back(FixItHint::CreateReplacement(
7963 NameRange, SelectorSlotNames[I]));
7964 } else
7965 FixIts.push_back(
7966 FixItHint::CreateInsertion(Locs[I], SelectorSlotNames[I]));
7967 }
7968 } else
7969 FixIts.push_back(FixItHint::CreateReplacement(UseRange, Replacement));
7970 } else
7971 FixIts.push_back(FixItHint::CreateReplacement(UseRange, Replacement));
7972 }
7973 }
7974
7975 if (!Message.empty()) {
7976 S.Diag(Loc, diag_message) << ReferringDecl << Message << FixIts;
7977 if (ObjCProperty)
7978 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
7979 << ObjCProperty->getDeclName() << property_note_select;
7980 } else if (!UnknownObjCClass) {
7981 S.Diag(Loc, diag) << ReferringDecl << FixIts;
7982 if (ObjCProperty)
7983 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute)
7984 << ObjCProperty->getDeclName() << property_note_select;
7985 } else {
7986 S.Diag(Loc, diag_fwdclass_message) << ReferringDecl << FixIts;
7987 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class);
7988 }
7989
7990 S.Diag(NoteLocation, diag_available_here)
7991 << OffendingDecl << available_here_select_kind;
7992}
7993
7994static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD,
7995 Decl *Ctx) {
7996 assert(DD.Kind == DelayedDiagnostic::Availability &&((DD.Kind == DelayedDiagnostic::Availability && "Expected an availability diagnostic here"
) ? static_cast<void> (0) : __assert_fail ("DD.Kind == DelayedDiagnostic::Availability && \"Expected an availability diagnostic here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 7997, __PRETTY_FUNCTION__))
7997 "Expected an availability diagnostic here")((DD.Kind == DelayedDiagnostic::Availability && "Expected an availability diagnostic here"
) ? static_cast<void> (0) : __assert_fail ("DD.Kind == DelayedDiagnostic::Availability && \"Expected an availability diagnostic here\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 7997, __PRETTY_FUNCTION__))
;
7998
7999 DD.Triggered = true;
8000 DoEmitAvailabilityWarning(
8001 S, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityReferringDecl(),
8002 DD.getAvailabilityOffendingDecl(), DD.getAvailabilityMessage(),
8003 DD.getAvailabilitySelectorLocs(), DD.getUnknownObjCClass(),
8004 DD.getObjCProperty(), false);
8005}
8006
8007void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) {
8008 assert(DelayedDiagnostics.getCurrentPool())((DelayedDiagnostics.getCurrentPool()) ? static_cast<void>
(0) : __assert_fail ("DelayedDiagnostics.getCurrentPool()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 8008, __PRETTY_FUNCTION__))
;
8009 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool();
8010 DelayedDiagnostics.popWithoutEmitting(state);
8011
8012 // When delaying diagnostics to run in the context of a parsed
8013 // declaration, we only want to actually emit anything if parsing
8014 // succeeds.
8015 if (!decl) return;
8016
8017 // We emit all the active diagnostics in this pool or any of its
8018 // parents. In general, we'll get one pool for the decl spec
8019 // and a child pool for each declarator; in a decl group like:
8020 // deprecated_typedef foo, *bar, baz();
8021 // only the declarator pops will be passed decls. This is correct;
8022 // we really do need to consider delayed diagnostics from the decl spec
8023 // for each of the different declarations.
8024 const DelayedDiagnosticPool *pool = &poppedPool;
8025 do {
8026 bool AnyAccessFailures = false;
8027 for (DelayedDiagnosticPool::pool_iterator
8028 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) {
8029 // This const_cast is a bit lame. Really, Triggered should be mutable.
8030 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i);
8031 if (diag.Triggered)
8032 continue;
8033
8034 switch (diag.Kind) {
8035 case DelayedDiagnostic::Availability:
8036 // Don't bother giving deprecation/unavailable diagnostics if
8037 // the decl is invalid.
8038 if (!decl->isInvalidDecl())
8039 handleDelayedAvailabilityCheck(*this, diag, decl);
8040 break;
8041
8042 case DelayedDiagnostic::Access:
8043 // Only produce one access control diagnostic for a structured binding
8044 // declaration: we don't need to tell the user that all the fields are
8045 // inaccessible one at a time.
8046 if (AnyAccessFailures && isa<DecompositionDecl>(decl))
8047 continue;
8048 HandleDelayedAccessCheck(diag, decl);
8049 if (diag.Triggered)
8050 AnyAccessFailures = true;
8051 break;
8052
8053 case DelayedDiagnostic::ForbiddenType:
8054 handleDelayedForbiddenType(*this, diag, decl);
8055 break;
8056 }
8057 }
8058 } while ((pool = pool->getParent()));
8059}
8060
8061/// Given a set of delayed diagnostics, re-emit them as if they had
8062/// been delayed in the current context instead of in the given pool.
8063/// Essentially, this just moves them to the current pool.
8064void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) {
8065 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool();
8066 assert(curPool && "re-emitting in undelayed context not supported")((curPool && "re-emitting in undelayed context not supported"
) ? static_cast<void> (0) : __assert_fail ("curPool && \"re-emitting in undelayed context not supported\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 8066, __PRETTY_FUNCTION__))
;
8067 curPool->steal(pool);
8068}
8069
8070static void EmitAvailabilityWarning(Sema &S, AvailabilityResult AR,
8071 const NamedDecl *ReferringDecl,
8072 const NamedDecl *OffendingDecl,
8073 StringRef Message,
8074 ArrayRef<SourceLocation> Locs,
8075 const ObjCInterfaceDecl *UnknownObjCClass,
8076 const ObjCPropertyDecl *ObjCProperty,
8077 bool ObjCPropertyAccess) {
8078 // Delay if we're currently parsing a declaration.
8079 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
8080 S.DelayedDiagnostics.add(
8081 DelayedDiagnostic::makeAvailability(
8082 AR, Locs, ReferringDecl, OffendingDecl, UnknownObjCClass,
8083 ObjCProperty, Message, ObjCPropertyAccess));
8084 return;
8085 }
8086
8087 Decl *Ctx = cast<Decl>(S.getCurLexicalContext());
8088 DoEmitAvailabilityWarning(S, AR, Ctx, ReferringDecl, OffendingDecl,
8089 Message, Locs, UnknownObjCClass, ObjCProperty,
8090 ObjCPropertyAccess);
8091}
8092
8093namespace {
8094
8095/// Returns true if the given statement can be a body-like child of \p Parent.
8096bool isBodyLikeChildStmt(const Stmt *S, const Stmt *Parent) {
8097 switch (Parent->getStmtClass()) {
8098 case Stmt::IfStmtClass:
8099 return cast<IfStmt>(Parent)->getThen() == S ||
8100 cast<IfStmt>(Parent)->getElse() == S;
8101 case Stmt::WhileStmtClass:
8102 return cast<WhileStmt>(Parent)->getBody() == S;
8103 case Stmt::DoStmtClass:
8104 return cast<DoStmt>(Parent)->getBody() == S;
8105 case Stmt::ForStmtClass:
8106 return cast<ForStmt>(Parent)->getBody() == S;
8107 case Stmt::CXXForRangeStmtClass:
8108 return cast<CXXForRangeStmt>(Parent)->getBody() == S;
8109 case Stmt::ObjCForCollectionStmtClass:
8110 return cast<ObjCForCollectionStmt>(Parent)->getBody() == S;
8111 case Stmt::CaseStmtClass:
8112 case Stmt::DefaultStmtClass:
8113 return cast<SwitchCase>(Parent)->getSubStmt() == S;
8114 default:
8115 return false;
8116 }
8117}
8118
8119class StmtUSEFinder : public RecursiveASTVisitor<StmtUSEFinder> {
8120 const Stmt *Target;
8121
8122public:
8123 bool VisitStmt(Stmt *S) { return S != Target; }
8124
8125 /// Returns true if the given statement is present in the given declaration.
8126 static bool isContained(const Stmt *Target, const Decl *D) {
8127 StmtUSEFinder Visitor;
8128 Visitor.Target = Target;
8129 return !Visitor.TraverseDecl(const_cast<Decl *>(D));
8130 }
8131};
8132
8133/// Traverses the AST and finds the last statement that used a given
8134/// declaration.
8135class LastDeclUSEFinder : public RecursiveASTVisitor<LastDeclUSEFinder> {
8136 const Decl *D;
8137
8138public:
8139 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
8140 if (DRE->getDecl() == D)
8141 return false;
8142 return true;
8143 }
8144
8145 static const Stmt *findLastStmtThatUsesDecl(const Decl *D,
8146 const CompoundStmt *Scope) {
8147 LastDeclUSEFinder Visitor;
8148 Visitor.D = D;
8149 for (auto I = Scope->body_rbegin(), E = Scope->body_rend(); I != E; ++I) {
8150 const Stmt *S = *I;
8151 if (!Visitor.TraverseStmt(const_cast<Stmt *>(S)))
8152 return S;
8153 }
8154 return nullptr;
8155 }
8156};
8157
8158/// This class implements -Wunguarded-availability.
8159///
8160/// This is done with a traversal of the AST of a function that makes reference
8161/// to a partially available declaration. Whenever we encounter an \c if of the
8162/// form: \c if(@available(...)), we use the version from the condition to visit
8163/// the then statement.
8164class DiagnoseUnguardedAvailability
8165 : public RecursiveASTVisitor<DiagnoseUnguardedAvailability> {
8166 typedef RecursiveASTVisitor<DiagnoseUnguardedAvailability> Base;
8167
8168 Sema &SemaRef;
8169 Decl *Ctx;
8170
8171 /// Stack of potentially nested 'if (@available(...))'s.
8172 SmallVector<VersionTuple, 8> AvailabilityStack;
8173 SmallVector<const Stmt *, 16> StmtStack;
8174
8175 void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range,
8176 ObjCInterfaceDecl *ClassReceiver = nullptr);
8177
8178public:
8179 DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx)
8180 : SemaRef(SemaRef), Ctx(Ctx) {
8181 AvailabilityStack.push_back(
8182 SemaRef.Context.getTargetInfo().getPlatformMinVersion());
8183 }
8184
8185 bool TraverseDecl(Decl *D) {
8186 // Avoid visiting nested functions to prevent duplicate warnings.
8187 if (!D || isa<FunctionDecl>(D))
8188 return true;
8189 return Base::TraverseDecl(D);
8190 }
8191
8192 bool TraverseStmt(Stmt *S) {
8193 if (!S)
8194 return true;
8195 StmtStack.push_back(S);
8196 bool Result = Base::TraverseStmt(S);
8197 StmtStack.pop_back();
8198 return Result;
8199 }
8200
8201 void IssueDiagnostics(Stmt *S) { TraverseStmt(S); }
8202
8203 bool TraverseIfStmt(IfStmt *If);
8204
8205 bool TraverseLambdaExpr(LambdaExpr *E) { return true; }
8206
8207 // for 'case X:' statements, don't bother looking at the 'X'; it can't lead
8208 // to any useful diagnostics.
8209 bool TraverseCaseStmt(CaseStmt *CS) { return TraverseStmt(CS->getSubStmt()); }
8210
8211 bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *PRE) {
8212 if (PRE->isClassReceiver())
8213 DiagnoseDeclAvailability(PRE->getClassReceiver(), PRE->getReceiverLocation());
8214 return true;
8215 }
8216
8217 bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) {
8218 if (ObjCMethodDecl *D = Msg->getMethodDecl()) {
8219 ObjCInterfaceDecl *ID = nullptr;
8220 QualType ReceiverTy = Msg->getClassReceiver();
8221 if (!ReceiverTy.isNull() && ReceiverTy->getAsObjCInterfaceType())
8222 ID = ReceiverTy->getAsObjCInterfaceType()->getInterface();
8223
8224 DiagnoseDeclAvailability(
8225 D, SourceRange(Msg->getSelectorStartLoc(), Msg->getEndLoc()), ID);
8226 }
8227 return true;
8228 }
8229
8230 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
8231 DiagnoseDeclAvailability(DRE->getDecl(),
8232 SourceRange(DRE->getBeginLoc(), DRE->getEndLoc()));
8233 return true;
8234 }
8235
8236 bool VisitMemberExpr(MemberExpr *ME) {
8237 DiagnoseDeclAvailability(ME->getMemberDecl(),
8238 SourceRange(ME->getBeginLoc(), ME->getEndLoc()));
8239 return true;
8240 }
8241
8242 bool VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
8243 SemaRef.Diag(E->getBeginLoc(), diag::warn_at_available_unchecked_use)
8244 << (!SemaRef.getLangOpts().ObjC);
8245 return true;
8246 }
8247
8248 bool VisitTypeLoc(TypeLoc Ty);
8249};
8250
8251void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability(
8252 NamedDecl *D, SourceRange Range, ObjCInterfaceDecl *ReceiverClass) {
8253 AvailabilityResult Result;
8254 const NamedDecl *OffendingDecl;
8255 std::tie(Result, OffendingDecl) =
8256 ShouldDiagnoseAvailabilityOfDecl(SemaRef, D, nullptr, ReceiverClass);
8257 if (Result != AR_Available) {
8258 // All other diagnostic kinds have already been handled in
8259 // DiagnoseAvailabilityOfDecl.
8260 if (Result != AR_NotYetIntroduced)
8261 return;
8262
8263 const AvailabilityAttr *AA =
8264 getAttrForPlatform(SemaRef.getASTContext(), OffendingDecl);
8265 VersionTuple Introduced = AA->getIntroduced();
8266
8267 if (AvailabilityStack.back() >= Introduced)
8268 return;
8269
8270 // If the context of this function is less available than D, we should not
8271 // emit a diagnostic.
8272 if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced, Ctx,
8273 OffendingDecl))
8274 return;
8275
8276 // We would like to emit the diagnostic even if -Wunguarded-availability is
8277 // not specified for deployment targets >= to iOS 11 or equivalent or
8278 // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or
8279 // later.
8280 unsigned DiagKind =
8281 shouldDiagnoseAvailabilityByDefault(
8282 SemaRef.Context,
8283 SemaRef.Context.getTargetInfo().getPlatformMinVersion(), Introduced)
8284 ? diag::warn_unguarded_availability_new
8285 : diag::warn_unguarded_availability;
8286
8287 std::string PlatformName = AvailabilityAttr::getPrettyPlatformName(
8288 SemaRef.getASTContext().getTargetInfo().getPlatformName());
8289
8290 SemaRef.Diag(Range.getBegin(), DiagKind)
8291 << Range << D << PlatformName << Introduced.getAsString();
8292
8293 SemaRef.Diag(OffendingDecl->getLocation(),
8294 diag::note_partial_availability_specified_here)
8295 << OffendingDecl << PlatformName << Introduced.getAsString()
8296 << SemaRef.Context.getTargetInfo()
8297 .getPlatformMinVersion()
8298 .getAsString();
8299
8300 auto FixitDiag =
8301 SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence)
8302 << Range << D
8303 << (SemaRef.getLangOpts().ObjC ? /*@available*/ 0
8304 : /*__builtin_available*/ 1);
8305
8306 // Find the statement which should be enclosed in the if @available check.
8307 if (StmtStack.empty())
8308 return;
8309 const Stmt *StmtOfUse = StmtStack.back();
8310 const CompoundStmt *Scope = nullptr;
8311 for (const Stmt *S : llvm::reverse(StmtStack)) {
8312 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
8313 Scope = CS;
8314 break;
8315 }
8316 if (isBodyLikeChildStmt(StmtOfUse, S)) {
8317 // The declaration won't be seen outside of the statement, so we don't
8318 // have to wrap the uses of any declared variables in if (@available).
8319 // Therefore we can avoid setting Scope here.
8320 break;
8321 }
8322 StmtOfUse = S;
8323 }
8324 const Stmt *LastStmtOfUse = nullptr;
8325 if (isa<DeclStmt>(StmtOfUse) && Scope) {
8326 for (const Decl *D : cast<DeclStmt>(StmtOfUse)->decls()) {
8327 if (StmtUSEFinder::isContained(StmtStack.back(), D)) {
8328 LastStmtOfUse = LastDeclUSEFinder::findLastStmtThatUsesDecl(D, Scope);
8329 break;
8330 }
8331 }
8332 }
8333
8334 const SourceManager &SM = SemaRef.getSourceManager();
8335 SourceLocation IfInsertionLoc =
8336 SM.getExpansionLoc(StmtOfUse->getBeginLoc());
8337 SourceLocation StmtEndLoc =
8338 SM.getExpansionRange(
8339 (LastStmtOfUse ? LastStmtOfUse : StmtOfUse)->getEndLoc())
8340 .getEnd();
8341 if (SM.getFileID(IfInsertionLoc) != SM.getFileID(StmtEndLoc))
8342 return;
8343
8344 StringRef Indentation = Lexer::getIndentationForLine(IfInsertionLoc, SM);
8345 const char *ExtraIndentation = " ";
8346 std::string FixItString;
8347 llvm::raw_string_ostream FixItOS(FixItString);
8348 FixItOS << "if (" << (SemaRef.getLangOpts().ObjC ? "@available"
8349 : "__builtin_available")
8350 << "("
8351 << AvailabilityAttr::getPlatformNameSourceSpelling(
8352 SemaRef.getASTContext().getTargetInfo().getPlatformName())
8353 << " " << Introduced.getAsString() << ", *)) {\n"
8354 << Indentation << ExtraIndentation;
8355 FixitDiag << FixItHint::CreateInsertion(IfInsertionLoc, FixItOS.str());
8356 SourceLocation ElseInsertionLoc = Lexer::findLocationAfterToken(
8357 StmtEndLoc, tok::semi, SM, SemaRef.getLangOpts(),
8358 /*SkipTrailingWhitespaceAndNewLine=*/false);
8359 if (ElseInsertionLoc.isInvalid())
8360 ElseInsertionLoc =
8361 Lexer::getLocForEndOfToken(StmtEndLoc, 0, SM, SemaRef.getLangOpts());
8362 FixItOS.str().clear();
8363 FixItOS << "\n"
8364 << Indentation << "} else {\n"
8365 << Indentation << ExtraIndentation
8366 << "// Fallback on earlier versions\n"
8367 << Indentation << "}";
8368 FixitDiag << FixItHint::CreateInsertion(ElseInsertionLoc, FixItOS.str());
8369 }
8370}
8371
8372bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) {
8373 const Type *TyPtr = Ty.getTypePtr();
8374 SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()};
8375
8376 if (Range.isInvalid())
8377 return true;
8378
8379 if (const auto *TT = dyn_cast<TagType>(TyPtr)) {
8380 TagDecl *TD = TT->getDecl();
8381 DiagnoseDeclAvailability(TD, Range);
8382
8383 } else if (const auto *TD = dyn_cast<TypedefType>(TyPtr)) {
8384 TypedefNameDecl *D = TD->getDecl();
8385 DiagnoseDeclAvailability(D, Range);
8386
8387 } else if (const auto *ObjCO = dyn_cast<ObjCObjectType>(TyPtr)) {
8388 if (NamedDecl *D = ObjCO->getInterface())
8389 DiagnoseDeclAvailability(D, Range);
8390 }
8391
8392 return true;
8393}
8394
8395bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) {
8396 VersionTuple CondVersion;
8397 if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) {
8398 CondVersion = E->getVersion();
8399
8400 // If we're using the '*' case here or if this check is redundant, then we
8401 // use the enclosing version to check both branches.
8402 if (CondVersion.empty() || CondVersion <= AvailabilityStack.back())
8403 return TraverseStmt(If->getThen()) && TraverseStmt(If->getElse());
8404 } else {
8405 // This isn't an availability checking 'if', we can just continue.
8406 return Base::TraverseIfStmt(If);
8407 }
8408
8409 AvailabilityStack.push_back(CondVersion);
8410 bool ShouldContinue = TraverseStmt(If->getThen());
8411 AvailabilityStack.pop_back();
8412
8413 return ShouldContinue && TraverseStmt(If->getElse());
8414}
8415
8416} // end anonymous namespace
8417
8418void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) {
8419 Stmt *Body = nullptr;
8420
8421 if (auto *FD = D->getAsFunction()) {
8422 // FIXME: We only examine the pattern decl for availability violations now,
8423 // but we should also examine instantiated templates.
8424 if (FD->isTemplateInstantiation())
8425 return;
8426
8427 Body = FD->getBody();
8428 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
8429 Body = MD->getBody();
8430 else if (auto *BD = dyn_cast<BlockDecl>(D))
8431 Body = BD->getBody();
8432
8433 assert(Body && "Need a body here!")((Body && "Need a body here!") ? static_cast<void>
(0) : __assert_fail ("Body && \"Need a body here!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaDeclAttr.cpp"
, 8433, __PRETTY_FUNCTION__))
;
8434
8435 DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body);
8436}
8437
8438void Sema::DiagnoseAvailabilityOfDecl(NamedDecl *D,
8439 ArrayRef<SourceLocation> Locs,
8440 const ObjCInterfaceDecl *UnknownObjCClass,
8441 bool ObjCPropertyAccess,
8442 bool AvoidPartialAvailabilityChecks,
8443 ObjCInterfaceDecl *ClassReceiver) {
8444 std::string Message;
8445 AvailabilityResult Result;
8446 const NamedDecl* OffendingDecl;
8447 // See if this declaration is unavailable, deprecated, or partial.
8448 std::tie(Result, OffendingDecl) =
8449 ShouldDiagnoseAvailabilityOfDecl(*this, D, &Message, ClassReceiver);
8450 if (Result == AR_Available)
8451 return;
8452
8453 if (Result == AR_NotYetIntroduced) {
8454 if (AvoidPartialAvailabilityChecks)
8455 return;
8456
8457 // We need to know the @available context in the current function to
8458 // diagnose this use, let DiagnoseUnguardedAvailabilityViolations do that
8459 // when we're done parsing the current function.
8460 if (getCurFunctionOrMethodDecl()) {
8461 getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
8462 return;
8463 } else if (getCurBlock() || getCurLambda()) {
8464 getCurFunction()->HasPotentialAvailabilityViolations = true;
8465 return;
8466 }
8467 }
8468
8469 const ObjCPropertyDecl *ObjCPDecl = nullptr;
8470 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
8471 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
8472 AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
8473 if (PDeclResult == Result)
8474 ObjCPDecl = PD;
8475 }
8476 }
8477
8478 EmitAvailabilityWarning(*this, Result, D, OffendingDecl, Message, Locs,
8479 UnknownObjCClass, ObjCPDecl, ObjCPropertyAccess);
8480}

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h

1//======- ParsedAttr.h - Parsed attribute sets ------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the ParsedAttr class, which is used to collect
10// parsed attributes.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_ATTRIBUTELIST_H
15#define LLVM_CLANG_SEMA_ATTRIBUTELIST_H
16
17#include "clang/Basic/AttrSubjectMatchRules.h"
18#include "clang/Basic/AttributeCommonInfo.h"
19#include "clang/Basic/Diagnostic.h"
20#include "clang/Basic/SourceLocation.h"
21#include "clang/Basic/TargetInfo.h"
22#include "clang/Sema/Ownership.h"
23#include "llvm/ADT/PointerUnion.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/TinyPtrVector.h"
26#include "llvm/Support/Allocator.h"
27#include "llvm/Support/VersionTuple.h"
28#include <cassert>
29#include <cstddef>
30#include <cstring>
31#include <utility>
32
33namespace clang {
34
35class ASTContext;
36class Decl;
37class Expr;
38class IdentifierInfo;
39class LangOptions;
40
41/// Represents information about a change in availability for
42/// an entity, which is part of the encoding of the 'availability'
43/// attribute.
44struct AvailabilityChange {
45 /// The location of the keyword indicating the kind of change.
46 SourceLocation KeywordLoc;
47
48 /// The version number at which the change occurred.
49 VersionTuple Version;
50
51 /// The source range covering the version number.
52 SourceRange VersionRange;
53
54 /// Determine whether this availability change is valid.
55 bool isValid() const { return !Version.empty(); }
56};
57
58namespace detail {
59enum AvailabilitySlot {
60 IntroducedSlot, DeprecatedSlot, ObsoletedSlot, NumAvailabilitySlots
61};
62
63/// Describes the trailing object for Availability attribute in ParsedAttr.
64struct AvailabilityData {
65 AvailabilityChange Changes[NumAvailabilitySlots];
66 SourceLocation StrictLoc;
67 const Expr *Replacement;
68
69 AvailabilityData(const AvailabilityChange &Introduced,
70 const AvailabilityChange &Deprecated,
71 const AvailabilityChange &Obsoleted,
72 SourceLocation Strict, const Expr *ReplaceExpr)
73 : StrictLoc(Strict), Replacement(ReplaceExpr) {
74 Changes[IntroducedSlot] = Introduced;
75 Changes[DeprecatedSlot] = Deprecated;
76 Changes[ObsoletedSlot] = Obsoleted;
77 }
78};
79
80struct TypeTagForDatatypeData {
81 ParsedType MatchingCType;
82 unsigned LayoutCompatible : 1;
83 unsigned MustBeNull : 1;
84};
85struct PropertyData {
86 IdentifierInfo *GetterId, *SetterId;
87
88 PropertyData(IdentifierInfo *getterId, IdentifierInfo *setterId)
89 : GetterId(getterId), SetterId(setterId) {}
90};
91
92} // namespace
93
94/// Wraps an identifier and optional source location for the identifier.
95struct IdentifierLoc {
96 SourceLocation Loc;
97 IdentifierInfo *Ident;
98
99 static IdentifierLoc *create(ASTContext &Ctx, SourceLocation Loc,
100 IdentifierInfo *Ident);
101};
102
103/// A union of the various pointer types that can be passed to an
104/// ParsedAttr as an argument.
105using ArgsUnion = llvm::PointerUnion<Expr *, IdentifierLoc *>;
106using ArgsVector = llvm::SmallVector<ArgsUnion, 12U>;
107
108/// ParsedAttr - Represents a syntactic attribute.
109///
110/// For a GNU attribute, there are four forms of this construct:
111///
112/// 1: __attribute__(( const )). ParmName/Args/NumArgs will all be unused.
113/// 2: __attribute__(( mode(byte) )). ParmName used, Args/NumArgs unused.
114/// 3: __attribute__(( format(printf, 1, 2) )). ParmName/Args/NumArgs all used.
115/// 4: __attribute__(( aligned(16) )). ParmName is unused, Args/Num used.
116///
117class ParsedAttr final
118 : public AttributeCommonInfo,
119 private llvm::TrailingObjects<
120 ParsedAttr, ArgsUnion, detail::AvailabilityData,
121 detail::TypeTagForDatatypeData, ParsedType, detail::PropertyData> {
122 friend TrailingObjects;
123
124 size_t numTrailingObjects(OverloadToken<ArgsUnion>) const { return NumArgs; }
125 size_t numTrailingObjects(OverloadToken<detail::AvailabilityData>) const {
126 return IsAvailability;
127 }
128 size_t
129 numTrailingObjects(OverloadToken<detail::TypeTagForDatatypeData>) const {
130 return IsTypeTagForDatatype;
131 }
132 size_t numTrailingObjects(OverloadToken<ParsedType>) const {
133 return HasParsedType;
134 }
135 size_t numTrailingObjects(OverloadToken<detail::PropertyData>) const {
136 return IsProperty;
137 }
138
139private:
140 IdentifierInfo *MacroII = nullptr;
141 SourceLocation MacroExpansionLoc;
142 SourceLocation EllipsisLoc;
143
144 /// The number of expression arguments this attribute has.
145 /// The expressions themselves are stored after the object.
146 unsigned NumArgs : 16;
147
148 /// True if already diagnosed as invalid.
149 mutable unsigned Invalid : 1;
150
151 /// True if this attribute was used as a type attribute.
152 mutable unsigned UsedAsTypeAttr : 1;
153
154 /// True if this has the extra information associated with an
155 /// availability attribute.
156 unsigned IsAvailability : 1;
157
158 /// True if this has extra information associated with a
159 /// type_tag_for_datatype attribute.
160 unsigned IsTypeTagForDatatype : 1;
161
162 /// True if this has extra information associated with a
163 /// Microsoft __delcspec(property) attribute.
164 unsigned IsProperty : 1;
165
166 /// True if this has a ParsedType
167 unsigned HasParsedType : 1;
168
169 /// True if the processing cache is valid.
170 mutable unsigned HasProcessingCache : 1;
171
172 /// A cached value.
173 mutable unsigned ProcessingCache : 8;
174
175 /// True if the attribute is specified using '#pragma clang attribute'.
176 mutable unsigned IsPragmaClangAttribute : 1;
177
178 /// The location of the 'unavailable' keyword in an
179 /// availability attribute.
180 SourceLocation UnavailableLoc;
181
182 const Expr *MessageExpr;
183
184 ArgsUnion *getArgsBuffer() { return getTrailingObjects<ArgsUnion>(); }
185 ArgsUnion const *getArgsBuffer() const {
186 return getTrailingObjects<ArgsUnion>();
187 }
188
189 detail::AvailabilityData *getAvailabilityData() {
190 return getTrailingObjects<detail::AvailabilityData>();
191 }
192 const detail::AvailabilityData *getAvailabilityData() const {
193 return getTrailingObjects<detail::AvailabilityData>();
194 }
195
196private:
197 friend class AttributeFactory;
198 friend class AttributePool;
199
200 /// Constructor for attributes with expression arguments.
201 ParsedAttr(IdentifierInfo *attrName, SourceRange attrRange,
202 IdentifierInfo *scopeName, SourceLocation scopeLoc,
203 ArgsUnion *args, unsigned numArgs, Syntax syntaxUsed,
204 SourceLocation ellipsisLoc)
205 : AttributeCommonInfo(attrName, scopeName, attrRange, scopeLoc,
206 syntaxUsed),
207 EllipsisLoc(ellipsisLoc), NumArgs(numArgs), Invalid(false),
208 UsedAsTypeAttr(false), IsAvailability(false),
209 IsTypeTagForDatatype(false), IsProperty(false), HasParsedType(false),
210 HasProcessingCache(false), IsPragmaClangAttribute(false) {
211 if (numArgs)
212 memcpy(getArgsBuffer(), args, numArgs * sizeof(ArgsUnion));
213 }
214
215 /// Constructor for availability attributes.
216 ParsedAttr(IdentifierInfo *attrName, SourceRange attrRange,
217 IdentifierInfo *scopeName, SourceLocation scopeLoc,
218 IdentifierLoc *Parm, const AvailabilityChange &introduced,
219 const AvailabilityChange &deprecated,
220 const AvailabilityChange &obsoleted, SourceLocation unavailable,
221 const Expr *messageExpr, Syntax syntaxUsed, SourceLocation strict,
222 const Expr *replacementExpr)
223 : AttributeCommonInfo(attrName, scopeName, attrRange, scopeLoc,
224 syntaxUsed),
225 NumArgs(1), Invalid(false), UsedAsTypeAttr(false), IsAvailability(true),
226 IsTypeTagForDatatype(false), IsProperty(false), HasParsedType(false),
227 HasProcessingCache(false), IsPragmaClangAttribute(false),
228 UnavailableLoc(unavailable), MessageExpr(messageExpr) {
229 ArgsUnion PVal(Parm);
230 memcpy(getArgsBuffer(), &PVal, sizeof(ArgsUnion));
231 new (getAvailabilityData()) detail::AvailabilityData(
232 introduced, deprecated, obsoleted, strict, replacementExpr);
233 }
234
235 /// Constructor for objc_bridge_related attributes.
236 ParsedAttr(IdentifierInfo *attrName, SourceRange attrRange,
237 IdentifierInfo *scopeName, SourceLocation scopeLoc,
238 IdentifierLoc *Parm1, IdentifierLoc *Parm2, IdentifierLoc *Parm3,
239 Syntax syntaxUsed)
240 : AttributeCommonInfo(attrName, scopeName, attrRange, scopeLoc,
241 syntaxUsed),
242 NumArgs(3), Invalid(false), UsedAsTypeAttr(false),
243 IsAvailability(false), IsTypeTagForDatatype(false), IsProperty(false),
244 HasParsedType(false), HasProcessingCache(false),
245 IsPragmaClangAttribute(false) {
246 ArgsUnion *Args = getArgsBuffer();
247 Args[0] = Parm1;
248 Args[1] = Parm2;
249 Args[2] = Parm3;
250 }
251
252 /// Constructor for type_tag_for_datatype attribute.
253 ParsedAttr(IdentifierInfo *attrName, SourceRange attrRange,
254 IdentifierInfo *scopeName, SourceLocation scopeLoc,
255 IdentifierLoc *ArgKind, ParsedType matchingCType,
256 bool layoutCompatible, bool mustBeNull, Syntax syntaxUsed)
257 : AttributeCommonInfo(attrName, scopeName, attrRange, scopeLoc,
258 syntaxUsed),
259 NumArgs(1), Invalid(false), UsedAsTypeAttr(false),
260 IsAvailability(false), IsTypeTagForDatatype(true), IsProperty(false),
261 HasParsedType(false), HasProcessingCache(false),
262 IsPragmaClangAttribute(false) {
263 ArgsUnion PVal(ArgKind);
264 memcpy(getArgsBuffer(), &PVal, sizeof(ArgsUnion));
265 detail::TypeTagForDatatypeData &ExtraData = getTypeTagForDatatypeDataSlot();
266 new (&ExtraData.MatchingCType) ParsedType(matchingCType);
267 ExtraData.LayoutCompatible = layoutCompatible;
268 ExtraData.MustBeNull = mustBeNull;
269 }
270
271 /// Constructor for attributes with a single type argument.
272 ParsedAttr(IdentifierInfo *attrName, SourceRange attrRange,
273 IdentifierInfo *scopeName, SourceLocation scopeLoc,
274 ParsedType typeArg, Syntax syntaxUsed)
275 : AttributeCommonInfo(attrName, scopeName, attrRange, scopeLoc,
276 syntaxUsed),
277 NumArgs(0), Invalid(false), UsedAsTypeAttr(false),
278 IsAvailability(false), IsTypeTagForDatatype(false), IsProperty(false),
279 HasParsedType(true), HasProcessingCache(false),
280 IsPragmaClangAttribute(false) {
281 new (&getTypeBuffer()) ParsedType(typeArg);
282 }
283
284 /// Constructor for microsoft __declspec(property) attribute.
285 ParsedAttr(IdentifierInfo *attrName, SourceRange attrRange,
286 IdentifierInfo *scopeName, SourceLocation scopeLoc,
287 IdentifierInfo *getterId, IdentifierInfo *setterId,
288 Syntax syntaxUsed)
289 : AttributeCommonInfo(attrName, scopeName, attrRange, scopeLoc,
290 syntaxUsed),
291 NumArgs(0), Invalid(false), UsedAsTypeAttr(false),
292 IsAvailability(false), IsTypeTagForDatatype(false), IsProperty(true),
293 HasParsedType(false), HasProcessingCache(false),
294 IsPragmaClangAttribute(false) {
295 new (&getPropertyDataBuffer()) detail::PropertyData(getterId, setterId);
296 }
297
298 /// Type tag information is stored immediately following the arguments, if
299 /// any, at the end of the object. They are mutually exclusive with
300 /// availability slots.
301 detail::TypeTagForDatatypeData &getTypeTagForDatatypeDataSlot() {
302 return *getTrailingObjects<detail::TypeTagForDatatypeData>();
303 }
304 const detail::TypeTagForDatatypeData &getTypeTagForDatatypeDataSlot() const {
305 return *getTrailingObjects<detail::TypeTagForDatatypeData>();
306 }
307
308 /// The type buffer immediately follows the object and are mutually exclusive
309 /// with arguments.
310 ParsedType &getTypeBuffer() { return *getTrailingObjects<ParsedType>(); }
311 const ParsedType &getTypeBuffer() const {
312 return *getTrailingObjects<ParsedType>();
313 }
314
315 /// The property data immediately follows the object is is mutually exclusive
316 /// with arguments.
317 detail::PropertyData &getPropertyDataBuffer() {
318 assert(IsProperty)((IsProperty) ? static_cast<void> (0) : __assert_fail (
"IsProperty", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 318, __PRETTY_FUNCTION__))
;
319 return *getTrailingObjects<detail::PropertyData>();
320 }
321 const detail::PropertyData &getPropertyDataBuffer() const {
322 assert(IsProperty)((IsProperty) ? static_cast<void> (0) : __assert_fail (
"IsProperty", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 322, __PRETTY_FUNCTION__))
;
323 return *getTrailingObjects<detail::PropertyData>();
324 }
325
326 size_t allocated_size() const;
327
328public:
329 ParsedAttr(const ParsedAttr &) = delete;
330 ParsedAttr(ParsedAttr &&) = delete;
331 ParsedAttr &operator=(const ParsedAttr &) = delete;
332 ParsedAttr &operator=(ParsedAttr &&) = delete;
333 ~ParsedAttr() = delete;
334
335 void operator delete(void *) = delete;
336
337 bool hasParsedType() const { return HasParsedType; }
338
339 /// Is this the Microsoft __declspec(property) attribute?
340 bool isDeclspecPropertyAttribute() const {
341 return IsProperty;
342 }
343
344 bool isInvalid() const { return Invalid; }
345 void setInvalid(bool b = true) const { Invalid = b; }
346
347 bool hasProcessingCache() const { return HasProcessingCache; }
348
349 unsigned getProcessingCache() const {
350 assert(hasProcessingCache())((hasProcessingCache()) ? static_cast<void> (0) : __assert_fail
("hasProcessingCache()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 350, __PRETTY_FUNCTION__))
;
351 return ProcessingCache;
352 }
353
354 void setProcessingCache(unsigned value) const {
355 ProcessingCache = value;
356 HasProcessingCache = true;
357 }
358
359 bool isUsedAsTypeAttr() const { return UsedAsTypeAttr; }
360 void setUsedAsTypeAttr(bool Used = true) { UsedAsTypeAttr = Used; }
361
362 /// True if the attribute is specified using '#pragma clang attribute'.
363 bool isPragmaClangAttribute() const { return IsPragmaClangAttribute; }
364
365 void setIsPragmaClangAttribute() { IsPragmaClangAttribute = true; }
366
367 bool isPackExpansion() const { return EllipsisLoc.isValid(); }
368 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
369
370 /// getNumArgs - Return the number of actual arguments to this attribute.
371 unsigned getNumArgs() const { return NumArgs; }
372
373 /// getArg - Return the specified argument.
374 ArgsUnion getArg(unsigned Arg) const {
375 assert(Arg < NumArgs && "Arg access out of range!")((Arg < NumArgs && "Arg access out of range!") ? static_cast
<void> (0) : __assert_fail ("Arg < NumArgs && \"Arg access out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 375, __PRETTY_FUNCTION__))
;
376 return getArgsBuffer()[Arg];
377 }
378
379 bool isArgExpr(unsigned Arg) const {
380 return Arg < NumArgs && getArg(Arg).is<Expr*>();
381 }
382
383 Expr *getArgAsExpr(unsigned Arg) const {
384 return getArg(Arg).get<Expr*>();
385 }
386
387 bool isArgIdent(unsigned Arg) const {
388 return Arg < NumArgs && getArg(Arg).is<IdentifierLoc*>();
2
Assuming 'Arg' is < field 'NumArgs'
3
Returning the value 1, which participates in a condition later
389 }
390
391 IdentifierLoc *getArgAsIdent(unsigned Arg) const {
392 return getArg(Arg).get<IdentifierLoc*>();
393 }
394
395 const AvailabilityChange &getAvailabilityIntroduced() const {
396 assert(getParsedKind() == AT_Availability &&((getParsedKind() == AT_Availability && "Not an availability attribute"
) ? static_cast<void> (0) : __assert_fail ("getParsedKind() == AT_Availability && \"Not an availability attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 397, __PRETTY_FUNCTION__))
397 "Not an availability attribute")((getParsedKind() == AT_Availability && "Not an availability attribute"
) ? static_cast<void> (0) : __assert_fail ("getParsedKind() == AT_Availability && \"Not an availability attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 397, __PRETTY_FUNCTION__))
;
398 return getAvailabilityData()->Changes[detail::IntroducedSlot];
399 }
400
401 const AvailabilityChange &getAvailabilityDeprecated() const {
402 assert(getParsedKind() == AT_Availability &&((getParsedKind() == AT_Availability && "Not an availability attribute"
) ? static_cast<void> (0) : __assert_fail ("getParsedKind() == AT_Availability && \"Not an availability attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 403, __PRETTY_FUNCTION__))
403 "Not an availability attribute")((getParsedKind() == AT_Availability && "Not an availability attribute"
) ? static_cast<void> (0) : __assert_fail ("getParsedKind() == AT_Availability && \"Not an availability attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 403, __PRETTY_FUNCTION__))
;
404 return getAvailabilityData()->Changes[detail::DeprecatedSlot];
405 }
406
407 const AvailabilityChange &getAvailabilityObsoleted() const {
408 assert(getParsedKind() == AT_Availability &&((getParsedKind() == AT_Availability && "Not an availability attribute"
) ? static_cast<void> (0) : __assert_fail ("getParsedKind() == AT_Availability && \"Not an availability attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 409, __PRETTY_FUNCTION__))
409 "Not an availability attribute")((getParsedKind() == AT_Availability && "Not an availability attribute"
) ? static_cast<void> (0) : __assert_fail ("getParsedKind() == AT_Availability && \"Not an availability attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 409, __PRETTY_FUNCTION__))
;
410 return getAvailabilityData()->Changes[detail::ObsoletedSlot];
411 }
412
413 SourceLocation getStrictLoc() const {
414 assert(getParsedKind() == AT_Availability &&((getParsedKind() == AT_Availability && "Not an availability attribute"
) ? static_cast<void> (0) : __assert_fail ("getParsedKind() == AT_Availability && \"Not an availability attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 415, __PRETTY_FUNCTION__))
415 "Not an availability attribute")((getParsedKind() == AT_Availability && "Not an availability attribute"
) ? static_cast<void> (0) : __assert_fail ("getParsedKind() == AT_Availability && \"Not an availability attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 415, __PRETTY_FUNCTION__))
;
416 return getAvailabilityData()->StrictLoc;
417 }
418
419 SourceLocation getUnavailableLoc() const {
420 assert(getParsedKind() == AT_Availability &&((getParsedKind() == AT_Availability && "Not an availability attribute"
) ? static_cast<void> (0) : __assert_fail ("getParsedKind() == AT_Availability && \"Not an availability attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 421, __PRETTY_FUNCTION__))
421 "Not an availability attribute")((getParsedKind() == AT_Availability && "Not an availability attribute"
) ? static_cast<void> (0) : __assert_fail ("getParsedKind() == AT_Availability && \"Not an availability attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 421, __PRETTY_FUNCTION__))
;
422 return UnavailableLoc;
423 }
424
425 const Expr * getMessageExpr() const {
426 assert(getParsedKind() == AT_Availability &&((getParsedKind() == AT_Availability && "Not an availability attribute"
) ? static_cast<void> (0) : __assert_fail ("getParsedKind() == AT_Availability && \"Not an availability attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 427, __PRETTY_FUNCTION__))
427 "Not an availability attribute")((getParsedKind() == AT_Availability && "Not an availability attribute"
) ? static_cast<void> (0) : __assert_fail ("getParsedKind() == AT_Availability && \"Not an availability attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 427, __PRETTY_FUNCTION__))
;
428 return MessageExpr;
429 }
430
431 const Expr *getReplacementExpr() const {
432 assert(getParsedKind() == AT_Availability &&((getParsedKind() == AT_Availability && "Not an availability attribute"
) ? static_cast<void> (0) : __assert_fail ("getParsedKind() == AT_Availability && \"Not an availability attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 433, __PRETTY_FUNCTION__))
433 "Not an availability attribute")((getParsedKind() == AT_Availability && "Not an availability attribute"
) ? static_cast<void> (0) : __assert_fail ("getParsedKind() == AT_Availability && \"Not an availability attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 433, __PRETTY_FUNCTION__))
;
434 return getAvailabilityData()->Replacement;
435 }
436
437 const ParsedType &getMatchingCType() const {
438 assert(getParsedKind() == AT_TypeTagForDatatype &&((getParsedKind() == AT_TypeTagForDatatype && "Not a type_tag_for_datatype attribute"
) ? static_cast<void> (0) : __assert_fail ("getParsedKind() == AT_TypeTagForDatatype && \"Not a type_tag_for_datatype attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 439, __PRETTY_FUNCTION__))
439 "Not a type_tag_for_datatype attribute")((getParsedKind() == AT_TypeTagForDatatype && "Not a type_tag_for_datatype attribute"
) ? static_cast<void> (0) : __assert_fail ("getParsedKind() == AT_TypeTagForDatatype && \"Not a type_tag_for_datatype attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 439, __PRETTY_FUNCTION__))
;
440 return getTypeTagForDatatypeDataSlot().MatchingCType;
441 }
442
443 bool getLayoutCompatible() const {
444 assert(getParsedKind() == AT_TypeTagForDatatype &&((getParsedKind() == AT_TypeTagForDatatype && "Not a type_tag_for_datatype attribute"
) ? static_cast<void> (0) : __assert_fail ("getParsedKind() == AT_TypeTagForDatatype && \"Not a type_tag_for_datatype attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 445, __PRETTY_FUNCTION__))
445 "Not a type_tag_for_datatype attribute")((getParsedKind() == AT_TypeTagForDatatype && "Not a type_tag_for_datatype attribute"
) ? static_cast<void> (0) : __assert_fail ("getParsedKind() == AT_TypeTagForDatatype && \"Not a type_tag_for_datatype attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 445, __PRETTY_FUNCTION__))
;
446 return getTypeTagForDatatypeDataSlot().LayoutCompatible;
447 }
448
449 bool getMustBeNull() const {
450 assert(getParsedKind() == AT_TypeTagForDatatype &&((getParsedKind() == AT_TypeTagForDatatype && "Not a type_tag_for_datatype attribute"
) ? static_cast<void> (0) : __assert_fail ("getParsedKind() == AT_TypeTagForDatatype && \"Not a type_tag_for_datatype attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 451, __PRETTY_FUNCTION__))
451 "Not a type_tag_for_datatype attribute")((getParsedKind() == AT_TypeTagForDatatype && "Not a type_tag_for_datatype attribute"
) ? static_cast<void> (0) : __assert_fail ("getParsedKind() == AT_TypeTagForDatatype && \"Not a type_tag_for_datatype attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 451, __PRETTY_FUNCTION__))
;
452 return getTypeTagForDatatypeDataSlot().MustBeNull;
453 }
454
455 const ParsedType &getTypeArg() const {
456 assert(HasParsedType && "Not a type attribute")((HasParsedType && "Not a type attribute") ? static_cast
<void> (0) : __assert_fail ("HasParsedType && \"Not a type attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 456, __PRETTY_FUNCTION__))
;
457 return getTypeBuffer();
458 }
459
460 IdentifierInfo *getPropertyDataGetter() const {
461 assert(isDeclspecPropertyAttribute() &&((isDeclspecPropertyAttribute() && "Not a __delcspec(property) attribute"
) ? static_cast<void> (0) : __assert_fail ("isDeclspecPropertyAttribute() && \"Not a __delcspec(property) attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 462, __PRETTY_FUNCTION__))
462 "Not a __delcspec(property) attribute")((isDeclspecPropertyAttribute() && "Not a __delcspec(property) attribute"
) ? static_cast<void> (0) : __assert_fail ("isDeclspecPropertyAttribute() && \"Not a __delcspec(property) attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 462, __PRETTY_FUNCTION__))
;
463 return getPropertyDataBuffer().GetterId;
464 }
465
466 IdentifierInfo *getPropertyDataSetter() const {
467 assert(isDeclspecPropertyAttribute() &&((isDeclspecPropertyAttribute() && "Not a __delcspec(property) attribute"
) ? static_cast<void> (0) : __assert_fail ("isDeclspecPropertyAttribute() && \"Not a __delcspec(property) attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 468, __PRETTY_FUNCTION__))
468 "Not a __delcspec(property) attribute")((isDeclspecPropertyAttribute() && "Not a __delcspec(property) attribute"
) ? static_cast<void> (0) : __assert_fail ("isDeclspecPropertyAttribute() && \"Not a __delcspec(property) attribute\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 468, __PRETTY_FUNCTION__))
;
469 return getPropertyDataBuffer().SetterId;
470 }
471
472 /// Set the macro identifier info object that this parsed attribute was
473 /// declared in if it was declared in a macro. Also set the expansion location
474 /// of the macro.
475 void setMacroIdentifier(IdentifierInfo *MacroName, SourceLocation Loc) {
476 MacroII = MacroName;
477 MacroExpansionLoc = Loc;
478 }
479
480 /// Returns true if this attribute was declared in a macro.
481 bool hasMacroIdentifier() const { return MacroII != nullptr; }
482
483 /// Return the macro identifier if this attribute was declared in a macro.
484 /// nullptr is returned if it was not declared in a macro.
485 IdentifierInfo *getMacroIdentifier() const { return MacroII; }
486
487 SourceLocation getMacroExpansionLoc() const {
488 assert(hasMacroIdentifier() && "Can only get the macro expansion location "((hasMacroIdentifier() && "Can only get the macro expansion location "
"if this attribute has a macro identifier.") ? static_cast<
void> (0) : __assert_fail ("hasMacroIdentifier() && \"Can only get the macro expansion location \" \"if this attribute has a macro identifier.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 489, __PRETTY_FUNCTION__))
489 "if this attribute has a macro identifier.")((hasMacroIdentifier() && "Can only get the macro expansion location "
"if this attribute has a macro identifier.") ? static_cast<
void> (0) : __assert_fail ("hasMacroIdentifier() && \"Can only get the macro expansion location \" \"if this attribute has a macro identifier.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 489, __PRETTY_FUNCTION__))
;
490 return MacroExpansionLoc;
491 }
492
493 bool isTargetSpecificAttr() const;
494 bool isTypeAttr() const;
495 bool isStmtAttr() const;
496
497 bool hasCustomParsing() const;
498 unsigned getMinArgs() const;
499 unsigned getMaxArgs() const;
500 bool hasVariadicArg() const;
501 bool diagnoseAppertainsTo(class Sema &S, const Decl *D) const;
502 bool appliesToDecl(const Decl *D, attr::SubjectMatchRule MatchRule) const;
503 void getMatchRules(const LangOptions &LangOpts,
504 SmallVectorImpl<std::pair<attr::SubjectMatchRule, bool>>
505 &MatchRules) const;
506 bool diagnoseLangOpts(class Sema &S) const;
507 bool existsInTarget(const TargetInfo &Target) const;
508 bool isKnownToGCC() const;
509 bool isSupportedByPragmaAttribute() const;
510
511 /// If the parsed attribute has a semantic equivalent, and it would
512 /// have a semantic Spelling enumeration (due to having semantically-distinct
513 /// spelling variations), return the value of that semantic spelling. If the
514 /// parsed attribute does not have a semantic equivalent, or would not have
515 /// a Spelling enumeration, the value UINT_MAX is returned.
516 unsigned getSemanticSpelling() const;
517
518 /// If this is an OpenCL addr space attribute returns its representation
519 /// in LangAS, otherwise returns default addr space.
520 LangAS asOpenCLLangAS() const {
521 switch (getParsedKind()) {
522 case ParsedAttr::AT_OpenCLConstantAddressSpace:
523 return LangAS::opencl_constant;
524 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
525 return LangAS::opencl_global;
526 case ParsedAttr::AT_OpenCLLocalAddressSpace:
527 return LangAS::opencl_local;
528 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
529 return LangAS::opencl_private;
530 case ParsedAttr::AT_OpenCLGenericAddressSpace:
531 return LangAS::opencl_generic;
532 default:
533 return LangAS::Default;
534 }
535 }
536
537 AttributeCommonInfo::Kind getKind() const { return getParsedKind(); }
538};
539
540class AttributePool;
541/// A factory, from which one makes pools, from which one creates
542/// individual attributes which are deallocated with the pool.
543///
544/// Note that it's tolerably cheap to create and destroy one of
545/// these as long as you don't actually allocate anything in it.
546class AttributeFactory {
547public:
548 enum {
549 AvailabilityAllocSize =
550 ParsedAttr::totalSizeToAlloc<ArgsUnion, detail::AvailabilityData,
551 detail::TypeTagForDatatypeData, ParsedType,
552 detail::PropertyData>(1, 1, 0, 0, 0),
553 TypeTagForDatatypeAllocSize =
554 ParsedAttr::totalSizeToAlloc<ArgsUnion, detail::AvailabilityData,
555 detail::TypeTagForDatatypeData, ParsedType,
556 detail::PropertyData>(1, 0, 1, 0, 0),
557 PropertyAllocSize =
558 ParsedAttr::totalSizeToAlloc<ArgsUnion, detail::AvailabilityData,
559 detail::TypeTagForDatatypeData, ParsedType,
560 detail::PropertyData>(0, 0, 0, 0, 1),
561 };
562
563private:
564 enum {
565 /// The number of free lists we want to be sure to support
566 /// inline. This is just enough that availability attributes
567 /// don't surpass it. It's actually very unlikely we'll see an
568 /// attribute that needs more than that; on x86-64 you'd need 10
569 /// expression arguments, and on i386 you'd need 19.
570 InlineFreeListsCapacity =
571 1 + (AvailabilityAllocSize - sizeof(ParsedAttr)) / sizeof(void *)
572 };
573
574 llvm::BumpPtrAllocator Alloc;
575
576 /// Free lists. The index is determined by the following formula:
577 /// (size - sizeof(ParsedAttr)) / sizeof(void*)
578 SmallVector<SmallVector<ParsedAttr *, 8>, InlineFreeListsCapacity> FreeLists;
579
580 // The following are the private interface used by AttributePool.
581 friend class AttributePool;
582
583 /// Allocate an attribute of the given size.
584 void *allocate(size_t size);
585
586 void deallocate(ParsedAttr *AL);
587
588 /// Reclaim all the attributes in the given pool chain, which is
589 /// non-empty. Note that the current implementation is safe
590 /// against reclaiming things which were not actually allocated
591 /// with the allocator, although of course it's important to make
592 /// sure that their allocator lives at least as long as this one.
593 void reclaimPool(AttributePool &head);
594
595public:
596 AttributeFactory();
597 ~AttributeFactory();
598};
599
600class AttributePool {
601 friend class AttributeFactory;
602 friend class ParsedAttributes;
603 AttributeFactory &Factory;
604 llvm::TinyPtrVector<ParsedAttr *> Attrs;
605
606 void *allocate(size_t size) {
607 return Factory.allocate(size);
608 }
609
610 ParsedAttr *add(ParsedAttr *attr) {
611 Attrs.push_back(attr);
612 return attr;
613 }
614
615 void remove(ParsedAttr *attr) {
616 assert(llvm::is_contained(Attrs, attr) &&((llvm::is_contained(Attrs, attr) && "Can't take attribute from a pool that doesn't own it!"
) ? static_cast<void> (0) : __assert_fail ("llvm::is_contained(Attrs, attr) && \"Can't take attribute from a pool that doesn't own it!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 617, __PRETTY_FUNCTION__))
617 "Can't take attribute from a pool that doesn't own it!")((llvm::is_contained(Attrs, attr) && "Can't take attribute from a pool that doesn't own it!"
) ? static_cast<void> (0) : __assert_fail ("llvm::is_contained(Attrs, attr) && \"Can't take attribute from a pool that doesn't own it!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 617, __PRETTY_FUNCTION__))
;
618 Attrs.erase(llvm::find(Attrs, attr));
619 }
620
621 void takePool(AttributePool &pool);
622
623public:
624 /// Create a new pool for a factory.
625 AttributePool(AttributeFactory &factory) : Factory(factory) {}
626
627 AttributePool(const AttributePool &) = delete;
628
629 ~AttributePool() { Factory.reclaimPool(*this); }
630
631 /// Move the given pool's allocations to this pool.
632 AttributePool(AttributePool &&pool) = default;
633
634 AttributeFactory &getFactory() const { return Factory; }
635
636 void clear() {
637 Factory.reclaimPool(*this);
638 Attrs.clear();
639 }
640
641 /// Take the given pool's allocations and add them to this pool.
642 void takeAllFrom(AttributePool &pool) {
643 takePool(pool);
644 pool.Attrs.clear();
645 }
646
647 ParsedAttr *create(IdentifierInfo *attrName, SourceRange attrRange,
648 IdentifierInfo *scopeName, SourceLocation scopeLoc,
649 ArgsUnion *args, unsigned numArgs,
650 ParsedAttr::Syntax syntax,
651 SourceLocation ellipsisLoc = SourceLocation()) {
652 size_t temp =
653 ParsedAttr::totalSizeToAlloc<ArgsUnion, detail::AvailabilityData,
654 detail::TypeTagForDatatypeData, ParsedType,
655 detail::PropertyData>(numArgs, 0, 0, 0, 0);
656 (void)temp;
657 void *memory = allocate(
658 ParsedAttr::totalSizeToAlloc<ArgsUnion, detail::AvailabilityData,
659 detail::TypeTagForDatatypeData, ParsedType,
660 detail::PropertyData>(numArgs, 0, 0, 0,
661 0));
662 return add(new (memory) ParsedAttr(attrName, attrRange, scopeName, scopeLoc,
663 args, numArgs, syntax, ellipsisLoc));
664 }
665
666 ParsedAttr *create(IdentifierInfo *attrName, SourceRange attrRange,
667 IdentifierInfo *scopeName, SourceLocation scopeLoc,
668 IdentifierLoc *Param, const AvailabilityChange &introduced,
669 const AvailabilityChange &deprecated,
670 const AvailabilityChange &obsoleted,
671 SourceLocation unavailable, const Expr *MessageExpr,
672 ParsedAttr::Syntax syntax, SourceLocation strict,
673 const Expr *ReplacementExpr) {
674 void *memory = allocate(AttributeFactory::AvailabilityAllocSize);
675 return add(new (memory) ParsedAttr(
676 attrName, attrRange, scopeName, scopeLoc, Param, introduced, deprecated,
677 obsoleted, unavailable, MessageExpr, syntax, strict, ReplacementExpr));
678 }
679
680 ParsedAttr *create(IdentifierInfo *attrName, SourceRange attrRange,
681 IdentifierInfo *scopeName, SourceLocation scopeLoc,
682 IdentifierLoc *Param1, IdentifierLoc *Param2,
683 IdentifierLoc *Param3, ParsedAttr::Syntax syntax) {
684 void *memory = allocate(
685 ParsedAttr::totalSizeToAlloc<ArgsUnion, detail::AvailabilityData,
686 detail::TypeTagForDatatypeData, ParsedType,
687 detail::PropertyData>(3, 0, 0, 0, 0));
688 return add(new (memory) ParsedAttr(attrName, attrRange, scopeName, scopeLoc,
689 Param1, Param2, Param3, syntax));
690 }
691
692 ParsedAttr *
693 createTypeTagForDatatype(IdentifierInfo *attrName, SourceRange attrRange,
694 IdentifierInfo *scopeName, SourceLocation scopeLoc,
695 IdentifierLoc *argumentKind,
696 ParsedType matchingCType, bool layoutCompatible,
697 bool mustBeNull, ParsedAttr::Syntax syntax) {
698 void *memory = allocate(AttributeFactory::TypeTagForDatatypeAllocSize);
699 return add(new (memory) ParsedAttr(attrName, attrRange, scopeName, scopeLoc,
700 argumentKind, matchingCType,
701 layoutCompatible, mustBeNull, syntax));
702 }
703
704 ParsedAttr *createTypeAttribute(IdentifierInfo *attrName,
705 SourceRange attrRange,
706 IdentifierInfo *scopeName,
707 SourceLocation scopeLoc, ParsedType typeArg,
708 ParsedAttr::Syntax syntaxUsed) {
709 void *memory = allocate(
710 ParsedAttr::totalSizeToAlloc<ArgsUnion, detail::AvailabilityData,
711 detail::TypeTagForDatatypeData, ParsedType,
712 detail::PropertyData>(0, 0, 0, 1, 0));
713 return add(new (memory) ParsedAttr(attrName, attrRange, scopeName, scopeLoc,
714 typeArg, syntaxUsed));
715 }
716
717 ParsedAttr *
718 createPropertyAttribute(IdentifierInfo *attrName, SourceRange attrRange,
719 IdentifierInfo *scopeName, SourceLocation scopeLoc,
720 IdentifierInfo *getterId, IdentifierInfo *setterId,
721 ParsedAttr::Syntax syntaxUsed) {
722 void *memory = allocate(AttributeFactory::PropertyAllocSize);
723 return add(new (memory) ParsedAttr(attrName, attrRange, scopeName, scopeLoc,
724 getterId, setterId, syntaxUsed));
725 }
726};
727
728class ParsedAttributesView {
729 using VecTy = llvm::TinyPtrVector<ParsedAttr *>;
730 using SizeType = decltype(std::declval<VecTy>().size());
731
732public:
733 bool empty() const { return AttrList.empty(); }
734 SizeType size() const { return AttrList.size(); }
735 ParsedAttr &operator[](SizeType pos) { return *AttrList[pos]; }
736 const ParsedAttr &operator[](SizeType pos) const { return *AttrList[pos]; }
737
738 void addAtEnd(ParsedAttr *newAttr) {
739 assert(newAttr)((newAttr) ? static_cast<void> (0) : __assert_fail ("newAttr"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 739, __PRETTY_FUNCTION__))
;
740 AttrList.push_back(newAttr);
741 }
742
743 void remove(ParsedAttr *ToBeRemoved) {
744 assert(is_contained(AttrList, ToBeRemoved) &&((is_contained(AttrList, ToBeRemoved) && "Cannot remove attribute that isn't in the list"
) ? static_cast<void> (0) : __assert_fail ("is_contained(AttrList, ToBeRemoved) && \"Cannot remove attribute that isn't in the list\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 745, __PRETTY_FUNCTION__))
745 "Cannot remove attribute that isn't in the list")((is_contained(AttrList, ToBeRemoved) && "Cannot remove attribute that isn't in the list"
) ? static_cast<void> (0) : __assert_fail ("is_contained(AttrList, ToBeRemoved) && \"Cannot remove attribute that isn't in the list\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 745, __PRETTY_FUNCTION__))
;
746 AttrList.erase(llvm::find(AttrList, ToBeRemoved));
747 }
748
749 void clearListOnly() { AttrList.clear(); }
750
751 struct iterator : llvm::iterator_adaptor_base<iterator, VecTy::iterator,
752 std::random_access_iterator_tag,
753 ParsedAttr> {
754 iterator() : iterator_adaptor_base(nullptr) {}
755 iterator(VecTy::iterator I) : iterator_adaptor_base(I) {}
756 reference operator*() { return **I; }
757 friend class ParsedAttributesView;
758 };
759 struct const_iterator
760 : llvm::iterator_adaptor_base<const_iterator, VecTy::const_iterator,
761 std::random_access_iterator_tag,
762 ParsedAttr> {
763 const_iterator() : iterator_adaptor_base(nullptr) {}
764 const_iterator(VecTy::const_iterator I) : iterator_adaptor_base(I) {}
765
766 reference operator*() const { return **I; }
767 friend class ParsedAttributesView;
768 };
769
770 void addAll(iterator B, iterator E) {
771 AttrList.insert(AttrList.begin(), B.I, E.I);
772 }
773
774 void addAll(const_iterator B, const_iterator E) {
775 AttrList.insert(AttrList.begin(), B.I, E.I);
776 }
777
778 void addAllAtEnd(iterator B, iterator E) {
779 AttrList.insert(AttrList.end(), B.I, E.I);
780 }
781
782 void addAllAtEnd(const_iterator B, const_iterator E) {
783 AttrList.insert(AttrList.end(), B.I, E.I);
784 }
785
786 iterator begin() { return iterator(AttrList.begin()); }
787 const_iterator begin() const { return const_iterator(AttrList.begin()); }
788 iterator end() { return iterator(AttrList.end()); }
789 const_iterator end() const { return const_iterator(AttrList.end()); }
790
791 ParsedAttr &front() {
792 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 792, __PRETTY_FUNCTION__))
;
793 return *AttrList.front();
794 }
795 const ParsedAttr &front() const {
796 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 796, __PRETTY_FUNCTION__))
;
797 return *AttrList.front();
798 }
799 ParsedAttr &back() {
800 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 800, __PRETTY_FUNCTION__))
;
801 return *AttrList.back();
802 }
803 const ParsedAttr &back() const {
804 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/Sema/ParsedAttr.h"
, 804, __PRETTY_FUNCTION__))
;
805 return *AttrList.back();
806 }
807
808 bool hasAttribute(ParsedAttr::Kind K) const {
809 return llvm::any_of(AttrList, [K](const ParsedAttr *AL) {
810 return AL->getParsedKind() == K;
811 });
812 }
813
814private:
815 VecTy AttrList;
816};
817
818/// ParsedAttributes - A collection of parsed attributes. Currently
819/// we don't differentiate between the various attribute syntaxes,
820/// which is basically silly.
821///
822/// Right now this is a very lightweight container, but the expectation
823/// is that this will become significantly more serious.
824class ParsedAttributes : public ParsedAttributesView {
825public:
826 ParsedAttributes(AttributeFactory &factory) : pool(factory) {}
827 ParsedAttributes(const ParsedAttributes &) = delete;
828
829 AttributePool &getPool() const { return pool; }
830
831 void takeAllFrom(ParsedAttributes &attrs) {
832 addAll(attrs.begin(), attrs.end());
833 attrs.clearListOnly();
834 pool.takeAllFrom(attrs.pool);
835 }
836
837 void takeOneFrom(ParsedAttributes &Attrs, ParsedAttr *PA) {
838 Attrs.getPool().remove(PA);
839 Attrs.remove(PA);
840 getPool().add(PA);
841 addAtEnd(PA);
842 }
843
844 void clear() {
845 clearListOnly();
846 pool.clear();
847 }
848
849 /// Add attribute with expression arguments.
850 ParsedAttr *addNew(IdentifierInfo *attrName, SourceRange attrRange,
851 IdentifierInfo *scopeName, SourceLocation scopeLoc,
852 ArgsUnion *args, unsigned numArgs,
853 ParsedAttr::Syntax syntax,
854 SourceLocation ellipsisLoc = SourceLocation()) {
855 ParsedAttr *attr = pool.create(attrName, attrRange, scopeName, scopeLoc,
856 args, numArgs, syntax, ellipsisLoc);
857 addAtEnd(attr);
858 return attr;
859 }
860
861 /// Add availability attribute.
862 ParsedAttr *addNew(IdentifierInfo *attrName, SourceRange attrRange,
863 IdentifierInfo *scopeName, SourceLocation scopeLoc,
864 IdentifierLoc *Param, const AvailabilityChange &introduced,
865 const AvailabilityChange &deprecated,
866 const AvailabilityChange &obsoleted,
867 SourceLocation unavailable, const Expr *MessageExpr,
868 ParsedAttr::Syntax syntax, SourceLocation strict,
869 const Expr *ReplacementExpr) {
870 ParsedAttr *attr = pool.create(
871 attrName, attrRange, scopeName, scopeLoc, Param, introduced, deprecated,
872 obsoleted, unavailable, MessageExpr, syntax, strict, ReplacementExpr);
873 addAtEnd(attr);
874 return attr;
875 }
876
877 /// Add objc_bridge_related attribute.
878 ParsedAttr *addNew(IdentifierInfo *attrName, SourceRange attrRange,
879 IdentifierInfo *scopeName, SourceLocation scopeLoc,
880 IdentifierLoc *Param1, IdentifierLoc *Param2,
881 IdentifierLoc *Param3, ParsedAttr::Syntax syntax) {
882 ParsedAttr *attr = pool.create(attrName, attrRange, scopeName, scopeLoc,
883 Param1, Param2, Param3, syntax);
884 addAtEnd(attr);
885 return attr;
886 }
887
888 /// Add type_tag_for_datatype attribute.
889 ParsedAttr *
890 addNewTypeTagForDatatype(IdentifierInfo *attrName, SourceRange attrRange,
891 IdentifierInfo *scopeName, SourceLocation scopeLoc,
892 IdentifierLoc *argumentKind,
893 ParsedType matchingCType, bool layoutCompatible,
894 bool mustBeNull, ParsedAttr::Syntax syntax) {
895 ParsedAttr *attr = pool.createTypeTagForDatatype(
896 attrName, attrRange, scopeName, scopeLoc, argumentKind, matchingCType,
897 layoutCompatible, mustBeNull, syntax);
898 addAtEnd(attr);
899 return attr;
900 }
901
902 /// Add an attribute with a single type argument.
903 ParsedAttr *addNewTypeAttr(IdentifierInfo *attrName, SourceRange attrRange,
904 IdentifierInfo *scopeName, SourceLocation scopeLoc,
905 ParsedType typeArg,
906 ParsedAttr::Syntax syntaxUsed) {
907 ParsedAttr *attr = pool.createTypeAttribute(attrName, attrRange, scopeName,
908 scopeLoc, typeArg, syntaxUsed);
909 addAtEnd(attr);
910 return attr;
911 }
912
913 /// Add microsoft __delspec(property) attribute.
914 ParsedAttr *
915 addNewPropertyAttr(IdentifierInfo *attrName, SourceRange attrRange,
916 IdentifierInfo *scopeName, SourceLocation scopeLoc,
917 IdentifierInfo *getterId, IdentifierInfo *setterId,
918 ParsedAttr::Syntax syntaxUsed) {
919 ParsedAttr *attr =
920 pool.createPropertyAttribute(attrName, attrRange, scopeName, scopeLoc,
921 getterId, setterId, syntaxUsed);
922 addAtEnd(attr);
923 return attr;
924 }
925
926private:
927 mutable AttributePool pool;
928};
929
930/// These constants match the enumerated choices of
931/// err_attribute_argument_n_type and err_attribute_argument_type.
932enum AttributeArgumentNType {
933 AANT_ArgumentIntOrBool,
934 AANT_ArgumentIntegerConstant,
935 AANT_ArgumentString,
936 AANT_ArgumentIdentifier
937};
938
939/// These constants match the enumerated choices of
940/// warn_attribute_wrong_decl_type and err_attribute_wrong_decl_type.
941enum AttributeDeclKind {
942 ExpectedFunction,
943 ExpectedUnion,
944 ExpectedVariableOrFunction,
945 ExpectedFunctionOrMethod,
946 ExpectedFunctionMethodOrBlock,
947 ExpectedFunctionMethodOrParameter,
948 ExpectedVariable,
949 ExpectedVariableOrField,
950 ExpectedVariableFieldOrTag,
951 ExpectedTypeOrNamespace,
952 ExpectedFunctionVariableOrClass,
953 ExpectedKernelFunction,
954 ExpectedFunctionWithProtoType,
955};
956
957inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
958 const ParsedAttr &At) {
959 DB.AddTaggedVal(reinterpret_cast<intptr_t>(At.getAttrName()),
960 DiagnosticsEngine::ak_identifierinfo);
961 return DB;
962}
963
964inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
965 const ParsedAttr &At) {
966 PD.AddTaggedVal(reinterpret_cast<intptr_t>(At.getAttrName()),
967 DiagnosticsEngine::ak_identifierinfo);
968 return PD;
969}
970
971inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
972 const ParsedAttr *At) {
973 DB.AddTaggedVal(reinterpret_cast<intptr_t>(At->getAttrName()),
974 DiagnosticsEngine::ak_identifierinfo);
975 return DB;
976}
977
978inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
979 const ParsedAttr *At) {
980 PD.AddTaggedVal(reinterpret_cast<intptr_t>(At->getAttrName()),
981 DiagnosticsEngine::ak_identifierinfo);
982 return PD;
983}
984
985} // namespace clang
986
987#endif // LLVM_CLANG_SEMA_ATTRIBUTELIST_H

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h

1//===- Type.h - C Language Family Type Representation -----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// C Language Family Type Representation
11///
12/// This file defines the clang::Type interface and subclasses, used to
13/// represent types for languages in the C family.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_AST_TYPE_H
18#define LLVM_CLANG_AST_TYPE_H
19
20#include "clang/AST/NestedNameSpecifier.h"
21#include "clang/AST/TemplateName.h"
22#include "clang/Basic/AddressSpaces.h"
23#include "clang/Basic/AttrKinds.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/ExceptionSpecificationType.h"
26#include "clang/Basic/LLVM.h"
27#include "clang/Basic/Linkage.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/SourceLocation.h"
30#include "clang/Basic/Specifiers.h"
31#include "clang/Basic/Visibility.h"
32#include "llvm/ADT/APInt.h"
33#include "llvm/ADT/APSInt.h"
34#include "llvm/ADT/ArrayRef.h"
35#include "llvm/ADT/FoldingSet.h"
36#include "llvm/ADT/None.h"
37#include "llvm/ADT/Optional.h"
38#include "llvm/ADT/PointerIntPair.h"
39#include "llvm/ADT/PointerUnion.h"
40#include "llvm/ADT/StringRef.h"
41#include "llvm/ADT/Twine.h"
42#include "llvm/ADT/iterator_range.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/Compiler.h"
45#include "llvm/Support/ErrorHandling.h"
46#include "llvm/Support/PointerLikeTypeTraits.h"
47#include "llvm/Support/type_traits.h"
48#include "llvm/Support/TrailingObjects.h"
49#include <cassert>
50#include <cstddef>
51#include <cstdint>
52#include <cstring>
53#include <string>
54#include <type_traits>
55#include <utility>
56
57namespace clang {
58
59class ExtQuals;
60class QualType;
61class TagDecl;
62class Type;
63
64enum {
65 TypeAlignmentInBits = 4,
66 TypeAlignment = 1 << TypeAlignmentInBits
67};
68
69} // namespace clang
70
71namespace llvm {
72
73 template <typename T>
74 struct PointerLikeTypeTraits;
75 template<>
76 struct PointerLikeTypeTraits< ::clang::Type*> {
77 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
78
79 static inline ::clang::Type *getFromVoidPointer(void *P) {
80 return static_cast< ::clang::Type*>(P);
81 }
82
83 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
84 };
85
86 template<>
87 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
88 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
89
90 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
91 return static_cast< ::clang::ExtQuals*>(P);
92 }
93
94 enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
95 };
96
97} // namespace llvm
98
99namespace clang {
100
101class ASTContext;
102template <typename> class CanQual;
103class CXXRecordDecl;
104class DeclContext;
105class EnumDecl;
106class Expr;
107class ExtQualsTypeCommonBase;
108class FunctionDecl;
109class IdentifierInfo;
110class NamedDecl;
111class ObjCInterfaceDecl;
112class ObjCProtocolDecl;
113class ObjCTypeParamDecl;
114struct PrintingPolicy;
115class RecordDecl;
116class Stmt;
117class TagDecl;
118class TemplateArgument;
119class TemplateArgumentListInfo;
120class TemplateArgumentLoc;
121class TemplateTypeParmDecl;
122class TypedefNameDecl;
123class UnresolvedUsingTypenameDecl;
124
125using CanQualType = CanQual<Type>;
126
127// Provide forward declarations for all of the *Type classes.
128#define TYPE(Class, Base) class Class##Type;
129#include "clang/AST/TypeNodes.inc"
130
131/// The collection of all-type qualifiers we support.
132/// Clang supports five independent qualifiers:
133/// * C99: const, volatile, and restrict
134/// * MS: __unaligned
135/// * Embedded C (TR18037): address spaces
136/// * Objective C: the GC attributes (none, weak, or strong)
137class Qualifiers {
138public:
139 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
140 Const = 0x1,
141 Restrict = 0x2,
142 Volatile = 0x4,
143 CVRMask = Const | Volatile | Restrict
144 };
145
146 enum GC {
147 GCNone = 0,
148 Weak,
149 Strong
150 };
151
152 enum ObjCLifetime {
153 /// There is no lifetime qualification on this type.
154 OCL_None,
155
156 /// This object can be modified without requiring retains or
157 /// releases.
158 OCL_ExplicitNone,
159
160 /// Assigning into this object requires the old value to be
161 /// released and the new value to be retained. The timing of the
162 /// release of the old value is inexact: it may be moved to
163 /// immediately after the last known point where the value is
164 /// live.
165 OCL_Strong,
166
167 /// Reading or writing from this object requires a barrier call.
168 OCL_Weak,
169
170 /// Assigning into this object requires a lifetime extension.
171 OCL_Autoreleasing
172 };
173
174 enum {
175 /// The maximum supported address space number.
176 /// 23 bits should be enough for anyone.
177 MaxAddressSpace = 0x7fffffu,
178
179 /// The width of the "fast" qualifier mask.
180 FastWidth = 3,
181
182 /// The fast qualifier mask.
183 FastMask = (1 << FastWidth) - 1
184 };
185
186 /// Returns the common set of qualifiers while removing them from
187 /// the given sets.
188 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
189 // If both are only CVR-qualified, bit operations are sufficient.
190 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
191 Qualifiers Q;
192 Q.Mask = L.Mask & R.Mask;
193 L.Mask &= ~Q.Mask;
194 R.Mask &= ~Q.Mask;
195 return Q;
196 }
197
198 Qualifiers Q;
199 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
200 Q.addCVRQualifiers(CommonCRV);
201 L.removeCVRQualifiers(CommonCRV);
202 R.removeCVRQualifiers(CommonCRV);
203
204 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
205 Q.setObjCGCAttr(L.getObjCGCAttr());
206 L.removeObjCGCAttr();
207 R.removeObjCGCAttr();
208 }
209
210 if (L.getObjCLifetime() == R.getObjCLifetime()) {
211 Q.setObjCLifetime(L.getObjCLifetime());
212 L.removeObjCLifetime();
213 R.removeObjCLifetime();
214 }
215
216 if (L.getAddressSpace() == R.getAddressSpace()) {
217 Q.setAddressSpace(L.getAddressSpace());
218 L.removeAddressSpace();
219 R.removeAddressSpace();
220 }
221 return Q;
222 }
223
224 static Qualifiers fromFastMask(unsigned Mask) {
225 Qualifiers Qs;
226 Qs.addFastQualifiers(Mask);
227 return Qs;
228 }
229
230 static Qualifiers fromCVRMask(unsigned CVR) {
231 Qualifiers Qs;
232 Qs.addCVRQualifiers(CVR);
233 return Qs;
234 }
235
236 static Qualifiers fromCVRUMask(unsigned CVRU) {
237 Qualifiers Qs;
238 Qs.addCVRUQualifiers(CVRU);
239 return Qs;
240 }
241
242 // Deserialize qualifiers from an opaque representation.
243 static Qualifiers fromOpaqueValue(unsigned opaque) {
244 Qualifiers Qs;
245 Qs.Mask = opaque;
246 return Qs;
247 }
248
249 // Serialize these qualifiers into an opaque representation.
250 unsigned getAsOpaqueValue() const {
251 return Mask;
252 }
253
254 bool hasConst() const { return Mask & Const; }
255 bool hasOnlyConst() const { return Mask == Const; }
256 void removeConst() { Mask &= ~Const; }
257 void addConst() { Mask |= Const; }
258
259 bool hasVolatile() const { return Mask & Volatile; }
260 bool hasOnlyVolatile() const { return Mask == Volatile; }
261 void removeVolatile() { Mask &= ~Volatile; }
262 void addVolatile() { Mask |= Volatile; }
263
264 bool hasRestrict() const { return Mask & Restrict; }
265 bool hasOnlyRestrict() const { return Mask == Restrict; }
266 void removeRestrict() { Mask &= ~Restrict; }
267 void addRestrict() { Mask |= Restrict; }
268
269 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
270 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
271 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
272
273 void setCVRQualifiers(unsigned mask) {
274 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 274, __PRETTY_FUNCTION__))
;
275 Mask = (Mask & ~CVRMask) | mask;
276 }
277 void removeCVRQualifiers(unsigned mask) {
278 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 278, __PRETTY_FUNCTION__))
;
279 Mask &= ~mask;
280 }
281 void removeCVRQualifiers() {
282 removeCVRQualifiers(CVRMask);
283 }
284 void addCVRQualifiers(unsigned mask) {
285 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 285, __PRETTY_FUNCTION__))
;
286 Mask |= mask;
287 }
288 void addCVRUQualifiers(unsigned mask) {
289 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 289, __PRETTY_FUNCTION__))
;
290 Mask |= mask;
291 }
292
293 bool hasUnaligned() const { return Mask & UMask; }
294 void setUnaligned(bool flag) {
295 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
296 }
297 void removeUnaligned() { Mask &= ~UMask; }
298 void addUnaligned() { Mask |= UMask; }
299
300 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
301 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
302 void setObjCGCAttr(GC type) {
303 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
304 }
305 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
306 void addObjCGCAttr(GC type) {
307 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 307, __PRETTY_FUNCTION__))
;
308 setObjCGCAttr(type);
309 }
310 Qualifiers withoutObjCGCAttr() const {
311 Qualifiers qs = *this;
312 qs.removeObjCGCAttr();
313 return qs;
314 }
315 Qualifiers withoutObjCLifetime() const {
316 Qualifiers qs = *this;
317 qs.removeObjCLifetime();
318 return qs;
319 }
320 Qualifiers withoutAddressSpace() const {
321 Qualifiers qs = *this;
322 qs.removeAddressSpace();
323 return qs;
324 }
325
326 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
327 ObjCLifetime getObjCLifetime() const {
328 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
329 }
330 void setObjCLifetime(ObjCLifetime type) {
331 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
332 }
333 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
334 void addObjCLifetime(ObjCLifetime type) {
335 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 335, __PRETTY_FUNCTION__))
;
336 assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 336, __PRETTY_FUNCTION__))
;
337 Mask |= (type << LifetimeShift);
338 }
339
340 /// True if the lifetime is neither None or ExplicitNone.
341 bool hasNonTrivialObjCLifetime() const {
342 ObjCLifetime lifetime = getObjCLifetime();
343 return (lifetime > OCL_ExplicitNone);
344 }
345
346 /// True if the lifetime is either strong or weak.
347 bool hasStrongOrWeakObjCLifetime() const {
348 ObjCLifetime lifetime = getObjCLifetime();
349 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
350 }
351
352 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
353 LangAS getAddressSpace() const {
354 return static_cast<LangAS>(Mask >> AddressSpaceShift);
355 }
356 bool hasTargetSpecificAddressSpace() const {
357 return isTargetAddressSpace(getAddressSpace());
358 }
359 /// Get the address space attribute value to be printed by diagnostics.
360 unsigned getAddressSpaceAttributePrintValue() const {
361 auto Addr = getAddressSpace();
362 // This function is not supposed to be used with language specific
363 // address spaces. If that happens, the diagnostic message should consider
364 // printing the QualType instead of the address space value.
365 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace())
? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 365, __PRETTY_FUNCTION__))
;
366 if (Addr != LangAS::Default)
367 return toTargetAddressSpace(Addr);
368 // TODO: The diagnostic messages where Addr may be 0 should be fixed
369 // since it cannot differentiate the situation where 0 denotes the default
370 // address space or user specified __attribute__((address_space(0))).
371 return 0;
372 }
373 void setAddressSpace(LangAS space) {
374 assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void
> (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 374, __PRETTY_FUNCTION__))
;
375 Mask = (Mask & ~AddressSpaceMask)
376 | (((uint32_t) space) << AddressSpaceShift);
377 }
378 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
379 void addAddressSpace(LangAS space) {
380 assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail
("space != LangAS::Default", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 380, __PRETTY_FUNCTION__))
;
381 setAddressSpace(space);
382 }
383
384 // Fast qualifiers are those that can be allocated directly
385 // on a QualType object.
386 bool hasFastQualifiers() const { return getFastQualifiers(); }
387 unsigned getFastQualifiers() const { return Mask & FastMask; }
388 void setFastQualifiers(unsigned mask) {
389 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 389, __PRETTY_FUNCTION__))
;
390 Mask = (Mask & ~FastMask) | mask;
391 }
392 void removeFastQualifiers(unsigned mask) {
393 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 393, __PRETTY_FUNCTION__))
;
394 Mask &= ~mask;
395 }
396 void removeFastQualifiers() {
397 removeFastQualifiers(FastMask);
398 }
399 void addFastQualifiers(unsigned mask) {
400 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 400, __PRETTY_FUNCTION__))
;
401 Mask |= mask;
402 }
403
404 /// Return true if the set contains any qualifiers which require an ExtQuals
405 /// node to be allocated.
406 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
407 Qualifiers getNonFastQualifiers() const {
408 Qualifiers Quals = *this;
409 Quals.setFastQualifiers(0);
410 return Quals;
411 }
412
413 /// Return true if the set contains any qualifiers.
414 bool hasQualifiers() const { return Mask; }
415 bool empty() const { return !Mask; }
416
417 /// Add the qualifiers from the given set to this set.
418 void addQualifiers(Qualifiers Q) {
419 // If the other set doesn't have any non-boolean qualifiers, just
420 // bit-or it in.
421 if (!(Q.Mask & ~CVRMask))
422 Mask |= Q.Mask;
423 else {
424 Mask |= (Q.Mask & CVRMask);
425 if (Q.hasAddressSpace())
426 addAddressSpace(Q.getAddressSpace());
427 if (Q.hasObjCGCAttr())
428 addObjCGCAttr(Q.getObjCGCAttr());
429 if (Q.hasObjCLifetime())
430 addObjCLifetime(Q.getObjCLifetime());
431 }
432 }
433
434 /// Remove the qualifiers from the given set from this set.
435 void removeQualifiers(Qualifiers Q) {
436 // If the other set doesn't have any non-boolean qualifiers, just
437 // bit-and the inverse in.
438 if (!(Q.Mask & ~CVRMask))
439 Mask &= ~Q.Mask;
440 else {
441 Mask &= ~(Q.Mask & CVRMask);
442 if (getObjCGCAttr() == Q.getObjCGCAttr())
443 removeObjCGCAttr();
444 if (getObjCLifetime() == Q.getObjCLifetime())
445 removeObjCLifetime();
446 if (getAddressSpace() == Q.getAddressSpace())
447 removeAddressSpace();
448 }
449 }
450
451 /// Add the qualifiers from the given set to this set, given that
452 /// they don't conflict.
453 void addConsistentQualifiers(Qualifiers qs) {
454 assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 455, __PRETTY_FUNCTION__))
455 !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 455, __PRETTY_FUNCTION__))
;
456 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 457, __PRETTY_FUNCTION__))
457 !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 457, __PRETTY_FUNCTION__))
;
458 assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 459, __PRETTY_FUNCTION__))
459 !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 459, __PRETTY_FUNCTION__))
;
460 Mask |= qs.Mask;
461 }
462
463 /// Returns true if address space A is equal to or a superset of B.
464 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
465 /// overlapping address spaces.
466 /// CL1.1 or CL1.2:
467 /// every address space is a superset of itself.
468 /// CL2.0 adds:
469 /// __generic is a superset of any address space except for __constant.
470 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
471 // Address spaces must match exactly.
472 return A == B ||
473 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
474 // for __constant can be used as __generic.
475 (A == LangAS::opencl_generic && B != LangAS::opencl_constant);
476 }
477
478 /// Returns true if the address space in these qualifiers is equal to or
479 /// a superset of the address space in the argument qualifiers.
480 bool isAddressSpaceSupersetOf(Qualifiers other) const {
481 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
482 }
483
484 /// Determines if these qualifiers compatibly include another set.
485 /// Generally this answers the question of whether an object with the other
486 /// qualifiers can be safely used as an object with these qualifiers.
487 bool compatiblyIncludes(Qualifiers other) const {
488 return isAddressSpaceSupersetOf(other) &&
489 // ObjC GC qualifiers can match, be added, or be removed, but can't
490 // be changed.
491 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
492 !other.hasObjCGCAttr()) &&
493 // ObjC lifetime qualifiers must match exactly.
494 getObjCLifetime() == other.getObjCLifetime() &&
495 // CVR qualifiers may subset.
496 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
497 // U qualifier may superset.
498 (!other.hasUnaligned() || hasUnaligned());
499 }
500
501 /// Determines if these qualifiers compatibly include another set of
502 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
503 ///
504 /// One set of Objective-C lifetime qualifiers compatibly includes the other
505 /// if the lifetime qualifiers match, or if both are non-__weak and the
506 /// including set also contains the 'const' qualifier, or both are non-__weak
507 /// and one is None (which can only happen in non-ARC modes).
508 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
509 if (getObjCLifetime() == other.getObjCLifetime())
510 return true;
511
512 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
513 return false;
514
515 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
516 return true;
517
518 return hasConst();
519 }
520
521 /// Determine whether this set of qualifiers is a strict superset of
522 /// another set of qualifiers, not considering qualifier compatibility.
523 bool isStrictSupersetOf(Qualifiers Other) const;
524
525 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
526 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
527
528 explicit operator bool() const { return hasQualifiers(); }
529
530 Qualifiers &operator+=(Qualifiers R) {
531 addQualifiers(R);
532 return *this;
533 }
534
535 // Union two qualifier sets. If an enumerated qualifier appears
536 // in both sets, use the one from the right.
537 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
538 L += R;
539 return L;
540 }
541
542 Qualifiers &operator-=(Qualifiers R) {
543 removeQualifiers(R);
544 return *this;
545 }
546
547 /// Compute the difference between two qualifier sets.
548 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
549 L -= R;
550 return L;
551 }
552
553 std::string getAsString() const;
554 std::string getAsString(const PrintingPolicy &Policy) const;
555
556 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
557 void print(raw_ostream &OS, const PrintingPolicy &Policy,
558 bool appendSpaceIfNonEmpty = false) const;
559
560 void Profile(llvm::FoldingSetNodeID &ID) const {
561 ID.AddInteger(Mask);
562 }
563
564private:
565 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
566 // |C R V|U|GCAttr|Lifetime|AddressSpace|
567 uint32_t Mask = 0;
568
569 static const uint32_t UMask = 0x8;
570 static const uint32_t UShift = 3;
571 static const uint32_t GCAttrMask = 0x30;
572 static const uint32_t GCAttrShift = 4;
573 static const uint32_t LifetimeMask = 0x1C0;
574 static const uint32_t LifetimeShift = 6;
575 static const uint32_t AddressSpaceMask =
576 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
577 static const uint32_t AddressSpaceShift = 9;
578};
579
580/// A std::pair-like structure for storing a qualified type split
581/// into its local qualifiers and its locally-unqualified type.
582struct SplitQualType {
583 /// The locally-unqualified type.
584 const Type *Ty = nullptr;
585
586 /// The local qualifiers.
587 Qualifiers Quals;
588
589 SplitQualType() = default;
590 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
591
592 SplitQualType getSingleStepDesugaredType() const; // end of this file
593
594 // Make std::tie work.
595 std::pair<const Type *,Qualifiers> asPair() const {
596 return std::pair<const Type *, Qualifiers>(Ty, Quals);
597 }
598
599 friend bool operator==(SplitQualType a, SplitQualType b) {
600 return a.Ty == b.Ty && a.Quals == b.Quals;
601 }
602 friend bool operator!=(SplitQualType a, SplitQualType b) {
603 return a.Ty != b.Ty || a.Quals != b.Quals;
604 }
605};
606
607/// The kind of type we are substituting Objective-C type arguments into.
608///
609/// The kind of substitution affects the replacement of type parameters when
610/// no concrete type information is provided, e.g., when dealing with an
611/// unspecialized type.
612enum class ObjCSubstitutionContext {
613 /// An ordinary type.
614 Ordinary,
615
616 /// The result type of a method or function.
617 Result,
618
619 /// The parameter type of a method or function.
620 Parameter,
621
622 /// The type of a property.
623 Property,
624
625 /// The superclass of a type.
626 Superclass,
627};
628
629/// A (possibly-)qualified type.
630///
631/// For efficiency, we don't store CV-qualified types as nodes on their
632/// own: instead each reference to a type stores the qualifiers. This
633/// greatly reduces the number of nodes we need to allocate for types (for
634/// example we only need one for 'int', 'const int', 'volatile int',
635/// 'const volatile int', etc).
636///
637/// As an added efficiency bonus, instead of making this a pair, we
638/// just store the two bits we care about in the low bits of the
639/// pointer. To handle the packing/unpacking, we make QualType be a
640/// simple wrapper class that acts like a smart pointer. A third bit
641/// indicates whether there are extended qualifiers present, in which
642/// case the pointer points to a special structure.
643class QualType {
644 friend class QualifierCollector;
645
646 // Thankfully, these are efficiently composable.
647 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
648 Qualifiers::FastWidth> Value;
649
650 const ExtQuals *getExtQualsUnsafe() const {
651 return Value.getPointer().get<const ExtQuals*>();
652 }
653
654 const Type *getTypePtrUnsafe() const {
655 return Value.getPointer().get<const Type*>();
656 }
657
658 const ExtQualsTypeCommonBase *getCommonPtr() const {
659 assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer")
? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 659, __PRETTY_FUNCTION__))
;
660 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
661 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
662 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
663 }
664
665public:
666 QualType() = default;
667 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
668 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
669
670 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
671 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
672
673 /// Retrieves a pointer to the underlying (unqualified) type.
674 ///
675 /// This function requires that the type not be NULL. If the type might be
676 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
677 const Type *getTypePtr() const;
678
679 const Type *getTypePtrOrNull() const;
680
681 /// Retrieves a pointer to the name of the base type.
682 const IdentifierInfo *getBaseTypeIdentifier() const;
683
684 /// Divides a QualType into its unqualified type and a set of local
685 /// qualifiers.
686 SplitQualType split() const;
687
688 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
689
690 static QualType getFromOpaquePtr(const void *Ptr) {
691 QualType T;
692 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
693 return T;
694 }
695
696 const Type &operator*() const {
697 return *getTypePtr();
698 }
699
700 const Type *operator->() const {
701 return getTypePtr();
702 }
703
704 bool isCanonical() const;
705 bool isCanonicalAsParam() const;
706
707 /// Return true if this QualType doesn't point to a type yet.
708 bool isNull() const {
709 return Value.getPointer().isNull();
710 }
711
712 /// Determine whether this particular QualType instance has the
713 /// "const" qualifier set, without looking through typedefs that may have
714 /// added "const" at a different level.
715 bool isLocalConstQualified() const {
716 return (getLocalFastQualifiers() & Qualifiers::Const);
717 }
718
719 /// Determine whether this type is const-qualified.
720 bool isConstQualified() const;
721
722 /// Determine whether this particular QualType instance has the
723 /// "restrict" qualifier set, without looking through typedefs that may have
724 /// added "restrict" at a different level.
725 bool isLocalRestrictQualified() const {
726 return (getLocalFastQualifiers() & Qualifiers::Restrict);
727 }
728
729 /// Determine whether this type is restrict-qualified.
730 bool isRestrictQualified() const;
731
732 /// Determine whether this particular QualType instance has the
733 /// "volatile" qualifier set, without looking through typedefs that may have
734 /// added "volatile" at a different level.
735 bool isLocalVolatileQualified() const {
736 return (getLocalFastQualifiers() & Qualifiers::Volatile);
737 }
738
739 /// Determine whether this type is volatile-qualified.
740 bool isVolatileQualified() const;
741
742 /// Determine whether this particular QualType instance has any
743 /// qualifiers, without looking through any typedefs that might add
744 /// qualifiers at a different level.
745 bool hasLocalQualifiers() const {
746 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
747 }
748
749 /// Determine whether this type has any qualifiers.
750 bool hasQualifiers() const;
751
752 /// Determine whether this particular QualType instance has any
753 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
754 /// instance.
755 bool hasLocalNonFastQualifiers() const {
756 return Value.getPointer().is<const ExtQuals*>();
757 }
758
759 /// Retrieve the set of qualifiers local to this particular QualType
760 /// instance, not including any qualifiers acquired through typedefs or
761 /// other sugar.
762 Qualifiers getLocalQualifiers() const;
763
764 /// Retrieve the set of qualifiers applied to this type.
765 Qualifiers getQualifiers() const;
766
767 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
768 /// local to this particular QualType instance, not including any qualifiers
769 /// acquired through typedefs or other sugar.
770 unsigned getLocalCVRQualifiers() const {
771 return getLocalFastQualifiers();
772 }
773
774 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
775 /// applied to this type.
776 unsigned getCVRQualifiers() const;
777
778 bool isConstant(const ASTContext& Ctx) const {
779 return QualType::isConstant(*this, Ctx);
780 }
781
782 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
783 bool isPODType(const ASTContext &Context) const;
784
785 /// Return true if this is a POD type according to the rules of the C++98
786 /// standard, regardless of the current compilation's language.
787 bool isCXX98PODType(const ASTContext &Context) const;
788
789 /// Return true if this is a POD type according to the more relaxed rules
790 /// of the C++11 standard, regardless of the current compilation's language.
791 /// (C++0x [basic.types]p9). Note that, unlike
792 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
793 bool isCXX11PODType(const ASTContext &Context) const;
794
795 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
796 bool isTrivialType(const ASTContext &Context) const;
797
798 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
799 bool isTriviallyCopyableType(const ASTContext &Context) const;
800
801
802 /// Returns true if it is a class and it might be dynamic.
803 bool mayBeDynamicClass() const;
804
805 /// Returns true if it is not a class or if the class might not be dynamic.
806 bool mayBeNotDynamicClass() const;
807
808 // Don't promise in the API that anything besides 'const' can be
809 // easily added.
810
811 /// Add the `const` type qualifier to this QualType.
812 void addConst() {
813 addFastQualifiers(Qualifiers::Const);
814 }
815 QualType withConst() const {
816 return withFastQualifiers(Qualifiers::Const);
817 }
818
819 /// Add the `volatile` type qualifier to this QualType.
820 void addVolatile() {
821 addFastQualifiers(Qualifiers::Volatile);
822 }
823 QualType withVolatile() const {
824 return withFastQualifiers(Qualifiers::Volatile);
825 }
826
827 /// Add the `restrict` qualifier to this QualType.
828 void addRestrict() {
829 addFastQualifiers(Qualifiers::Restrict);
830 }
831 QualType withRestrict() const {
832 return withFastQualifiers(Qualifiers::Restrict);
833 }
834
835 QualType withCVRQualifiers(unsigned CVR) const {
836 return withFastQualifiers(CVR);
837 }
838
839 void addFastQualifiers(unsigned TQs) {
840 assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 841, __PRETTY_FUNCTION__))
841 && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 841, __PRETTY_FUNCTION__))
;
842 Value.setInt(Value.getInt() | TQs);
843 }
844
845 void removeLocalConst();
846 void removeLocalVolatile();
847 void removeLocalRestrict();
848 void removeLocalCVRQualifiers(unsigned Mask);
849
850 void removeLocalFastQualifiers() { Value.setInt(0); }
851 void removeLocalFastQualifiers(unsigned Mask) {
852 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 852, __PRETTY_FUNCTION__))
;
853 Value.setInt(Value.getInt() & ~Mask);
854 }
855
856 // Creates a type with the given qualifiers in addition to any
857 // qualifiers already on this type.
858 QualType withFastQualifiers(unsigned TQs) const {
859 QualType T = *this;
860 T.addFastQualifiers(TQs);
861 return T;
862 }
863
864 // Creates a type with exactly the given fast qualifiers, removing
865 // any existing fast qualifiers.
866 QualType withExactLocalFastQualifiers(unsigned TQs) const {
867 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
868 }
869
870 // Removes fast qualifiers, but leaves any extended qualifiers in place.
871 QualType withoutLocalFastQualifiers() const {
872 QualType T = *this;
873 T.removeLocalFastQualifiers();
874 return T;
875 }
876
877 QualType getCanonicalType() const;
878
879 /// Return this type with all of the instance-specific qualifiers
880 /// removed, but without removing any qualifiers that may have been applied
881 /// through typedefs.
882 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
883
884 /// Retrieve the unqualified variant of the given type,
885 /// removing as little sugar as possible.
886 ///
887 /// This routine looks through various kinds of sugar to find the
888 /// least-desugared type that is unqualified. For example, given:
889 ///
890 /// \code
891 /// typedef int Integer;
892 /// typedef const Integer CInteger;
893 /// typedef CInteger DifferenceType;
894 /// \endcode
895 ///
896 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
897 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
898 ///
899 /// The resulting type might still be qualified if it's sugar for an array
900 /// type. To strip qualifiers even from within a sugared array type, use
901 /// ASTContext::getUnqualifiedArrayType.
902 inline QualType getUnqualifiedType() const;
903
904 /// Retrieve the unqualified variant of the given type, removing as little
905 /// sugar as possible.
906 ///
907 /// Like getUnqualifiedType(), but also returns the set of
908 /// qualifiers that were built up.
909 ///
910 /// The resulting type might still be qualified if it's sugar for an array
911 /// type. To strip qualifiers even from within a sugared array type, use
912 /// ASTContext::getUnqualifiedArrayType.
913 inline SplitQualType getSplitUnqualifiedType() const;
914
915 /// Determine whether this type is more qualified than the other
916 /// given type, requiring exact equality for non-CVR qualifiers.
917 bool isMoreQualifiedThan(QualType Other) const;
918
919 /// Determine whether this type is at least as qualified as the other
920 /// given type, requiring exact equality for non-CVR qualifiers.
921 bool isAtLeastAsQualifiedAs(QualType Other) const;
922
923 QualType getNonReferenceType() const;
924
925 /// Determine the type of a (typically non-lvalue) expression with the
926 /// specified result type.
927 ///
928 /// This routine should be used for expressions for which the return type is
929 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
930 /// an lvalue. It removes a top-level reference (since there are no
931 /// expressions of reference type) and deletes top-level cvr-qualifiers
932 /// from non-class types (in C++) or all types (in C).
933 QualType getNonLValueExprType(const ASTContext &Context) const;
934
935 /// Return the specified type with any "sugar" removed from
936 /// the type. This takes off typedefs, typeof's etc. If the outer level of
937 /// the type is already concrete, it returns it unmodified. This is similar
938 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
939 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
940 /// concrete.
941 ///
942 /// Qualifiers are left in place.
943 QualType getDesugaredType(const ASTContext &Context) const {
944 return getDesugaredType(*this, Context);
945 }
946
947 SplitQualType getSplitDesugaredType() const {
948 return getSplitDesugaredType(*this);
949 }
950
951 /// Return the specified type with one level of "sugar" removed from
952 /// the type.
953 ///
954 /// This routine takes off the first typedef, typeof, etc. If the outer level
955 /// of the type is already concrete, it returns it unmodified.
956 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
957 return getSingleStepDesugaredTypeImpl(*this, Context);
958 }
959
960 /// Returns the specified type after dropping any
961 /// outer-level parentheses.
962 QualType IgnoreParens() const {
963 if (isa<ParenType>(*this))
964 return QualType::IgnoreParens(*this);
965 return *this;
966 }
967
968 /// Indicate whether the specified types and qualifiers are identical.
969 friend bool operator==(const QualType &LHS, const QualType &RHS) {
970 return LHS.Value == RHS.Value;
971 }
972 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
973 return LHS.Value != RHS.Value;
974 }
975 friend bool operator<(const QualType &LHS, const QualType &RHS) {
976 return LHS.Value < RHS.Value;
977 }
978
979 static std::string getAsString(SplitQualType split,
980 const PrintingPolicy &Policy) {
981 return getAsString(split.Ty, split.Quals, Policy);
982 }
983 static std::string getAsString(const Type *ty, Qualifiers qs,
984 const PrintingPolicy &Policy);
985
986 std::string getAsString() const;
987 std::string getAsString(const PrintingPolicy &Policy) const;
988
989 void print(raw_ostream &OS, const PrintingPolicy &Policy,
990 const Twine &PlaceHolder = Twine(),
991 unsigned Indentation = 0) const;
992
993 static void print(SplitQualType split, raw_ostream &OS,
994 const PrintingPolicy &policy, const Twine &PlaceHolder,
995 unsigned Indentation = 0) {
996 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
997 }
998
999 static void print(const Type *ty, Qualifiers qs,
1000 raw_ostream &OS, const PrintingPolicy &policy,
1001 const Twine &PlaceHolder,
1002 unsigned Indentation = 0);
1003
1004 void getAsStringInternal(std::string &Str,
1005 const PrintingPolicy &Policy) const;
1006
1007 static void getAsStringInternal(SplitQualType split, std::string &out,
1008 const PrintingPolicy &policy) {
1009 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1010 }
1011
1012 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1013 std::string &out,
1014 const PrintingPolicy &policy);
1015
1016 class StreamedQualTypeHelper {
1017 const QualType &T;
1018 const PrintingPolicy &Policy;
1019 const Twine &PlaceHolder;
1020 unsigned Indentation;
1021
1022 public:
1023 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1024 const Twine &PlaceHolder, unsigned Indentation)
1025 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1026 Indentation(Indentation) {}
1027
1028 friend raw_ostream &operator<<(raw_ostream &OS,
1029 const StreamedQualTypeHelper &SQT) {
1030 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1031 return OS;
1032 }
1033 };
1034
1035 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1036 const Twine &PlaceHolder = Twine(),
1037 unsigned Indentation = 0) const {
1038 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1039 }
1040
1041 void dump(const char *s) const;
1042 void dump() const;
1043 void dump(llvm::raw_ostream &OS) const;
1044
1045 void Profile(llvm::FoldingSetNodeID &ID) const {
1046 ID.AddPointer(getAsOpaquePtr());
1047 }
1048
1049 /// Return the address space of this type.
1050 inline LangAS getAddressSpace() const;
1051
1052 /// Returns gc attribute of this type.
1053 inline Qualifiers::GC getObjCGCAttr() const;
1054
1055 /// true when Type is objc's weak.
1056 bool isObjCGCWeak() const {
1057 return getObjCGCAttr() == Qualifiers::Weak;
1058 }
1059
1060 /// true when Type is objc's strong.
1061 bool isObjCGCStrong() const {
1062 return getObjCGCAttr() == Qualifiers::Strong;
1063 }
1064
1065 /// Returns lifetime attribute of this type.
1066 Qualifiers::ObjCLifetime getObjCLifetime() const {
1067 return getQualifiers().getObjCLifetime();
1068 }
1069
1070 bool hasNonTrivialObjCLifetime() const {
1071 return getQualifiers().hasNonTrivialObjCLifetime();
1072 }
1073
1074 bool hasStrongOrWeakObjCLifetime() const {
1075 return getQualifiers().hasStrongOrWeakObjCLifetime();
1076 }
1077
1078 // true when Type is objc's weak and weak is enabled but ARC isn't.
1079 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1080
1081 enum PrimitiveDefaultInitializeKind {
1082 /// The type does not fall into any of the following categories. Note that
1083 /// this case is zero-valued so that values of this enum can be used as a
1084 /// boolean condition for non-triviality.
1085 PDIK_Trivial,
1086
1087 /// The type is an Objective-C retainable pointer type that is qualified
1088 /// with the ARC __strong qualifier.
1089 PDIK_ARCStrong,
1090
1091 /// The type is an Objective-C retainable pointer type that is qualified
1092 /// with the ARC __weak qualifier.
1093 PDIK_ARCWeak,
1094
1095 /// The type is a struct containing a field whose type is not PCK_Trivial.
1096 PDIK_Struct
1097 };
1098
1099 /// Functions to query basic properties of non-trivial C struct types.
1100
1101 /// Check if this is a non-trivial type that would cause a C struct
1102 /// transitively containing this type to be non-trivial to default initialize
1103 /// and return the kind.
1104 PrimitiveDefaultInitializeKind
1105 isNonTrivialToPrimitiveDefaultInitialize() const;
1106
1107 enum PrimitiveCopyKind {
1108 /// The type does not fall into any of the following categories. Note that
1109 /// this case is zero-valued so that values of this enum can be used as a
1110 /// boolean condition for non-triviality.
1111 PCK_Trivial,
1112
1113 /// The type would be trivial except that it is volatile-qualified. Types
1114 /// that fall into one of the other non-trivial cases may additionally be
1115 /// volatile-qualified.
1116 PCK_VolatileTrivial,
1117
1118 /// The type is an Objective-C retainable pointer type that is qualified
1119 /// with the ARC __strong qualifier.
1120 PCK_ARCStrong,
1121
1122 /// The type is an Objective-C retainable pointer type that is qualified
1123 /// with the ARC __weak qualifier.
1124 PCK_ARCWeak,
1125
1126 /// The type is a struct containing a field whose type is neither
1127 /// PCK_Trivial nor PCK_VolatileTrivial.
1128 /// Note that a C++ struct type does not necessarily match this; C++ copying
1129 /// semantics are too complex to express here, in part because they depend
1130 /// on the exact constructor or assignment operator that is chosen by
1131 /// overload resolution to do the copy.
1132 PCK_Struct
1133 };
1134
1135 /// Check if this is a non-trivial type that would cause a C struct
1136 /// transitively containing this type to be non-trivial to copy and return the
1137 /// kind.
1138 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1139
1140 /// Check if this is a non-trivial type that would cause a C struct
1141 /// transitively containing this type to be non-trivial to destructively
1142 /// move and return the kind. Destructive move in this context is a C++-style
1143 /// move in which the source object is placed in a valid but unspecified state
1144 /// after it is moved, as opposed to a truly destructive move in which the
1145 /// source object is placed in an uninitialized state.
1146 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1147
1148 enum DestructionKind {
1149 DK_none,
1150 DK_cxx_destructor,
1151 DK_objc_strong_lifetime,
1152 DK_objc_weak_lifetime,
1153 DK_nontrivial_c_struct
1154 };
1155
1156 /// Returns a nonzero value if objects of this type require
1157 /// non-trivial work to clean up after. Non-zero because it's
1158 /// conceivable that qualifiers (objc_gc(weak)?) could make
1159 /// something require destruction.
1160 DestructionKind isDestructedType() const {
1161 return isDestructedTypeImpl(*this);
1162 }
1163
1164 /// Check if this is or contains a C union that is non-trivial to
1165 /// default-initialize, which is a union that has a member that is non-trivial
1166 /// to default-initialize. If this returns true,
1167 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1168 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1169
1170 /// Check if this is or contains a C union that is non-trivial to destruct,
1171 /// which is a union that has a member that is non-trivial to destruct. If
1172 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1173 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1174
1175 /// Check if this is or contains a C union that is non-trivial to copy, which
1176 /// is a union that has a member that is non-trivial to copy. If this returns
1177 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1178 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1179
1180 /// Determine whether expressions of the given type are forbidden
1181 /// from being lvalues in C.
1182 ///
1183 /// The expression types that are forbidden to be lvalues are:
1184 /// - 'void', but not qualified void
1185 /// - function types
1186 ///
1187 /// The exact rule here is C99 6.3.2.1:
1188 /// An lvalue is an expression with an object type or an incomplete
1189 /// type other than void.
1190 bool isCForbiddenLValueType() const;
1191
1192 /// Substitute type arguments for the Objective-C type parameters used in the
1193 /// subject type.
1194 ///
1195 /// \param ctx ASTContext in which the type exists.
1196 ///
1197 /// \param typeArgs The type arguments that will be substituted for the
1198 /// Objective-C type parameters in the subject type, which are generally
1199 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1200 /// parameters will be replaced with their bounds or id/Class, as appropriate
1201 /// for the context.
1202 ///
1203 /// \param context The context in which the subject type was written.
1204 ///
1205 /// \returns the resulting type.
1206 QualType substObjCTypeArgs(ASTContext &ctx,
1207 ArrayRef<QualType> typeArgs,
1208 ObjCSubstitutionContext context) const;
1209
1210 /// Substitute type arguments from an object type for the Objective-C type
1211 /// parameters used in the subject type.
1212 ///
1213 /// This operation combines the computation of type arguments for
1214 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1215 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1216 /// callers that need to perform a single substitution in isolation.
1217 ///
1218 /// \param objectType The type of the object whose member type we're
1219 /// substituting into. For example, this might be the receiver of a message
1220 /// or the base of a property access.
1221 ///
1222 /// \param dc The declaration context from which the subject type was
1223 /// retrieved, which indicates (for example) which type parameters should
1224 /// be substituted.
1225 ///
1226 /// \param context The context in which the subject type was written.
1227 ///
1228 /// \returns the subject type after replacing all of the Objective-C type
1229 /// parameters with their corresponding arguments.
1230 QualType substObjCMemberType(QualType objectType,
1231 const DeclContext *dc,
1232 ObjCSubstitutionContext context) const;
1233
1234 /// Strip Objective-C "__kindof" types from the given type.
1235 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1236
1237 /// Remove all qualifiers including _Atomic.
1238 QualType getAtomicUnqualifiedType() const;
1239
1240private:
1241 // These methods are implemented in a separate translation unit;
1242 // "static"-ize them to avoid creating temporary QualTypes in the
1243 // caller.
1244 static bool isConstant(QualType T, const ASTContext& Ctx);
1245 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1246 static SplitQualType getSplitDesugaredType(QualType T);
1247 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1248 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1249 const ASTContext &C);
1250 static QualType IgnoreParens(QualType T);
1251 static DestructionKind isDestructedTypeImpl(QualType type);
1252
1253 /// Check if \param RD is or contains a non-trivial C union.
1254 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1255 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1256 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1257};
1258
1259} // namespace clang
1260
1261namespace llvm {
1262
1263/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1264/// to a specific Type class.
1265template<> struct simplify_type< ::clang::QualType> {
1266 using SimpleType = const ::clang::Type *;
1267
1268 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1269 return Val.getTypePtr();
1270 }
1271};
1272
1273// Teach SmallPtrSet that QualType is "basically a pointer".
1274template<>
1275struct PointerLikeTypeTraits<clang::QualType> {
1276 static inline void *getAsVoidPointer(clang::QualType P) {
1277 return P.getAsOpaquePtr();
1278 }
1279
1280 static inline clang::QualType getFromVoidPointer(void *P) {
1281 return clang::QualType::getFromOpaquePtr(P);
1282 }
1283
1284 // Various qualifiers go in low bits.
1285 enum { NumLowBitsAvailable = 0 };
1286};
1287
1288} // namespace llvm
1289
1290namespace clang {
1291
1292/// Base class that is common to both the \c ExtQuals and \c Type
1293/// classes, which allows \c QualType to access the common fields between the
1294/// two.
1295class ExtQualsTypeCommonBase {
1296 friend class ExtQuals;
1297 friend class QualType;
1298 friend class Type;
1299
1300 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1301 /// a self-referential pointer (for \c Type).
1302 ///
1303 /// This pointer allows an efficient mapping from a QualType to its
1304 /// underlying type pointer.
1305 const Type *const BaseType;
1306
1307 /// The canonical type of this type. A QualType.
1308 QualType CanonicalType;
1309
1310 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1311 : BaseType(baseType), CanonicalType(canon) {}
1312};
1313
1314/// We can encode up to four bits in the low bits of a
1315/// type pointer, but there are many more type qualifiers that we want
1316/// to be able to apply to an arbitrary type. Therefore we have this
1317/// struct, intended to be heap-allocated and used by QualType to
1318/// store qualifiers.
1319///
1320/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1321/// in three low bits on the QualType pointer; a fourth bit records whether
1322/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1323/// Objective-C GC attributes) are much more rare.
1324class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1325 // NOTE: changing the fast qualifiers should be straightforward as
1326 // long as you don't make 'const' non-fast.
1327 // 1. Qualifiers:
1328 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1329 // Fast qualifiers must occupy the low-order bits.
1330 // b) Update Qualifiers::FastWidth and FastMask.
1331 // 2. QualType:
1332 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1333 // b) Update remove{Volatile,Restrict}, defined near the end of
1334 // this header.
1335 // 3. ASTContext:
1336 // a) Update get{Volatile,Restrict}Type.
1337
1338 /// The immutable set of qualifiers applied by this node. Always contains
1339 /// extended qualifiers.
1340 Qualifiers Quals;
1341
1342 ExtQuals *this_() { return this; }
1343
1344public:
1345 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1346 : ExtQualsTypeCommonBase(baseType,
1347 canon.isNull() ? QualType(this_(), 0) : canon),
1348 Quals(quals) {
1349 assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1350, __PRETTY_FUNCTION__))
1350 && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1350, __PRETTY_FUNCTION__))
;
1351 assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1352, __PRETTY_FUNCTION__))
1352 && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1352, __PRETTY_FUNCTION__))
;
1353 }
1354
1355 Qualifiers getQualifiers() const { return Quals; }
1356
1357 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1358 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1359
1360 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1361 Qualifiers::ObjCLifetime getObjCLifetime() const {
1362 return Quals.getObjCLifetime();
1363 }
1364
1365 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1366 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1367
1368 const Type *getBaseType() const { return BaseType; }
1369
1370public:
1371 void Profile(llvm::FoldingSetNodeID &ID) const {
1372 Profile(ID, getBaseType(), Quals);
1373 }
1374
1375 static void Profile(llvm::FoldingSetNodeID &ID,
1376 const Type *BaseType,
1377 Qualifiers Quals) {
1378 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1378, __PRETTY_FUNCTION__))
;
1379 ID.AddPointer(BaseType);
1380 Quals.Profile(ID);
1381 }
1382};
1383
1384/// The kind of C++11 ref-qualifier associated with a function type.
1385/// This determines whether a member function's "this" object can be an
1386/// lvalue, rvalue, or neither.
1387enum RefQualifierKind {
1388 /// No ref-qualifier was provided.
1389 RQ_None = 0,
1390
1391 /// An lvalue ref-qualifier was provided (\c &).
1392 RQ_LValue,
1393
1394 /// An rvalue ref-qualifier was provided (\c &&).
1395 RQ_RValue
1396};
1397
1398/// Which keyword(s) were used to create an AutoType.
1399enum class AutoTypeKeyword {
1400 /// auto
1401 Auto,
1402
1403 /// decltype(auto)
1404 DecltypeAuto,
1405
1406 /// __auto_type (GNU extension)
1407 GNUAutoType
1408};
1409
1410/// The base class of the type hierarchy.
1411///
1412/// A central concept with types is that each type always has a canonical
1413/// type. A canonical type is the type with any typedef names stripped out
1414/// of it or the types it references. For example, consider:
1415///
1416/// typedef int foo;
1417/// typedef foo* bar;
1418/// 'int *' 'foo *' 'bar'
1419///
1420/// There will be a Type object created for 'int'. Since int is canonical, its
1421/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1422/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1423/// there is a PointerType that represents 'int*', which, like 'int', is
1424/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1425/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1426/// is also 'int*'.
1427///
1428/// Non-canonical types are useful for emitting diagnostics, without losing
1429/// information about typedefs being used. Canonical types are useful for type
1430/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1431/// about whether something has a particular form (e.g. is a function type),
1432/// because they implicitly, recursively, strip all typedefs out of a type.
1433///
1434/// Types, once created, are immutable.
1435///
1436class alignas(8) Type : public ExtQualsTypeCommonBase {
1437public:
1438 enum TypeClass {
1439#define TYPE(Class, Base) Class,
1440#define LAST_TYPE(Class) TypeLast = Class
1441#define ABSTRACT_TYPE(Class, Base)
1442#include "clang/AST/TypeNodes.inc"
1443 };
1444
1445private:
1446 /// Bitfields required by the Type class.
1447 class TypeBitfields {
1448 friend class Type;
1449 template <class T> friend class TypePropertyCache;
1450
1451 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1452 unsigned TC : 8;
1453
1454 /// Whether this type is a dependent type (C++ [temp.dep.type]).
1455 unsigned Dependent : 1;
1456
1457 /// Whether this type somehow involves a template parameter, even
1458 /// if the resolution of the type does not depend on a template parameter.
1459 unsigned InstantiationDependent : 1;
1460
1461 /// Whether this type is a variably-modified type (C99 6.7.5).
1462 unsigned VariablyModified : 1;
1463
1464 /// Whether this type contains an unexpanded parameter pack
1465 /// (for C++11 variadic templates).
1466 unsigned ContainsUnexpandedParameterPack : 1;
1467
1468 /// True if the cache (i.e. the bitfields here starting with
1469 /// 'Cache') is valid.
1470 mutable unsigned CacheValid : 1;
1471
1472 /// Linkage of this type.
1473 mutable unsigned CachedLinkage : 3;
1474
1475 /// Whether this type involves and local or unnamed types.
1476 mutable unsigned CachedLocalOrUnnamed : 1;
1477
1478 /// Whether this type comes from an AST file.
1479 mutable unsigned FromAST : 1;
1480
1481 bool isCacheValid() const {
1482 return CacheValid;
1483 }
1484
1485 Linkage getLinkage() const {
1486 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1486, __PRETTY_FUNCTION__))
;
1487 return static_cast<Linkage>(CachedLinkage);
1488 }
1489
1490 bool hasLocalOrUnnamedType() const {
1491 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 1491, __PRETTY_FUNCTION__))
;
1492 return CachedLocalOrUnnamed;
1493 }
1494 };
1495 enum { NumTypeBits = 18 };
1496
1497protected:
1498 // These classes allow subclasses to somewhat cleanly pack bitfields
1499 // into Type.
1500
1501 class ArrayTypeBitfields {
1502 friend class ArrayType;
1503
1504 unsigned : NumTypeBits;
1505
1506 /// CVR qualifiers from declarations like
1507 /// 'int X[static restrict 4]'. For function parameters only.
1508 unsigned IndexTypeQuals : 3;
1509
1510 /// Storage class qualifiers from declarations like
1511 /// 'int X[static restrict 4]'. For function parameters only.
1512 /// Actually an ArrayType::ArraySizeModifier.
1513 unsigned SizeModifier : 3;
1514 };
1515
1516 class BuiltinTypeBitfields {
1517 friend class BuiltinType;
1518
1519 unsigned : NumTypeBits;
1520
1521 /// The kind (BuiltinType::Kind) of builtin type this is.
1522 unsigned Kind : 8;
1523 };
1524
1525 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1526 /// Only common bits are stored here. Additional uncommon bits are stored
1527 /// in a trailing object after FunctionProtoType.
1528 class FunctionTypeBitfields {
1529 friend class FunctionProtoType;
1530 friend class FunctionType;
1531
1532 unsigned : NumTypeBits;
1533
1534 /// Extra information which affects how the function is called, like
1535 /// regparm and the calling convention.
1536 unsigned ExtInfo : 12;
1537
1538 /// The ref-qualifier associated with a \c FunctionProtoType.
1539 ///
1540 /// This is a value of type \c RefQualifierKind.
1541 unsigned RefQualifier : 2;
1542
1543 /// Used only by FunctionProtoType, put here to pack with the
1544 /// other bitfields.
1545 /// The qualifiers are part of FunctionProtoType because...
1546 ///
1547 /// C++ 8.3.5p4: The return type, the parameter type list and the
1548 /// cv-qualifier-seq, [...], are part of the function type.
1549 unsigned FastTypeQuals : Qualifiers::FastWidth;
1550 /// Whether this function has extended Qualifiers.
1551 unsigned HasExtQuals : 1;
1552
1553 /// The number of parameters this function has, not counting '...'.
1554 /// According to [implimits] 8 bits should be enough here but this is
1555 /// somewhat easy to exceed with metaprogramming and so we would like to
1556 /// keep NumParams as wide as reasonably possible.
1557 unsigned NumParams : 16;
1558
1559 /// The type of exception specification this function has.
1560 unsigned ExceptionSpecType : 4;
1561
1562 /// Whether this function has extended parameter information.
1563 unsigned HasExtParameterInfos : 1;
1564
1565 /// Whether the function is variadic.
1566 unsigned Variadic : 1;
1567
1568 /// Whether this function has a trailing return type.
1569 unsigned HasTrailingReturn : 1;
1570 };
1571
1572 class ObjCObjectTypeBitfields {
1573 friend class ObjCObjectType;
1574
1575 unsigned : NumTypeBits;
1576
1577 /// The number of type arguments stored directly on this object type.
1578 unsigned NumTypeArgs : 7;
1579
1580 /// The number of protocols stored directly on this object type.
1581 unsigned NumProtocols : 6;
1582
1583 /// Whether this is a "kindof" type.
1584 unsigned IsKindOf : 1;
1585 };
1586
1587 class ReferenceTypeBitfields {
1588 friend class ReferenceType;
1589
1590 unsigned : NumTypeBits;
1591
1592 /// True if the type was originally spelled with an lvalue sigil.
1593 /// This is never true of rvalue references but can also be false
1594 /// on lvalue references because of C++0x [dcl.typedef]p9,
1595 /// as follows:
1596 ///
1597 /// typedef int &ref; // lvalue, spelled lvalue
1598 /// typedef int &&rvref; // rvalue
1599 /// ref &a; // lvalue, inner ref, spelled lvalue
1600 /// ref &&a; // lvalue, inner ref
1601 /// rvref &a; // lvalue, inner ref, spelled lvalue
1602 /// rvref &&a; // rvalue, inner ref
1603 unsigned SpelledAsLValue : 1;
1604
1605 /// True if the inner type is a reference type. This only happens
1606 /// in non-canonical forms.
1607 unsigned InnerRef : 1;
1608 };
1609
1610 class TypeWithKeywordBitfields {
1611 friend class TypeWithKeyword;
1612
1613 unsigned : NumTypeBits;
1614
1615 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1616 unsigned Keyword : 8;
1617 };
1618
1619 enum { NumTypeWithKeywordBits = 8 };
1620
1621 class ElaboratedTypeBitfields {
1622 friend class ElaboratedType;
1623
1624 unsigned : NumTypeBits;
1625 unsigned : NumTypeWithKeywordBits;
1626
1627 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1628 unsigned HasOwnedTagDecl : 1;
1629 };
1630
1631 class VectorTypeBitfields {
1632 friend class VectorType;
1633 friend class DependentVectorType;
1634
1635 unsigned : NumTypeBits;
1636
1637 /// The kind of vector, either a generic vector type or some
1638 /// target-specific vector type such as for AltiVec or Neon.
1639 unsigned VecKind : 3;
1640
1641 /// The number of elements in the vector.
1642 unsigned NumElements : 29 - NumTypeBits;
1643
1644 enum { MaxNumElements = (1 << (29 - NumTypeBits)) - 1 };
1645 };
1646
1647 class AttributedTypeBitfields {
1648 friend class AttributedType;
1649
1650 unsigned : NumTypeBits;
1651
1652 /// An AttributedType::Kind
1653 unsigned AttrKind : 32 - NumTypeBits;
1654 };
1655
1656 class AutoTypeBitfields {
1657 friend class AutoType;
1658
1659 unsigned : NumTypeBits;
1660
1661 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1662 /// or '__auto_type'? AutoTypeKeyword value.
1663 unsigned Keyword : 2;
1664 };
1665
1666 class SubstTemplateTypeParmPackTypeBitfields {
1667 friend class SubstTemplateTypeParmPackType;
1668
1669 unsigned : NumTypeBits;
1670
1671 /// The number of template arguments in \c Arguments, which is
1672 /// expected to be able to hold at least 1024 according to [implimits].
1673 /// However as this limit is somewhat easy to hit with template
1674 /// metaprogramming we'd prefer to keep it as large as possible.
1675 /// At the moment it has been left as a non-bitfield since this type
1676 /// safely fits in 64 bits as an unsigned, so there is no reason to
1677 /// introduce the performance impact of a bitfield.
1678 unsigned NumArgs;
1679 };
1680
1681 class TemplateSpecializationTypeBitfields {
1682 friend class TemplateSpecializationType;
1683
1684 unsigned : NumTypeBits;
1685
1686 /// Whether this template specialization type is a substituted type alias.
1687 unsigned TypeAlias : 1;
1688
1689 /// The number of template arguments named in this class template
1690 /// specialization, which is expected to be able to hold at least 1024
1691 /// according to [implimits]. However, as this limit is somewhat easy to
1692 /// hit with template metaprogramming we'd prefer to keep it as large
1693 /// as possible. At the moment it has been left as a non-bitfield since
1694 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1695 /// to introduce the performance impact of a bitfield.
1696 unsigned NumArgs;
1697 };
1698
1699 class DependentTemplateSpecializationTypeBitfields {
1700 friend class DependentTemplateSpecializationType;
1701
1702 unsigned : NumTypeBits;
1703 unsigned : NumTypeWithKeywordBits;
1704
1705 /// The number of template arguments named in this class template
1706 /// specialization, which is expected to be able to hold at least 1024
1707 /// according to [implimits]. However, as this limit is somewhat easy to
1708 /// hit with template metaprogramming we'd prefer to keep it as large
1709 /// as possible. At the moment it has been left as a non-bitfield since
1710 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1711 /// to introduce the performance impact of a bitfield.
1712 unsigned NumArgs;
1713 };
1714
1715 class PackExpansionTypeBitfields {
1716 friend class PackExpansionType;
1717
1718 unsigned : NumTypeBits;
1719
1720 /// The number of expansions that this pack expansion will
1721 /// generate when substituted (+1), which is expected to be able to
1722 /// hold at least 1024 according to [implimits]. However, as this limit
1723 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1724 /// keep it as large as possible. At the moment it has been left as a
1725 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1726 /// there is no reason to introduce the performance impact of a bitfield.
1727 ///
1728 /// This field will only have a non-zero value when some of the parameter
1729 /// packs that occur within the pattern have been substituted but others
1730 /// have not.
1731 unsigned NumExpansions;
1732 };
1733
1734 union {
1735 TypeBitfields TypeBits;
1736 ArrayTypeBitfields ArrayTypeBits;
1737 AttributedTypeBitfields AttributedTypeBits;
1738 AutoTypeBitfields AutoTypeBits;
1739 BuiltinTypeBitfields BuiltinTypeBits;
1740 FunctionTypeBitfields FunctionTypeBits;
1741 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1742 ReferenceTypeBitfields ReferenceTypeBits;
1743 TypeWithKeywordBitfields TypeWithKeywordBits;
1744 ElaboratedTypeBitfields ElaboratedTypeBits;
1745 VectorTypeBitfields VectorTypeBits;
1746 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1747 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1748 DependentTemplateSpecializationTypeBitfields
1749 DependentTemplateSpecializationTypeBits;
1750 PackExpansionTypeBitfields PackExpansionTypeBits;
1751
1752 static_assert(sizeof(TypeBitfields) <= 8,
1753 "TypeBitfields is larger than 8 bytes!");
1754 static_assert(sizeof(ArrayTypeBitfields) <= 8,
1755 "ArrayTypeBitfields is larger than 8 bytes!");
1756 static_assert(sizeof(AttributedTypeBitfields) <= 8,
1757 "AttributedTypeBitfields is larger than 8 bytes!");
1758 static_assert(sizeof(AutoTypeBitfields) <= 8,
1759 "AutoTypeBitfields is larger than 8 bytes!");
1760 static_assert(sizeof(BuiltinTypeBitfields) <= 8,
1761 "BuiltinTypeBitfields is larger than 8 bytes!");
1762 static_assert(sizeof(FunctionTypeBitfields) <= 8,
1763 "FunctionTypeBitfields is larger than 8 bytes!");
1764 static_assert(sizeof(ObjCObjectTypeBitfields) <= 8,
1765 "ObjCObjectTypeBitfields is larger than 8 bytes!");
1766 static_assert(sizeof(ReferenceTypeBitfields) <= 8,
1767 "ReferenceTypeBitfields is larger than 8 bytes!");
1768 static_assert(sizeof(TypeWithKeywordBitfields) <= 8,
1769 "TypeWithKeywordBitfields is larger than 8 bytes!");
1770 static_assert(sizeof(ElaboratedTypeBitfields) <= 8,
1771 "ElaboratedTypeBitfields is larger than 8 bytes!");
1772 static_assert(sizeof(VectorTypeBitfields) <= 8,
1773 "VectorTypeBitfields is larger than 8 bytes!");
1774 static_assert(sizeof(SubstTemplateTypeParmPackTypeBitfields) <= 8,
1775 "SubstTemplateTypeParmPackTypeBitfields is larger"
1776 " than 8 bytes!");
1777 static_assert(sizeof(TemplateSpecializationTypeBitfields) <= 8,
1778 "TemplateSpecializationTypeBitfields is larger"
1779 " than 8 bytes!");
1780 static_assert(sizeof(DependentTemplateSpecializationTypeBitfields) <= 8,
1781 "DependentTemplateSpecializationTypeBitfields is larger"
1782 " than 8 bytes!");
1783 static_assert(sizeof(PackExpansionTypeBitfields) <= 8,
1784 "PackExpansionTypeBitfields is larger than 8 bytes");
1785 };
1786
1787private:
1788 template <class T> friend class TypePropertyCache;
1789
1790 /// Set whether this type comes from an AST file.
1791 void setFromAST(bool V = true) const {
1792 TypeBits.FromAST = V;
1793 }
1794
1795protected:
1796 friend class ASTContext;
1797
1798 Type(TypeClass tc, QualType canon, bool Dependent,
1799 bool InstantiationDependent, bool VariablyModified,
1800 bool ContainsUnexpandedParameterPack)
1801 : ExtQualsTypeCommonBase(this,
1802 canon.isNull() ? QualType(this_(), 0) : canon) {
1803 TypeBits.TC = tc;
1804 TypeBits.Dependent = Dependent;
1805 TypeBits.InstantiationDependent = Dependent || InstantiationDependent;
1806 TypeBits.VariablyModified = VariablyModified;
1807 TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1808 TypeBits.CacheValid = false;
1809 TypeBits.CachedLocalOrUnnamed = false;
1810 TypeBits.CachedLinkage = NoLinkage;
1811 TypeBits.FromAST = false;
1812 }
1813
1814 // silence VC++ warning C4355: 'this' : used in base member initializer list
1815 Type *this_() { return this; }
1816
1817 void setDependent(bool D = true) {
1818 TypeBits.Dependent = D;
1819 if (D)
1820 TypeBits.InstantiationDependent = true;
1821 }
1822
1823 void setInstantiationDependent(bool D = true) {
1824 TypeBits.InstantiationDependent = D; }
1825
1826 void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; }
1827
1828 void setContainsUnexpandedParameterPack(bool PP = true) {
1829 TypeBits.ContainsUnexpandedParameterPack = PP;
1830 }
1831
1832public:
1833 friend class ASTReader;
1834 friend class ASTWriter;
1835
1836 Type(const Type &) = delete;
1837 Type(Type &&) = delete;
1838 Type &operator=(const Type &) = delete;
1839 Type &operator=(Type &&) = delete;
1840
1841 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1842
1843 /// Whether this type comes from an AST file.
1844 bool isFromAST() const { return TypeBits.FromAST; }
1845
1846 /// Whether this type is or contains an unexpanded parameter
1847 /// pack, used to support C++0x variadic templates.
1848 ///
1849 /// A type that contains a parameter pack shall be expanded by the
1850 /// ellipsis operator at some point. For example, the typedef in the
1851 /// following example contains an unexpanded parameter pack 'T':
1852 ///
1853 /// \code
1854 /// template<typename ...T>
1855 /// struct X {
1856 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1857 /// };
1858 /// \endcode
1859 ///
1860 /// Note that this routine does not specify which
1861 bool containsUnexpandedParameterPack() const {
1862 return TypeBits.ContainsUnexpandedParameterPack;
1863 }
1864
1865 /// Determines if this type would be canonical if it had no further
1866 /// qualification.
1867 bool isCanonicalUnqualified() const {
1868 return CanonicalType == QualType(this, 0);
1869 }
1870
1871 /// Pull a single level of sugar off of this locally-unqualified type.
1872 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1873 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1874 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1875
1876 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1877 /// object types, function types, and incomplete types.
1878
1879 /// Return true if this is an incomplete type.
1880 /// A type that can describe objects, but which lacks information needed to
1881 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1882 /// routine will need to determine if the size is actually required.
1883 ///
1884 /// Def If non-null, and the type refers to some kind of declaration
1885 /// that can be completed (such as a C struct, C++ class, or Objective-C
1886 /// class), will be set to the declaration.
1887 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1888
1889 /// Return true if this is an incomplete or object
1890 /// type, in other words, not a function type.
1891 bool isIncompleteOrObjectType() const {
1892 return !isFunctionType();
1893 }
1894
1895 /// Determine whether this type is an object type.
1896 bool isObjectType() const {
1897 // C++ [basic.types]p8:
1898 // An object type is a (possibly cv-qualified) type that is not a
1899 // function type, not a reference type, and not a void type.
1900 return !isReferenceType() && !isFunctionType() && !isVoidType();
1901 }
1902
1903 /// Return true if this is a literal type
1904 /// (C++11 [basic.types]p10)
1905 bool isLiteralType(const ASTContext &Ctx) const;
1906
1907 /// Test if this type is a standard-layout type.
1908 /// (C++0x [basic.type]p9)
1909 bool isStandardLayoutType() const;
1910
1911 /// Helper methods to distinguish type categories. All type predicates
1912 /// operate on the canonical type, ignoring typedefs and qualifiers.
1913
1914 /// Returns true if the type is a builtin type.
1915 bool isBuiltinType() const;
1916
1917 /// Test for a particular builtin type.
1918 bool isSpecificBuiltinType(unsigned K) const;
1919
1920 /// Test for a type which does not represent an actual type-system type but
1921 /// is instead used as a placeholder for various convenient purposes within
1922 /// Clang. All such types are BuiltinTypes.
1923 bool isPlaceholderType() const;
1924 const BuiltinType *getAsPlaceholderType() const;
1925
1926 /// Test for a specific placeholder type.
1927 bool isSpecificPlaceholderType(unsigned K) const;
1928
1929 /// Test for a placeholder type other than Overload; see
1930 /// BuiltinType::isNonOverloadPlaceholderType.
1931 bool isNonOverloadPlaceholderType() const;
1932
1933 /// isIntegerType() does *not* include complex integers (a GCC extension).
1934 /// isComplexIntegerType() can be used to test for complex integers.
1935 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1936 bool isEnumeralType() const;
1937
1938 /// Determine whether this type is a scoped enumeration type.
1939 bool isScopedEnumeralType() const;
1940 bool isBooleanType() const;
1941 bool isCharType() const;
1942 bool isWideCharType() const;
1943 bool isChar8Type() const;
1944 bool isChar16Type() const;
1945 bool isChar32Type() const;
1946 bool isAnyCharacterType() const;
1947 bool isIntegralType(const ASTContext &Ctx) const;
1948
1949 /// Determine whether this type is an integral or enumeration type.
1950 bool isIntegralOrEnumerationType() const;
1951
1952 /// Determine whether this type is an integral or unscoped enumeration type.
1953 bool isIntegralOrUnscopedEnumerationType() const;
1954
1955 /// Floating point categories.
1956 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1957 /// isComplexType() does *not* include complex integers (a GCC extension).
1958 /// isComplexIntegerType() can be used to test for complex integers.
1959 bool isComplexType() const; // C99 6.2.5p11 (complex)
1960 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1961 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1962 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1963 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
1964 bool isFloat128Type() const;
1965 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1966 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1967 bool isVoidType() const; // C99 6.2.5p19
1968 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1969 bool isAggregateType() const;
1970 bool isFundamentalType() const;
1971 bool isCompoundType() const;
1972
1973 // Type Predicates: Check to see if this type is structurally the specified
1974 // type, ignoring typedefs and qualifiers.
1975 bool isFunctionType() const;
1976 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1977 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1978 bool isPointerType() const;
1979 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
1980 bool isBlockPointerType() const;
1981 bool isVoidPointerType() const;
1982 bool isReferenceType() const;
1983 bool isLValueReferenceType() const;
1984 bool isRValueReferenceType() const;
1985 bool isFunctionPointerType() const;
1986 bool isFunctionReferenceType() const;
1987 bool isMemberPointerType() const;
1988 bool isMemberFunctionPointerType() const;
1989 bool isMemberDataPointerType() const;
1990 bool isArrayType() const;
1991 bool isConstantArrayType() const;
1992 bool isIncompleteArrayType() const;
1993 bool isVariableArrayType() const;
1994 bool isDependentSizedArrayType() const;
1995 bool isRecordType() const;
1996 bool isClassType() const;
1997 bool isStructureType() const;
1998 bool isObjCBoxableRecordType() const;
1999 bool isInterfaceType() const;
2000 bool isStructureOrClassType() const;
2001 bool isUnionType() const;
2002 bool isComplexIntegerType() const; // GCC _Complex integer type.
2003 bool isVectorType() const; // GCC vector type.
2004 bool isExtVectorType() const; // Extended vector type.
2005 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2006 bool isObjCObjectPointerType() const; // pointer to ObjC object
2007 bool isObjCRetainableType() const; // ObjC object or block pointer
2008 bool isObjCLifetimeType() const; // (array of)* retainable type
2009 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2010 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2011 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2012 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2013 // for the common case.
2014 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2015 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2016 bool isObjCQualifiedIdType() const; // id<foo>
2017 bool isObjCQualifiedClassType() const; // Class<foo>
2018 bool isObjCObjectOrInterfaceType() const;
2019 bool isObjCIdType() const; // id
2020 bool isDecltypeType() const;
2021 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2022 /// qualifier?
2023 ///
2024 /// This approximates the answer to the following question: if this
2025 /// translation unit were compiled in ARC, would this type be qualified
2026 /// with __unsafe_unretained?
2027 bool isObjCInertUnsafeUnretainedType() const {
2028 return hasAttr(attr::ObjCInertUnsafeUnretained);
2029 }
2030
2031 /// Whether the type is Objective-C 'id' or a __kindof type of an
2032 /// object type, e.g., __kindof NSView * or __kindof id
2033 /// <NSCopying>.
2034 ///
2035 /// \param bound Will be set to the bound on non-id subtype types,
2036 /// which will be (possibly specialized) Objective-C class type, or
2037 /// null for 'id.
2038 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2039 const ObjCObjectType *&bound) const;
2040
2041 bool isObjCClassType() const; // Class
2042
2043 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2044 /// Class type, e.g., __kindof Class <NSCopying>.
2045 ///
2046 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2047 /// here because Objective-C's type system cannot express "a class
2048 /// object for a subclass of NSFoo".
2049 bool isObjCClassOrClassKindOfType() const;
2050
2051 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2052 bool isObjCSelType() const; // Class
2053 bool isObjCBuiltinType() const; // 'id' or 'Class'
2054 bool isObjCARCBridgableType() const;
2055 bool isCARCBridgableType() const;
2056 bool isTemplateTypeParmType() const; // C++ template type parameter
2057 bool isNullPtrType() const; // C++11 std::nullptr_t
2058 bool isNothrowT() const; // C++ std::nothrow_t
2059 bool isAlignValT() const; // C++17 std::align_val_t
2060 bool isStdByteType() const; // C++17 std::byte
2061 bool isAtomicType() const; // C11 _Atomic()
2062
2063#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2064 bool is##Id##Type() const;
2065#include "clang/Basic/OpenCLImageTypes.def"
2066
2067 bool isImageType() const; // Any OpenCL image type
2068
2069 bool isSamplerT() const; // OpenCL sampler_t
2070 bool isEventT() const; // OpenCL event_t
2071 bool isClkEventT() const; // OpenCL clk_event_t
2072 bool isQueueT() const; // OpenCL queue_t
2073 bool isReserveIDT() const; // OpenCL reserve_id_t
2074
2075#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2076 bool is##Id##Type() const;
2077#include "clang/Basic/OpenCLExtensionTypes.def"
2078 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2079 bool isOCLIntelSubgroupAVCType() const;
2080 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2081
2082 bool isPipeType() const; // OpenCL pipe type
2083 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2084
2085 /// Determines if this type, which must satisfy
2086 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2087 /// than implicitly __strong.
2088 bool isObjCARCImplicitlyUnretainedType() const;
2089
2090 /// Return the implicit lifetime for this type, which must not be dependent.
2091 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2092
2093 enum ScalarTypeKind {
2094 STK_CPointer,
2095 STK_BlockPointer,
2096 STK_ObjCObjectPointer,
2097 STK_MemberPointer,
2098 STK_Bool,
2099 STK_Integral,
2100 STK_Floating,
2101 STK_IntegralComplex,
2102 STK_FloatingComplex,
2103 STK_FixedPoint
2104 };
2105
2106 /// Given that this is a scalar type, classify it.
2107 ScalarTypeKind getScalarTypeKind() const;
2108
2109 /// Whether this type is a dependent type, meaning that its definition
2110 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2111 bool isDependentType() const { return TypeBits.Dependent; }
2112
2113 /// Determine whether this type is an instantiation-dependent type,
2114 /// meaning that the type involves a template parameter (even if the
2115 /// definition does not actually depend on the type substituted for that
2116 /// template parameter).
2117 bool isInstantiationDependentType() const {
2118 return TypeBits.InstantiationDependent;
2119 }
2120
2121 /// Determine whether this type is an undeduced type, meaning that
2122 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2123 /// deduced.
2124 bool isUndeducedType() const;
2125
2126 /// Whether this type is a variably-modified type (C99 6.7.5).
2127 bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
2128
2129 /// Whether this type involves a variable-length array type
2130 /// with a definite size.
2131 bool hasSizedVLAType() const;
2132
2133 /// Whether this type is or contains a local or unnamed type.
2134 bool hasUnnamedOrLocalType() const;
2135
2136 bool isOverloadableType() const;
2137
2138 /// Determine wither this type is a C++ elaborated-type-specifier.
2139 bool isElaboratedTypeSpecifier() const;
2140
2141 bool canDecayToPointerType() const;
2142
2143 /// Whether this type is represented natively as a pointer. This includes
2144 /// pointers, references, block pointers, and Objective-C interface,
2145 /// qualified id, and qualified interface types, as well as nullptr_t.
2146 bool hasPointerRepresentation() const;
2147
2148 /// Whether this type can represent an objective pointer type for the
2149 /// purpose of GC'ability
2150 bool hasObjCPointerRepresentation() const;
2151
2152 /// Determine whether this type has an integer representation
2153 /// of some sort, e.g., it is an integer type or a vector.
2154 bool hasIntegerRepresentation() const;
2155
2156 /// Determine whether this type has an signed integer representation
2157 /// of some sort, e.g., it is an signed integer type or a vector.
2158 bool hasSignedIntegerRepresentation() const;
2159
2160 /// Determine whether this type has an unsigned integer representation
2161 /// of some sort, e.g., it is an unsigned integer type or a vector.
2162 bool hasUnsignedIntegerRepresentation() const;
2163
2164 /// Determine whether this type has a floating-point representation
2165 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2166 bool hasFloatingRepresentation() const;
2167
2168 // Type Checking Functions: Check to see if this type is structurally the
2169 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2170 // the best type we can.
2171 const RecordType *getAsStructureType() const;
2172 /// NOTE: getAs*ArrayType are methods on ASTContext.
2173 const RecordType *getAsUnionType() const;
2174 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2175 const ObjCObjectType *getAsObjCInterfaceType() const;
2176
2177 // The following is a convenience method that returns an ObjCObjectPointerType
2178 // for object declared using an interface.
2179 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2180 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2181 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2182 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2183
2184 /// Retrieves the CXXRecordDecl that this type refers to, either
2185 /// because the type is a RecordType or because it is the injected-class-name
2186 /// type of a class template or class template partial specialization.
2187 CXXRecordDecl *getAsCXXRecordDecl() const;
2188
2189 /// Retrieves the RecordDecl this type refers to.
2190 RecordDecl *getAsRecordDecl() const;
2191
2192 /// Retrieves the TagDecl that this type refers to, either
2193 /// because the type is a TagType or because it is the injected-class-name
2194 /// type of a class template or class template partial specialization.
2195 TagDecl *getAsTagDecl() const;
2196
2197 /// If this is a pointer or reference to a RecordType, return the
2198 /// CXXRecordDecl that the type refers to.
2199 ///
2200 /// If this is not a pointer or reference, or the type being pointed to does
2201 /// not refer to a CXXRecordDecl, returns NULL.
2202 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2203
2204 /// Get the DeducedType whose type will be deduced for a variable with
2205 /// an initializer of this type. This looks through declarators like pointer
2206 /// types, but not through decltype or typedefs.
2207 DeducedType *getContainedDeducedType() const;
2208
2209 /// Get the AutoType whose type will be deduced for a variable with
2210 /// an initializer of this type. This looks through declarators like pointer
2211 /// types, but not through decltype or typedefs.
2212 AutoType *getContainedAutoType() const {
2213 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2214 }
2215
2216 /// Determine whether this type was written with a leading 'auto'
2217 /// corresponding to a trailing return type (possibly for a nested
2218 /// function type within a pointer to function type or similar).
2219 bool hasAutoForTrailingReturnType() const;
2220
2221 /// Member-template getAs<specific type>'. Look through sugar for
2222 /// an instance of \<specific type>. This scheme will eventually
2223 /// replace the specific getAsXXXX methods above.
2224 ///
2225 /// There are some specializations of this member template listed
2226 /// immediately following this class.
2227 template <typename T> const T *getAs() const;
2228
2229 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2230 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2231 /// This is used when you need to walk over sugar nodes that represent some
2232 /// kind of type adjustment from a type that was written as a \<specific type>
2233 /// to another type that is still canonically a \<specific type>.
2234 template <typename T> const T *getAsAdjusted() const;
2235
2236 /// A variant of getAs<> for array types which silently discards
2237 /// qualifiers from the outermost type.
2238 const ArrayType *getAsArrayTypeUnsafe() const;
2239
2240 /// Member-template castAs<specific type>. Look through sugar for
2241 /// the underlying instance of \<specific type>.
2242 ///
2243 /// This method has the same relationship to getAs<T> as cast<T> has
2244 /// to dyn_cast<T>; which is to say, the underlying type *must*
2245 /// have the intended type, and this method will never return null.
2246 template <typename T> const T *castAs() const;
2247
2248 /// A variant of castAs<> for array type which silently discards
2249 /// qualifiers from the outermost type.
2250 const ArrayType *castAsArrayTypeUnsafe() const;
2251
2252 /// Determine whether this type had the specified attribute applied to it
2253 /// (looking through top-level type sugar).
2254 bool hasAttr(attr::Kind AK) const;
2255
2256 /// Get the base element type of this type, potentially discarding type
2257 /// qualifiers. This should never be used when type qualifiers
2258 /// are meaningful.
2259 const Type *getBaseElementTypeUnsafe() const;
2260
2261 /// If this is an array type, return the element type of the array,
2262 /// potentially with type qualifiers missing.
2263 /// This should never be used when type qualifiers are meaningful.
2264 const Type *getArrayElementTypeNoTypeQual() const;
2265
2266 /// If this is a pointer type, return the pointee type.
2267 /// If this is an array type, return the array element type.
2268 /// This should never be used when type qualifiers are meaningful.
2269 const Type *getPointeeOrArrayElementType() const;
2270
2271 /// If this is a pointer, ObjC object pointer, or block
2272 /// pointer, this returns the respective pointee.
2273 QualType getPointeeType() const;
2274
2275 /// Return the specified type with any "sugar" removed from the type,
2276 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2277 const Type *getUnqualifiedDesugaredType() const;
2278
2279 /// More type predicates useful for type checking/promotion
2280 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2281
2282 /// Return true if this is an integer type that is
2283 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2284 /// or an enum decl which has a signed representation.
2285 bool isSignedIntegerType() const;
2286
2287 /// Return true if this is an integer type that is
2288 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2289 /// or an enum decl which has an unsigned representation.
2290 bool isUnsignedIntegerType() const;
2291
2292 /// Determines whether this is an integer type that is signed or an
2293 /// enumeration types whose underlying type is a signed integer type.
2294 bool isSignedIntegerOrEnumerationType() const;
2295
2296 /// Determines whether this is an integer type that is unsigned or an
2297 /// enumeration types whose underlying type is a unsigned integer type.
2298 bool isUnsignedIntegerOrEnumerationType() const;
2299
2300 /// Return true if this is a fixed point type according to
2301 /// ISO/IEC JTC1 SC22 WG14 N1169.
2302 bool isFixedPointType() const;
2303
2304 /// Return true if this is a fixed point or integer type.
2305 bool isFixedPointOrIntegerType() const;
2306
2307 /// Return true if this is a saturated fixed point type according to
2308 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2309 bool isSaturatedFixedPointType() const;
2310
2311 /// Return true if this is a saturated fixed point type according to
2312 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2313 bool isUnsaturatedFixedPointType() const;
2314
2315 /// Return true if this is a fixed point type that is signed according
2316 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2317 bool isSignedFixedPointType() const;
2318
2319 /// Return true if this is a fixed point type that is unsigned according
2320 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2321 bool isUnsignedFixedPointType() const;
2322
2323 /// Return true if this is not a variable sized type,
2324 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2325 /// incomplete types.
2326 bool isConstantSizeType() const;
2327
2328 /// Returns true if this type can be represented by some
2329 /// set of type specifiers.
2330 bool isSpecifierType() const;
2331
2332 /// Determine the linkage of this type.
2333 Linkage getLinkage() const;
2334
2335 /// Determine the visibility of this type.
2336 Visibility getVisibility() const {
2337 return getLinkageAndVisibility().getVisibility();
2338 }
2339
2340 /// Return true if the visibility was explicitly set is the code.
2341 bool isVisibilityExplicit() const {
2342 return getLinkageAndVisibility().isVisibilityExplicit();
2343 }
2344
2345 /// Determine the linkage and visibility of this type.
2346 LinkageInfo getLinkageAndVisibility() const;
2347
2348 /// True if the computed linkage is valid. Used for consistency
2349 /// checking. Should always return true.
2350 bool isLinkageValid() const;
2351
2352 /// Determine the nullability of the given type.
2353 ///
2354 /// Note that nullability is only captured as sugar within the type
2355 /// system, not as part of the canonical type, so nullability will
2356 /// be lost by canonicalization and desugaring.
2357 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2358
2359 /// Determine whether the given type can have a nullability
2360 /// specifier applied to it, i.e., if it is any kind of pointer type.
2361 ///
2362 /// \param ResultIfUnknown The value to return if we don't yet know whether
2363 /// this type can have nullability because it is dependent.
2364 bool canHaveNullability(bool ResultIfUnknown = true) const;
2365
2366 /// Retrieve the set of substitutions required when accessing a member
2367 /// of the Objective-C receiver type that is declared in the given context.
2368 ///
2369 /// \c *this is the type of the object we're operating on, e.g., the
2370 /// receiver for a message send or the base of a property access, and is
2371 /// expected to be of some object or object pointer type.
2372 ///
2373 /// \param dc The declaration context for which we are building up a
2374 /// substitution mapping, which should be an Objective-C class, extension,
2375 /// category, or method within.
2376 ///
2377 /// \returns an array of type arguments that can be substituted for
2378 /// the type parameters of the given declaration context in any type described
2379 /// within that context, or an empty optional to indicate that no
2380 /// substitution is required.
2381 Optional<ArrayRef<QualType>>
2382 getObjCSubstitutions(const DeclContext *dc) const;
2383
2384 /// Determines if this is an ObjC interface type that may accept type
2385 /// parameters.
2386 bool acceptsObjCTypeParams() const;
2387
2388 const char *getTypeClassName() const;
2389
2390 QualType getCanonicalTypeInternal() const {
2391 return CanonicalType;
2392 }
2393
2394 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2395 void dump() const;
2396 void dump(llvm::raw_ostream &OS) const;
2397};
2398
2399/// This will check for a TypedefType by removing any existing sugar
2400/// until it reaches a TypedefType or a non-sugared type.
2401template <> const TypedefType *Type::getAs() const;
2402
2403/// This will check for a TemplateSpecializationType by removing any
2404/// existing sugar until it reaches a TemplateSpecializationType or a
2405/// non-sugared type.
2406template <> const TemplateSpecializationType *Type::getAs() const;
2407
2408/// This will check for an AttributedType by removing any existing sugar
2409/// until it reaches an AttributedType or a non-sugared type.
2410template <> const AttributedType *Type::getAs() const;
2411
2412// We can do canonical leaf types faster, because we don't have to
2413// worry about preserving child type decoration.
2414#define TYPE(Class, Base)
2415#define LEAF_TYPE(Class) \
2416template <> inline const Class##Type *Type::getAs() const { \
2417 return dyn_cast<Class##Type>(CanonicalType); \
2418} \
2419template <> inline const Class##Type *Type::castAs() const { \
2420 return cast<Class##Type>(CanonicalType); \
2421}
2422#include "clang/AST/TypeNodes.inc"
2423
2424/// This class is used for builtin types like 'int'. Builtin
2425/// types are always canonical and have a literal name field.
2426class BuiltinType : public Type {
2427public:
2428 enum Kind {
2429// OpenCL image types
2430#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2431#include "clang/Basic/OpenCLImageTypes.def"
2432// OpenCL extension types
2433#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2434#include "clang/Basic/OpenCLExtensionTypes.def"
2435// SVE Types
2436#define SVE_TYPE(Name, Id, SingletonId) Id,
2437#include "clang/Basic/AArch64SVEACLETypes.def"
2438// All other builtin types
2439#define BUILTIN_TYPE(Id, SingletonId) Id,
2440#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2441#include "clang/AST/BuiltinTypes.def"
2442 };
2443
2444private:
2445 friend class ASTContext; // ASTContext creates these.
2446
2447 BuiltinType(Kind K)
2448 : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
2449 /*InstantiationDependent=*/(K == Dependent),
2450 /*VariablyModified=*/false,
2451 /*Unexpanded parameter pack=*/false) {
2452 BuiltinTypeBits.Kind = K;
2453 }
2454
2455public:
2456 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2457 StringRef getName(const PrintingPolicy &Policy) const;
2458
2459 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2460 // The StringRef is null-terminated.
2461 StringRef str = getName(Policy);
2462 assert(!str.empty() && str.data()[str.size()] == '\0')((!str.empty() && str.data()[str.size()] == '\0') ? static_cast
<void> (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 2462, __PRETTY_FUNCTION__))
;
2463 return str.data();
2464 }
2465
2466 bool isSugared() const { return false; }
2467 QualType desugar() const { return QualType(this, 0); }
2468
2469 bool isInteger() const {
2470 return getKind() >= Bool && getKind() <= Int128;
2471 }
2472
2473 bool isSignedInteger() const {
2474 return getKind() >= Char_S && getKind() <= Int128;
2475 }
2476
2477 bool isUnsignedInteger() const {
2478 return getKind() >= Bool && getKind() <= UInt128;
2479 }
2480
2481 bool isFloatingPoint() const {
2482 return getKind() >= Half && getKind() <= Float128;
2483 }
2484
2485 /// Determines whether the given kind corresponds to a placeholder type.
2486 static bool isPlaceholderTypeKind(Kind K) {
2487 return K >= Overload;
2488 }
2489
2490 /// Determines whether this type is a placeholder type, i.e. a type
2491 /// which cannot appear in arbitrary positions in a fully-formed
2492 /// expression.
2493 bool isPlaceholderType() const {
2494 return isPlaceholderTypeKind(getKind());
2495 }
2496
2497 /// Determines whether this type is a placeholder type other than
2498 /// Overload. Most placeholder types require only syntactic
2499 /// information about their context in order to be resolved (e.g.
2500 /// whether it is a call expression), which means they can (and
2501 /// should) be resolved in an earlier "phase" of analysis.
2502 /// Overload expressions sometimes pick up further information
2503 /// from their context, like whether the context expects a
2504 /// specific function-pointer type, and so frequently need
2505 /// special treatment.
2506 bool isNonOverloadPlaceholderType() const {
2507 return getKind() > Overload;
2508 }
2509
2510 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2511};
2512
2513/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2514/// types (_Complex float etc) as well as the GCC integer complex extensions.
2515class ComplexType : public Type, public llvm::FoldingSetNode {
2516 friend class ASTContext; // ASTContext creates these.
2517
2518 QualType ElementType;
2519
2520 ComplexType(QualType Element, QualType CanonicalPtr)
2521 : Type(Complex, CanonicalPtr, Element->isDependentType(),
2522 Element->isInstantiationDependentType(),
2523 Element->isVariablyModifiedType(),
2524 Element->containsUnexpandedParameterPack()),
2525 ElementType(Element) {}
2526
2527public:
2528 QualType getElementType() const { return ElementType; }
2529
2530 bool isSugared() const { return false; }
2531 QualType desugar() const { return QualType(this, 0); }
2532
2533 void Profile(llvm::FoldingSetNodeID &ID) {
2534 Profile(ID, getElementType());
2535 }
2536
2537 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2538 ID.AddPointer(Element.getAsOpaquePtr());
2539 }
2540
2541 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2542};
2543
2544/// Sugar for parentheses used when specifying types.
2545class ParenType : public Type, public llvm::FoldingSetNode {
2546 friend class ASTContext; // ASTContext creates these.
2547
2548 QualType Inner;
2549
2550 ParenType(QualType InnerType, QualType CanonType)
2551 : Type(Paren, CanonType, InnerType->isDependentType(),
2552 InnerType->isInstantiationDependentType(),
2553 InnerType->isVariablyModifiedType(),
2554 InnerType->containsUnexpandedParameterPack()),
2555 Inner(InnerType) {}
2556
2557public:
2558 QualType getInnerType() const { return Inner; }
2559
2560 bool isSugared() const { return true; }
2561 QualType desugar() const { return getInnerType(); }
2562
2563 void Profile(llvm::FoldingSetNodeID &ID) {
2564 Profile(ID, getInnerType());
2565 }
2566
2567 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2568 Inner.Profile(ID);
2569 }
2570
2571 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2572};
2573
2574/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2575class PointerType : public Type, public llvm::FoldingSetNode {
2576 friend class ASTContext; // ASTContext creates these.
2577
2578 QualType PointeeType;
2579
2580 PointerType(QualType Pointee, QualType CanonicalPtr)
2581 : Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
2582 Pointee->isInstantiationDependentType(),
2583 Pointee->isVariablyModifiedType(),
2584 Pointee->containsUnexpandedParameterPack()),
2585 PointeeType(Pointee) {}
2586
2587public:
2588 QualType getPointeeType() const { return PointeeType; }
2589
2590 /// Returns true if address spaces of pointers overlap.
2591 /// OpenCL v2.0 defines conversion rules for pointers to different
2592 /// address spaces (OpenCLC v2.0 s6.5.5) and notion of overlapping
2593 /// address spaces.
2594 /// CL1.1 or CL1.2:
2595 /// address spaces overlap iff they are they same.
2596 /// CL2.0 adds:
2597 /// __generic overlaps with any address space except for __constant.
2598 bool isAddressSpaceOverlapping(const PointerType &other) const {
2599 Qualifiers thisQuals = PointeeType.getQualifiers();
2600 Qualifiers otherQuals = other.getPointeeType().getQualifiers();
2601 // Address spaces overlap if at least one of them is a superset of another
2602 return thisQuals.isAddressSpaceSupersetOf(otherQuals) ||
2603 otherQuals.isAddressSpaceSupersetOf(thisQuals);
2604 }
2605
2606 bool isSugared() const { return false; }
2607 QualType desugar() const { return QualType(this, 0); }
2608
2609 void Profile(llvm::FoldingSetNodeID &ID) {
2610 Profile(ID, getPointeeType());
2611 }
2612
2613 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2614 ID.AddPointer(Pointee.getAsOpaquePtr());
2615 }
2616
2617 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2618};
2619
2620/// Represents a type which was implicitly adjusted by the semantic
2621/// engine for arbitrary reasons. For example, array and function types can
2622/// decay, and function types can have their calling conventions adjusted.
2623class AdjustedType : public Type, public llvm::FoldingSetNode {
2624 QualType OriginalTy;
2625 QualType AdjustedTy;
2626
2627protected:
2628 friend class ASTContext; // ASTContext creates these.
2629
2630 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2631 QualType CanonicalPtr)
2632 : Type(TC, CanonicalPtr, OriginalTy->isDependentType(),
2633 OriginalTy->isInstantiationDependentType(),
2634 OriginalTy->isVariablyModifiedType(),
2635 OriginalTy->containsUnexpandedParameterPack()),
2636 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2637
2638public:
2639 QualType getOriginalType() const { return OriginalTy; }
2640 QualType getAdjustedType() const { return AdjustedTy; }
2641
2642 bool isSugared() const { return true; }
2643 QualType desugar() const { return AdjustedTy; }
2644
2645 void Profile(llvm::FoldingSetNodeID &ID) {
2646 Profile(ID, OriginalTy, AdjustedTy);
2647 }
2648
2649 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2650 ID.AddPointer(Orig.getAsOpaquePtr());
2651 ID.AddPointer(New.getAsOpaquePtr());
2652 }
2653
2654 static bool classof(const Type *T) {
2655 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2656 }
2657};
2658
2659/// Represents a pointer type decayed from an array or function type.
2660class DecayedType : public AdjustedType {
2661 friend class ASTContext; // ASTContext creates these.
2662
2663 inline
2664 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2665
2666public:
2667 QualType getDecayedType() const { return getAdjustedType(); }
2668
2669 inline QualType getPointeeType() const;
2670
2671 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2672};
2673
2674/// Pointer to a block type.
2675/// This type is to represent types syntactically represented as
2676/// "void (^)(int)", etc. Pointee is required to always be a function type.
2677class BlockPointerType : public Type, public llvm::FoldingSetNode {
2678 friend class ASTContext; // ASTContext creates these.
2679
2680 // Block is some kind of pointer type
2681 QualType PointeeType;
2682
2683 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2684 : Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
2685 Pointee->isInstantiationDependentType(),
2686 Pointee->isVariablyModifiedType(),
2687 Pointee->containsUnexpandedParameterPack()),
2688 PointeeType(Pointee) {}
2689
2690public:
2691 // Get the pointee type. Pointee is required to always be a function type.
2692 QualType getPointeeType() const { return PointeeType; }
2693
2694 bool isSugared() const { return false; }
2695 QualType desugar() const { return QualType(this, 0); }
2696
2697 void Profile(llvm::FoldingSetNodeID &ID) {
2698 Profile(ID, getPointeeType());
2699 }
2700
2701 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2702 ID.AddPointer(Pointee.getAsOpaquePtr());
2703 }
2704
2705 static bool classof(const Type *T) {
2706 return T->getTypeClass() == BlockPointer;
2707 }
2708};
2709
2710/// Base for LValueReferenceType and RValueReferenceType
2711class ReferenceType : public Type, public llvm::FoldingSetNode {
2712 QualType PointeeType;
2713
2714protected:
2715 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2716 bool SpelledAsLValue)
2717 : Type(tc, CanonicalRef, Referencee->isDependentType(),
2718 Referencee->isInstantiationDependentType(),
2719 Referencee->isVariablyModifiedType(),
2720 Referencee->containsUnexpandedParameterPack()),
2721 PointeeType(Referencee) {
2722 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2723 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2724 }
2725
2726public:
2727 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2728 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2729
2730 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2731
2732 QualType getPointeeType() const {
2733 // FIXME: this might strip inner qualifiers; okay?
2734 const ReferenceType *T = this;
2735 while (T->isInnerRef())
2736 T = T->PointeeType->castAs<ReferenceType>();
2737 return T->PointeeType;
2738 }
2739
2740 void Profile(llvm::FoldingSetNodeID &ID) {
2741 Profile(ID, PointeeType, isSpelledAsLValue());
2742 }
2743
2744 static void Profile(llvm::FoldingSetNodeID &ID,
2745 QualType Referencee,
2746 bool SpelledAsLValue) {
2747 ID.AddPointer(Referencee.getAsOpaquePtr());
2748 ID.AddBoolean(SpelledAsLValue);
2749 }
2750
2751 static bool classof(const Type *T) {
2752 return T->getTypeClass() == LValueReference ||
2753 T->getTypeClass() == RValueReference;
2754 }
2755};
2756
2757/// An lvalue reference type, per C++11 [dcl.ref].
2758class LValueReferenceType : public ReferenceType {
2759 friend class ASTContext; // ASTContext creates these
2760
2761 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2762 bool SpelledAsLValue)
2763 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2764 SpelledAsLValue) {}
2765
2766public:
2767 bool isSugared() const { return false; }
2768 QualType desugar() const { return QualType(this, 0); }
2769
2770 static bool classof(const Type *T) {
2771 return T->getTypeClass() == LValueReference;
2772 }
2773};
2774
2775/// An rvalue reference type, per C++11 [dcl.ref].
2776class RValueReferenceType : public ReferenceType {
2777 friend class ASTContext; // ASTContext creates these
2778
2779 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2780 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2781
2782public:
2783 bool isSugared() const { return false; }
2784 QualType desugar() const { return QualType(this, 0); }
2785
2786 static bool classof(const Type *T) {
2787 return T->getTypeClass() == RValueReference;
2788 }
2789};
2790
2791/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2792///
2793/// This includes both pointers to data members and pointer to member functions.
2794class MemberPointerType : public Type, public llvm::FoldingSetNode {
2795 friend class ASTContext; // ASTContext creates these.
2796
2797 QualType PointeeType;
2798
2799 /// The class of which the pointee is a member. Must ultimately be a
2800 /// RecordType, but could be a typedef or a template parameter too.
2801 const Type *Class;
2802
2803 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2804 : Type(MemberPointer, CanonicalPtr,
2805 Cls->isDependentType() || Pointee->isDependentType(),
2806 (Cls->isInstantiationDependentType() ||
2807 Pointee->isInstantiationDependentType()),
2808 Pointee->isVariablyModifiedType(),
2809 (Cls->containsUnexpandedParameterPack() ||
2810 Pointee->containsUnexpandedParameterPack())),
2811 PointeeType(Pointee), Class(Cls) {}
2812
2813public:
2814 QualType getPointeeType() const { return PointeeType; }
2815
2816 /// Returns true if the member type (i.e. the pointee type) is a
2817 /// function type rather than a data-member type.
2818 bool isMemberFunctionPointer() const {
2819 return PointeeType->isFunctionProtoType();
2820 }
2821
2822 /// Returns true if the member type (i.e. the pointee type) is a
2823 /// data type rather than a function type.
2824 bool isMemberDataPointer() const {
2825 return !PointeeType->isFunctionProtoType();
2826 }
2827
2828 const Type *getClass() const { return Class; }
2829 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2830
2831 bool isSugared() const { return false; }
2832 QualType desugar() const { return QualType(this, 0); }
2833
2834 void Profile(llvm::FoldingSetNodeID &ID) {
2835 Profile(ID, getPointeeType(), getClass());
2836 }
2837
2838 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2839 const Type *Class) {
2840 ID.AddPointer(Pointee.getAsOpaquePtr());
2841 ID.AddPointer(Class);
2842 }
2843
2844 static bool classof(const Type *T) {
2845 return T->getTypeClass() == MemberPointer;
2846 }
2847};
2848
2849/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2850class ArrayType : public Type, public llvm::FoldingSetNode {
2851public:
2852 /// Capture whether this is a normal array (e.g. int X[4])
2853 /// an array with a static size (e.g. int X[static 4]), or an array
2854 /// with a star size (e.g. int X[*]).
2855 /// 'static' is only allowed on function parameters.
2856 enum ArraySizeModifier {
2857 Normal, Static, Star
2858 };
2859
2860private:
2861 /// The element type of the array.
2862 QualType ElementType;
2863
2864protected:
2865 friend class ASTContext; // ASTContext creates these.
2866
2867 // C++ [temp.dep.type]p1:
2868 // A type is dependent if it is...
2869 // - an array type constructed from any dependent type or whose
2870 // size is specified by a constant expression that is
2871 // value-dependent,
2872 ArrayType(TypeClass tc, QualType et, QualType can,
2873 ArraySizeModifier sm, unsigned tq,
2874 bool ContainsUnexpandedParameterPack)
2875 : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
2876 et->isInstantiationDependentType() || tc == DependentSizedArray,
2877 (tc == VariableArray || et->isVariablyModifiedType()),
2878 ContainsUnexpandedParameterPack),
2879 ElementType(et) {
2880 ArrayTypeBits.IndexTypeQuals = tq;
2881 ArrayTypeBits.SizeModifier = sm;
2882 }
2883
2884public:
2885 QualType getElementType() const { return ElementType; }
2886
2887 ArraySizeModifier getSizeModifier() const {
2888 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2889 }
2890
2891 Qualifiers getIndexTypeQualifiers() const {
2892 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2893 }
2894
2895 unsigned getIndexTypeCVRQualifiers() const {
2896 return ArrayTypeBits.IndexTypeQuals;
2897 }
2898
2899 static bool classof(const Type *T) {
2900 return T->getTypeClass() == ConstantArray ||
2901 T->getTypeClass() == VariableArray ||
2902 T->getTypeClass() == IncompleteArray ||
2903 T->getTypeClass() == DependentSizedArray;
2904 }
2905};
2906
2907/// Represents the canonical version of C arrays with a specified constant size.
2908/// For example, the canonical type for 'int A[4 + 4*100]' is a
2909/// ConstantArrayType where the element type is 'int' and the size is 404.
2910class ConstantArrayType : public ArrayType {
2911 llvm::APInt Size; // Allows us to unique the type.
2912
2913 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2914 ArraySizeModifier sm, unsigned tq)
2915 : ArrayType(ConstantArray, et, can, sm, tq,
2916 et->containsUnexpandedParameterPack()),
2917 Size(size) {}
2918
2919protected:
2920 friend class ASTContext; // ASTContext creates these.
2921
2922 ConstantArrayType(TypeClass tc, QualType et, QualType can,
2923 const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
2924 : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
2925 Size(size) {}
2926
2927public:
2928 const llvm::APInt &getSize() const { return Size; }
2929 bool isSugared() const { return false; }
2930 QualType desugar() const { return QualType(this, 0); }
2931
2932 /// Determine the number of bits required to address a member of
2933 // an array with the given element type and number of elements.
2934 static unsigned getNumAddressingBits(const ASTContext &Context,
2935 QualType ElementType,
2936 const llvm::APInt &NumElements);
2937
2938 /// Determine the maximum number of active bits that an array's size
2939 /// can require, which limits the maximum size of the array.
2940 static unsigned getMaxSizeBits(const ASTContext &Context);
2941
2942 void Profile(llvm::FoldingSetNodeID &ID) {
2943 Profile(ID, getElementType(), getSize(),
2944 getSizeModifier(), getIndexTypeCVRQualifiers());
2945 }
2946
2947 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2948 const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
2949 unsigned TypeQuals) {
2950 ID.AddPointer(ET.getAsOpaquePtr());
2951 ID.AddInteger(ArraySize.getZExtValue());
2952 ID.AddInteger(SizeMod);
2953 ID.AddInteger(TypeQuals);
2954 }
2955
2956 static bool classof(const Type *T) {
2957 return T->getTypeClass() == ConstantArray;
2958 }
2959};
2960
2961/// Represents a C array with an unspecified size. For example 'int A[]' has
2962/// an IncompleteArrayType where the element type is 'int' and the size is
2963/// unspecified.
2964class IncompleteArrayType : public ArrayType {
2965 friend class ASTContext; // ASTContext creates these.
2966
2967 IncompleteArrayType(QualType et, QualType can,
2968 ArraySizeModifier sm, unsigned tq)
2969 : ArrayType(IncompleteArray, et, can, sm, tq,
2970 et->containsUnexpandedParameterPack()) {}
2971
2972public:
2973 friend class StmtIteratorBase;
2974
2975 bool isSugared() const { return false; }
2976 QualType desugar() const { return QualType(this, 0); }
2977
2978 static bool classof(const Type *T) {
2979 return T->getTypeClass() == IncompleteArray;
2980 }
2981
2982 void Profile(llvm::FoldingSetNodeID &ID) {
2983 Profile(ID, getElementType(), getSizeModifier(),
2984 getIndexTypeCVRQualifiers());
2985 }
2986
2987 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2988 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2989 ID.AddPointer(ET.getAsOpaquePtr());
2990 ID.AddInteger(SizeMod);
2991 ID.AddInteger(TypeQuals);
2992 }
2993};
2994
2995/// Represents a C array with a specified size that is not an
2996/// integer-constant-expression. For example, 'int s[x+foo()]'.
2997/// Since the size expression is an arbitrary expression, we store it as such.
2998///
2999/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3000/// should not be: two lexically equivalent variable array types could mean
3001/// different things, for example, these variables do not have the same type
3002/// dynamically:
3003///
3004/// void foo(int x) {
3005/// int Y[x];
3006/// ++x;
3007/// int Z[x];
3008/// }
3009class VariableArrayType : public ArrayType {
3010 friend class ASTContext; // ASTContext creates these.
3011
3012 /// An assignment-expression. VLA's are only permitted within
3013 /// a function block.
3014 Stmt *SizeExpr;
3015
3016 /// The range spanned by the left and right array brackets.
3017 SourceRange Brackets;
3018
3019 VariableArrayType(QualType et, QualType can, Expr *e,
3020 ArraySizeModifier sm, unsigned tq,
3021 SourceRange brackets)
3022 : ArrayType(VariableArray, et, can, sm, tq,
3023 et->containsUnexpandedParameterPack()),
3024 SizeExpr((Stmt*) e), Brackets(brackets) {}
3025
3026public:
3027 friend class StmtIteratorBase;
3028
3029 Expr *getSizeExpr() const {
3030 // We use C-style casts instead of cast<> here because we do not wish
3031 // to have a dependency of Type.h on Stmt.h/Expr.h.
3032 return (Expr*) SizeExpr;
3033 }
3034
3035 SourceRange getBracketsRange() const { return Brackets; }
3036 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3037 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3038
3039 bool isSugared() const { return false; }
3040 QualType desugar() const { return QualType(this, 0); }
3041
3042 static bool classof(const Type *T) {
3043 return T->getTypeClass() == VariableArray;
3044 }
3045
3046 void Profile(llvm::FoldingSetNodeID &ID) {
3047 llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes."
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3047)
;
3048 }
3049};
3050
3051/// Represents an array type in C++ whose size is a value-dependent expression.
3052///
3053/// For example:
3054/// \code
3055/// template<typename T, int Size>
3056/// class array {
3057/// T data[Size];
3058/// };
3059/// \endcode
3060///
3061/// For these types, we won't actually know what the array bound is
3062/// until template instantiation occurs, at which point this will
3063/// become either a ConstantArrayType or a VariableArrayType.
3064class DependentSizedArrayType : public ArrayType {
3065 friend class ASTContext; // ASTContext creates these.
3066
3067 const ASTContext &Context;
3068
3069 /// An assignment expression that will instantiate to the
3070 /// size of the array.
3071 ///
3072 /// The expression itself might be null, in which case the array
3073 /// type will have its size deduced from an initializer.
3074 Stmt *SizeExpr;
3075
3076 /// The range spanned by the left and right array brackets.
3077 SourceRange Brackets;
3078
3079 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3080 Expr *e, ArraySizeModifier sm, unsigned tq,
3081 SourceRange brackets);
3082
3083public:
3084 friend class StmtIteratorBase;
3085
3086 Expr *getSizeExpr() const {
3087 // We use C-style casts instead of cast<> here because we do not wish
3088 // to have a dependency of Type.h on Stmt.h/Expr.h.
3089 return (Expr*) SizeExpr;
3090 }
3091
3092 SourceRange getBracketsRange() const { return Brackets; }
3093 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3094 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3095
3096 bool isSugared() const { return false; }
3097 QualType desugar() const { return QualType(this, 0); }
3098
3099 static bool classof(const Type *T) {
3100 return T->getTypeClass() == DependentSizedArray;
3101 }
3102
3103 void Profile(llvm::FoldingSetNodeID &ID) {
3104 Profile(ID, Context, getElementType(),
3105 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3106 }
3107
3108 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3109 QualType ET, ArraySizeModifier SizeMod,
3110 unsigned TypeQuals, Expr *E);
3111};
3112
3113/// Represents an extended address space qualifier where the input address space
3114/// value is dependent. Non-dependent address spaces are not represented with a
3115/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3116///
3117/// For example:
3118/// \code
3119/// template<typename T, int AddrSpace>
3120/// class AddressSpace {
3121/// typedef T __attribute__((address_space(AddrSpace))) type;
3122/// }
3123/// \endcode
3124class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3125 friend class ASTContext;
3126
3127 const ASTContext &Context;
3128 Expr *AddrSpaceExpr;
3129 QualType PointeeType;
3130 SourceLocation loc;
3131
3132 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3133 QualType can, Expr *AddrSpaceExpr,
3134 SourceLocation loc);
3135
3136public:
3137 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3138 QualType getPointeeType() const { return PointeeType; }
3139 SourceLocation getAttributeLoc() const { return loc; }
3140
3141 bool isSugared() const { return false; }
3142 QualType desugar() const { return QualType(this, 0); }
3143
3144 static bool classof(const Type *T) {
3145 return T->getTypeClass() == DependentAddressSpace;
3146 }
3147
3148 void Profile(llvm::FoldingSetNodeID &ID) {
3149 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3150 }
3151
3152 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3153 QualType PointeeType, Expr *AddrSpaceExpr);
3154};
3155
3156/// Represents an extended vector type where either the type or size is
3157/// dependent.
3158///
3159/// For example:
3160/// \code
3161/// template<typename T, int Size>
3162/// class vector {
3163/// typedef T __attribute__((ext_vector_type(Size))) type;
3164/// }
3165/// \endcode
3166class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3167 friend class ASTContext;
3168
3169 const ASTContext &Context;
3170 Expr *SizeExpr;
3171
3172 /// The element type of the array.
3173 QualType ElementType;
3174
3175 SourceLocation loc;
3176
3177 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3178 QualType can, Expr *SizeExpr, SourceLocation loc);
3179
3180public:
3181 Expr *getSizeExpr() const { return SizeExpr; }
3182 QualType getElementType() const { return ElementType; }
3183 SourceLocation getAttributeLoc() const { return loc; }
3184
3185 bool isSugared() const { return false; }
3186 QualType desugar() const { return QualType(this, 0); }
3187
3188 static bool classof(const Type *T) {
3189 return T->getTypeClass() == DependentSizedExtVector;
3190 }
3191
3192 void Profile(llvm::FoldingSetNodeID &ID) {
3193 Profile(ID, Context, getElementType(), getSizeExpr());
3194 }
3195
3196 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3197 QualType ElementType, Expr *SizeExpr);
3198};
3199
3200
3201/// Represents a GCC generic vector type. This type is created using
3202/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3203/// bytes; or from an Altivec __vector or vector declaration.
3204/// Since the constructor takes the number of vector elements, the
3205/// client is responsible for converting the size into the number of elements.
3206class VectorType : public Type, public llvm::FoldingSetNode {
3207public:
3208 enum VectorKind {
3209 /// not a target-specific vector type
3210 GenericVector,
3211
3212 /// is AltiVec vector
3213 AltiVecVector,
3214
3215 /// is AltiVec 'vector Pixel'
3216 AltiVecPixel,
3217
3218 /// is AltiVec 'vector bool ...'
3219 AltiVecBool,
3220
3221 /// is ARM Neon vector
3222 NeonVector,
3223
3224 /// is ARM Neon polynomial vector
3225 NeonPolyVector
3226 };
3227
3228protected:
3229 friend class ASTContext; // ASTContext creates these.
3230
3231 /// The element type of the vector.
3232 QualType ElementType;
3233
3234 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3235 VectorKind vecKind);
3236
3237 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3238 QualType canonType, VectorKind vecKind);
3239
3240public:
3241 QualType getElementType() const { return ElementType; }
3242 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3243
3244 static bool isVectorSizeTooLarge(unsigned NumElements) {
3245 return NumElements > VectorTypeBitfields::MaxNumElements;
3246 }
3247
3248 bool isSugared() const { return false; }
3249 QualType desugar() const { return QualType(this, 0); }
3250
3251 VectorKind getVectorKind() const {
3252 return VectorKind(VectorTypeBits.VecKind);
3253 }
3254
3255 void Profile(llvm::FoldingSetNodeID &ID) {
3256 Profile(ID, getElementType(), getNumElements(),
3257 getTypeClass(), getVectorKind());
3258 }
3259
3260 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3261 unsigned NumElements, TypeClass TypeClass,
3262 VectorKind VecKind) {
3263 ID.AddPointer(ElementType.getAsOpaquePtr());
3264 ID.AddInteger(NumElements);
3265 ID.AddInteger(TypeClass);
3266 ID.AddInteger(VecKind);
3267 }
3268
3269 static bool classof(const Type *T) {
3270 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3271 }
3272};
3273
3274/// Represents a vector type where either the type or size is dependent.
3275////
3276/// For example:
3277/// \code
3278/// template<typename T, int Size>
3279/// class vector {
3280/// typedef T __attribute__((vector_size(Size))) type;
3281/// }
3282/// \endcode
3283class DependentVectorType : public Type, public llvm::FoldingSetNode {
3284 friend class ASTContext;
3285
3286 const ASTContext &Context;
3287 QualType ElementType;
3288 Expr *SizeExpr;
3289 SourceLocation Loc;
3290
3291 DependentVectorType(const ASTContext &Context, QualType ElementType,
3292 QualType CanonType, Expr *SizeExpr,
3293 SourceLocation Loc, VectorType::VectorKind vecKind);
3294
3295public:
3296 Expr *getSizeExpr() const { return SizeExpr; }
3297 QualType getElementType() const { return ElementType; }
3298 SourceLocation getAttributeLoc() const { return Loc; }
3299 VectorType::VectorKind getVectorKind() const {
3300 return VectorType::VectorKind(VectorTypeBits.VecKind);
3301 }
3302
3303 bool isSugared() const { return false; }
3304 QualType desugar() const { return QualType(this, 0); }
3305
3306 static bool classof(const Type *T) {
3307 return T->getTypeClass() == DependentVector;
3308 }
3309
3310 void Profile(llvm::FoldingSetNodeID &ID) {
3311 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3312 }
3313
3314 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3315 QualType ElementType, const Expr *SizeExpr,
3316 VectorType::VectorKind VecKind);
3317};
3318
3319/// ExtVectorType - Extended vector type. This type is created using
3320/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3321/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3322/// class enables syntactic extensions, like Vector Components for accessing
3323/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3324/// Shading Language).
3325class ExtVectorType : public VectorType {
3326 friend class ASTContext; // ASTContext creates these.
3327
3328 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3329 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3330
3331public:
3332 static int getPointAccessorIdx(char c) {
3333 switch (c) {
3334 default: return -1;
3335 case 'x': case 'r': return 0;
3336 case 'y': case 'g': return 1;
3337 case 'z': case 'b': return 2;
3338 case 'w': case 'a': return 3;
3339 }
3340 }
3341
3342 static int getNumericAccessorIdx(char c) {
3343 switch (c) {
3344 default: return -1;
3345 case '0': return 0;
3346 case '1': return 1;
3347 case '2': return 2;
3348 case '3': return 3;
3349 case '4': return 4;
3350 case '5': return 5;
3351 case '6': return 6;
3352 case '7': return 7;
3353 case '8': return 8;
3354 case '9': return 9;
3355 case 'A':
3356 case 'a': return 10;
3357 case 'B':
3358 case 'b': return 11;
3359 case 'C':
3360 case 'c': return 12;
3361 case 'D':
3362 case 'd': return 13;
3363 case 'E':
3364 case 'e': return 14;
3365 case 'F':
3366 case 'f': return 15;
3367 }
3368 }
3369
3370 static int getAccessorIdx(char c, bool isNumericAccessor) {
3371 if (isNumericAccessor)
3372 return getNumericAccessorIdx(c);
3373 else
3374 return getPointAccessorIdx(c);
3375 }
3376
3377 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3378 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3379 return unsigned(idx-1) < getNumElements();
3380 return false;
3381 }
3382
3383 bool isSugared() const { return false; }
3384 QualType desugar() const { return QualType(this, 0); }
3385
3386 static bool classof(const Type *T) {
3387 return T->getTypeClass() == ExtVector;
3388 }
3389};
3390
3391/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3392/// class of FunctionNoProtoType and FunctionProtoType.
3393class FunctionType : public Type {
3394 // The type returned by the function.
3395 QualType ResultType;
3396
3397public:
3398 /// Interesting information about a specific parameter that can't simply
3399 /// be reflected in parameter's type. This is only used by FunctionProtoType
3400 /// but is in FunctionType to make this class available during the
3401 /// specification of the bases of FunctionProtoType.
3402 ///
3403 /// It makes sense to model language features this way when there's some
3404 /// sort of parameter-specific override (such as an attribute) that
3405 /// affects how the function is called. For example, the ARC ns_consumed
3406 /// attribute changes whether a parameter is passed at +0 (the default)
3407 /// or +1 (ns_consumed). This must be reflected in the function type,
3408 /// but isn't really a change to the parameter type.
3409 ///
3410 /// One serious disadvantage of modelling language features this way is
3411 /// that they generally do not work with language features that attempt
3412 /// to destructure types. For example, template argument deduction will
3413 /// not be able to match a parameter declared as
3414 /// T (*)(U)
3415 /// against an argument of type
3416 /// void (*)(__attribute__((ns_consumed)) id)
3417 /// because the substitution of T=void, U=id into the former will
3418 /// not produce the latter.
3419 class ExtParameterInfo {
3420 enum {
3421 ABIMask = 0x0F,
3422 IsConsumed = 0x10,
3423 HasPassObjSize = 0x20,
3424 IsNoEscape = 0x40,
3425 };
3426 unsigned char Data = 0;
3427
3428 public:
3429 ExtParameterInfo() = default;
3430
3431 /// Return the ABI treatment of this parameter.
3432 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3433 ExtParameterInfo withABI(ParameterABI kind) const {
3434 ExtParameterInfo copy = *this;
3435 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3436 return copy;
3437 }
3438
3439 /// Is this parameter considered "consumed" by Objective-C ARC?
3440 /// Consumed parameters must have retainable object type.
3441 bool isConsumed() const { return (Data & IsConsumed); }
3442 ExtParameterInfo withIsConsumed(bool consumed) const {
3443 ExtParameterInfo copy = *this;
3444 if (consumed)
3445 copy.Data |= IsConsumed;
3446 else
3447 copy.Data &= ~IsConsumed;
3448 return copy;
3449 }
3450
3451 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3452 ExtParameterInfo withHasPassObjectSize() const {
3453 ExtParameterInfo Copy = *this;
3454 Copy.Data |= HasPassObjSize;
3455 return Copy;
3456 }
3457
3458 bool isNoEscape() const { return Data & IsNoEscape; }
3459 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3460 ExtParameterInfo Copy = *this;
3461 if (NoEscape)
3462 Copy.Data |= IsNoEscape;
3463 else
3464 Copy.Data &= ~IsNoEscape;
3465 return Copy;
3466 }
3467
3468 unsigned char getOpaqueValue() const { return Data; }
3469 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3470 ExtParameterInfo result;
3471 result.Data = data;
3472 return result;
3473 }
3474
3475 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3476 return lhs.Data == rhs.Data;
3477 }
3478
3479 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3480 return lhs.Data != rhs.Data;
3481 }
3482 };
3483
3484 /// A class which abstracts out some details necessary for
3485 /// making a call.
3486 ///
3487 /// It is not actually used directly for storing this information in
3488 /// a FunctionType, although FunctionType does currently use the
3489 /// same bit-pattern.
3490 ///
3491 // If you add a field (say Foo), other than the obvious places (both,
3492 // constructors, compile failures), what you need to update is
3493 // * Operator==
3494 // * getFoo
3495 // * withFoo
3496 // * functionType. Add Foo, getFoo.
3497 // * ASTContext::getFooType
3498 // * ASTContext::mergeFunctionTypes
3499 // * FunctionNoProtoType::Profile
3500 // * FunctionProtoType::Profile
3501 // * TypePrinter::PrintFunctionProto
3502 // * AST read and write
3503 // * Codegen
3504 class ExtInfo {
3505 friend class FunctionType;
3506
3507 // Feel free to rearrange or add bits, but if you go over 12,
3508 // you'll need to adjust both the Bits field below and
3509 // Type::FunctionTypeBitfields.
3510
3511 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|
3512 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 |
3513 //
3514 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3515 enum { CallConvMask = 0x1F };
3516 enum { NoReturnMask = 0x20 };
3517 enum { ProducesResultMask = 0x40 };
3518 enum { NoCallerSavedRegsMask = 0x80 };
3519 enum { NoCfCheckMask = 0x800 };
3520 enum {
3521 RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask |
3522 NoCallerSavedRegsMask | NoCfCheckMask),
3523 RegParmOffset = 8
3524 }; // Assumed to be the last field
3525 uint16_t Bits = CC_C;
3526
3527 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3528
3529 public:
3530 // Constructor with no defaults. Use this when you know that you
3531 // have all the elements (when reading an AST file for example).
3532 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3533 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck) {
3534 assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(((!hasRegParm || regParm < 7) && "Invalid regparm value"
) ? static_cast<void> (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3534, __PRETTY_FUNCTION__))
;
3535 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3536 (producesResult ? ProducesResultMask : 0) |
3537 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3538 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3539 (NoCfCheck ? NoCfCheckMask : 0);
3540 }
3541
3542 // Constructor with all defaults. Use when for example creating a
3543 // function known to use defaults.
3544 ExtInfo() = default;
3545
3546 // Constructor with just the calling convention, which is an important part
3547 // of the canonical type.
3548 ExtInfo(CallingConv CC) : Bits(CC) {}
3549
3550 bool getNoReturn() const { return Bits & NoReturnMask; }
3551 bool getProducesResult() const { return Bits & ProducesResultMask; }
3552 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3553 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3554 bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
3555
3556 unsigned getRegParm() const {
3557 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3558 if (RegParm > 0)
3559 --RegParm;
3560 return RegParm;
3561 }
3562
3563 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3564
3565 bool operator==(ExtInfo Other) const {
3566 return Bits == Other.Bits;
3567 }
3568 bool operator!=(ExtInfo Other) const {
3569 return Bits != Other.Bits;
3570 }
3571
3572 // Note that we don't have setters. That is by design, use
3573 // the following with methods instead of mutating these objects.
3574
3575 ExtInfo withNoReturn(bool noReturn) const {
3576 if (noReturn)
3577 return ExtInfo(Bits | NoReturnMask);
3578 else
3579 return ExtInfo(Bits & ~NoReturnMask);
3580 }
3581
3582 ExtInfo withProducesResult(bool producesResult) const {
3583 if (producesResult)
3584 return ExtInfo(Bits | ProducesResultMask);
3585 else
3586 return ExtInfo(Bits & ~ProducesResultMask);
3587 }
3588
3589 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3590 if (noCallerSavedRegs)
3591 return ExtInfo(Bits | NoCallerSavedRegsMask);
3592 else
3593 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3594 }
3595
3596 ExtInfo withNoCfCheck(bool noCfCheck) const {
3597 if (noCfCheck)
3598 return ExtInfo(Bits | NoCfCheckMask);
3599 else
3600 return ExtInfo(Bits & ~NoCfCheckMask);
3601 }
3602
3603 ExtInfo withRegParm(unsigned RegParm) const {
3604 assert(RegParm < 7 && "Invalid regparm value")((RegParm < 7 && "Invalid regparm value") ? static_cast
<void> (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3604, __PRETTY_FUNCTION__))
;
3605 return ExtInfo((Bits & ~RegParmMask) |
3606 ((RegParm + 1) << RegParmOffset));
3607 }
3608
3609 ExtInfo withCallingConv(CallingConv cc) const {
3610 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3611 }
3612
3613 void Profile(llvm::FoldingSetNodeID &ID) const {
3614 ID.AddInteger(Bits);
3615 }
3616 };
3617
3618 /// A simple holder for a QualType representing a type in an
3619 /// exception specification. Unfortunately needed by FunctionProtoType
3620 /// because TrailingObjects cannot handle repeated types.
3621 struct ExceptionType { QualType Type; };
3622
3623 /// A simple holder for various uncommon bits which do not fit in
3624 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3625 /// alignment of subsequent objects in TrailingObjects. You must update
3626 /// hasExtraBitfields in FunctionProtoType after adding extra data here.
3627 struct alignas(void *) FunctionTypeExtraBitfields {
3628 /// The number of types in the exception specification.
3629 /// A whole unsigned is not needed here and according to
3630 /// [implimits] 8 bits would be enough here.
3631 unsigned NumExceptionType;
3632 };
3633
3634protected:
3635 FunctionType(TypeClass tc, QualType res,
3636 QualType Canonical, bool Dependent,
3637 bool InstantiationDependent,
3638 bool VariablyModified, bool ContainsUnexpandedParameterPack,
3639 ExtInfo Info)
3640 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3641 ContainsUnexpandedParameterPack),
3642 ResultType(res) {
3643 FunctionTypeBits.ExtInfo = Info.Bits;
3644 }
3645
3646 Qualifiers getFastTypeQuals() const {
3647 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3648 }
3649
3650public:
3651 QualType getReturnType() const { return ResultType; }
3652
3653 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3654 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3655
3656 /// Determine whether this function type includes the GNU noreturn
3657 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3658 /// type.
3659 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3660
3661 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3662 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3663
3664 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3665 "Const, volatile and restrict are assumed to be a subset of "
3666 "the fast qualifiers.");
3667
3668 bool isConst() const { return getFastTypeQuals().hasConst(); }
3669 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3670 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3671
3672 /// Determine the type of an expression that calls a function of
3673 /// this type.
3674 QualType getCallResultType(const ASTContext &Context) const {
3675 return getReturnType().getNonLValueExprType(Context);
3676 }
3677
3678 static StringRef getNameForCallConv(CallingConv CC);
3679
3680 static bool classof(const Type *T) {
3681 return T->getTypeClass() == FunctionNoProto ||
3682 T->getTypeClass() == FunctionProto;
3683 }
3684};
3685
3686/// Represents a K&R-style 'int foo()' function, which has
3687/// no information available about its arguments.
3688class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3689 friend class ASTContext; // ASTContext creates these.
3690
3691 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3692 : FunctionType(FunctionNoProto, Result, Canonical,
3693 /*Dependent=*/false, /*InstantiationDependent=*/false,
3694 Result->isVariablyModifiedType(),
3695 /*ContainsUnexpandedParameterPack=*/false, Info) {}
3696
3697public:
3698 // No additional state past what FunctionType provides.
3699
3700 bool isSugared() const { return false; }
3701 QualType desugar() const { return QualType(this, 0); }
3702
3703 void Profile(llvm::FoldingSetNodeID &ID) {
3704 Profile(ID, getReturnType(), getExtInfo());
3705 }
3706
3707 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3708 ExtInfo Info) {
3709 Info.Profile(ID);
3710 ID.AddPointer(ResultType.getAsOpaquePtr());
3711 }
3712
3713 static bool classof(const Type *T) {
3714 return T->getTypeClass() == FunctionNoProto;
3715 }
3716};
3717
3718/// Represents a prototype with parameter type info, e.g.
3719/// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3720/// parameters, not as having a single void parameter. Such a type can have
3721/// an exception specification, but this specification is not part of the
3722/// canonical type. FunctionProtoType has several trailing objects, some of
3723/// which optional. For more information about the trailing objects see
3724/// the first comment inside FunctionProtoType.
3725class FunctionProtoType final
3726 : public FunctionType,
3727 public llvm::FoldingSetNode,
3728 private llvm::TrailingObjects<
3729 FunctionProtoType, QualType, FunctionType::FunctionTypeExtraBitfields,
3730 FunctionType::ExceptionType, Expr *, FunctionDecl *,
3731 FunctionType::ExtParameterInfo, Qualifiers> {
3732 friend class ASTContext; // ASTContext creates these.
3733 friend TrailingObjects;
3734
3735 // FunctionProtoType is followed by several trailing objects, some of
3736 // which optional. They are in order:
3737 //
3738 // * An array of getNumParams() QualType holding the parameter types.
3739 // Always present. Note that for the vast majority of FunctionProtoType,
3740 // these will be the only trailing objects.
3741 //
3742 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
3743 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
3744 // a single FunctionTypeExtraBitfields. Present if and only if
3745 // hasExtraBitfields() is true.
3746 //
3747 // * Optionally exactly one of:
3748 // * an array of getNumExceptions() ExceptionType,
3749 // * a single Expr *,
3750 // * a pair of FunctionDecl *,
3751 // * a single FunctionDecl *
3752 // used to store information about the various types of exception
3753 // specification. See getExceptionSpecSize for the details.
3754 //
3755 // * Optionally an array of getNumParams() ExtParameterInfo holding
3756 // an ExtParameterInfo for each of the parameters. Present if and
3757 // only if hasExtParameterInfos() is true.
3758 //
3759 // * Optionally a Qualifiers object to represent extra qualifiers that can't
3760 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
3761 // if hasExtQualifiers() is true.
3762 //
3763 // The optional FunctionTypeExtraBitfields has to be before the data
3764 // related to the exception specification since it contains the number
3765 // of exception types.
3766 //
3767 // We put the ExtParameterInfos last. If all were equal, it would make
3768 // more sense to put these before the exception specification, because
3769 // it's much easier to skip past them compared to the elaborate switch
3770 // required to skip the exception specification. However, all is not
3771 // equal; ExtParameterInfos are used to model very uncommon features,
3772 // and it's better not to burden the more common paths.
3773
3774public:
3775 /// Holds information about the various types of exception specification.
3776 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
3777 /// used to group together the various bits of information about the
3778 /// exception specification.
3779 struct ExceptionSpecInfo {
3780 /// The kind of exception specification this is.
3781 ExceptionSpecificationType Type = EST_None;
3782
3783 /// Explicitly-specified list of exception types.
3784 ArrayRef<QualType> Exceptions;
3785
3786 /// Noexcept expression, if this is a computed noexcept specification.
3787 Expr *NoexceptExpr = nullptr;
3788
3789 /// The function whose exception specification this is, for
3790 /// EST_Unevaluated and EST_Uninstantiated.
3791 FunctionDecl *SourceDecl = nullptr;
3792
3793 /// The function template whose exception specification this is instantiated
3794 /// from, for EST_Uninstantiated.
3795 FunctionDecl *SourceTemplate = nullptr;
3796
3797 ExceptionSpecInfo() = default;
3798
3799 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3800 };
3801
3802 /// Extra information about a function prototype. ExtProtoInfo is not
3803 /// stored as such in FunctionProtoType but is used to group together
3804 /// the various bits of extra information about a function prototype.
3805 struct ExtProtoInfo {
3806 FunctionType::ExtInfo ExtInfo;
3807 bool Variadic : 1;
3808 bool HasTrailingReturn : 1;
3809 Qualifiers TypeQuals;
3810 RefQualifierKind RefQualifier = RQ_None;
3811 ExceptionSpecInfo ExceptionSpec;
3812 const ExtParameterInfo *ExtParameterInfos = nullptr;
3813
3814 ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {}
3815
3816 ExtProtoInfo(CallingConv CC)
3817 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3818
3819 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) {
3820 ExtProtoInfo Result(*this);
3821 Result.ExceptionSpec = ESI;
3822 return Result;
3823 }
3824 };
3825
3826private:
3827 unsigned numTrailingObjects(OverloadToken<QualType>) const {
3828 return getNumParams();
3829 }
3830
3831 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
3832 return hasExtraBitfields();
3833 }
3834
3835 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
3836 return getExceptionSpecSize().NumExceptionType;
3837 }
3838
3839 unsigned numTrailingObjects(OverloadToken<Expr *>) const {
3840 return getExceptionSpecSize().NumExprPtr;
3841 }
3842
3843 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
3844 return getExceptionSpecSize().NumFunctionDeclPtr;
3845 }
3846
3847 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
3848 return hasExtParameterInfos() ? getNumParams() : 0;
3849 }
3850
3851 /// Determine whether there are any argument types that
3852 /// contain an unexpanded parameter pack.
3853 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3854 unsigned numArgs) {
3855 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3856 if (ArgArray[Idx]->containsUnexpandedParameterPack())
3857 return true;
3858
3859 return false;
3860 }
3861
3862 FunctionProtoType(QualType result, ArrayRef<QualType> params,
3863 QualType canonical, const ExtProtoInfo &epi);
3864
3865 /// This struct is returned by getExceptionSpecSize and is used to
3866 /// translate an ExceptionSpecificationType to the number and kind
3867 /// of trailing objects related to the exception specification.
3868 struct ExceptionSpecSizeHolder {
3869 unsigned NumExceptionType;
3870 unsigned NumExprPtr;
3871 unsigned NumFunctionDeclPtr;
3872 };
3873
3874 /// Return the number and kind of trailing objects
3875 /// related to the exception specification.
3876 static ExceptionSpecSizeHolder
3877 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
3878 switch (EST) {
3879 case EST_None:
3880 case EST_DynamicNone:
3881 case EST_MSAny:
3882 case EST_BasicNoexcept:
3883 case EST_Unparsed:
3884 case EST_NoThrow:
3885 return {0, 0, 0};
3886
3887 case EST_Dynamic:
3888 return {NumExceptions, 0, 0};
3889
3890 case EST_DependentNoexcept:
3891 case EST_NoexceptFalse:
3892 case EST_NoexceptTrue:
3893 return {0, 1, 0};
3894
3895 case EST_Uninstantiated:
3896 return {0, 0, 2};
3897
3898 case EST_Unevaluated:
3899 return {0, 0, 1};
3900 }
3901 llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3901)
;
3902 }
3903
3904 /// Return the number and kind of trailing objects
3905 /// related to the exception specification.
3906 ExceptionSpecSizeHolder getExceptionSpecSize() const {
3907 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
3908 }
3909
3910 /// Whether the trailing FunctionTypeExtraBitfields is present.
3911 static bool hasExtraBitfields(ExceptionSpecificationType EST) {
3912 // If the exception spec type is EST_Dynamic then we have > 0 exception
3913 // types and the exact number is stored in FunctionTypeExtraBitfields.
3914 return EST == EST_Dynamic;
3915 }
3916
3917 /// Whether the trailing FunctionTypeExtraBitfields is present.
3918 bool hasExtraBitfields() const {
3919 return hasExtraBitfields(getExceptionSpecType());
3920 }
3921
3922 bool hasExtQualifiers() const {
3923 return FunctionTypeBits.HasExtQuals;
3924 }
3925
3926public:
3927 unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
3928
3929 QualType getParamType(unsigned i) const {
3930 assert(i < getNumParams() && "invalid parameter index")((i < getNumParams() && "invalid parameter index")
? static_cast<void> (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3930, __PRETTY_FUNCTION__))
;
3931 return param_type_begin()[i];
3932 }
3933
3934 ArrayRef<QualType> getParamTypes() const {
3935 return llvm::makeArrayRef(param_type_begin(), param_type_end());
3936 }
3937
3938 ExtProtoInfo getExtProtoInfo() const {
3939 ExtProtoInfo EPI;
3940 EPI.ExtInfo = getExtInfo();
3941 EPI.Variadic = isVariadic();
3942 EPI.HasTrailingReturn = hasTrailingReturn();
3943 EPI.ExceptionSpec.Type = getExceptionSpecType();
3944 EPI.TypeQuals = getMethodQuals();
3945 EPI.RefQualifier = getRefQualifier();
3946 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3947 EPI.ExceptionSpec.Exceptions = exceptions();
3948 } else if (isComputedNoexcept(EPI.ExceptionSpec.Type)) {
3949 EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
3950 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3951 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3952 EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
3953 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3954 EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3955 }
3956 EPI.ExtParameterInfos = getExtParameterInfosOrNull();
3957 return EPI;
3958 }
3959
3960 /// Get the kind of exception specification on this function.
3961 ExceptionSpecificationType getExceptionSpecType() const {
3962 return static_cast<ExceptionSpecificationType>(
3963 FunctionTypeBits.ExceptionSpecType);
3964 }
3965
3966 /// Return whether this function has any kind of exception spec.
3967 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
3968
3969 /// Return whether this function has a dynamic (throw) exception spec.
3970 bool hasDynamicExceptionSpec() const {
3971 return isDynamicExceptionSpec(getExceptionSpecType());
3972 }
3973
3974 /// Return whether this function has a noexcept exception spec.
3975 bool hasNoexceptExceptionSpec() const {
3976 return isNoexceptExceptionSpec(getExceptionSpecType());
3977 }
3978
3979 /// Return whether this function has a dependent exception spec.
3980 bool hasDependentExceptionSpec() const;
3981
3982 /// Return whether this function has an instantiation-dependent exception
3983 /// spec.
3984 bool hasInstantiationDependentExceptionSpec() const;
3985
3986 /// Return the number of types in the exception specification.
3987 unsigned getNumExceptions() const {
3988 return getExceptionSpecType() == EST_Dynamic
3989 ? getTrailingObjects<FunctionTypeExtraBitfields>()
3990 ->NumExceptionType
3991 : 0;
3992 }
3993
3994 /// Return the ith exception type, where 0 <= i < getNumExceptions().
3995 QualType getExceptionType(unsigned i) const {
3996 assert(i < getNumExceptions() && "Invalid exception number!")((i < getNumExceptions() && "Invalid exception number!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 3996, __PRETTY_FUNCTION__))
;
3997 return exception_begin()[i];
3998 }
3999
4000 /// Return the expression inside noexcept(expression), or a null pointer
4001 /// if there is none (because the exception spec is not of this form).
4002 Expr *getNoexceptExpr() const {
4003 if (!isComputedNoexcept(getExceptionSpecType()))
4004 return nullptr;
4005 return *getTrailingObjects<Expr *>();
4006 }
4007
4008 /// If this function type has an exception specification which hasn't
4009 /// been determined yet (either because it has not been evaluated or because
4010 /// it has not been instantiated), this is the function whose exception
4011 /// specification is represented by this type.
4012 FunctionDecl *getExceptionSpecDecl() const {
4013 if (getExceptionSpecType() != EST_Uninstantiated &&
4014 getExceptionSpecType() != EST_Unevaluated)
4015 return nullptr;
4016 return getTrailingObjects<FunctionDecl *>()[0];
4017 }
4018
4019 /// If this function type has an uninstantiated exception
4020 /// specification, this is the function whose exception specification
4021 /// should be instantiated to find the exception specification for
4022 /// this type.
4023 FunctionDecl *getExceptionSpecTemplate() const {
4024 if (getExceptionSpecType() != EST_Uninstantiated)
4025 return nullptr;
4026 return getTrailingObjects<FunctionDecl *>()[1];
4027 }
4028
4029 /// Determine whether this function type has a non-throwing exception
4030 /// specification.
4031 CanThrowResult canThrow() const;
4032
4033 /// Determine whether this function type has a non-throwing exception
4034 /// specification. If this depends on template arguments, returns
4035 /// \c ResultIfDependent.
4036 bool isNothrow(bool ResultIfDependent = false) const {
4037 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4038 }
4039
4040 /// Whether this function prototype is variadic.
4041 bool isVariadic() const { return FunctionTypeBits.Variadic; }
4042
4043 /// Determines whether this function prototype contains a
4044 /// parameter pack at the end.
4045 ///
4046 /// A function template whose last parameter is a parameter pack can be
4047 /// called with an arbitrary number of arguments, much like a variadic
4048 /// function.
4049 bool isTemplateVariadic() const;
4050
4051 /// Whether this function prototype has a trailing return type.
4052 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4053
4054 Qualifiers getMethodQuals() const {
4055 if (hasExtQualifiers())
4056 return *getTrailingObjects<Qualifiers>();
4057 else
4058 return getFastTypeQuals();
4059 }
4060
4061 /// Retrieve the ref-qualifier associated with this function type.
4062 RefQualifierKind getRefQualifier() const {
4063 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4064 }
4065
4066 using param_type_iterator = const QualType *;
4067 using param_type_range = llvm::iterator_range<param_type_iterator>;
4068
4069 param_type_range param_types() const {
4070 return param_type_range(param_type_begin(), param_type_end());
4071 }
4072
4073 param_type_iterator param_type_begin() const {
4074 return getTrailingObjects<QualType>();
4075 }
4076
4077 param_type_iterator param_type_end() const {
4078 return param_type_begin() + getNumParams();
4079 }
4080
4081 using exception_iterator = const QualType *;
4082
4083 ArrayRef<QualType> exceptions() const {
4084 return llvm::makeArrayRef(exception_begin(), exception_end());
4085 }
4086
4087 exception_iterator exception_begin() const {
4088 return reinterpret_cast<exception_iterator>(
4089 getTrailingObjects<ExceptionType>());
4090 }
4091
4092 exception_iterator exception_end() const {
4093 return exception_begin() + getNumExceptions();
4094 }
4095
4096 /// Is there any interesting extra information for any of the parameters
4097 /// of this function type?
4098 bool hasExtParameterInfos() const {
4099 return FunctionTypeBits.HasExtParameterInfos;
4100 }
4101
4102 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
4103 assert(hasExtParameterInfos())((hasExtParameterInfos()) ? static_cast<void> (0) : __assert_fail
("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4103, __PRETTY_FUNCTION__))
;
4104 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4105 getNumParams());
4106 }
4107
4108 /// Return a pointer to the beginning of the array of extra parameter
4109 /// information, if present, or else null if none of the parameters
4110 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4111 const ExtParameterInfo *getExtParameterInfosOrNull() const {
4112 if (!hasExtParameterInfos())
4113 return nullptr;
4114 return getTrailingObjects<ExtParameterInfo>();
4115 }
4116
4117 ExtParameterInfo getExtParameterInfo(unsigned I) const {
4118 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4118, __PRETTY_FUNCTION__))
;
4119 if (hasExtParameterInfos())
4120 return getTrailingObjects<ExtParameterInfo>()[I];
4121 return ExtParameterInfo();
4122 }
4123
4124 ParameterABI getParameterABI(unsigned I) const {
4125 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4125, __PRETTY_FUNCTION__))
;
4126 if (hasExtParameterInfos())
4127 return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4128 return ParameterABI::Ordinary;
4129 }
4130
4131 bool isParamConsumed(unsigned I) const {
4132 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4132, __PRETTY_FUNCTION__))
;
4133 if (hasExtParameterInfos())
4134 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4135 return false;
4136 }
4137
4138 bool isSugared() const { return false; }
4139 QualType desugar() const { return QualType(this, 0); }
4140
4141 void printExceptionSpecification(raw_ostream &OS,
4142 const PrintingPolicy &Policy) const;
4143
4144 static bool classof(const Type *T) {
4145 return T->getTypeClass() == FunctionProto;
4146 }
4147
4148 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4149 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4150 param_type_iterator ArgTys, unsigned NumArgs,
4151 const ExtProtoInfo &EPI, const ASTContext &Context,
4152 bool Canonical);
4153};
4154
4155/// Represents the dependent type named by a dependently-scoped
4156/// typename using declaration, e.g.
4157/// using typename Base<T>::foo;
4158///
4159/// Template instantiation turns these into the underlying type.
4160class UnresolvedUsingType : public Type {
4161 friend class ASTContext; // ASTContext creates these.
4162
4163 UnresolvedUsingTypenameDecl *Decl;
4164
4165 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
4166 : Type(UnresolvedUsing, QualType(), true, true, false,
4167 /*ContainsUnexpandedParameterPack=*/false),
4168 Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
4169
4170public:
4171 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
4172
4173 bool isSugared() const { return false; }
4174 QualType desugar() const { return QualType(this, 0); }
4175
4176 static bool classof(const Type *T) {
4177 return T->getTypeClass() == UnresolvedUsing;
4178 }
4179
4180 void Profile(llvm::FoldingSetNodeID &ID) {
4181 return Profile(ID, Decl);
4182 }
4183
4184 static void Profile(llvm::FoldingSetNodeID &ID,
4185 UnresolvedUsingTypenameDecl *D) {
4186 ID.AddPointer(D);
4187 }
4188};
4189
4190class TypedefType : public Type {
4191 TypedefNameDecl *Decl;
4192
4193protected:
4194 friend class ASTContext; // ASTContext creates these.
4195
4196 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
4197 : Type(tc, can, can->isDependentType(),
4198 can->isInstantiationDependentType(),
4199 can->isVariablyModifiedType(),
4200 /*ContainsUnexpandedParameterPack=*/false),
4201 Decl(const_cast<TypedefNameDecl*>(D)) {
4202 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4202, __PRETTY_FUNCTION__))
;
4203 }
4204
4205public:
4206 TypedefNameDecl *getDecl() const { return Decl; }
4207
4208 bool isSugared() const { return true; }
4209 QualType desugar() const;
4210
4211 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
4212};
4213
4214/// Sugar type that represents a type that was qualified by a qualifier written
4215/// as a macro invocation.
4216class MacroQualifiedType : public Type {
4217 friend class ASTContext; // ASTContext creates these.
4218
4219 QualType UnderlyingTy;
4220 const IdentifierInfo *MacroII;
4221
4222 MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy,
4223 const IdentifierInfo *MacroII)
4224 : Type(MacroQualified, CanonTy, UnderlyingTy->isDependentType(),
4225 UnderlyingTy->isInstantiationDependentType(),
4226 UnderlyingTy->isVariablyModifiedType(),
4227 UnderlyingTy->containsUnexpandedParameterPack()),
4228 UnderlyingTy(UnderlyingTy), MacroII(MacroII) {
4229 assert(isa<AttributedType>(UnderlyingTy) &&((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4230, __PRETTY_FUNCTION__))
4230 "Expected a macro qualified type to only wrap attributed types.")((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4230, __PRETTY_FUNCTION__))
;
4231 }
4232
4233public:
4234 const IdentifierInfo *getMacroIdentifier() const { return MacroII; }
4235 QualType getUnderlyingType() const { return UnderlyingTy; }
4236
4237 /// Return this attributed type's modified type with no qualifiers attached to
4238 /// it.
4239 QualType getModifiedType() const;
4240
4241 bool isSugared() const { return true; }
4242 QualType desugar() const;
4243
4244 static bool classof(const Type *T) {
4245 return T->getTypeClass() == MacroQualified;
4246 }
4247};
4248
4249/// Represents a `typeof` (or __typeof__) expression (a GCC extension).
4250class TypeOfExprType : public Type {
4251 Expr *TOExpr;
4252
4253protected:
4254 friend class ASTContext; // ASTContext creates these.
4255
4256 TypeOfExprType(Expr *E, QualType can = QualType());
4257
4258public:
4259 Expr *getUnderlyingExpr() const { return TOExpr; }
4260
4261 /// Remove a single level of sugar.
4262 QualType desugar() const;
4263
4264 /// Returns whether this type directly provides sugar.
4265 bool isSugared() const;
4266
4267 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
4268};
4269
4270/// Internal representation of canonical, dependent
4271/// `typeof(expr)` types.
4272///
4273/// This class is used internally by the ASTContext to manage
4274/// canonical, dependent types, only. Clients will only see instances
4275/// of this class via TypeOfExprType nodes.
4276class DependentTypeOfExprType
4277 : public TypeOfExprType, public llvm::FoldingSetNode {
4278 const ASTContext &Context;
4279
4280public:
4281 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
4282 : TypeOfExprType(E), Context(Context) {}
4283
4284 void Profile(llvm::FoldingSetNodeID &ID) {
4285 Profile(ID, Context, getUnderlyingExpr());
4286 }
4287
4288 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4289 Expr *E);
4290};
4291
4292/// Represents `typeof(type)`, a GCC extension.
4293class TypeOfType : public Type {
4294 friend class ASTContext; // ASTContext creates these.
4295
4296 QualType TOType;
4297
4298 TypeOfType(QualType T, QualType can)
4299 : Type(TypeOf, can, T->isDependentType(),
4300 T->isInstantiationDependentType(),
4301 T->isVariablyModifiedType(),
4302 T->containsUnexpandedParameterPack()),
4303 TOType(T) {
4304 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4304, __PRETTY_FUNCTION__))
;
4305 }
4306
4307public:
4308 QualType getUnderlyingType() const { return TOType; }
4309
4310 /// Remove a single level of sugar.
4311 QualType desugar() const { return getUnderlyingType(); }
4312
4313 /// Returns whether this type directly provides sugar.
4314 bool isSugared() const { return true; }
4315
4316 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4317};
4318
4319/// Represents the type `decltype(expr)` (C++11).
4320class DecltypeType : public Type {
4321 Expr *E;
4322 QualType UnderlyingType;
4323
4324protected:
4325 friend class ASTContext; // ASTContext creates these.
4326
4327 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4328
4329public:
4330 Expr *getUnderlyingExpr() const { return E; }
4331 QualType getUnderlyingType() const { return UnderlyingType; }
4332
4333 /// Remove a single level of sugar.
4334 QualType desugar() const;
4335
4336 /// Returns whether this type directly provides sugar.
4337 bool isSugared() const;
4338
4339 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4340};
4341
4342/// Internal representation of canonical, dependent
4343/// decltype(expr) types.
4344///
4345/// This class is used internally by the ASTContext to manage
4346/// canonical, dependent types, only. Clients will only see instances
4347/// of this class via DecltypeType nodes.
4348class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4349 const ASTContext &Context;
4350
4351public:
4352 DependentDecltypeType(const ASTContext &Context, Expr *E);
4353
4354 void Profile(llvm::FoldingSetNodeID &ID) {
4355 Profile(ID, Context, getUnderlyingExpr());
4356 }
4357
4358 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4359 Expr *E);
4360};
4361
4362/// A unary type transform, which is a type constructed from another.
4363class UnaryTransformType : public Type {
4364public:
4365 enum UTTKind {
4366 EnumUnderlyingType
4367 };
4368
4369private:
4370 /// The untransformed type.
4371 QualType BaseType;
4372
4373 /// The transformed type if not dependent, otherwise the same as BaseType.
4374 QualType UnderlyingType;
4375
4376 UTTKind UKind;
4377
4378protected:
4379 friend class ASTContext;
4380
4381 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4382 QualType CanonicalTy);
4383
4384public:
4385 bool isSugared() const { return !isDependentType(); }
4386 QualType desugar() const { return UnderlyingType; }
4387
4388 QualType getUnderlyingType() const { return UnderlyingType; }
4389 QualType getBaseType() const { return BaseType; }
4390
4391 UTTKind getUTTKind() const { return UKind; }
4392
4393 static bool classof(const Type *T) {
4394 return T->getTypeClass() == UnaryTransform;
4395 }
4396};
4397
4398/// Internal representation of canonical, dependent
4399/// __underlying_type(type) types.
4400///
4401/// This class is used internally by the ASTContext to manage
4402/// canonical, dependent types, only. Clients will only see instances
4403/// of this class via UnaryTransformType nodes.
4404class DependentUnaryTransformType : public UnaryTransformType,
4405 public llvm::FoldingSetNode {
4406public:
4407 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4408 UTTKind UKind);
4409
4410 void Profile(llvm::FoldingSetNodeID &ID) {
4411 Profile(ID, getBaseType(), getUTTKind());
4412 }
4413
4414 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4415 UTTKind UKind) {
4416 ID.AddPointer(BaseType.getAsOpaquePtr());
4417 ID.AddInteger((unsigned)UKind);
4418 }
4419};
4420
4421class TagType : public Type {
4422 friend class ASTReader;
4423
4424 /// Stores the TagDecl associated with this type. The decl may point to any
4425 /// TagDecl that declares the entity.
4426 TagDecl *decl;
4427
4428protected:
4429 TagType(TypeClass TC, const TagDecl *D, QualType can);
4430
4431public:
4432 TagDecl *getDecl() const;
4433
4434 /// Determines whether this type is in the process of being defined.
4435 bool isBeingDefined() const;
4436
4437 static bool classof(const Type *T) {
4438 return T->getTypeClass() == Enum || T->getTypeClass() == Record;
4439 }
4440};
4441
4442/// A helper class that allows the use of isa/cast/dyncast
4443/// to detect TagType objects of structs/unions/classes.
4444class RecordType : public TagType {
4445protected:
4446 friend class ASTContext; // ASTContext creates these.
4447
4448 explicit RecordType(const RecordDecl *D)
4449 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4450 explicit RecordType(TypeClass TC, RecordDecl *D)
4451 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4452
4453public:
4454 RecordDecl *getDecl() const {
4455 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4456 }
4457
4458 /// Recursively check all fields in the record for const-ness. If any field
4459 /// is declared const, return true. Otherwise, return false.
4460 bool hasConstFields() const;
4461
4462 bool isSugared() const { return false; }
4463 QualType desugar() const { return QualType(this, 0); }
4464
4465 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4466};
4467
4468/// A helper class that allows the use of isa/cast/dyncast
4469/// to detect TagType objects of enums.
4470class EnumType : public TagType {
4471 friend class ASTContext; // ASTContext creates these.
4472
4473 explicit EnumType(const EnumDecl *D)
4474 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4475
4476public:
4477 EnumDecl *getDecl() const {
4478 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4479 }
4480
4481 bool isSugared() const { return false; }
4482 QualType desugar() const { return QualType(this, 0); }
4483
4484 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4485};
4486
4487/// An attributed type is a type to which a type attribute has been applied.
4488///
4489/// The "modified type" is the fully-sugared type to which the attributed
4490/// type was applied; generally it is not canonically equivalent to the
4491/// attributed type. The "equivalent type" is the minimally-desugared type
4492/// which the type is canonically equivalent to.
4493///
4494/// For example, in the following attributed type:
4495/// int32_t __attribute__((vector_size(16)))
4496/// - the modified type is the TypedefType for int32_t
4497/// - the equivalent type is VectorType(16, int32_t)
4498/// - the canonical type is VectorType(16, int)
4499class AttributedType : public Type, public llvm::FoldingSetNode {
4500public:
4501 using Kind = attr::Kind;
4502
4503private:
4504 friend class ASTContext; // ASTContext creates these
4505
4506 QualType ModifiedType;
4507 QualType EquivalentType;
4508
4509 AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
4510 QualType equivalent)
4511 : Type(Attributed, canon, equivalent->isDependentType(),
4512 equivalent->isInstantiationDependentType(),
4513 equivalent->isVariablyModifiedType(),
4514 equivalent->containsUnexpandedParameterPack()),
4515 ModifiedType(modified), EquivalentType(equivalent) {
4516 AttributedTypeBits.AttrKind = attrKind;
4517 }
4518
4519public:
4520 Kind getAttrKind() const {
4521 return static_cast<Kind>(AttributedTypeBits.AttrKind);
4522 }
4523
4524 QualType getModifiedType() const { return ModifiedType; }
4525 QualType getEquivalentType() const { return EquivalentType; }
4526
4527 bool isSugared() const { return true; }
4528 QualType desugar() const { return getEquivalentType(); }
4529
4530 /// Does this attribute behave like a type qualifier?
4531 ///
4532 /// A type qualifier adjusts a type to provide specialized rules for
4533 /// a specific object, like the standard const and volatile qualifiers.
4534 /// This includes attributes controlling things like nullability,
4535 /// address spaces, and ARC ownership. The value of the object is still
4536 /// largely described by the modified type.
4537 ///
4538 /// In contrast, many type attributes "rewrite" their modified type to
4539 /// produce a fundamentally different type, not necessarily related in any
4540 /// formalizable way to the original type. For example, calling convention
4541 /// and vector attributes are not simple type qualifiers.
4542 ///
4543 /// Type qualifiers are often, but not always, reflected in the canonical
4544 /// type.
4545 bool isQualifier() const;
4546
4547 bool isMSTypeSpec() const;
4548
4549 bool isCallingConv() const;
4550
4551 llvm::Optional<NullabilityKind> getImmediateNullability() const;
4552
4553 /// Retrieve the attribute kind corresponding to the given
4554 /// nullability kind.
4555 static Kind getNullabilityAttrKind(NullabilityKind kind) {
4556 switch (kind) {
4557 case NullabilityKind::NonNull:
4558 return attr::TypeNonNull;
4559
4560 case NullabilityKind::Nullable:
4561 return attr::TypeNullable;
4562
4563 case NullabilityKind::Unspecified:
4564 return attr::TypeNullUnspecified;
4565 }
4566 llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind."
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4566)
;
4567 }
4568
4569 /// Strip off the top-level nullability annotation on the given
4570 /// type, if it's there.
4571 ///
4572 /// \param T The type to strip. If the type is exactly an
4573 /// AttributedType specifying nullability (without looking through
4574 /// type sugar), the nullability is returned and this type changed
4575 /// to the underlying modified type.
4576 ///
4577 /// \returns the top-level nullability, if present.
4578 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4579
4580 void Profile(llvm::FoldingSetNodeID &ID) {
4581 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4582 }
4583
4584 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4585 QualType modified, QualType equivalent) {
4586 ID.AddInteger(attrKind);
4587 ID.AddPointer(modified.getAsOpaquePtr());
4588 ID.AddPointer(equivalent.getAsOpaquePtr());
4589 }
4590
4591 static bool classof(const Type *T) {
4592 return T->getTypeClass() == Attributed;
4593 }
4594};
4595
4596class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4597 friend class ASTContext; // ASTContext creates these
4598
4599 // Helper data collector for canonical types.
4600 struct CanonicalTTPTInfo {
4601 unsigned Depth : 15;
4602 unsigned ParameterPack : 1;
4603 unsigned Index : 16;
4604 };
4605
4606 union {
4607 // Info for the canonical type.
4608 CanonicalTTPTInfo CanTTPTInfo;
4609
4610 // Info for the non-canonical type.
4611 TemplateTypeParmDecl *TTPDecl;
4612 };
4613
4614 /// Build a non-canonical type.
4615 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4616 : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
4617 /*InstantiationDependent=*/true,
4618 /*VariablyModified=*/false,
4619 Canon->containsUnexpandedParameterPack()),
4620 TTPDecl(TTPDecl) {}
4621
4622 /// Build the canonical type.
4623 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4624 : Type(TemplateTypeParm, QualType(this, 0),
4625 /*Dependent=*/true,
4626 /*InstantiationDependent=*/true,
4627 /*VariablyModified=*/false, PP) {
4628 CanTTPTInfo.Depth = D;
4629 CanTTPTInfo.Index = I;
4630 CanTTPTInfo.ParameterPack = PP;
4631 }
4632
4633 const CanonicalTTPTInfo& getCanTTPTInfo() const {
4634 QualType Can = getCanonicalTypeInternal();
4635 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4636 }
4637
4638public:
4639 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4640 unsigned getIndex() const { return getCanTTPTInfo().Index; }
4641 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4642
4643 TemplateTypeParmDecl *getDecl() const {
4644 return isCanonicalUnqualified() ? nullptr : TTPDecl;
4645 }
4646
4647 IdentifierInfo *getIdentifier() const;
4648
4649 bool isSugared() const { return false; }
4650 QualType desugar() const { return QualType(this, 0); }
4651
4652 void Profile(llvm::FoldingSetNodeID &ID) {
4653 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4654 }
4655
4656 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4657 unsigned Index, bool ParameterPack,
4658 TemplateTypeParmDecl *TTPDecl) {
4659 ID.AddInteger(Depth);
4660 ID.AddInteger(Index);
4661 ID.AddBoolean(ParameterPack);
4662 ID.AddPointer(TTPDecl);
4663 }
4664
4665 static bool classof(const Type *T) {
4666 return T->getTypeClass() == TemplateTypeParm;
4667 }
4668};
4669
4670/// Represents the result of substituting a type for a template
4671/// type parameter.
4672///
4673/// Within an instantiated template, all template type parameters have
4674/// been replaced with these. They are used solely to record that a
4675/// type was originally written as a template type parameter;
4676/// therefore they are never canonical.
4677class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4678 friend class ASTContext;
4679
4680 // The original type parameter.
4681 const TemplateTypeParmType *Replaced;
4682
4683 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4684 : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
4685 Canon->isInstantiationDependentType(),
4686 Canon->isVariablyModifiedType(),
4687 Canon->containsUnexpandedParameterPack()),
4688 Replaced(Param) {}
4689
4690public:
4691 /// Gets the template parameter that was substituted for.
4692 const TemplateTypeParmType *getReplacedParameter() const {
4693 return Replaced;
4694 }
4695
4696 /// Gets the type that was substituted for the template
4697 /// parameter.
4698 QualType getReplacementType() const {
4699 return getCanonicalTypeInternal();
4700 }
4701
4702 bool isSugared() const { return true; }
4703 QualType desugar() const { return getReplacementType(); }
4704
4705 void Profile(llvm::FoldingSetNodeID &ID) {
4706 Profile(ID, getReplacedParameter(), getReplacementType());
4707 }
4708
4709 static void Profile(llvm::FoldingSetNodeID &ID,
4710 const TemplateTypeParmType *Replaced,
4711 QualType Replacement) {
4712 ID.AddPointer(Replaced);
4713 ID.AddPointer(Replacement.getAsOpaquePtr());
4714 }
4715
4716 static bool classof(const Type *T) {
4717 return T->getTypeClass() == SubstTemplateTypeParm;
4718 }
4719};
4720
4721/// Represents the result of substituting a set of types for a template
4722/// type parameter pack.
4723///
4724/// When a pack expansion in the source code contains multiple parameter packs
4725/// and those parameter packs correspond to different levels of template
4726/// parameter lists, this type node is used to represent a template type
4727/// parameter pack from an outer level, which has already had its argument pack
4728/// substituted but that still lives within a pack expansion that itself
4729/// could not be instantiated. When actually performing a substitution into
4730/// that pack expansion (e.g., when all template parameters have corresponding
4731/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4732/// at the current pack substitution index.
4733class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4734 friend class ASTContext;
4735
4736 /// The original type parameter.
4737 const TemplateTypeParmType *Replaced;
4738
4739 /// A pointer to the set of template arguments that this
4740 /// parameter pack is instantiated with.
4741 const TemplateArgument *Arguments;
4742
4743 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4744 QualType Canon,
4745 const TemplateArgument &ArgPack);
4746
4747public:
4748 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4749
4750 /// Gets the template parameter that was substituted for.
4751 const TemplateTypeParmType *getReplacedParameter() const {
4752 return Replaced;
4753 }
4754
4755 unsigned getNumArgs() const {
4756 return SubstTemplateTypeParmPackTypeBits.NumArgs;
4757 }
4758
4759 bool isSugared() const { return false; }
4760 QualType desugar() const { return QualType(this, 0); }
4761
4762 TemplateArgument getArgumentPack() const;
4763
4764 void Profile(llvm::FoldingSetNodeID &ID);
4765 static void Profile(llvm::FoldingSetNodeID &ID,
4766 const TemplateTypeParmType *Replaced,
4767 const TemplateArgument &ArgPack);
4768
4769 static bool classof(const Type *T) {
4770 return T->getTypeClass() == SubstTemplateTypeParmPack;
4771 }
4772};
4773
4774/// Common base class for placeholders for types that get replaced by
4775/// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4776/// class template types, and (eventually) constrained type names from the C++
4777/// Concepts TS.
4778///
4779/// These types are usually a placeholder for a deduced type. However, before
4780/// the initializer is attached, or (usually) if the initializer is
4781/// type-dependent, there is no deduced type and the type is canonical. In
4782/// the latter case, it is also a dependent type.
4783class DeducedType : public Type {
4784protected:
4785 DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent,
4786 bool IsInstantiationDependent, bool ContainsParameterPack)
4787 : Type(TC,
4788 // FIXME: Retain the sugared deduced type?
4789 DeducedAsType.isNull() ? QualType(this, 0)
4790 : DeducedAsType.getCanonicalType(),
4791 IsDependent, IsInstantiationDependent,
4792 /*VariablyModified=*/false, ContainsParameterPack) {
4793 if (!DeducedAsType.isNull()) {
4794 if (DeducedAsType->isDependentType())
4795 setDependent();
4796 if (DeducedAsType->isInstantiationDependentType())
4797 setInstantiationDependent();
4798 if (DeducedAsType->containsUnexpandedParameterPack())
4799 setContainsUnexpandedParameterPack();
4800 }
4801 }
4802
4803public:
4804 bool isSugared() const { return !isCanonicalUnqualified(); }
4805 QualType desugar() const { return getCanonicalTypeInternal(); }
4806
4807 /// Get the type deduced for this placeholder type, or null if it's
4808 /// either not been deduced or was deduced to a dependent type.
4809 QualType getDeducedType() const {
4810 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4811 }
4812 bool isDeduced() const {
4813 return !isCanonicalUnqualified() || isDependentType();
4814 }
4815
4816 static bool classof(const Type *T) {
4817 return T->getTypeClass() == Auto ||
4818 T->getTypeClass() == DeducedTemplateSpecialization;
4819 }
4820};
4821
4822/// Represents a C++11 auto or C++14 decltype(auto) type.
4823class AutoType : public DeducedType, public llvm::FoldingSetNode {
4824 friend class ASTContext; // ASTContext creates these
4825
4826 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4827 bool IsDeducedAsDependent, bool IsDeducedAsPack)
4828 : DeducedType(Auto, DeducedAsType, IsDeducedAsDependent,
4829 IsDeducedAsDependent, IsDeducedAsPack) {
4830 AutoTypeBits.Keyword = (unsigned)Keyword;
4831 }
4832
4833public:
4834 bool isDecltypeAuto() const {
4835 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
4836 }
4837
4838 AutoTypeKeyword getKeyword() const {
4839 return (AutoTypeKeyword)AutoTypeBits.Keyword;
4840 }
4841
4842 void Profile(llvm::FoldingSetNodeID &ID) {
4843 Profile(ID, getDeducedType(), getKeyword(), isDependentType(),
4844 containsUnexpandedParameterPack());
4845 }
4846
4847 static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
4848 AutoTypeKeyword Keyword, bool IsDependent, bool IsPack) {
4849 ID.AddPointer(Deduced.getAsOpaquePtr());
4850 ID.AddInteger((unsigned)Keyword);
4851 ID.AddBoolean(IsDependent);
4852 ID.AddBoolean(IsPack);
4853 }
4854
4855 static bool classof(const Type *T) {
4856 return T->getTypeClass() == Auto;
4857 }
4858};
4859
4860/// Represents a C++17 deduced template specialization type.
4861class DeducedTemplateSpecializationType : public DeducedType,
4862 public llvm::FoldingSetNode {
4863 friend class ASTContext; // ASTContext creates these
4864
4865 /// The name of the template whose arguments will be deduced.
4866 TemplateName Template;
4867
4868 DeducedTemplateSpecializationType(TemplateName Template,
4869 QualType DeducedAsType,
4870 bool IsDeducedAsDependent)
4871 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
4872 IsDeducedAsDependent || Template.isDependent(),
4873 IsDeducedAsDependent || Template.isInstantiationDependent(),
4874 Template.containsUnexpandedParameterPack()),
4875 Template(Template) {}
4876
4877public:
4878 /// Retrieve the name of the template that we are deducing.
4879 TemplateName getTemplateName() const { return Template;}
4880
4881 void Profile(llvm::FoldingSetNodeID &ID) {
4882 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
4883 }
4884
4885 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
4886 QualType Deduced, bool IsDependent) {
4887 Template.Profile(ID);
4888 ID.AddPointer(Deduced.getAsOpaquePtr());
4889 ID.AddBoolean(IsDependent);
4890 }
4891
4892 static bool classof(const Type *T) {
4893 return T->getTypeClass() == DeducedTemplateSpecialization;
4894 }
4895};
4896
4897/// Represents a type template specialization; the template
4898/// must be a class template, a type alias template, or a template
4899/// template parameter. A template which cannot be resolved to one of
4900/// these, e.g. because it is written with a dependent scope
4901/// specifier, is instead represented as a
4902/// @c DependentTemplateSpecializationType.
4903///
4904/// A non-dependent template specialization type is always "sugar",
4905/// typically for a \c RecordType. For example, a class template
4906/// specialization type of \c vector<int> will refer to a tag type for
4907/// the instantiation \c std::vector<int, std::allocator<int>>
4908///
4909/// Template specializations are dependent if either the template or
4910/// any of the template arguments are dependent, in which case the
4911/// type may also be canonical.
4912///
4913/// Instances of this type are allocated with a trailing array of
4914/// TemplateArguments, followed by a QualType representing the
4915/// non-canonical aliased type when the template is a type alias
4916/// template.
4917class alignas(8) TemplateSpecializationType
4918 : public Type,
4919 public llvm::FoldingSetNode {
4920 friend class ASTContext; // ASTContext creates these
4921
4922 /// The name of the template being specialized. This is
4923 /// either a TemplateName::Template (in which case it is a
4924 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
4925 /// TypeAliasTemplateDecl*), a
4926 /// TemplateName::SubstTemplateTemplateParmPack, or a
4927 /// TemplateName::SubstTemplateTemplateParm (in which case the
4928 /// replacement must, recursively, be one of these).
4929 TemplateName Template;
4930
4931 TemplateSpecializationType(TemplateName T,
4932 ArrayRef<TemplateArgument> Args,
4933 QualType Canon,
4934 QualType Aliased);
4935
4936public:
4937 /// Determine whether any of the given template arguments are dependent.
4938 static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
4939 bool &InstantiationDependent);
4940
4941 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
4942 bool &InstantiationDependent);
4943
4944 /// True if this template specialization type matches a current
4945 /// instantiation in the context in which it is found.
4946 bool isCurrentInstantiation() const {
4947 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
4948 }
4949
4950 /// Determine if this template specialization type is for a type alias
4951 /// template that has been substituted.
4952 ///
4953 /// Nearly every template specialization type whose template is an alias
4954 /// template will be substituted. However, this is not the case when
4955 /// the specialization contains a pack expansion but the template alias
4956 /// does not have a corresponding parameter pack, e.g.,
4957 ///
4958 /// \code
4959 /// template<typename T, typename U, typename V> struct S;
4960 /// template<typename T, typename U> using A = S<T, int, U>;
4961 /// template<typename... Ts> struct X {
4962 /// typedef A<Ts...> type; // not a type alias
4963 /// };
4964 /// \endcode
4965 bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; }
4966
4967 /// Get the aliased type, if this is a specialization of a type alias
4968 /// template.
4969 QualType getAliasedType() const {
4970 assert(isTypeAlias() && "not a type alias template specialization")((isTypeAlias() && "not a type alias template specialization"
) ? static_cast<void> (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 4970, __PRETTY_FUNCTION__))
;
4971 return *reinterpret_cast<const QualType*>(end());
4972 }
4973
4974 using iterator = const TemplateArgument *;
4975
4976 iterator begin() const { return getArgs(); }
4977 iterator end() const; // defined inline in TemplateBase.h
4978
4979 /// Retrieve the name of the template that we are specializing.
4980 TemplateName getTemplateName() const { return Template; }
4981
4982 /// Retrieve the template arguments.
4983 const TemplateArgument *getArgs() const {
4984 return reinterpret_cast<const TemplateArgument *>(this + 1);
4985 }
4986
4987 /// Retrieve the number of template arguments.
4988 unsigned getNumArgs() const {
4989 return TemplateSpecializationTypeBits.NumArgs;
4990 }
4991
4992 /// Retrieve a specific template argument as a type.
4993 /// \pre \c isArgType(Arg)
4994 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4995
4996 ArrayRef<TemplateArgument> template_arguments() const {
4997 return {getArgs(), getNumArgs()};
4998 }
4999
5000 bool isSugared() const {
5001 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
5002 }
5003
5004 QualType desugar() const {
5005 return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal();
5006 }
5007
5008 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
5009 Profile(ID, Template, template_arguments(), Ctx);
5010 if (isTypeAlias())
5011 getAliasedType().Profile(ID);
5012 }
5013
5014 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
5015 ArrayRef<TemplateArgument> Args,
5016 const ASTContext &Context);
5017
5018 static bool classof(const Type *T) {
5019 return T->getTypeClass() == TemplateSpecialization;
5020 }
5021};
5022
5023/// Print a template argument list, including the '<' and '>'
5024/// enclosing the template arguments.
5025void printTemplateArgumentList(raw_ostream &OS,
5026 ArrayRef<TemplateArgument> Args,
5027 const PrintingPolicy &Policy);
5028
5029void printTemplateArgumentList(raw_ostream &OS,
5030 ArrayRef<TemplateArgumentLoc> Args,
5031 const PrintingPolicy &Policy);
5032
5033void printTemplateArgumentList(raw_ostream &OS,
5034 const TemplateArgumentListInfo &Args,
5035 const PrintingPolicy &Policy);
5036
5037/// The injected class name of a C++ class template or class
5038/// template partial specialization. Used to record that a type was
5039/// spelled with a bare identifier rather than as a template-id; the
5040/// equivalent for non-templated classes is just RecordType.
5041///
5042/// Injected class name types are always dependent. Template
5043/// instantiation turns these into RecordTypes.
5044///
5045/// Injected class name types are always canonical. This works
5046/// because it is impossible to compare an injected class name type
5047/// with the corresponding non-injected template type, for the same
5048/// reason that it is impossible to directly compare template
5049/// parameters from different dependent contexts: injected class name
5050/// types can only occur within the scope of a particular templated
5051/// declaration, and within that scope every template specialization
5052/// will canonicalize to the injected class name (when appropriate
5053/// according to the rules of the language).
5054class InjectedClassNameType : public Type {
5055 friend class ASTContext; // ASTContext creates these.
5056 friend class ASTNodeImporter;
5057 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
5058 // currently suitable for AST reading, too much
5059 // interdependencies.
5060
5061 CXXRecordDecl *Decl;
5062
5063 /// The template specialization which this type represents.
5064 /// For example, in
5065 /// template <class T> class A { ... };
5066 /// this is A<T>, whereas in
5067 /// template <class X, class Y> class A<B<X,Y> > { ... };
5068 /// this is A<B<X,Y> >.
5069 ///
5070 /// It is always unqualified, always a template specialization type,
5071 /// and always dependent.
5072 QualType InjectedType;
5073
5074 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
5075 : Type(InjectedClassName, QualType(), /*Dependent=*/true,
5076 /*InstantiationDependent=*/true,
5077 /*VariablyModified=*/false,
5078 /*ContainsUnexpandedParameterPack=*/false),
5079 Decl(D), InjectedType(TST) {
5080 assert(isa<TemplateSpecializationType>(TST))((isa<TemplateSpecializationType>(TST)) ? static_cast<
void> (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5080, __PRETTY_FUNCTION__))
;
5081 assert(!TST.hasQualifiers())((!TST.hasQualifiers()) ? static_cast<void> (0) : __assert_fail
("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5081, __PRETTY_FUNCTION__))
;
5082 assert(TST->isDependentType())((TST->isDependentType()) ? static_cast<void> (0) : __assert_fail
("TST->isDependentType()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5082, __PRETTY_FUNCTION__))
;
5083 }
5084
5085public:
5086 QualType getInjectedSpecializationType() const { return InjectedType; }
5087
5088 const TemplateSpecializationType *getInjectedTST() const {
5089 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
5090 }
5091
5092 TemplateName getTemplateName() const {
5093 return getInjectedTST()->getTemplateName();
5094 }
5095
5096 CXXRecordDecl *getDecl() const;
5097
5098 bool isSugared() const { return false; }
5099 QualType desugar() const { return QualType(this, 0); }
5100
5101 static bool classof(const Type *T) {
5102 return T->getTypeClass() == InjectedClassName;
5103 }
5104};
5105
5106/// The kind of a tag type.
5107enum TagTypeKind {
5108 /// The "struct" keyword.
5109 TTK_Struct,
5110
5111 /// The "__interface" keyword.
5112 TTK_Interface,
5113
5114 /// The "union" keyword.
5115 TTK_Union,
5116
5117 /// The "class" keyword.
5118 TTK_Class,
5119
5120 /// The "enum" keyword.
5121 TTK_Enum
5122};
5123
5124/// The elaboration keyword that precedes a qualified type name or
5125/// introduces an elaborated-type-specifier.
5126enum ElaboratedTypeKeyword {
5127 /// The "struct" keyword introduces the elaborated-type-specifier.
5128 ETK_Struct,
5129
5130 /// The "__interface" keyword introduces the elaborated-type-specifier.
5131 ETK_Interface,
5132
5133 /// The "union" keyword introduces the elaborated-type-specifier.
5134 ETK_Union,
5135
5136 /// The "class" keyword introduces the elaborated-type-specifier.
5137 ETK_Class,
5138
5139 /// The "enum" keyword introduces the elaborated-type-specifier.
5140 ETK_Enum,
5141
5142 /// The "typename" keyword precedes the qualified type name, e.g.,
5143 /// \c typename T::type.
5144 ETK_Typename,
5145
5146 /// No keyword precedes the qualified type name.
5147 ETK_None
5148};
5149
5150/// A helper class for Type nodes having an ElaboratedTypeKeyword.
5151/// The keyword in stored in the free bits of the base class.
5152/// Also provides a few static helpers for converting and printing
5153/// elaborated type keyword and tag type kind enumerations.
5154class TypeWithKeyword : public Type {
5155protected:
5156 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
5157 QualType Canonical, bool Dependent,
5158 bool InstantiationDependent, bool VariablyModified,
5159 bool ContainsUnexpandedParameterPack)
5160 : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
5161 ContainsUnexpandedParameterPack) {
5162 TypeWithKeywordBits.Keyword = Keyword;
5163 }
5164
5165public:
5166 ElaboratedTypeKeyword getKeyword() const {
5167 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
5168 }
5169
5170 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
5171 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
5172
5173 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
5174 /// It is an error to provide a type specifier which *isn't* a tag kind here.
5175 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
5176
5177 /// Converts a TagTypeKind into an elaborated type keyword.
5178 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
5179
5180 /// Converts an elaborated type keyword into a TagTypeKind.
5181 /// It is an error to provide an elaborated type keyword
5182 /// which *isn't* a tag kind here.
5183 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
5184
5185 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
5186
5187 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
5188
5189 static StringRef getTagTypeKindName(TagTypeKind Kind) {
5190 return getKeywordName(getKeywordForTagTypeKind(Kind));
5191 }
5192
5193 class CannotCastToThisType {};
5194 static CannotCastToThisType classof(const Type *);
5195};
5196
5197/// Represents a type that was referred to using an elaborated type
5198/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
5199/// or both.
5200///
5201/// This type is used to keep track of a type name as written in the
5202/// source code, including tag keywords and any nested-name-specifiers.
5203/// The type itself is always "sugar", used to express what was written
5204/// in the source code but containing no additional semantic information.
5205class ElaboratedType final
5206 : public TypeWithKeyword,
5207 public llvm::FoldingSetNode,
5208 private llvm::TrailingObjects<ElaboratedType, TagDecl *> {
5209 friend class ASTContext; // ASTContext creates these
5210 friend TrailingObjects;
5211
5212 /// The nested name specifier containing the qualifier.
5213 NestedNameSpecifier *NNS;
5214
5215 /// The type that this qualified name refers to.
5216 QualType NamedType;
5217
5218 /// The (re)declaration of this tag type owned by this occurrence is stored
5219 /// as a trailing object if there is one. Use getOwnedTagDecl to obtain
5220 /// it, or obtain a null pointer if there is none.
5221
5222 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5223 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
5224 : TypeWithKeyword(Keyword, Elaborated, CanonType,
5225 NamedType->isDependentType(),
5226 NamedType->isInstantiationDependentType(),
5227 NamedType->isVariablyModifiedType(),
5228 NamedType->containsUnexpandedParameterPack()),
5229 NNS(NNS), NamedType(NamedType) {
5230 ElaboratedTypeBits.HasOwnedTagDecl = false;
5231 if (OwnedTagDecl) {
5232 ElaboratedTypeBits.HasOwnedTagDecl = true;
5233 *getTrailingObjects<TagDecl *>() = OwnedTagDecl;
5234 }
5235 assert(!(Keyword == ETK_None && NNS == nullptr) &&((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5237, __PRETTY_FUNCTION__))
5236 "ElaboratedType cannot have elaborated type keyword "((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5237, __PRETTY_FUNCTION__))
5237 "and name qualifier both null.")((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5237, __PRETTY_FUNCTION__))
;
5238 }
5239
5240public:
5241 /// Retrieve the qualification on this type.
5242 NestedNameSpecifier *getQualifier() const { return NNS; }
5243
5244 /// Retrieve the type named by the qualified-id.
5245 QualType getNamedType() const { return NamedType; }
5246
5247 /// Remove a single level of sugar.
5248 QualType desugar() const { return getNamedType(); }
5249
5250 /// Returns whether this type directly provides sugar.
5251 bool isSugared() const { return true; }
5252
5253 /// Return the (re)declaration of this type owned by this occurrence of this
5254 /// type, or nullptr if there is none.
5255 TagDecl *getOwnedTagDecl() const {
5256 return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>()
5257 : nullptr;
5258 }
5259
5260 void Profile(llvm::FoldingSetNodeID &ID) {
5261 Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl());
5262 }
5263
5264 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5265 NestedNameSpecifier *NNS, QualType NamedType,
5266 TagDecl *OwnedTagDecl) {
5267 ID.AddInteger(Keyword);
5268 ID.AddPointer(NNS);
5269 NamedType.Profile(ID);
5270 ID.AddPointer(OwnedTagDecl);
5271 }
5272
5273 static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
5274};
5275
5276/// Represents a qualified type name for which the type name is
5277/// dependent.
5278///
5279/// DependentNameType represents a class of dependent types that involve a
5280/// possibly dependent nested-name-specifier (e.g., "T::") followed by a
5281/// name of a type. The DependentNameType may start with a "typename" (for a
5282/// typename-specifier), "class", "struct", "union", or "enum" (for a
5283/// dependent elaborated-type-specifier), or nothing (in contexts where we
5284/// know that we must be referring to a type, e.g., in a base class specifier).
5285/// Typically the nested-name-specifier is dependent, but in MSVC compatibility
5286/// mode, this type is used with non-dependent names to delay name lookup until
5287/// instantiation.
5288class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
5289 friend class ASTContext; // ASTContext creates these
5290
5291 /// The nested name specifier containing the qualifier.
5292 NestedNameSpecifier *NNS;
5293
5294 /// The type that this typename specifier refers to.
5295 const IdentifierInfo *Name;
5296
5297 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5298 const IdentifierInfo *Name, QualType CanonType)
5299 : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
5300 /*InstantiationDependent=*/true,
5301 /*VariablyModified=*/false,
5302 NNS->containsUnexpandedParameterPack()),
5303 NNS(NNS), Name(Name) {}
5304
5305public:
5306 /// Retrieve the qualification on this type.
5307 NestedNameSpecifier *getQualifier() const { return NNS; }
5308
5309 /// Retrieve the type named by the typename specifier as an identifier.
5310 ///
5311 /// This routine will return a non-NULL identifier pointer when the
5312 /// form of the original typename was terminated by an identifier,
5313 /// e.g., "typename T::type".
5314 const IdentifierInfo *getIdentifier() const {
5315 return Name;
5316 }
5317
5318 bool isSugared() const { return false; }
5319 QualType desugar() const { return QualType(this, 0); }
5320
5321 void Profile(llvm::FoldingSetNodeID &ID) {
5322 Profile(ID, getKeyword(), NNS, Name);
5323 }
5324
5325 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5326 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
5327 ID.AddInteger(Keyword);
5328 ID.AddPointer(NNS);
5329 ID.AddPointer(Name);
5330 }
5331
5332 static bool classof(const Type *T) {
5333 return T->getTypeClass() == DependentName;
5334 }
5335};
5336
5337/// Represents a template specialization type whose template cannot be
5338/// resolved, e.g.
5339/// A<T>::template B<T>
5340class alignas(8) DependentTemplateSpecializationType
5341 : public TypeWithKeyword,
5342 public llvm::FoldingSetNode {
5343 friend class ASTContext; // ASTContext creates these
5344
5345 /// The nested name specifier containing the qualifier.
5346 NestedNameSpecifier *NNS;
5347
5348 /// The identifier of the template.
5349 const IdentifierInfo *Name;
5350
5351 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
5352 NestedNameSpecifier *NNS,
5353 const IdentifierInfo *Name,
5354 ArrayRef<TemplateArgument> Args,
5355 QualType Canon);
5356
5357 const TemplateArgument *getArgBuffer() const {
5358 return reinterpret_cast<const TemplateArgument*>(this+1);
5359 }
5360
5361 TemplateArgument *getArgBuffer() {
5362 return reinterpret_cast<TemplateArgument*>(this+1);
5363 }
5364
5365public:
5366 NestedNameSpecifier *getQualifier() const { return NNS; }
5367 const IdentifierInfo *getIdentifier() const { return Name; }
5368
5369 /// Retrieve the template arguments.
5370 const TemplateArgument *getArgs() const {
5371 return getArgBuffer();
5372 }
5373
5374 /// Retrieve the number of template arguments.
5375 unsigned getNumArgs() const {
5376 return DependentTemplateSpecializationTypeBits.NumArgs;
5377 }
5378
5379 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5380
5381 ArrayRef<TemplateArgument> template_arguments() const {
5382 return {getArgs(), getNumArgs()};
5383 }
5384
5385 using iterator = const TemplateArgument *;
5386
5387 iterator begin() const { return getArgs(); }
5388 iterator end() const; // inline in TemplateBase.h
5389
5390 bool isSugared() const { return false; }
5391 QualType desugar() const { return QualType(this, 0); }
5392
5393 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5394 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()});
5395 }
5396
5397 static void Profile(llvm::FoldingSetNodeID &ID,
5398 const ASTContext &Context,
5399 ElaboratedTypeKeyword Keyword,
5400 NestedNameSpecifier *Qualifier,
5401 const IdentifierInfo *Name,
5402 ArrayRef<TemplateArgument> Args);
5403
5404 static bool classof(const Type *T) {
5405 return T->getTypeClass() == DependentTemplateSpecialization;
5406 }
5407};
5408
5409/// Represents a pack expansion of types.
5410///
5411/// Pack expansions are part of C++11 variadic templates. A pack
5412/// expansion contains a pattern, which itself contains one or more
5413/// "unexpanded" parameter packs. When instantiated, a pack expansion
5414/// produces a series of types, each instantiated from the pattern of
5415/// the expansion, where the Ith instantiation of the pattern uses the
5416/// Ith arguments bound to each of the unexpanded parameter packs. The
5417/// pack expansion is considered to "expand" these unexpanded
5418/// parameter packs.
5419///
5420/// \code
5421/// template<typename ...Types> struct tuple;
5422///
5423/// template<typename ...Types>
5424/// struct tuple_of_references {
5425/// typedef tuple<Types&...> type;
5426/// };
5427/// \endcode
5428///
5429/// Here, the pack expansion \c Types&... is represented via a
5430/// PackExpansionType whose pattern is Types&.
5431class PackExpansionType : public Type, public llvm::FoldingSetNode {
5432 friend class ASTContext; // ASTContext creates these
5433
5434 /// The pattern of the pack expansion.
5435 QualType Pattern;
5436
5437 PackExpansionType(QualType Pattern, QualType Canon,
5438 Optional<unsigned> NumExpansions)
5439 : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
5440 /*InstantiationDependent=*/true,
5441 /*VariablyModified=*/Pattern->isVariablyModifiedType(),
5442 /*ContainsUnexpandedParameterPack=*/false),
5443 Pattern(Pattern) {
5444 PackExpansionTypeBits.NumExpansions =
5445 NumExpansions ? *NumExpansions + 1 : 0;
5446 }
5447
5448public:
5449 /// Retrieve the pattern of this pack expansion, which is the
5450 /// type that will be repeatedly instantiated when instantiating the
5451 /// pack expansion itself.
5452 QualType getPattern() const { return Pattern; }
5453
5454 /// Retrieve the number of expansions that this pack expansion will
5455 /// generate, if known.
5456 Optional<unsigned> getNumExpansions() const {
5457 if (PackExpansionTypeBits.NumExpansions)
5458 return PackExpansionTypeBits.NumExpansions - 1;
5459 return None;
5460 }
5461
5462 bool isSugared() const { return !Pattern->isDependentType(); }
5463 QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
5464
5465 void Profile(llvm::FoldingSetNodeID &ID) {
5466 Profile(ID, getPattern(), getNumExpansions());
5467 }
5468
5469 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5470 Optional<unsigned> NumExpansions) {
5471 ID.AddPointer(Pattern.getAsOpaquePtr());
5472 ID.AddBoolean(NumExpansions.hasValue());
5473 if (NumExpansions)
5474 ID.AddInteger(*NumExpansions);
5475 }
5476
5477 static bool classof(const Type *T) {
5478 return T->getTypeClass() == PackExpansion;
5479 }
5480};
5481
5482/// This class wraps the list of protocol qualifiers. For types that can
5483/// take ObjC protocol qualifers, they can subclass this class.
5484template <class T>
5485class ObjCProtocolQualifiers {
5486protected:
5487 ObjCProtocolQualifiers() = default;
5488
5489 ObjCProtocolDecl * const *getProtocolStorage() const {
5490 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5491 }
5492
5493 ObjCProtocolDecl **getProtocolStorage() {
5494 return static_cast<T*>(this)->getProtocolStorageImpl();
5495 }
5496
5497 void setNumProtocols(unsigned N) {
5498 static_cast<T*>(this)->setNumProtocolsImpl(N);
5499 }
5500
5501 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5502 setNumProtocols(protocols.size());
5503 assert(getNumProtocols() == protocols.size() &&((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5504, __PRETTY_FUNCTION__))
5504 "bitfield overflow in protocol count")((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5504, __PRETTY_FUNCTION__))
;
5505 if (!protocols.empty())
5506 memcpy(getProtocolStorage(), protocols.data(),
5507 protocols.size() * sizeof(ObjCProtocolDecl*));
5508 }
5509
5510public:
5511 using qual_iterator = ObjCProtocolDecl * const *;
5512 using qual_range = llvm::iterator_range<qual_iterator>;
5513
5514 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5515 qual_iterator qual_begin() const { return getProtocolStorage(); }
5516 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5517
5518 bool qual_empty() const { return getNumProtocols() == 0; }
5519
5520 /// Return the number of qualifying protocols in this type, or 0 if
5521 /// there are none.
5522 unsigned getNumProtocols() const {
5523 return static_cast<const T*>(this)->getNumProtocolsImpl();
5524 }
5525
5526 /// Fetch a protocol by index.
5527 ObjCProtocolDecl *getProtocol(unsigned I) const {
5528 assert(I < getNumProtocols() && "Out-of-range protocol access")((I < getNumProtocols() && "Out-of-range protocol access"
) ? static_cast<void> (0) : __assert_fail ("I < getNumProtocols() && \"Out-of-range protocol access\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5528, __PRETTY_FUNCTION__))
;
5529 return qual_begin()[I];
5530 }
5531
5532 /// Retrieve all of the protocol qualifiers.
5533 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5534 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5535 }
5536};
5537
5538/// Represents a type parameter type in Objective C. It can take
5539/// a list of protocols.
5540class ObjCTypeParamType : public Type,
5541 public ObjCProtocolQualifiers<ObjCTypeParamType>,
5542 public llvm::FoldingSetNode {
5543 friend class ASTContext;
5544 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5545
5546 /// The number of protocols stored on this type.
5547 unsigned NumProtocols : 6;
5548
5549 ObjCTypeParamDecl *OTPDecl;
5550
5551 /// The protocols are stored after the ObjCTypeParamType node. In the
5552 /// canonical type, the list of protocols are sorted alphabetically
5553 /// and uniqued.
5554 ObjCProtocolDecl **getProtocolStorageImpl();
5555
5556 /// Return the number of qualifying protocols in this interface type,
5557 /// or 0 if there are none.
5558 unsigned getNumProtocolsImpl() const {
5559 return NumProtocols;
5560 }
5561
5562 void setNumProtocolsImpl(unsigned N) {
5563 NumProtocols = N;
5564 }
5565
5566 ObjCTypeParamType(const ObjCTypeParamDecl *D,
5567 QualType can,
5568 ArrayRef<ObjCProtocolDecl *> protocols);
5569
5570public:
5571 bool isSugared() const { return true; }
5572 QualType desugar() const { return getCanonicalTypeInternal(); }
5573
5574 static bool classof(const Type *T) {
5575 return T->getTypeClass() == ObjCTypeParam;
5576 }
5577
5578 void Profile(llvm::FoldingSetNodeID &ID);
5579 static void Profile(llvm::FoldingSetNodeID &ID,
5580 const ObjCTypeParamDecl *OTPDecl,
5581 ArrayRef<ObjCProtocolDecl *> protocols);
5582
5583 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5584};
5585
5586/// Represents a class type in Objective C.
5587///
5588/// Every Objective C type is a combination of a base type, a set of
5589/// type arguments (optional, for parameterized classes) and a list of
5590/// protocols.
5591///
5592/// Given the following declarations:
5593/// \code
5594/// \@class C<T>;
5595/// \@protocol P;
5596/// \endcode
5597///
5598/// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
5599/// with base C and no protocols.
5600///
5601/// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5602/// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
5603/// protocol list.
5604/// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5605/// and protocol list [P].
5606///
5607/// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5608/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5609/// and no protocols.
5610///
5611/// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5612/// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
5613/// this should get its own sugar class to better represent the source.
5614class ObjCObjectType : public Type,
5615 public ObjCProtocolQualifiers<ObjCObjectType> {
5616 friend class ObjCProtocolQualifiers<ObjCObjectType>;
5617
5618 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5619 // after the ObjCObjectPointerType node.
5620 // ObjCObjectType.NumProtocols - the number of protocols stored
5621 // after the type arguments of ObjCObjectPointerType node.
5622 //
5623 // These protocols are those written directly on the type. If
5624 // protocol qualifiers ever become additive, the iterators will need
5625 // to get kindof complicated.
5626 //
5627 // In the canonical object type, these are sorted alphabetically
5628 // and uniqued.
5629
5630 /// Either a BuiltinType or an InterfaceType or sugar for either.
5631 QualType BaseType;
5632
5633 /// Cached superclass type.
5634 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5635 CachedSuperClassType;
5636
5637 QualType *getTypeArgStorage();
5638 const QualType *getTypeArgStorage() const {
5639 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5640 }
5641
5642 ObjCProtocolDecl **getProtocolStorageImpl();
5643 /// Return the number of qualifying protocols in this interface type,
5644 /// or 0 if there are none.
5645 unsigned getNumProtocolsImpl() const {
5646 return ObjCObjectTypeBits.NumProtocols;
5647 }
5648 void setNumProtocolsImpl(unsigned N) {
5649 ObjCObjectTypeBits.NumProtocols = N;
5650 }
5651
5652protected:
5653 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5654
5655 ObjCObjectType(QualType Canonical, QualType Base,
5656 ArrayRef<QualType> typeArgs,
5657 ArrayRef<ObjCProtocolDecl *> protocols,
5658 bool isKindOf);
5659
5660 ObjCObjectType(enum Nonce_ObjCInterface)
5661 : Type(ObjCInterface, QualType(), false, false, false, false),
5662 BaseType(QualType(this_(), 0)) {
5663 ObjCObjectTypeBits.NumProtocols = 0;
5664 ObjCObjectTypeBits.NumTypeArgs = 0;
5665 ObjCObjectTypeBits.IsKindOf = 0;
5666 }
5667
5668 void computeSuperClassTypeSlow() const;
5669
5670public:
5671 /// Gets the base type of this object type. This is always (possibly
5672 /// sugar for) one of:
5673 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
5674 /// user, which is a typedef for an ObjCObjectPointerType)
5675 /// - the 'Class' builtin type (same caveat)
5676 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
5677 QualType getBaseType() const { return BaseType; }
5678
5679 bool isObjCId() const {
5680 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5681 }
5682
5683 bool isObjCClass() const {
5684 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5685 }
5686
5687 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5688 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5689 bool isObjCUnqualifiedIdOrClass() const {
5690 if (!qual_empty()) return false;
5691 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5692 return T->getKind() == BuiltinType::ObjCId ||
5693 T->getKind() == BuiltinType::ObjCClass;
5694 return false;
5695 }
5696 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5697 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5698
5699 /// Gets the interface declaration for this object type, if the base type
5700 /// really is an interface.
5701 ObjCInterfaceDecl *getInterface() const;
5702
5703 /// Determine whether this object type is "specialized", meaning
5704 /// that it has type arguments.
5705 bool isSpecialized() const;
5706
5707 /// Determine whether this object type was written with type arguments.
5708 bool isSpecializedAsWritten() const {
5709 return ObjCObjectTypeBits.NumTypeArgs > 0;
5710 }
5711
5712 /// Determine whether this object type is "unspecialized", meaning
5713 /// that it has no type arguments.
5714 bool isUnspecialized() const { return !isSpecialized(); }
5715
5716 /// Determine whether this object type is "unspecialized" as
5717 /// written, meaning that it has no type arguments.
5718 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5719
5720 /// Retrieve the type arguments of this object type (semantically).
5721 ArrayRef<QualType> getTypeArgs() const;
5722
5723 /// Retrieve the type arguments of this object type as they were
5724 /// written.
5725 ArrayRef<QualType> getTypeArgsAsWritten() const {
5726 return llvm::makeArrayRef(getTypeArgStorage(),
5727 ObjCObjectTypeBits.NumTypeArgs);
5728 }
5729
5730 /// Whether this is a "__kindof" type as written.
5731 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5732
5733 /// Whether this ia a "__kindof" type (semantically).
5734 bool isKindOfType() const;
5735
5736 /// Retrieve the type of the superclass of this object type.
5737 ///
5738 /// This operation substitutes any type arguments into the
5739 /// superclass of the current class type, potentially producing a
5740 /// specialization of the superclass type. Produces a null type if
5741 /// there is no superclass.
5742 QualType getSuperClassType() const {
5743 if (!CachedSuperClassType.getInt())
5744 computeSuperClassTypeSlow();
5745
5746 assert(CachedSuperClassType.getInt() && "Superclass not set?")((CachedSuperClassType.getInt() && "Superclass not set?"
) ? static_cast<void> (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 5746, __PRETTY_FUNCTION__))
;
5747 return QualType(CachedSuperClassType.getPointer(), 0);
5748 }
5749
5750 /// Strip off the Objective-C "kindof" type and (with it) any
5751 /// protocol qualifiers.
5752 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5753
5754 bool isSugared() const { return false; }
5755 QualType desugar() const { return QualType(this, 0); }
5756
5757 static bool classof(const Type *T) {
5758 return T->getTypeClass() == ObjCObject ||
5759 T->getTypeClass() == ObjCInterface;
5760 }
5761};
5762
5763/// A class providing a concrete implementation
5764/// of ObjCObjectType, so as to not increase the footprint of
5765/// ObjCInterfaceType. Code outside of ASTContext and the core type
5766/// system should not reference this type.
5767class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5768 friend class ASTContext;
5769
5770 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5771 // will need to be modified.
5772
5773 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5774 ArrayRef<QualType> typeArgs,
5775 ArrayRef<ObjCProtocolDecl *> protocols,
5776 bool isKindOf)
5777 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5778
5779public:
5780 void Profile(llvm::FoldingSetNodeID &ID);
5781 static void Profile(llvm::FoldingSetNodeID &ID,
5782 QualType Base,
5783 ArrayRef<QualType> typeArgs,
5784 ArrayRef<ObjCProtocolDecl *> protocols,
5785 bool isKindOf);
5786};
5787
5788inline QualType *ObjCObjectType::getTypeArgStorage() {
5789 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5790}
5791
5792inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5793 return reinterpret_cast<ObjCProtocolDecl**>(
5794 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5795}
5796
5797inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5798 return reinterpret_cast<ObjCProtocolDecl**>(
5799 static_cast<ObjCTypeParamType*>(this)+1);
5800}
5801
5802/// Interfaces are the core concept in Objective-C for object oriented design.
5803/// They basically correspond to C++ classes. There are two kinds of interface
5804/// types: normal interfaces like `NSString`, and qualified interfaces, which
5805/// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
5806///
5807/// ObjCInterfaceType guarantees the following properties when considered
5808/// as a subtype of its superclass, ObjCObjectType:
5809/// - There are no protocol qualifiers. To reinforce this, code which
5810/// tries to invoke the protocol methods via an ObjCInterfaceType will
5811/// fail to compile.
5812/// - It is its own base type. That is, if T is an ObjCInterfaceType*,
5813/// T->getBaseType() == QualType(T, 0).
5814class ObjCInterfaceType : public ObjCObjectType {
5815 friend class ASTContext; // ASTContext creates these.
5816 friend class ASTReader;
5817 friend class ObjCInterfaceDecl;
5818
5819 mutable ObjCInterfaceDecl *Decl;
5820
5821 ObjCInterfaceType(const ObjCInterfaceDecl *D)
5822 : ObjCObjectType(Nonce_ObjCInterface),
5823 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
5824
5825public:
5826 /// Get the declaration of this interface.
5827 ObjCInterfaceDecl *getDecl() const { return Decl; }
5828
5829 bool isSugared() const { return false; }
5830 QualType desugar() const { return QualType(this, 0); }
5831
5832 static bool classof(const Type *T) {
5833 return T->getTypeClass() == ObjCInterface;
5834 }
5835
5836 // Nonsense to "hide" certain members of ObjCObjectType within this
5837 // class. People asking for protocols on an ObjCInterfaceType are
5838 // not going to get what they want: ObjCInterfaceTypes are
5839 // guaranteed to have no protocols.
5840 enum {
5841 qual_iterator,
5842 qual_begin,
5843 qual_end,
5844 getNumProtocols,
5845 getProtocol
5846 };
5847};
5848
5849inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
5850 QualType baseType = getBaseType();
5851 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
5852 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
5853 return T->getDecl();
5854
5855 baseType = ObjT->getBaseType();
5856 }
5857
5858 return nullptr;
5859}
5860
5861/// Represents a pointer to an Objective C object.
5862///
5863/// These are constructed from pointer declarators when the pointee type is
5864/// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
5865/// types are typedefs for these, and the protocol-qualified types 'id<P>'
5866/// and 'Class<P>' are translated into these.
5867///
5868/// Pointers to pointers to Objective C objects are still PointerTypes;
5869/// only the first level of pointer gets it own type implementation.
5870class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
5871 friend class ASTContext; // ASTContext creates these.
5872
5873 QualType PointeeType;
5874
5875 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
5876 : Type(ObjCObjectPointer, Canonical,
5877 Pointee->isDependentType(),
5878 Pointee->isInstantiationDependentType(),
5879 Pointee->isVariablyModifiedType(),
5880 Pointee->containsUnexpandedParameterPack()),
5881 PointeeType(Pointee) {}
5882
5883public:
5884 /// Gets the type pointed to by this ObjC pointer.
5885 /// The result will always be an ObjCObjectType or sugar thereof.
5886 QualType getPointeeType() const { return PointeeType; }
5887
5888 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
5889 ///
5890 /// This method is equivalent to getPointeeType() except that
5891 /// it discards any typedefs (or other sugar) between this
5892 /// type and the "outermost" object type. So for:
5893 /// \code
5894 /// \@class A; \@protocol P; \@protocol Q;
5895 /// typedef A<P> AP;
5896 /// typedef A A1;
5897 /// typedef A1<P> A1P;
5898 /// typedef A1P<Q> A1PQ;
5899 /// \endcode
5900 /// For 'A*', getObjectType() will return 'A'.
5901 /// For 'A<P>*', getObjectType() will return 'A<P>'.
5902 /// For 'AP*', getObjectType() will return 'A<P>'.
5903 /// For 'A1*', getObjectType() will return 'A'.
5904 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
5905 /// For 'A1P*', getObjectType() will return 'A1<P>'.
5906 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
5907 /// adding protocols to a protocol-qualified base discards the
5908 /// old qualifiers (for now). But if it didn't, getObjectType()
5909 /// would return 'A1P<Q>' (and we'd have to make iterating over
5910 /// qualifiers more complicated).
5911 const ObjCObjectType *getObjectType() const {
5912 return PointeeType->castAs<ObjCObjectType>();
5913 }
5914
5915 /// If this pointer points to an Objective C
5916 /// \@interface type, gets the type for that interface. Any protocol
5917 /// qualifiers on the interface are ignored.
5918 ///
5919 /// \return null if the base type for this pointer is 'id' or 'Class'
5920 const ObjCInterfaceType *getInterfaceType() const;
5921
5922 /// If this pointer points to an Objective \@interface
5923 /// type, gets the declaration for that interface.
5924 ///
5925 /// \return null if the base type for this pointer is 'id' or 'Class'
5926 ObjCInterfaceDecl *getInterfaceDecl() const {
5927 return getObjectType()->getInterface();
5928 }
5929
5930 /// True if this is equivalent to the 'id' type, i.e. if
5931 /// its object type is the primitive 'id' type with no protocols.
5932 bool isObjCIdType() const {
5933 return getObjectType()->isObjCUnqualifiedId();
5934 }
5935
5936 /// True if this is equivalent to the 'Class' type,
5937 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
5938 bool isObjCClassType() const {
5939 return getObjectType()->isObjCUnqualifiedClass();
5940 }
5941
5942 /// True if this is equivalent to the 'id' or 'Class' type,
5943 bool isObjCIdOrClassType() const {
5944 return getObjectType()->isObjCUnqualifiedIdOrClass();
5945 }
5946
5947 /// True if this is equivalent to 'id<P>' for some non-empty set of
5948 /// protocols.
5949 bool isObjCQualifiedIdType() const {
5950 return getObjectType()->isObjCQualifiedId();
5951 }
5952
5953 /// True if this is equivalent to 'Class<P>' for some non-empty set of
5954 /// protocols.
5955 bool isObjCQualifiedClassType() const {
5956 return getObjectType()->isObjCQualifiedClass();
5957 }
5958
5959 /// Whether this is a "__kindof" type.
5960 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
5961
5962 /// Whether this type is specialized, meaning that it has type arguments.
5963 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
5964
5965 /// Whether this type is specialized, meaning that it has type arguments.
5966 bool isSpecializedAsWritten() const {
5967 return getObjectType()->isSpecializedAsWritten();
5968 }
5969
5970 /// Whether this type is unspecialized, meaning that is has no type arguments.
5971 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
5972
5973 /// Determine whether this object type is "unspecialized" as
5974 /// written, meaning that it has no type arguments.
5975 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5976
5977 /// Retrieve the type arguments for this type.
5978 ArrayRef<QualType> getTypeArgs() const {
5979 return getObjectType()->getTypeArgs();
5980 }
5981
5982 /// Retrieve the type arguments for this type.
5983 ArrayRef<QualType> getTypeArgsAsWritten() const {
5984 return getObjectType()->getTypeArgsAsWritten();
5985 }
5986
5987 /// An iterator over the qualifiers on the object type. Provided
5988 /// for convenience. This will always iterate over the full set of
5989 /// protocols on a type, not just those provided directly.
5990 using qual_iterator = ObjCObjectType::qual_iterator;
5991 using qual_range = llvm::iterator_range<qual_iterator>;
5992
5993 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5994
5995 qual_iterator qual_begin() const {
5996 return getObjectType()->qual_begin();
5997 }
5998
5999 qual_iterator qual_end() const {
6000 return getObjectType()->qual_end();
6001 }
6002
6003 bool qual_empty() const { return getObjectType()->qual_empty(); }
6004
6005 /// Return the number of qualifying protocols on the object type.
6006 unsigned getNumProtocols() const {
6007 return getObjectType()->getNumProtocols();
6008 }
6009
6010 /// Retrieve a qualifying protocol by index on the object type.
6011 ObjCProtocolDecl *getProtocol(unsigned I) const {
6012 return getObjectType()->getProtocol(I);
6013 }
6014
6015 bool isSugared() const { return false; }
6016 QualType desugar() const { return QualType(this, 0); }
6017
6018 /// Retrieve the type of the superclass of this object pointer type.
6019 ///
6020 /// This operation substitutes any type arguments into the
6021 /// superclass of the current class type, potentially producing a
6022 /// pointer to a specialization of the superclass type. Produces a
6023 /// null type if there is no superclass.
6024 QualType getSuperClassType() const;
6025
6026 /// Strip off the Objective-C "kindof" type and (with it) any
6027 /// protocol qualifiers.
6028 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
6029 const ASTContext &ctx) const;
6030
6031 void Profile(llvm::FoldingSetNodeID &ID) {
6032 Profile(ID, getPointeeType());
6033 }
6034
6035 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6036 ID.AddPointer(T.getAsOpaquePtr());
6037 }
6038
6039 static bool classof(const Type *T) {
6040 return T->getTypeClass() == ObjCObjectPointer;
6041 }
6042};
6043
6044class AtomicType : public Type, public llvm::FoldingSetNode {
6045 friend class ASTContext; // ASTContext creates these.
6046
6047 QualType ValueType;
6048
6049 AtomicType(QualType ValTy, QualType Canonical)
6050 : Type(Atomic, Canonical, ValTy->isDependentType(),
6051 ValTy->isInstantiationDependentType(),
6052 ValTy->isVariablyModifiedType(),
6053 ValTy->containsUnexpandedParameterPack()),
6054 ValueType(ValTy) {}
6055
6056public:
6057 /// Gets the type contained by this atomic type, i.e.
6058 /// the type returned by performing an atomic load of this atomic type.
6059 QualType getValueType() const { return ValueType; }
6060
6061 bool isSugared() const { return false; }
6062 QualType desugar() const { return QualType(this, 0); }
6063
6064 void Profile(llvm::FoldingSetNodeID &ID) {
6065 Profile(ID, getValueType());
6066 }
6067
6068 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6069 ID.AddPointer(T.getAsOpaquePtr());
6070 }
6071
6072 static bool classof(const Type *T) {
6073 return T->getTypeClass() == Atomic;
6074 }
6075};
6076
6077/// PipeType - OpenCL20.
6078class PipeType : public Type, public llvm::FoldingSetNode {
6079 friend class ASTContext; // ASTContext creates these.
6080
6081 QualType ElementType;
6082 bool isRead;
6083
6084 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
6085 : Type(Pipe, CanonicalPtr, elemType->isDependentType(),
6086 elemType->isInstantiationDependentType(),
6087 elemType->isVariablyModifiedType(),
6088 elemType->containsUnexpandedParameterPack()),
6089 ElementType(elemType), isRead(isRead) {}
6090
6091public:
6092 QualType getElementType() const { return ElementType; }
6093
6094 bool isSugared() const { return false; }
6095
6096 QualType desugar() const { return QualType(this, 0); }
6097
6098 void Profile(llvm::FoldingSetNodeID &ID) {
6099 Profile(ID, getElementType(), isReadOnly());
6100 }
6101
6102 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
6103 ID.AddPointer(T.getAsOpaquePtr());
6104 ID.AddBoolean(isRead);
6105 }
6106
6107 static bool classof(const Type *T) {
6108 return T->getTypeClass() == Pipe;
6109 }
6110
6111 bool isReadOnly() const { return isRead; }
6112};
6113
6114/// A qualifier set is used to build a set of qualifiers.
6115class QualifierCollector : public Qualifiers {
6116public:
6117 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
6118
6119 /// Collect any qualifiers on the given type and return an
6120 /// unqualified type. The qualifiers are assumed to be consistent
6121 /// with those already in the type.
6122 const Type *strip(QualType type) {
6123 addFastQualifiers(type.getLocalFastQualifiers());
6124 if (!type.hasLocalNonFastQualifiers())
6125 return type.getTypePtrUnsafe();
6126
6127 const ExtQuals *extQuals = type.getExtQualsUnsafe();
6128 addConsistentQualifiers(extQuals->getQualifiers());
6129 return extQuals->getBaseType();
6130 }
6131
6132 /// Apply the collected qualifiers to the given type.
6133 QualType apply(const ASTContext &Context, QualType QT) const;
6134
6135 /// Apply the collected qualifiers to the given type.
6136 QualType apply(const ASTContext &Context, const Type* T) const;
6137};
6138
6139// Inline function definitions.
6140
6141inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
6142 SplitQualType desugar =
6143 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
6144 desugar.Quals.addConsistentQualifiers(Quals);
6145 return desugar;
6146}
6147
6148inline const Type *QualType::getTypePtr() const {
6149 return getCommonPtr()->BaseType;
6150}
6151
6152inline const Type *QualType::getTypePtrOrNull() const {
6153 return (isNull() ? nullptr : getCommonPtr()->BaseType);
6154}
6155
6156inline SplitQualType QualType::split() const {
6157 if (!hasLocalNonFastQualifiers())
6158 return SplitQualType(getTypePtrUnsafe(),
6159 Qualifiers::fromFastMask(getLocalFastQualifiers()));
6160
6161 const ExtQuals *eq = getExtQualsUnsafe();
6162 Qualifiers qs = eq->getQualifiers();
6163 qs.addFastQualifiers(getLocalFastQualifiers());
6164 return SplitQualType(eq->getBaseType(), qs);
6165}
6166
6167inline Qualifiers QualType::getLocalQualifiers() const {
6168 Qualifiers Quals;
6169 if (hasLocalNonFastQualifiers())
6170 Quals = getExtQualsUnsafe()->getQualifiers();
6171 Quals.addFastQualifiers(getLocalFastQualifiers());
6172 return Quals;
6173}
6174
6175inline Qualifiers QualType::getQualifiers() const {
6176 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
6177 quals.addFastQualifiers(getLocalFastQualifiers());
6178 return quals;
6179}
6180
6181inline unsigned QualType::getCVRQualifiers() const {
6182 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
6183 cvr |= getLocalCVRQualifiers();
6184 return cvr;
6185}
6186
6187inline QualType QualType::getCanonicalType() const {
6188 QualType canon = getCommonPtr()->CanonicalType;
6189 return canon.withFastQualifiers(getLocalFastQualifiers());
6190}
6191
6192inline bool QualType::isCanonical() const {
6193 return getTypePtr()->isCanonicalUnqualified();
6194}
6195
6196inline bool QualType::isCanonicalAsParam() const {
6197 if (!isCanonical()) return false;
6198 if (hasLocalQualifiers()) return false;
6199
6200 const Type *T = getTypePtr();
6201 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
6202 return false;
6203
6204 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
6205}
6206
6207inline bool QualType::isConstQualified() const {
6208 return isLocalConstQualified() ||
6209 getCommonPtr()->CanonicalType.isLocalConstQualified();
6210}
6211
6212inline bool QualType::isRestrictQualified() const {
6213 return isLocalRestrictQualified() ||
6214 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
6215}
6216
6217
6218inline bool QualType::isVolatileQualified() const {
6219 return isLocalVolatileQualified() ||
6220 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
6221}
6222
6223inline bool QualType::hasQualifiers() const {
6224 return hasLocalQualifiers() ||
6225 getCommonPtr()->CanonicalType.hasLocalQualifiers();
6226}
6227
6228inline QualType QualType::getUnqualifiedType() const {
6229 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6230 return QualType(getTypePtr(), 0);
6231
6232 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
6233}
6234
6235inline SplitQualType QualType::getSplitUnqualifiedType() const {
6236 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6237 return split();
6238
6239 return getSplitUnqualifiedTypeImpl(*this);
6240}
6241
6242inline void QualType::removeLocalConst() {
6243 removeLocalFastQualifiers(Qualifiers::Const);
6244}
6245
6246inline void QualType::removeLocalRestrict() {
6247 removeLocalFastQualifiers(Qualifiers::Restrict);
6248}
6249
6250inline void QualType::removeLocalVolatile() {
6251 removeLocalFastQualifiers(Qualifiers::Volatile);
6252}
6253
6254inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
6255 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")((!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6255, __PRETTY_FUNCTION__))
;
6256 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
6257 "Fast bits differ from CVR bits!");
6258
6259 // Fast path: we don't need to touch the slow qualifiers.
6260 removeLocalFastQualifiers(Mask);
6261}
6262
6263/// Return the address space of this type.
6264inline LangAS QualType::getAddressSpace() const {
6265 return getQualifiers().getAddressSpace();
6266}
6267
6268/// Return the gc attribute of this type.
6269inline Qualifiers::GC QualType::getObjCGCAttr() const {
6270 return getQualifiers().getObjCGCAttr();
6271}
6272
6273inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
6274 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6275 return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD);
6276 return false;
6277}
6278
6279inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const {
6280 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6281 return hasNonTrivialToPrimitiveDestructCUnion(RD);
6282 return false;
6283}
6284
6285inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const {
6286 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6287 return hasNonTrivialToPrimitiveCopyCUnion(RD);
6288 return false;
6289}
6290
6291inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
6292 if (const auto *PT = t.getAs<PointerType>()) {
6293 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
6294 return FT->getExtInfo();
6295 } else if (const auto *FT = t.getAs<FunctionType>())
6296 return FT->getExtInfo();
6297
6298 return FunctionType::ExtInfo();
6299}
6300
6301inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
6302 return getFunctionExtInfo(*t);
6303}
6304
6305/// Determine whether this type is more
6306/// qualified than the Other type. For example, "const volatile int"
6307/// is more qualified than "const int", "volatile int", and
6308/// "int". However, it is not more qualified than "const volatile
6309/// int".
6310inline bool QualType::isMoreQualifiedThan(QualType other) const {
6311 Qualifiers MyQuals = getQualifiers();
6312 Qualifiers OtherQuals = other.getQualifiers();
6313 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
6314}
6315
6316/// Determine whether this type is at last
6317/// as qualified as the Other type. For example, "const volatile
6318/// int" is at least as qualified as "const int", "volatile int",
6319/// "int", and "const volatile int".
6320inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
6321 Qualifiers OtherQuals = other.getQualifiers();
6322
6323 // Ignore __unaligned qualifier if this type is a void.
6324 if (getUnqualifiedType()->isVoidType())
6325 OtherQuals.removeUnaligned();
6326
6327 return getQualifiers().compatiblyIncludes(OtherQuals);
6328}
6329
6330/// If Type is a reference type (e.g., const
6331/// int&), returns the type that the reference refers to ("const
6332/// int"). Otherwise, returns the type itself. This routine is used
6333/// throughout Sema to implement C++ 5p6:
6334///
6335/// If an expression initially has the type "reference to T" (8.3.2,
6336/// 8.5.3), the type is adjusted to "T" prior to any further
6337/// analysis, the expression designates the object or function
6338/// denoted by the reference, and the expression is an lvalue.
6339inline QualType QualType::getNonReferenceType() const {
6340 if (const auto *RefType = (*this)->getAs<ReferenceType>())
6341 return RefType->getPointeeType();
6342 else
6343 return *this;
6344}
6345
6346inline bool QualType::isCForbiddenLValueType() const {
6347 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
6348 getTypePtr()->isFunctionType());
6349}
6350
6351/// Tests whether the type is categorized as a fundamental type.
6352///
6353/// \returns True for types specified in C++0x [basic.fundamental].
6354inline bool Type::isFundamentalType() const {
6355 return isVoidType() ||
6356 isNullPtrType() ||
6357 // FIXME: It's really annoying that we don't have an
6358 // 'isArithmeticType()' which agrees with the standard definition.
6359 (isArithmeticType() && !isEnumeralType());
6360}
6361
6362/// Tests whether the type is categorized as a compound type.
6363///
6364/// \returns True for types specified in C++0x [basic.compound].
6365inline bool Type::isCompoundType() const {
6366 // C++0x [basic.compound]p1:
6367 // Compound types can be constructed in the following ways:
6368 // -- arrays of objects of a given type [...];
6369 return isArrayType() ||
6370 // -- functions, which have parameters of given types [...];
6371 isFunctionType() ||
6372 // -- pointers to void or objects or functions [...];
6373 isPointerType() ||
6374 // -- references to objects or functions of a given type. [...]
6375 isReferenceType() ||
6376 // -- classes containing a sequence of objects of various types, [...];
6377 isRecordType() ||
6378 // -- unions, which are classes capable of containing objects of different
6379 // types at different times;
6380 isUnionType() ||
6381 // -- enumerations, which comprise a set of named constant values. [...];
6382 isEnumeralType() ||
6383 // -- pointers to non-static class members, [...].
6384 isMemberPointerType();
6385}
6386
6387inline bool Type::isFunctionType() const {
6388 return isa<FunctionType>(CanonicalType);
6389}
6390
6391inline bool Type::isPointerType() const {
6392 return isa<PointerType>(CanonicalType);
23
Assuming field 'CanonicalType' is a 'PointerType'
24
Returning the value 1, which participates in a condition later
6393}
6394
6395inline bool Type::isAnyPointerType() const {
6396 return isPointerType() || isObjCObjectPointerType();
6397}
6398
6399inline bool Type::isBlockPointerType() const {
6400 return isa<BlockPointerType>(CanonicalType);
6401}
6402
6403inline bool Type::isReferenceType() const {
6404 return isa<ReferenceType>(CanonicalType);
6405}
6406
6407inline bool Type::isLValueReferenceType() const {
6408 return isa<LValueReferenceType>(CanonicalType);
6409}
6410
6411inline bool Type::isRValueReferenceType() const {
6412 return isa<RValueReferenceType>(CanonicalType);
6413}
6414
6415inline bool Type::isFunctionPointerType() const {
6416 if (const auto *T = getAs<PointerType>())
6417 return T->getPointeeType()->isFunctionType();
6418 else
6419 return false;
6420}
6421
6422inline bool Type::isFunctionReferenceType() const {
6423 if (const auto *T = getAs<ReferenceType>())
6424 return T->getPointeeType()->isFunctionType();
6425 else
6426 return false;
6427}
6428
6429inline bool Type::isMemberPointerType() const {
6430 return isa<MemberPointerType>(CanonicalType);
6431}
6432
6433inline bool Type::isMemberFunctionPointerType() const {
6434 if (const auto *T = getAs<MemberPointerType>())
6435 return T->isMemberFunctionPointer();
6436 else
6437 return false;
6438}
6439
6440inline bool Type::isMemberDataPointerType() const {
6441 if (const auto *T = getAs<MemberPointerType>())
6442 return T->isMemberDataPointer();
6443 else
6444 return false;
6445}
6446
6447inline bool Type::isArrayType() const {
6448 return isa<ArrayType>(CanonicalType);
6449}
6450
6451inline bool Type::isConstantArrayType() const {
6452 return isa<ConstantArrayType>(CanonicalType);
6453}
6454
6455inline bool Type::isIncompleteArrayType() const {
6456 return isa<IncompleteArrayType>(CanonicalType);
6457}
6458
6459inline bool Type::isVariableArrayType() const {
6460 return isa<VariableArrayType>(CanonicalType);
6461}
6462
6463inline bool Type::isDependentSizedArrayType() const {
6464 return isa<DependentSizedArrayType>(CanonicalType);
6465}
6466
6467inline bool Type::isBuiltinType() const {
6468 return isa<BuiltinType>(CanonicalType);
6469}
6470
6471inline bool Type::isRecordType() const {
6472 return isa<RecordType>(CanonicalType);
6473}
6474
6475inline bool Type::isEnumeralType() const {
6476 return isa<EnumType>(CanonicalType);
6477}
6478
6479inline bool Type::isAnyComplexType() const {
6480 return isa<ComplexType>(CanonicalType);
6481}
6482
6483inline bool Type::isVectorType() const {
6484 return isa<VectorType>(CanonicalType);
6485}
6486
6487inline bool Type::isExtVectorType() const {
6488 return isa<ExtVectorType>(CanonicalType);
6489}
6490
6491inline bool Type::isDependentAddressSpaceType() const {
6492 return isa<DependentAddressSpaceType>(CanonicalType);
6493}
6494
6495inline bool Type::isObjCObjectPointerType() const {
6496 return isa<ObjCObjectPointerType>(CanonicalType);
6497}
6498
6499inline bool Type::isObjCObjectType() const {
6500 return isa<ObjCObjectType>(CanonicalType);
6501}
6502
6503inline bool Type::isObjCObjectOrInterfaceType() const {
6504 return isa<ObjCInterfaceType>(CanonicalType) ||
6505 isa<ObjCObjectType>(CanonicalType);
6506}
6507
6508inline bool Type::isAtomicType() const {
6509 return isa<AtomicType>(CanonicalType);
6510}
6511
6512inline bool Type::isObjCQualifiedIdType() const {
6513 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6514 return OPT->isObjCQualifiedIdType();
6515 return false;
6516}
6517
6518inline bool Type::isObjCQualifiedClassType() const {
6519 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6520 return OPT->isObjCQualifiedClassType();
6521 return false;
6522}
6523
6524inline bool Type::isObjCIdType() const {
6525 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6526 return OPT->isObjCIdType();
6527 return false;
6528}
6529
6530inline bool Type::isObjCClassType() const {
6531 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6532 return OPT->isObjCClassType();
6533 return false;
6534}
6535
6536inline bool Type::isObjCSelType() const {
6537 if (const auto *OPT = getAs<PointerType>())
6538 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6539 return false;
6540}
6541
6542inline bool Type::isObjCBuiltinType() const {
6543 return isObjCIdType() || isObjCClassType() || isObjCSelType();
6544}
6545
6546inline bool Type::isDecltypeType() const {
6547 return isa<DecltypeType>(this);
6548}
6549
6550#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6551 inline bool Type::is##Id##Type() const { \
6552 return isSpecificBuiltinType(BuiltinType::Id); \
6553 }
6554#include "clang/Basic/OpenCLImageTypes.def"
6555
6556inline bool Type::isSamplerT() const {
6557 return isSpecificBuiltinType(BuiltinType::OCLSampler);
6558}
6559
6560inline bool Type::isEventT() const {
6561 return isSpecificBuiltinType(BuiltinType::OCLEvent);
6562}
6563
6564inline bool Type::isClkEventT() const {
6565 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6566}
6567
6568inline bool Type::isQueueT() const {
6569 return isSpecificBuiltinType(BuiltinType::OCLQueue);
6570}
6571
6572inline bool Type::isReserveIDT() const {
6573 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6574}
6575
6576inline bool Type::isImageType() const {
6577#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6578 return
6579#include "clang/Basic/OpenCLImageTypes.def"
6580 false; // end boolean or operation
6581}
6582
6583inline bool Type::isPipeType() const {
6584 return isa<PipeType>(CanonicalType);
6585}
6586
6587#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6588 inline bool Type::is##Id##Type() const { \
6589 return isSpecificBuiltinType(BuiltinType::Id); \
6590 }
6591#include "clang/Basic/OpenCLExtensionTypes.def"
6592
6593inline bool Type::isOCLIntelSubgroupAVCType() const {
6594#define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \
6595 isOCLIntelSubgroupAVC##Id##Type() ||
6596 return
6597#include "clang/Basic/OpenCLExtensionTypes.def"
6598 false; // end of boolean or operation
6599}
6600
6601inline bool Type::isOCLExtOpaqueType() const {
6602#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() ||
6603 return
6604#include "clang/Basic/OpenCLExtensionTypes.def"
6605 false; // end of boolean or operation
6606}
6607
6608inline bool Type::isOpenCLSpecificType() const {
6609 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6610 isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType();
6611}
6612
6613inline bool Type::isTemplateTypeParmType() const {
6614 return isa<TemplateTypeParmType>(CanonicalType);
6615}
6616
6617inline bool Type::isSpecificBuiltinType(unsigned K) const {
6618 if (const BuiltinType *BT = getAs<BuiltinType>())
6619 if (BT->getKind() == (BuiltinType::Kind) K)
6620 return true;
6621 return false;
6622}
6623
6624inline bool Type::isPlaceholderType() const {
6625 if (const auto *BT = dyn_cast<BuiltinType>(this))
6626 return BT->isPlaceholderType();
6627 return false;
6628}
6629
6630inline const BuiltinType *Type::getAsPlaceholderType() const {
6631 if (const auto *BT = dyn_cast<BuiltinType>(this))
6632 if (BT->isPlaceholderType())
6633 return BT;
6634 return nullptr;
6635}
6636
6637inline bool Type::isSpecificPlaceholderType(unsigned K) const {
6638 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))((BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)) ?
static_cast<void> (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6638, __PRETTY_FUNCTION__))
;
6639 if (const auto *BT = dyn_cast<BuiltinType>(this))
6640 return (BT->getKind() == (BuiltinType::Kind) K);
6641 return false;
6642}
6643
6644inline bool Type::isNonOverloadPlaceholderType() const {
6645 if (const auto *BT = dyn_cast<BuiltinType>(this))
6646 return BT->isNonOverloadPlaceholderType();
6647 return false;
6648}
6649
6650inline bool Type::isVoidType() const {
6651 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6652 return BT->getKind() == BuiltinType::Void;
6653 return false;
6654}
6655
6656inline bool Type::isHalfType() const {
6657 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6658 return BT->getKind() == BuiltinType::Half;
6659 // FIXME: Should we allow complex __fp16? Probably not.
6660 return false;
6661}
6662
6663inline bool Type::isFloat16Type() const {
6664 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6665 return BT->getKind() == BuiltinType::Float16;
6666 return false;
6667}
6668
6669inline bool Type::isFloat128Type() const {
6670 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6671 return BT->getKind() == BuiltinType::Float128;
6672 return false;
6673}
6674
6675inline bool Type::isNullPtrType() const {
6676 if (const auto *BT = getAs<BuiltinType>())
6677 return BT->getKind() == BuiltinType::NullPtr;
6678 return false;
6679}
6680
6681bool IsEnumDeclComplete(EnumDecl *);
6682bool IsEnumDeclScoped(EnumDecl *);
6683
6684inline bool Type::isIntegerType() const {
6685 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6686 return BT->getKind() >= BuiltinType::Bool &&
6687 BT->getKind() <= BuiltinType::Int128;
6688 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
6689 // Incomplete enum types are not treated as integer types.
6690 // FIXME: In C++, enum types are never integer types.
6691 return IsEnumDeclComplete(ET->getDecl()) &&
6692 !IsEnumDeclScoped(ET->getDecl());
6693 }
6694 return false;
6695}
6696
6697inline bool Type::isFixedPointType() const {
6698 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6699 return BT->getKind() >= BuiltinType::ShortAccum &&
6700 BT->getKind() <= BuiltinType::SatULongFract;
6701 }
6702 return false;
6703}
6704
6705inline bool Type::isFixedPointOrIntegerType() const {
6706 return isFixedPointType() || isIntegerType();
6707}
6708
6709inline bool Type::isSaturatedFixedPointType() const {
6710 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6711 return BT->getKind() >= BuiltinType::SatShortAccum &&
6712 BT->getKind() <= BuiltinType::SatULongFract;
6713 }
6714 return false;
6715}
6716
6717inline bool Type::isUnsaturatedFixedPointType() const {
6718 return isFixedPointType() && !isSaturatedFixedPointType();
6719}
6720
6721inline bool Type::isSignedFixedPointType() const {
6722 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6723 return ((BT->getKind() >= BuiltinType::ShortAccum &&
6724 BT->getKind() <= BuiltinType::LongAccum) ||
6725 (BT->getKind() >= BuiltinType::ShortFract &&
6726 BT->getKind() <= BuiltinType::LongFract) ||
6727 (BT->getKind() >= BuiltinType::SatShortAccum &&
6728 BT->getKind() <= BuiltinType::SatLongAccum) ||
6729 (BT->getKind() >= BuiltinType::SatShortFract &&
6730 BT->getKind() <= BuiltinType::SatLongFract));
6731 }
6732 return false;
6733}
6734
6735inline bool Type::isUnsignedFixedPointType() const {
6736 return isFixedPointType() && !isSignedFixedPointType();
6737}
6738
6739inline bool Type::isScalarType() const {
6740 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6741 return BT->getKind() > BuiltinType::Void &&
6742 BT->getKind() <= BuiltinType::NullPtr;
6743 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
6744 // Enums are scalar types, but only if they are defined. Incomplete enums
6745 // are not treated as scalar types.
6746 return IsEnumDeclComplete(ET->getDecl());
6747 return isa<PointerType>(CanonicalType) ||
6748 isa<BlockPointerType>(CanonicalType) ||
6749 isa<MemberPointerType>(CanonicalType) ||
6750 isa<ComplexType>(CanonicalType) ||
6751 isa<ObjCObjectPointerType>(CanonicalType);
6752}
6753
6754inline bool Type::isIntegralOrEnumerationType() const {
6755 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6756 return BT->getKind() >= BuiltinType::Bool &&
6757 BT->getKind() <= BuiltinType::Int128;
6758
6759 // Check for a complete enum type; incomplete enum types are not properly an
6760 // enumeration type in the sense required here.
6761 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
6762 return IsEnumDeclComplete(ET->getDecl());
6763
6764 return false;
6765}
6766
6767inline bool Type::isBooleanType() const {
6768 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6769 return BT->getKind() == BuiltinType::Bool;
6770 return false;
6771}
6772
6773inline bool Type::isUndeducedType() const {
6774 auto *DT = getContainedDeducedType();
6775 return DT && !DT->isDeduced();
6776}
6777
6778/// Determines whether this is a type for which one can define
6779/// an overloaded operator.
6780inline bool Type::isOverloadableType() const {
6781 return isDependentType() || isRecordType() || isEnumeralType();
6782}
6783
6784/// Determines whether this type can decay to a pointer type.
6785inline bool Type::canDecayToPointerType() const {
6786 return isFunctionType() || isArrayType();
6787}
6788
6789inline bool Type::hasPointerRepresentation() const {
6790 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
6791 isObjCObjectPointerType() || isNullPtrType());
6792}
6793
6794inline bool Type::hasObjCPointerRepresentation() const {
6795 return isObjCObjectPointerType();
6796}
6797
6798inline const Type *Type::getBaseElementTypeUnsafe() const {
6799 const Type *type = this;
6800 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
6801 type = arrayType->getElementType().getTypePtr();
6802 return type;
6803}
6804
6805inline const Type *Type::getPointeeOrArrayElementType() const {
6806 const Type *type = this;
6807 if (type->isAnyPointerType())
6808 return type->getPointeeType().getTypePtr();
6809 else if (type->isArrayType())
6810 return type->getBaseElementTypeUnsafe();
6811 return type;
6812}
6813
6814/// Insertion operator for diagnostics. This allows sending Qualifiers into a
6815/// diagnostic with <<.
6816inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6817 Qualifiers Q) {
6818 DB.AddTaggedVal(Q.getAsOpaqueValue(),
6819 DiagnosticsEngine::ArgumentKind::ak_qual);
6820 return DB;
6821}
6822
6823/// Insertion operator for partial diagnostics. This allows sending Qualifiers
6824/// into a diagnostic with <<.
6825inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6826 Qualifiers Q) {
6827 PD.AddTaggedVal(Q.getAsOpaqueValue(),
6828 DiagnosticsEngine::ArgumentKind::ak_qual);
6829 return PD;
6830}
6831
6832/// Insertion operator for diagnostics. This allows sending QualType's into a
6833/// diagnostic with <<.
6834inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6835 QualType T) {
6836 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6837 DiagnosticsEngine::ak_qualtype);
6838 return DB;
6839}
6840
6841/// Insertion operator for partial diagnostics. This allows sending QualType's
6842/// into a diagnostic with <<.
6843inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6844 QualType T) {
6845 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6846 DiagnosticsEngine::ak_qualtype);
6847 return PD;
6848}
6849
6850// Helper class template that is used by Type::getAs to ensure that one does
6851// not try to look through a qualified type to get to an array type.
6852template <typename T>
6853using TypeIsArrayType =
6854 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
6855 std::is_base_of<ArrayType, T>::value>;
6856
6857// Member-template getAs<specific type>'.
6858template <typename T> const T *Type::getAs() const {
6859 static_assert(!TypeIsArrayType<T>::value,
6860 "ArrayType cannot be used with getAs!");
6861
6862 // If this is directly a T type, return it.
6863 if (const auto *Ty = dyn_cast<T>(this))
6864 return Ty;
6865
6866 // If the canonical form of this type isn't the right kind, reject it.
6867 if (!isa<T>(CanonicalType))
6868 return nullptr;
6869
6870 // If this is a typedef for the type, strip the typedef off without
6871 // losing all typedef information.
6872 return cast<T>(getUnqualifiedDesugaredType());
6873}
6874
6875template <typename T> const T *Type::getAsAdjusted() const {
6876 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
6877
6878 // If this is directly a T type, return it.
6879 if (const auto *Ty = dyn_cast<T>(this))
6880 return Ty;
6881
6882 // If the canonical form of this type isn't the right kind, reject it.
6883 if (!isa<T>(CanonicalType))
6884 return nullptr;
6885
6886 // Strip off type adjustments that do not modify the underlying nature of the
6887 // type.
6888 const Type *Ty = this;
6889 while (Ty) {
6890 if (const auto *A = dyn_cast<AttributedType>(Ty))
6891 Ty = A->getModifiedType().getTypePtr();
6892 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
6893 Ty = E->desugar().getTypePtr();
6894 else if (const auto *P = dyn_cast<ParenType>(Ty))
6895 Ty = P->desugar().getTypePtr();
6896 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
6897 Ty = A->desugar().getTypePtr();
6898 else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty))
6899 Ty = M->desugar().getTypePtr();
6900 else
6901 break;
6902 }
6903
6904 // Just because the canonical type is correct does not mean we can use cast<>,
6905 // since we may not have stripped off all the sugar down to the base type.
6906 return dyn_cast<T>(Ty);
6907}
6908
6909inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
6910 // If this is directly an array type, return it.
6911 if (const auto *arr = dyn_cast<ArrayType>(this))
6912 return arr;
6913
6914 // If the canonical form of this type isn't the right kind, reject it.
6915 if (!isa<ArrayType>(CanonicalType))
6916 return nullptr;
6917
6918 // If this is a typedef for the type, strip the typedef off without
6919 // losing all typedef information.
6920 return cast<ArrayType>(getUnqualifiedDesugaredType());
6921}
6922
6923template <typename T> const T *Type::castAs() const {
6924 static_assert(!TypeIsArrayType<T>::value,
6925 "ArrayType cannot be used with castAs!");
6926
6927 if (const auto *ty = dyn_cast<T>(this)) return ty;
6928 assert(isa<T>(CanonicalType))((isa<T>(CanonicalType)) ? static_cast<void> (0) :
__assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6928, __PRETTY_FUNCTION__))
;
6929 return cast<T>(getUnqualifiedDesugaredType());
6930}
6931
6932inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
6933 assert(isa<ArrayType>(CanonicalType))((isa<ArrayType>(CanonicalType)) ? static_cast<void>
(0) : __assert_fail ("isa<ArrayType>(CanonicalType)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6933, __PRETTY_FUNCTION__))
;
6934 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
6935 return cast<ArrayType>(getUnqualifiedDesugaredType());
6936}
6937
6938DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
6939 QualType CanonicalPtr)
6940 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
6941#ifndef NDEBUG
6942 QualType Adjusted = getAdjustedType();
6943 (void)AttributedType::stripOuterNullability(Adjusted);
6944 assert(isa<PointerType>(Adjusted))((isa<PointerType>(Adjusted)) ? static_cast<void>
(0) : __assert_fail ("isa<PointerType>(Adjusted)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Type.h"
, 6944, __PRETTY_FUNCTION__))
;
6945#endif
6946}
6947
6948QualType DecayedType::getPointeeType() const {
6949 QualType Decayed = getDecayedType();
6950 (void)AttributedType::stripOuterNullability(Decayed);
6951 return cast<PointerType>(Decayed)->getPointeeType();
6952}
6953
6954// Get the decimal string representation of a fixed point type, represented
6955// as a scaled integer.
6956// TODO: At some point, we should change the arguments to instead just accept an
6957// APFixedPoint instead of APSInt and scale.
6958void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val,
6959 unsigned Scale);
6960
6961} // namespace clang
6962
6963#endif // LLVM_CLANG_AST_TYPE_H