Bug Summary

File:tools/clang/lib/AST/QualTypeNames.cpp
Warning:line 198, column 9
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 QualTypeNames.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn325118/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn325118/build-llvm/tools/clang/lib/AST -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-02-14-150435-17243-1 -x c++ /build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/QualTypeNames.cpp

/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/QualTypeNames.cpp

1//===------- QualTypeNames.cpp - Generate Complete QualType Names ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5//===----------------------------------------------------------------------===//
6//
7// This file is distributed under the University of Illinois Open Source
8// License. See LICENSE.TXT for details.
9//
10//===----------------------------------------------------------------------===//
11
12#include "clang/AST/DeclTemplate.h"
13#include "clang/AST/DeclarationName.h"
14#include "clang/AST/GlobalDecl.h"
15#include "clang/AST/Mangle.h"
16#include "clang/AST/QualTypeNames.h"
17
18#include <stdio.h>
19#include <memory>
20
21namespace clang {
22
23namespace TypeName {
24
25/// \brief Create a NestedNameSpecifier for Namesp and its enclosing
26/// scopes.
27///
28/// \param[in] Ctx - the AST Context to be used.
29/// \param[in] Namesp - the NamespaceDecl for which a NestedNameSpecifier
30/// is requested.
31/// \param[in] WithGlobalNsPrefix - Indicate whether the global namespace
32/// specifier "::" should be prepended or not.
33static NestedNameSpecifier *createNestedNameSpecifier(
34 const ASTContext &Ctx,
35 const NamespaceDecl *Namesp,
36 bool WithGlobalNsPrefix);
37
38/// \brief Create a NestedNameSpecifier for TagDecl and its enclosing
39/// scopes.
40///
41/// \param[in] Ctx - the AST Context to be used.
42/// \param[in] TD - the TagDecl for which a NestedNameSpecifier is
43/// requested.
44/// \param[in] FullyQualify - Convert all template arguments into fully
45/// qualified names.
46/// \param[in] WithGlobalNsPrefix - Indicate whether the global namespace
47/// specifier "::" should be prepended or not.
48static NestedNameSpecifier *createNestedNameSpecifier(
49 const ASTContext &Ctx, const TypeDecl *TD,
50 bool FullyQualify, bool WithGlobalNsPrefix);
51
52static NestedNameSpecifier *createNestedNameSpecifierForScopeOf(
53 const ASTContext &Ctx, const Decl *decl,
54 bool FullyQualified, bool WithGlobalNsPrefix);
55
56static NestedNameSpecifier *getFullyQualifiedNestedNameSpecifier(
57 const ASTContext &Ctx, NestedNameSpecifier *scope, bool WithGlobalNsPrefix);
58
59static bool getFullyQualifiedTemplateName(const ASTContext &Ctx,
60 TemplateName &TName,
61 bool WithGlobalNsPrefix) {
62 bool Changed = false;
63 NestedNameSpecifier *NNS = nullptr;
64
65 TemplateDecl *ArgTDecl = TName.getAsTemplateDecl();
66 // ArgTDecl won't be NULL because we asserted that this isn't a
67 // dependent context very early in the call chain.
68 assert(ArgTDecl != nullptr)(static_cast <bool> (ArgTDecl != nullptr) ? void (0) : __assert_fail
("ArgTDecl != nullptr", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/QualTypeNames.cpp"
, 68, __extension__ __PRETTY_FUNCTION__))
;
69 QualifiedTemplateName *QTName = TName.getAsQualifiedTemplateName();
70
71 if (QTName && !QTName->hasTemplateKeyword()) {
1
Assuming 'QTName' is null
72 NNS = QTName->getQualifier();
73 NestedNameSpecifier *QNNS = getFullyQualifiedNestedNameSpecifier(
74 Ctx, NNS, WithGlobalNsPrefix);
75 if (QNNS != NNS) {
76 Changed = true;
77 NNS = QNNS;
78 } else {
79 NNS = nullptr;
80 }
81 } else {
82 NNS = createNestedNameSpecifierForScopeOf(
2
Calling 'createNestedNameSpecifierForScopeOf'
83 Ctx, ArgTDecl, true, WithGlobalNsPrefix);
84 }
85 if (NNS) {
86 TName = Ctx.getQualifiedTemplateName(NNS,
87 /*TemplateKeyword=*/false, ArgTDecl);
88 Changed = true;
89 }
90 return Changed;
91}
92
93static bool getFullyQualifiedTemplateArgument(const ASTContext &Ctx,
94 TemplateArgument &Arg,
95 bool WithGlobalNsPrefix) {
96 bool Changed = false;
97
98 // Note: we do not handle TemplateArgument::Expression, to replace it
99 // we need the information for the template instance decl.
100
101 if (Arg.getKind() == TemplateArgument::Template) {
102 TemplateName TName = Arg.getAsTemplate();
103 Changed = getFullyQualifiedTemplateName(Ctx, TName, WithGlobalNsPrefix);
104 if (Changed) {
105 Arg = TemplateArgument(TName);
106 }
107 } else if (Arg.getKind() == TemplateArgument::Type) {
108 QualType SubTy = Arg.getAsType();
109 // Check if the type needs more desugaring and recurse.
110 QualType QTFQ = getFullyQualifiedType(SubTy, Ctx, WithGlobalNsPrefix);
111 if (QTFQ != SubTy) {
112 Arg = TemplateArgument(QTFQ);
113 Changed = true;
114 }
115 }
116 return Changed;
117}
118
119static const Type *getFullyQualifiedTemplateType(const ASTContext &Ctx,
120 const Type *TypePtr,
121 bool WithGlobalNsPrefix) {
122 // DependentTemplateTypes exist within template declarations and
123 // definitions. Therefore we shouldn't encounter them at the end of
124 // a translation unit. If we do, the caller has made an error.
125 assert(!isa<DependentTemplateSpecializationType>(TypePtr))(static_cast <bool> (!isa<DependentTemplateSpecializationType
>(TypePtr)) ? void (0) : __assert_fail ("!isa<DependentTemplateSpecializationType>(TypePtr)"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/QualTypeNames.cpp"
, 125, __extension__ __PRETTY_FUNCTION__))
;
126 // In case of template specializations, iterate over the arguments
127 // and fully qualify them as well.
128 if (const auto *TST = dyn_cast<const TemplateSpecializationType>(TypePtr)) {
129 bool MightHaveChanged = false;
130 SmallVector<TemplateArgument, 4> FQArgs;
131 for (TemplateSpecializationType::iterator I = TST->begin(), E = TST->end();
132 I != E; ++I) {
133 // Cheap to copy and potentially modified by
134 // getFullyQualifedTemplateArgument.
135 TemplateArgument Arg(*I);
136 MightHaveChanged |= getFullyQualifiedTemplateArgument(
137 Ctx, Arg, WithGlobalNsPrefix);
138 FQArgs.push_back(Arg);
139 }
140
141 // If a fully qualified arg is different from the unqualified arg,
142 // allocate new type in the AST.
143 if (MightHaveChanged) {
144 QualType QT = Ctx.getTemplateSpecializationType(
145 TST->getTemplateName(), FQArgs,
146 TST->getCanonicalTypeInternal());
147 // getTemplateSpecializationType returns a fully qualified
148 // version of the specialization itself, so no need to qualify
149 // it.
150 return QT.getTypePtr();
151 }
152 } else if (const auto *TSTRecord = dyn_cast<const RecordType>(TypePtr)) {
153 // We are asked to fully qualify and we have a Record Type,
154 // which can point to a template instantiation with no sugar in any of
155 // its template argument, however we still need to fully qualify them.
156
157 if (const auto *TSTDecl =
158 dyn_cast<ClassTemplateSpecializationDecl>(TSTRecord->getDecl())) {
159 const TemplateArgumentList &TemplateArgs = TSTDecl->getTemplateArgs();
160
161 bool MightHaveChanged = false;
162 SmallVector<TemplateArgument, 4> FQArgs;
163 for (unsigned int I = 0, E = TemplateArgs.size(); I != E; ++I) {
164 // cheap to copy and potentially modified by
165 // getFullyQualifedTemplateArgument
166 TemplateArgument Arg(TemplateArgs[I]);
167 MightHaveChanged |= getFullyQualifiedTemplateArgument(
168 Ctx, Arg, WithGlobalNsPrefix);
169 FQArgs.push_back(Arg);
170 }
171
172 // If a fully qualified arg is different from the unqualified arg,
173 // allocate new type in the AST.
174 if (MightHaveChanged) {
175 TemplateName TN(TSTDecl->getSpecializedTemplate());
176 QualType QT = Ctx.getTemplateSpecializationType(
177 TN, FQArgs,
178 TSTRecord->getCanonicalTypeInternal());
179 // getTemplateSpecializationType returns a fully qualified
180 // version of the specialization itself, so no need to qualify
181 // it.
182 return QT.getTypePtr();
183 }
184 }
185 }
186 return TypePtr;
187}
188
189static NestedNameSpecifier *createOuterNNS(const ASTContext &Ctx, const Decl *D,
190 bool FullyQualify,
191 bool WithGlobalNsPrefix) {
192 const DeclContext *DC = D->getDeclContext();
193 if (const auto *NS = dyn_cast<NamespaceDecl>(DC)) {
11
Assuming 'NS' is non-null
12
Taking true branch
194 while (NS && NS->isInline()) {
13
Loop condition is true. Entering loop body
53
Assuming 'NS' is null
54
Assuming pointer value is null
195 // Ignore inline namespace;
196 NS = dyn_cast<NamespaceDecl>(NS->getDeclContext());
14
Calling 'dyn_cast'
51
Returning from 'dyn_cast'
52
Value assigned to 'NS'
197 }
198 if (NS->getDeclName()) {
55
Called C++ object pointer is null
199 return createNestedNameSpecifier(Ctx, NS, WithGlobalNsPrefix);
200 }
201 return nullptr; // no starting '::', no anonymous
202 } else if (const auto *TD = dyn_cast<TagDecl>(DC)) {
203 return createNestedNameSpecifier(Ctx, TD, FullyQualify, WithGlobalNsPrefix);
204 } else if (const auto *TDD = dyn_cast<TypedefNameDecl>(DC)) {
205 return createNestedNameSpecifier(
206 Ctx, TDD, FullyQualify, WithGlobalNsPrefix);
207 } else if (WithGlobalNsPrefix && DC->isTranslationUnit()) {
208 return NestedNameSpecifier::GlobalSpecifier(Ctx);
209 }
210 return nullptr; // no starting '::' if |WithGlobalNsPrefix| is false
211}
212
213/// \brief Return a fully qualified version of this name specifier.
214static NestedNameSpecifier *getFullyQualifiedNestedNameSpecifier(
215 const ASTContext &Ctx, NestedNameSpecifier *Scope,
216 bool WithGlobalNsPrefix) {
217 switch (Scope->getKind()) {
218 case NestedNameSpecifier::Global:
219 // Already fully qualified
220 return Scope;
221 case NestedNameSpecifier::Namespace:
222 return TypeName::createNestedNameSpecifier(
223 Ctx, Scope->getAsNamespace(), WithGlobalNsPrefix);
224 case NestedNameSpecifier::NamespaceAlias:
225 // Namespace aliases are only valid for the duration of the
226 // scope where they were introduced, and therefore are often
227 // invalid at the end of the TU. So use the namespace name more
228 // likely to be valid at the end of the TU.
229 return TypeName::createNestedNameSpecifier(
230 Ctx,
231 Scope->getAsNamespaceAlias()->getNamespace()->getCanonicalDecl(),
232 WithGlobalNsPrefix);
233 case NestedNameSpecifier::Identifier:
234 // A function or some other construct that makes it un-namable
235 // at the end of the TU. Skip the current component of the name,
236 // but use the name of it's prefix.
237 return getFullyQualifiedNestedNameSpecifier(
238 Ctx, Scope->getPrefix(), WithGlobalNsPrefix);
239 case NestedNameSpecifier::Super:
240 case NestedNameSpecifier::TypeSpec:
241 case NestedNameSpecifier::TypeSpecWithTemplate: {
242 const Type *Type = Scope->getAsType();
243 // Find decl context.
244 const TagDecl *TD = nullptr;
245 if (const TagType *TagDeclType = Type->getAs<TagType>()) {
246 TD = TagDeclType->getDecl();
247 } else {
248 TD = Type->getAsCXXRecordDecl();
249 }
250 if (TD) {
251 return TypeName::createNestedNameSpecifier(Ctx, TD,
252 true /*FullyQualified*/,
253 WithGlobalNsPrefix);
254 } else if (const auto *TDD = dyn_cast<TypedefType>(Type)) {
255 return TypeName::createNestedNameSpecifier(Ctx, TDD->getDecl(),
256 true /*FullyQualified*/,
257 WithGlobalNsPrefix);
258 }
259 return Scope;
260 }
261 }
262 llvm_unreachable("bad NNS kind")::llvm::llvm_unreachable_internal("bad NNS kind", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/QualTypeNames.cpp"
, 262)
;
263}
264
265/// \brief Create a nested name specifier for the declaring context of
266/// the type.
267static NestedNameSpecifier *createNestedNameSpecifierForScopeOf(
268 const ASTContext &Ctx, const Decl *Decl,
269 bool FullyQualified, bool WithGlobalNsPrefix) {
270 assert(Decl)(static_cast <bool> (Decl) ? void (0) : __assert_fail (
"Decl", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/QualTypeNames.cpp"
, 270, __extension__ __PRETTY_FUNCTION__))
;
271
272 const DeclContext *DC = Decl->getDeclContext()->getRedeclContext();
273 const auto *Outer = dyn_cast_or_null<NamedDecl>(DC);
274 const auto *OuterNS = dyn_cast_or_null<NamespaceDecl>(DC);
275 if (Outer && !(OuterNS && OuterNS->isAnonymousNamespace())) {
3
Assuming 'Outer' is non-null
4
Taking true branch
276 if (const auto *CxxDecl = dyn_cast<CXXRecordDecl>(DC)) {
5
Taking false branch
277 if (ClassTemplateDecl *ClassTempl =
278 CxxDecl->getDescribedClassTemplate()) {
279 // We are in the case of a type(def) that was declared in a
280 // class template but is *not* type dependent. In clang, it
281 // gets attached to the class template declaration rather than
282 // any specific class template instantiation. This result in
283 // 'odd' fully qualified typename:
284 //
285 // vector<_Tp,_Alloc>::size_type
286 //
287 // Make the situation is 'useable' but looking a bit odd by
288 // picking a random instance as the declaring context.
289 if (ClassTempl->spec_begin() != ClassTempl->spec_end()) {
290 Decl = *(ClassTempl->spec_begin());
291 Outer = dyn_cast<NamedDecl>(Decl);
292 OuterNS = dyn_cast<NamespaceDecl>(Decl);
293 }
294 }
295 }
296
297 if (OuterNS) {
6
Taking false branch
298 return createNestedNameSpecifier(Ctx, OuterNS, WithGlobalNsPrefix);
299 } else if (const auto *TD = dyn_cast<TagDecl>(Outer)) {
7
Assuming 'TD' is non-null
8
Taking true branch
300 return createNestedNameSpecifier(
9
Calling 'createNestedNameSpecifier'
301 Ctx, TD, FullyQualified, WithGlobalNsPrefix);
302 } else if (dyn_cast<TranslationUnitDecl>(Outer)) {
303 // Context is the TU. Nothing needs to be done.
304 return nullptr;
305 } else {
306 // Decl's context was neither the TU, a namespace, nor a
307 // TagDecl, which means it is a type local to a scope, and not
308 // accessible at the end of the TU.
309 return nullptr;
310 }
311 } else if (WithGlobalNsPrefix && DC->isTranslationUnit()) {
312 return NestedNameSpecifier::GlobalSpecifier(Ctx);
313 }
314 return nullptr;
315}
316
317/// \brief Create a nested name specifier for the declaring context of
318/// the type.
319static NestedNameSpecifier *createNestedNameSpecifierForScopeOf(
320 const ASTContext &Ctx, const Type *TypePtr,
321 bool FullyQualified, bool WithGlobalNsPrefix) {
322 if (!TypePtr) return nullptr;
323
324 Decl *Decl = nullptr;
325 // There are probably other cases ...
326 if (const auto *TDT = dyn_cast<TypedefType>(TypePtr)) {
327 Decl = TDT->getDecl();
328 } else if (const auto *TagDeclType = dyn_cast<TagType>(TypePtr)) {
329 Decl = TagDeclType->getDecl();
330 } else if (const auto *TST = dyn_cast<TemplateSpecializationType>(TypePtr)) {
331 Decl = TST->getTemplateName().getAsTemplateDecl();
332 } else {
333 Decl = TypePtr->getAsCXXRecordDecl();
334 }
335
336 if (!Decl) return nullptr;
337
338 return createNestedNameSpecifierForScopeOf(
339 Ctx, Decl, FullyQualified, WithGlobalNsPrefix);
340}
341
342NestedNameSpecifier *createNestedNameSpecifier(const ASTContext &Ctx,
343 const NamespaceDecl *Namespace,
344 bool WithGlobalNsPrefix) {
345 while (Namespace && Namespace->isInline()) {
346 // Ignore inline namespace;
347 Namespace = dyn_cast<NamespaceDecl>(Namespace->getDeclContext());
348 }
349 if (!Namespace) return nullptr;
350
351 bool FullyQualified = true; // doesn't matter, DeclContexts are namespaces
352 return NestedNameSpecifier::Create(
353 Ctx,
354 createOuterNNS(Ctx, Namespace, FullyQualified, WithGlobalNsPrefix),
355 Namespace);
356}
357
358NestedNameSpecifier *createNestedNameSpecifier(const ASTContext &Ctx,
359 const TypeDecl *TD,
360 bool FullyQualify,
361 bool WithGlobalNsPrefix) {
362 return NestedNameSpecifier::Create(
363 Ctx,
364 createOuterNNS(Ctx, TD, FullyQualify, WithGlobalNsPrefix),
10
Calling 'createOuterNNS'
365 false /*No TemplateKeyword*/,
366 TD->getTypeForDecl());
367}
368
369/// \brief Return the fully qualified type, including fully-qualified
370/// versions of any template parameters.
371QualType getFullyQualifiedType(QualType QT, const ASTContext &Ctx,
372 bool WithGlobalNsPrefix) {
373 // In case of myType* we need to strip the pointer first, fully
374 // qualify and attach the pointer once again.
375 if (isa<PointerType>(QT.getTypePtr())) {
376 // Get the qualifiers.
377 Qualifiers Quals = QT.getQualifiers();
378 QT = getFullyQualifiedType(QT->getPointeeType(), Ctx, WithGlobalNsPrefix);
379 QT = Ctx.getPointerType(QT);
380 // Add back the qualifiers.
381 QT = Ctx.getQualifiedType(QT, Quals);
382 return QT;
383 }
384
385 // In case of myType& we need to strip the reference first, fully
386 // qualify and attach the reference once again.
387 if (isa<ReferenceType>(QT.getTypePtr())) {
388 // Get the qualifiers.
389 bool IsLValueRefTy = isa<LValueReferenceType>(QT.getTypePtr());
390 Qualifiers Quals = QT.getQualifiers();
391 QT = getFullyQualifiedType(QT->getPointeeType(), Ctx, WithGlobalNsPrefix);
392 // Add the r- or l-value reference type back to the fully
393 // qualified one.
394 if (IsLValueRefTy)
395 QT = Ctx.getLValueReferenceType(QT);
396 else
397 QT = Ctx.getRValueReferenceType(QT);
398 // Add back the qualifiers.
399 QT = Ctx.getQualifiedType(QT, Quals);
400 return QT;
401 }
402
403 // Remove the part of the type related to the type being a template
404 // parameter (we won't report it as part of the 'type name' and it
405 // is actually make the code below to be more complex (to handle
406 // those)
407 while (isa<SubstTemplateTypeParmType>(QT.getTypePtr())) {
408 // Get the qualifiers.
409 Qualifiers Quals = QT.getQualifiers();
410
411 QT = dyn_cast<SubstTemplateTypeParmType>(QT.getTypePtr())->desugar();
412
413 // Add back the qualifiers.
414 QT = Ctx.getQualifiedType(QT, Quals);
415 }
416
417 NestedNameSpecifier *Prefix = nullptr;
418 // Local qualifiers are attached to the QualType outside of the
419 // elaborated type. Retrieve them before descending into the
420 // elaborated type.
421 Qualifiers PrefixQualifiers = QT.getLocalQualifiers();
422 QT = QualType(QT.getTypePtr(), 0);
423 ElaboratedTypeKeyword Keyword = ETK_None;
424 if (const auto *ETypeInput = dyn_cast<ElaboratedType>(QT.getTypePtr())) {
425 QT = ETypeInput->getNamedType();
426 assert(!QT.hasLocalQualifiers())(static_cast <bool> (!QT.hasLocalQualifiers()) ? void (
0) : __assert_fail ("!QT.hasLocalQualifiers()", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/lib/AST/QualTypeNames.cpp"
, 426, __extension__ __PRETTY_FUNCTION__))
;
427 Keyword = ETypeInput->getKeyword();
428 }
429 // Create a nested name specifier if needed.
430 Prefix = createNestedNameSpecifierForScopeOf(Ctx, QT.getTypePtr(),
431 true /*FullyQualified*/,
432 WithGlobalNsPrefix);
433
434 // In case of template specializations iterate over the arguments and
435 // fully qualify them as well.
436 if (isa<const TemplateSpecializationType>(QT.getTypePtr()) ||
437 isa<const RecordType>(QT.getTypePtr())) {
438 // We are asked to fully qualify and we have a Record Type (which
439 // may point to a template specialization) or Template
440 // Specialization Type. We need to fully qualify their arguments.
441
442 const Type *TypePtr = getFullyQualifiedTemplateType(
443 Ctx, QT.getTypePtr(), WithGlobalNsPrefix);
444 QT = QualType(TypePtr, 0);
445 }
446 if (Prefix || Keyword != ETK_None) {
447 QT = Ctx.getElaboratedType(Keyword, Prefix, QT);
448 }
449 QT = Ctx.getQualifiedType(QT, PrefixQualifiers);
450 return QT;
451}
452
453std::string getFullyQualifiedName(QualType QT,
454 const ASTContext &Ctx,
455 bool WithGlobalNsPrefix) {
456 PrintingPolicy Policy(Ctx.getPrintingPolicy());
457 Policy.SuppressScope = false;
458 Policy.AnonymousTagLocations = false;
459 Policy.PolishForDeclaration = true;
460 Policy.SuppressUnwrittenScope = true;
461 QualType FQQT = getFullyQualifiedType(QT, Ctx, WithGlobalNsPrefix);
462 return FQQT.getAsString(Policy);
463}
464
465} // end namespace TypeName
466} // end namespace clang

/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h

1//===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the isa<X>(), cast<X>(), dyn_cast<X>(), cast_or_null<X>(),
11// and dyn_cast_or_null<X>() templates.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_SUPPORT_CASTING_H
16#define LLVM_SUPPORT_CASTING_H
17
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/type_traits.h"
20#include <cassert>
21#include <memory>
22#include <type_traits>
23
24namespace llvm {
25
26//===----------------------------------------------------------------------===//
27// isa<x> Support Templates
28//===----------------------------------------------------------------------===//
29
30// Define a template that can be specialized by smart pointers to reflect the
31// fact that they are automatically dereferenced, and are not involved with the
32// template selection process... the default implementation is a noop.
33//
34template<typename From> struct simplify_type {
35 using SimpleType = From; // The real type this represents...
36
37 // An accessor to get the real value...
38 static SimpleType &getSimplifiedValue(From &Val) { return Val; }
39};
40
41template<typename From> struct simplify_type<const From> {
42 using NonConstSimpleType = typename simplify_type<From>::SimpleType;
43 using SimpleType =
44 typename add_const_past_pointer<NonConstSimpleType>::type;
45 using RetType =
46 typename add_lvalue_reference_if_not_pointer<SimpleType>::type;
47
48 static RetType getSimplifiedValue(const From& Val) {
49 return simplify_type<From>::getSimplifiedValue(const_cast<From&>(Val));
18
Calling 'simplify_type::getSimplifiedValue'
19
Returning from 'simplify_type::getSimplifiedValue'
40
Calling 'simplify_type::getSimplifiedValue'
41
Returning from 'simplify_type::getSimplifiedValue'
50 }
51};
52
53// The core of the implementation of isa<X> is here; To and From should be
54// the names of classes. This template can be specialized to customize the
55// implementation of isa<> without rewriting it from scratch.
56template <typename To, typename From, typename Enabler = void>
57struct isa_impl {
58 static inline bool doit(const From &Val) {
59 return To::classof(&Val);
60 }
61};
62
63/// \brief Always allow upcasts, and perform no dynamic check for them.
64template <typename To, typename From>
65struct isa_impl<
66 To, From, typename std::enable_if<std::is_base_of<To, From>::value>::type> {
67 static inline bool doit(const From &) { return true; }
68};
69
70template <typename To, typename From> struct isa_impl_cl {
71 static inline bool doit(const From &Val) {
72 return isa_impl<To, From>::doit(Val);
73 }
74};
75
76template <typename To, typename From> struct isa_impl_cl<To, const From> {
77 static inline bool doit(const From &Val) {
78 return isa_impl<To, From>::doit(Val);
79 }
80};
81
82template <typename To, typename From>
83struct isa_impl_cl<To, const std::unique_ptr<From>> {
84 static inline bool doit(const std::unique_ptr<From> &Val) {
85 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 85, __extension__ __PRETTY_FUNCTION__))
;
86 return isa_impl_cl<To, From>::doit(*Val);
87 }
88};
89
90template <typename To, typename From> struct isa_impl_cl<To, From*> {
91 static inline bool doit(const From *Val) {
92 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 92, __extension__ __PRETTY_FUNCTION__))
;
93 return isa_impl<To, From>::doit(*Val);
94 }
95};
96
97template <typename To, typename From> struct isa_impl_cl<To, From*const> {
98 static inline bool doit(const From *Val) {
99 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 99, __extension__ __PRETTY_FUNCTION__))
;
100 return isa_impl<To, From>::doit(*Val);
101 }
102};
103
104template <typename To, typename From> struct isa_impl_cl<To, const From*> {
105 static inline bool doit(const From *Val) {
106 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 106, __extension__ __PRETTY_FUNCTION__))
;
23
Within the expansion of the macro 'assert':
a
Assuming 'Val' is non-null
107 return isa_impl<To, From>::doit(*Val);
24
Calling 'isa_impl::doit'
30
Returning from 'isa_impl::doit'
108 }
109};
110
111template <typename To, typename From> struct isa_impl_cl<To, const From*const> {
112 static inline bool doit(const From *Val) {
113 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 113, __extension__ __PRETTY_FUNCTION__))
;
114 return isa_impl<To, From>::doit(*Val);
115 }
116};
117
118template<typename To, typename From, typename SimpleFrom>
119struct isa_impl_wrap {
120 // When From != SimplifiedType, we can simplify the type some more by using
121 // the simplify_type template.
122 static bool doit(const From &Val) {
123 return isa_impl_wrap<To, SimpleFrom,
21
Calling 'isa_impl_wrap::doit'
32
Returning from 'isa_impl_wrap::doit'
43
Calling 'isa_impl_wrap::doit'
44
Returning from 'isa_impl_wrap::doit'
124 typename simplify_type<SimpleFrom>::SimpleType>::doit(
125 simplify_type<const From>::getSimplifiedValue(Val));
17
Calling 'simplify_type::getSimplifiedValue'
20
Returning from 'simplify_type::getSimplifiedValue'
39
Calling 'simplify_type::getSimplifiedValue'
42
Returning from 'simplify_type::getSimplifiedValue'
126 }
127};
128
129template<typename To, typename FromTy>
130struct isa_impl_wrap<To, FromTy, FromTy> {
131 // When From == SimpleType, we are as simple as we are going to get.
132 static bool doit(const FromTy &Val) {
133 return isa_impl_cl<To,FromTy>::doit(Val);
22
Calling 'isa_impl_cl::doit'
31
Returning from 'isa_impl_cl::doit'
134 }
135};
136
137// isa<X> - Return true if the parameter to the template is an instance of the
138// template type argument. Used like this:
139//
140// if (isa<Type>(myVal)) { ... }
141//
142template <class X, class Y> LLVM_NODISCARD[[clang::warn_unused_result]] inline bool isa(const Y &Val) {
143 return isa_impl_wrap<X, const Y,
16
Calling 'isa_impl_wrap::doit'
33
Returning from 'isa_impl_wrap::doit'
38
Calling 'isa_impl_wrap::doit'
45
Returning from 'isa_impl_wrap::doit'
144 typename simplify_type<const Y>::SimpleType>::doit(Val);
145}
146
147//===----------------------------------------------------------------------===//
148// cast<x> Support Templates
149//===----------------------------------------------------------------------===//
150
151template<class To, class From> struct cast_retty;
152
153// Calculate what type the 'cast' function should return, based on a requested
154// type of To and a source type of From.
155template<class To, class From> struct cast_retty_impl {
156 using ret_type = To &; // Normal case, return Ty&
157};
158template<class To, class From> struct cast_retty_impl<To, const From> {
159 using ret_type = const To &; // Normal case, return Ty&
160};
161
162template<class To, class From> struct cast_retty_impl<To, From*> {
163 using ret_type = To *; // Pointer arg case, return Ty*
164};
165
166template<class To, class From> struct cast_retty_impl<To, const From*> {
167 using ret_type = const To *; // Constant pointer arg case, return const Ty*
168};
169
170template<class To, class From> struct cast_retty_impl<To, const From*const> {
171 using ret_type = const To *; // Constant pointer arg case, return const Ty*
172};
173
174template <class To, class From>
175struct cast_retty_impl<To, std::unique_ptr<From>> {
176private:
177 using PointerType = typename cast_retty_impl<To, From *>::ret_type;
178 using ResultType = typename std::remove_pointer<PointerType>::type;
179
180public:
181 using ret_type = std::unique_ptr<ResultType>;
182};
183
184template<class To, class From, class SimpleFrom>
185struct cast_retty_wrap {
186 // When the simplified type and the from type are not the same, use the type
187 // simplifier to reduce the type, then reuse cast_retty_impl to get the
188 // resultant type.
189 using ret_type = typename cast_retty<To, SimpleFrom>::ret_type;
190};
191
192template<class To, class FromTy>
193struct cast_retty_wrap<To, FromTy, FromTy> {
194 // When the simplified type is equal to the from type, use it directly.
195 using ret_type = typename cast_retty_impl<To,FromTy>::ret_type;
196};
197
198template<class To, class From>
199struct cast_retty {
200 using ret_type = typename cast_retty_wrap<
201 To, From, typename simplify_type<From>::SimpleType>::ret_type;
202};
203
204// Ensure the non-simple values are converted using the simplify_type template
205// that may be specialized by smart pointers...
206//
207template<class To, class From, class SimpleFrom> struct cast_convert_val {
208 // This is not a simple type, use the template to simplify it...
209 static typename cast_retty<To, From>::ret_type doit(From &Val) {
210 return cast_convert_val<To, SimpleFrom,
211 typename simplify_type<SimpleFrom>::SimpleType>::doit(
212 simplify_type<From>::getSimplifiedValue(Val));
213 }
214};
215
216template<class To, class FromTy> struct cast_convert_val<To,FromTy,FromTy> {
217 // This _is_ a simple type, just cast it.
218 static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) {
219 typename cast_retty<To, FromTy>::ret_type Res2
220 = (typename cast_retty<To, FromTy>::ret_type)const_cast<FromTy&>(Val);
221 return Res2;
222 }
223};
224
225template <class X> struct is_simple_type {
226 static const bool value =
227 std::is_same<X, typename simplify_type<X>::SimpleType>::value;
228};
229
230// cast<X> - Return the argument parameter cast to the specified type. This
231// casting operator asserts that the type is correct, so it does not return null
232// on failure. It does not allow a null argument (use cast_or_null for that).
233// It is typically used like this:
234//
235// cast<Instruction>(myVal)->getParent()
236//
237template <class X, class Y>
238inline typename std::enable_if<!is_simple_type<Y>::value,
239 typename cast_retty<X, const Y>::ret_type>::type
240cast(const Y &Val) {
241 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 241, __extension__ __PRETTY_FUNCTION__))
;
242 return cast_convert_val<
243 X, const Y, typename simplify_type<const Y>::SimpleType>::doit(Val);
244}
245
246template <class X, class Y>
247inline typename cast_retty<X, Y>::ret_type cast(Y &Val) {
248 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 248, __extension__ __PRETTY_FUNCTION__))
;
249 return cast_convert_val<X, Y,
250 typename simplify_type<Y>::SimpleType>::doit(Val);
251}
252
253template <class X, class Y>
254inline typename cast_retty<X, Y *>::ret_type cast(Y *Val) {
255 assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 255, __extension__ __PRETTY_FUNCTION__))
;
37
Within the expansion of the macro 'assert':
a
Calling 'isa'
b
Returning from 'isa'
c
Assuming the condition is true
256 return cast_convert_val<X, Y*,
46
Calling 'cast_convert_val::doit'
49
Returning from 'cast_convert_val::doit'
257 typename simplify_type<Y*>::SimpleType>::doit(Val);
258}
259
260template <class X, class Y>
261inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
262cast(std::unique_ptr<Y> &&Val) {
263 assert(isa<X>(Val.get()) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val.get()) &&
"cast<Ty>() argument of incompatible type!") ? void (0
) : __assert_fail ("isa<X>(Val.get()) && \"cast<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 263, __extension__ __PRETTY_FUNCTION__))
;
264 using ret_type = typename cast_retty<X, std::unique_ptr<Y>>::ret_type;
265 return ret_type(
266 cast_convert_val<X, Y *, typename simplify_type<Y *>::SimpleType>::doit(
267 Val.release()));
268}
269
270// cast_or_null<X> - Functionally identical to cast, except that a null value is
271// accepted.
272//
273template <class X, class Y>
274LLVM_NODISCARD[[clang::warn_unused_result]] inline
275 typename std::enable_if<!is_simple_type<Y>::value,
276 typename cast_retty<X, const Y>::ret_type>::type
277 cast_or_null(const Y &Val) {
278 if (!Val)
279 return nullptr;
280 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 280, __extension__ __PRETTY_FUNCTION__))
;
281 return cast<X>(Val);
282}
283
284template <class X, class Y>
285LLVM_NODISCARD[[clang::warn_unused_result]] inline
286 typename std::enable_if<!is_simple_type<Y>::value,
287 typename cast_retty<X, Y>::ret_type>::type
288 cast_or_null(Y &Val) {
289 if (!Val)
290 return nullptr;
291 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 291, __extension__ __PRETTY_FUNCTION__))
;
292 return cast<X>(Val);
293}
294
295template <class X, class Y>
296LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
297cast_or_null(Y *Val) {
298 if (!Val) return nullptr;
299 assert(isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_or_null<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_or_null<Ty>() argument of incompatible type!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/include/llvm/Support/Casting.h"
, 299, __extension__ __PRETTY_FUNCTION__))
;
300 return cast<X>(Val);
301}
302
303template <class X, class Y>
304inline typename cast_retty<X, std::unique_ptr<Y>>::ret_type
305cast_or_null(std::unique_ptr<Y> &&Val) {
306 if (!Val)
307 return nullptr;
308 return cast<X>(std::move(Val));
309}
310
311// dyn_cast<X> - Return the argument parameter cast to the specified type. This
312// casting operator returns null if the argument is of the wrong type, so it can
313// be used to test for a type as well as cast if successful. This should be
314// used in the context of an if statement like this:
315//
316// if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... }
317//
318
319template <class X, class Y>
320LLVM_NODISCARD[[clang::warn_unused_result]] inline
321 typename std::enable_if<!is_simple_type<Y>::value,
322 typename cast_retty<X, const Y>::ret_type>::type
323 dyn_cast(const Y &Val) {
324 return isa<X>(Val) ? cast<X>(Val) : nullptr;
325}
326
327template <class X, class Y>
328LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y>::ret_type dyn_cast(Y &Val) {
329 return isa<X>(Val) ? cast<X>(Val) : nullptr;
330}
331
332template <class X, class Y>
333LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type dyn_cast(Y *Val) {
334 return isa<X>(Val) ? cast<X>(Val) : nullptr;
15
Calling 'isa'
34
Returning from 'isa'
35
'?' condition is true
36
Calling 'cast'
50
Returning from 'cast'
335}
336
337// dyn_cast_or_null<X> - Functionally identical to dyn_cast, except that a null
338// value is accepted.
339//
340template <class X, class Y>
341LLVM_NODISCARD[[clang::warn_unused_result]] inline
342 typename std::enable_if<!is_simple_type<Y>::value,
343 typename cast_retty<X, const Y>::ret_type>::type
344 dyn_cast_or_null(const Y &Val) {
345 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
346}
347
348template <class X, class Y>
349LLVM_NODISCARD[[clang::warn_unused_result]] inline
350 typename std::enable_if<!is_simple_type<Y>::value,
351 typename cast_retty<X, Y>::ret_type>::type
352 dyn_cast_or_null(Y &Val) {
353 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
354}
355
356template <class X, class Y>
357LLVM_NODISCARD[[clang::warn_unused_result]] inline typename cast_retty<X, Y *>::ret_type
358dyn_cast_or_null(Y *Val) {
359 return (Val && isa<X>(Val)) ? cast<X>(Val) : nullptr;
360}
361
362// unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>,
363// taking ownership of the input pointer iff isa<X>(Val) is true. If the
364// cast is successful, From refers to nullptr on exit and the casted value
365// is returned. If the cast is unsuccessful, the function returns nullptr
366// and From is unchanged.
367template <class X, class Y>
368LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &Val)
369 -> decltype(cast<X>(Val)) {
370 if (!isa<X>(Val))
371 return nullptr;
372 return cast<X>(std::move(Val));
373}
374
375template <class X, class Y>
376LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val)
377 -> decltype(cast<X>(Val)) {
378 return unique_dyn_cast<X, Y>(Val);
379}
380
381// dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast, except that
382// a null value is accepted.
383template <class X, class Y>
384LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &Val)
385 -> decltype(cast<X>(Val)) {
386 if (!Val)
387 return nullptr;
388 return unique_dyn_cast<X, Y>(Val);
389}
390
391template <class X, class Y>
392LLVM_NODISCARD[[clang::warn_unused_result]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val)
393 -> decltype(cast<X>(Val)) {
394 return unique_dyn_cast_or_null<X, Y>(Val);
395}
396
397} // end namespace llvm
398
399#endif // LLVM_SUPPORT_CASTING_H

/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h

1//===- DeclBase.h - Base Classes for representing declarations --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the Decl and DeclContext interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_DECLBASE_H
15#define LLVM_CLANG_AST_DECLBASE_H
16
17#include "clang/AST/AttrIterator.h"
18#include "clang/AST/DeclarationName.h"
19#include "clang/Basic/LLVM.h"
20#include "clang/Basic/SourceLocation.h"
21#include "clang/Basic/Specifiers.h"
22#include "clang/Basic/VersionTuple.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/PointerIntPair.h"
25#include "llvm/ADT/PointerUnion.h"
26#include "llvm/ADT/iterator.h"
27#include "llvm/ADT/iterator_range.h"
28#include "llvm/Support/Casting.h"
29#include "llvm/Support/Compiler.h"
30#include "llvm/Support/PrettyStackTrace.h"
31#include <algorithm>
32#include <cassert>
33#include <cstddef>
34#include <iterator>
35#include <string>
36#include <type_traits>
37#include <utility>
38
39namespace clang {
40
41class ASTContext;
42class ASTMutationListener;
43class Attr;
44class DeclContext;
45class ExternalSourceSymbolAttr;
46class FunctionDecl;
47class FunctionType;
48class IdentifierInfo;
49enum Linkage : unsigned char;
50class LinkageSpecDecl;
51class Module;
52class NamedDecl;
53class ObjCCategoryDecl;
54class ObjCCategoryImplDecl;
55class ObjCContainerDecl;
56class ObjCImplDecl;
57class ObjCImplementationDecl;
58class ObjCInterfaceDecl;
59class ObjCMethodDecl;
60class ObjCProtocolDecl;
61struct PrintingPolicy;
62class RecordDecl;
63class SourceManager;
64class Stmt;
65class StoredDeclsMap;
66class TemplateDecl;
67class TranslationUnitDecl;
68class UsingDirectiveDecl;
69
70/// \brief Captures the result of checking the availability of a
71/// declaration.
72enum AvailabilityResult {
73 AR_Available = 0,
74 AR_NotYetIntroduced,
75 AR_Deprecated,
76 AR_Unavailable
77};
78
79/// Decl - This represents one declaration (or definition), e.g. a variable,
80/// typedef, function, struct, etc.
81///
82/// Note: There are objects tacked on before the *beginning* of Decl
83/// (and its subclasses) in its Decl::operator new(). Proper alignment
84/// of all subclasses (not requiring more than the alignment of Decl) is
85/// asserted in DeclBase.cpp.
86class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8)alignas(8) Decl {
87public:
88 /// \brief Lists the kind of concrete classes of Decl.
89 enum Kind {
90#define DECL(DERIVED, BASE) DERIVED,
91#define ABSTRACT_DECL(DECL)
92#define DECL_RANGE(BASE, START, END) \
93 first##BASE = START, last##BASE = END,
94#define LAST_DECL_RANGE(BASE, START, END) \
95 first##BASE = START, last##BASE = END
96#include "clang/AST/DeclNodes.inc"
97 };
98
99 /// \brief A placeholder type used to construct an empty shell of a
100 /// decl-derived type that will be filled in later (e.g., by some
101 /// deserialization method).
102 struct EmptyShell {};
103
104 /// IdentifierNamespace - The different namespaces in which
105 /// declarations may appear. According to C99 6.2.3, there are
106 /// four namespaces, labels, tags, members and ordinary
107 /// identifiers. C++ describes lookup completely differently:
108 /// certain lookups merely "ignore" certain kinds of declarations,
109 /// usually based on whether the declaration is of a type, etc.
110 ///
111 /// These are meant as bitmasks, so that searches in
112 /// C++ can look into the "tag" namespace during ordinary lookup.
113 ///
114 /// Decl currently provides 15 bits of IDNS bits.
115 enum IdentifierNamespace {
116 /// Labels, declared with 'x:' and referenced with 'goto x'.
117 IDNS_Label = 0x0001,
118
119 /// Tags, declared with 'struct foo;' and referenced with
120 /// 'struct foo'. All tags are also types. This is what
121 /// elaborated-type-specifiers look for in C.
122 /// This also contains names that conflict with tags in the
123 /// same scope but that are otherwise ordinary names (non-type
124 /// template parameters and indirect field declarations).
125 IDNS_Tag = 0x0002,
126
127 /// Types, declared with 'struct foo', typedefs, etc.
128 /// This is what elaborated-type-specifiers look for in C++,
129 /// but note that it's ill-formed to find a non-tag.
130 IDNS_Type = 0x0004,
131
132 /// Members, declared with object declarations within tag
133 /// definitions. In C, these can only be found by "qualified"
134 /// lookup in member expressions. In C++, they're found by
135 /// normal lookup.
136 IDNS_Member = 0x0008,
137
138 /// Namespaces, declared with 'namespace foo {}'.
139 /// Lookup for nested-name-specifiers find these.
140 IDNS_Namespace = 0x0010,
141
142 /// Ordinary names. In C, everything that's not a label, tag,
143 /// member, or function-local extern ends up here.
144 IDNS_Ordinary = 0x0020,
145
146 /// Objective C \@protocol.
147 IDNS_ObjCProtocol = 0x0040,
148
149 /// This declaration is a friend function. A friend function
150 /// declaration is always in this namespace but may also be in
151 /// IDNS_Ordinary if it was previously declared.
152 IDNS_OrdinaryFriend = 0x0080,
153
154 /// This declaration is a friend class. A friend class
155 /// declaration is always in this namespace but may also be in
156 /// IDNS_Tag|IDNS_Type if it was previously declared.
157 IDNS_TagFriend = 0x0100,
158
159 /// This declaration is a using declaration. A using declaration
160 /// *introduces* a number of other declarations into the current
161 /// scope, and those declarations use the IDNS of their targets,
162 /// but the actual using declarations go in this namespace.
163 IDNS_Using = 0x0200,
164
165 /// This declaration is a C++ operator declared in a non-class
166 /// context. All such operators are also in IDNS_Ordinary.
167 /// C++ lexical operator lookup looks for these.
168 IDNS_NonMemberOperator = 0x0400,
169
170 /// This declaration is a function-local extern declaration of a
171 /// variable or function. This may also be IDNS_Ordinary if it
172 /// has been declared outside any function. These act mostly like
173 /// invisible friend declarations, but are also visible to unqualified
174 /// lookup within the scope of the declaring function.
175 IDNS_LocalExtern = 0x0800,
176
177 /// This declaration is an OpenMP user defined reduction construction.
178 IDNS_OMPReduction = 0x1000
179 };
180
181 /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
182 /// parameter types in method declarations. Other than remembering
183 /// them and mangling them into the method's signature string, these
184 /// are ignored by the compiler; they are consumed by certain
185 /// remote-messaging frameworks.
186 ///
187 /// in, inout, and out are mutually exclusive and apply only to
188 /// method parameters. bycopy and byref are mutually exclusive and
189 /// apply only to method parameters (?). oneway applies only to
190 /// results. All of these expect their corresponding parameter to
191 /// have a particular type. None of this is currently enforced by
192 /// clang.
193 ///
194 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
195 enum ObjCDeclQualifier {
196 OBJC_TQ_None = 0x0,
197 OBJC_TQ_In = 0x1,
198 OBJC_TQ_Inout = 0x2,
199 OBJC_TQ_Out = 0x4,
200 OBJC_TQ_Bycopy = 0x8,
201 OBJC_TQ_Byref = 0x10,
202 OBJC_TQ_Oneway = 0x20,
203
204 /// The nullability qualifier is set when the nullability of the
205 /// result or parameter was expressed via a context-sensitive
206 /// keyword.
207 OBJC_TQ_CSNullability = 0x40
208 };
209
210 /// The kind of ownership a declaration has, for visibility purposes.
211 /// This enumeration is designed such that higher values represent higher
212 /// levels of name hiding.
213 enum class ModuleOwnershipKind : unsigned {
214 /// This declaration is not owned by a module.
215 Unowned,
216
217 /// This declaration has an owning module, but is globally visible
218 /// (typically because its owning module is visible and we know that
219 /// modules cannot later become hidden in this compilation).
220 /// After serialization and deserialization, this will be converted
221 /// to VisibleWhenImported.
222 Visible,
223
224 /// This declaration has an owning module, and is visible when that
225 /// module is imported.
226 VisibleWhenImported,
227
228 /// This declaration has an owning module, but is only visible to
229 /// lookups that occur within that module.
230 ModulePrivate
231 };
232
233protected:
234 /// \brief The next declaration within the same lexical
235 /// DeclContext. These pointers form the linked list that is
236 /// traversed via DeclContext's decls_begin()/decls_end().
237 ///
238 /// The extra two bits are used for the ModuleOwnershipKind.
239 llvm::PointerIntPair<Decl *, 2, ModuleOwnershipKind> NextInContextAndBits;
240
241private:
242 friend class DeclContext;
243
244 struct MultipleDC {
245 DeclContext *SemanticDC;
246 DeclContext *LexicalDC;
247 };
248
249 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
250 /// For declarations that don't contain C++ scope specifiers, it contains
251 /// the DeclContext where the Decl was declared.
252 /// For declarations with C++ scope specifiers, it contains a MultipleDC*
253 /// with the context where it semantically belongs (SemanticDC) and the
254 /// context where it was lexically declared (LexicalDC).
255 /// e.g.:
256 ///
257 /// namespace A {
258 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
259 /// }
260 /// void A::f(); // SemanticDC == namespace 'A'
261 /// // LexicalDC == global namespace
262 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
263
264 bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
265 bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
266
267 MultipleDC *getMultipleDC() const {
268 return DeclCtx.get<MultipleDC*>();
269 }
270
271 DeclContext *getSemanticDC() const {
272 return DeclCtx.get<DeclContext*>();
273 }
274
275 /// Loc - The location of this decl.
276 SourceLocation Loc;
277
278 /// DeclKind - This indicates which class this is.
279 unsigned DeclKind : 7;
280
281 /// InvalidDecl - This indicates a semantic error occurred.
282 unsigned InvalidDecl : 1;
283
284 /// HasAttrs - This indicates whether the decl has attributes or not.
285 unsigned HasAttrs : 1;
286
287 /// Implicit - Whether this declaration was implicitly generated by
288 /// the implementation rather than explicitly written by the user.
289 unsigned Implicit : 1;
290
291 /// \brief Whether this declaration was "used", meaning that a definition is
292 /// required.
293 unsigned Used : 1;
294
295 /// \brief Whether this declaration was "referenced".
296 /// The difference with 'Used' is whether the reference appears in a
297 /// evaluated context or not, e.g. functions used in uninstantiated templates
298 /// are regarded as "referenced" but not "used".
299 unsigned Referenced : 1;
300
301 /// \brief Whether this declaration is a top-level declaration (function,
302 /// global variable, etc.) that is lexically inside an objc container
303 /// definition.
304 unsigned TopLevelDeclInObjCContainer : 1;
305
306 /// \brief Whether statistic collection is enabled.
307 static bool StatisticsEnabled;
308
309protected:
310 friend class ASTDeclReader;
311 friend class ASTDeclWriter;
312 friend class ASTReader;
313 friend class CXXClassMemberWrapper;
314 friend class LinkageComputer;
315 template<typename decl_type> friend class Redeclarable;
316
317 /// Access - Used by C++ decls for the access specifier.
318 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
319 unsigned Access : 2;
320
321 /// \brief Whether this declaration was loaded from an AST file.
322 unsigned FromASTFile : 1;
323
324 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
325 unsigned IdentifierNamespace : 13;
326
327 /// \brief If 0, we have not computed the linkage of this declaration.
328 /// Otherwise, it is the linkage + 1.
329 mutable unsigned CacheValidAndLinkage : 3;
330
331 /// \brief Allocate memory for a deserialized declaration.
332 ///
333 /// This routine must be used to allocate memory for any declaration that is
334 /// deserialized from a module file.
335 ///
336 /// \param Size The size of the allocated object.
337 /// \param Ctx The context in which we will allocate memory.
338 /// \param ID The global ID of the deserialized declaration.
339 /// \param Extra The amount of extra space to allocate after the object.
340 void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
341 std::size_t Extra = 0);
342
343 /// \brief Allocate memory for a non-deserialized declaration.
344 void *operator new(std::size_t Size, const ASTContext &Ctx,
345 DeclContext *Parent, std::size_t Extra = 0);
346
347private:
348 bool AccessDeclContextSanity() const;
349
350 /// Get the module ownership kind to use for a local lexical child of \p DC,
351 /// which may be either a local or (rarely) an imported declaration.
352 static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) {
353 if (DC) {
354 auto *D = cast<Decl>(DC);
355 auto MOK = D->getModuleOwnershipKind();
356 if (MOK != ModuleOwnershipKind::Unowned &&
357 (!D->isFromASTFile() || D->hasLocalOwningModuleStorage()))
358 return MOK;
359 // If D is not local and we have no local module storage, then we don't
360 // need to track module ownership at all.
361 }
362 return ModuleOwnershipKind::Unowned;
363 }
364
365protected:
366 Decl(Kind DK, DeclContext *DC, SourceLocation L)
367 : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)),
368 DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false),
369 Implicit(false), Used(false), Referenced(false),
370 TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0),
371 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
372 CacheValidAndLinkage(0) {
373 if (StatisticsEnabled) add(DK);
374 }
375
376 Decl(Kind DK, EmptyShell Empty)
377 : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false),
378 Used(false), Referenced(false), TopLevelDeclInObjCContainer(false),
379 Access(AS_none), FromASTFile(0),
380 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
381 CacheValidAndLinkage(0) {
382 if (StatisticsEnabled) add(DK);
383 }
384
385 virtual ~Decl();
386
387 /// \brief Update a potentially out-of-date declaration.
388 void updateOutOfDate(IdentifierInfo &II) const;
389
390 Linkage getCachedLinkage() const {
391 return Linkage(CacheValidAndLinkage - 1);
392 }
393
394 void setCachedLinkage(Linkage L) const {
395 CacheValidAndLinkage = L + 1;
396 }
397
398 bool hasCachedLinkage() const {
399 return CacheValidAndLinkage;
400 }
401
402public:
403 /// \brief Source range that this declaration covers.
404 virtual SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
405 return SourceRange(getLocation(), getLocation());
406 }
407
408 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
409 return getSourceRange().getBegin();
410 }
411
412 SourceLocation getLocEnd() const LLVM_READONLY__attribute__((__pure__)) {
413 return getSourceRange().getEnd();
414 }
415
416 SourceLocation getLocation() const { return Loc; }
417 void setLocation(SourceLocation L) { Loc = L; }
418
419 Kind getKind() const { return static_cast<Kind>(DeclKind); }
420 const char *getDeclKindName() const;
421
422 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
423 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
424
425 DeclContext *getDeclContext() {
426 if (isInSemaDC())
427 return getSemanticDC();
428 return getMultipleDC()->SemanticDC;
429 }
430 const DeclContext *getDeclContext() const {
431 return const_cast<Decl*>(this)->getDeclContext();
432 }
433
434 /// Find the innermost non-closure ancestor of this declaration,
435 /// walking up through blocks, lambdas, etc. If that ancestor is
436 /// not a code context (!isFunctionOrMethod()), returns null.
437 ///
438 /// A declaration may be its own non-closure context.
439 Decl *getNonClosureContext();
440 const Decl *getNonClosureContext() const {
441 return const_cast<Decl*>(this)->getNonClosureContext();
442 }
443
444 TranslationUnitDecl *getTranslationUnitDecl();
445 const TranslationUnitDecl *getTranslationUnitDecl() const {
446 return const_cast<Decl*>(this)->getTranslationUnitDecl();
447 }
448
449 bool isInAnonymousNamespace() const;
450
451 bool isInStdNamespace() const;
452
453 ASTContext &getASTContext() const LLVM_READONLY__attribute__((__pure__));
454
455 void setAccess(AccessSpecifier AS) {
456 Access = AS;
457 assert(AccessDeclContextSanity())(static_cast <bool> (AccessDeclContextSanity()) ? void (
0) : __assert_fail ("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 457, __extension__ __PRETTY_FUNCTION__))
;
458 }
459
460 AccessSpecifier getAccess() const {
461 assert(AccessDeclContextSanity())(static_cast <bool> (AccessDeclContextSanity()) ? void (
0) : __assert_fail ("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 461, __extension__ __PRETTY_FUNCTION__))
;
462 return AccessSpecifier(Access);
463 }
464
465 /// \brief Retrieve the access specifier for this declaration, even though
466 /// it may not yet have been properly set.
467 AccessSpecifier getAccessUnsafe() const {
468 return AccessSpecifier(Access);
469 }
470
471 bool hasAttrs() const { return HasAttrs; }
472
473 void setAttrs(const AttrVec& Attrs) {
474 return setAttrsImpl(Attrs, getASTContext());
475 }
476
477 AttrVec &getAttrs() {
478 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
479 }
480
481 const AttrVec &getAttrs() const;
482 void dropAttrs();
483
484 void addAttr(Attr *A) {
485 if (hasAttrs())
486 getAttrs().push_back(A);
487 else
488 setAttrs(AttrVec(1, A));
489 }
490
491 using attr_iterator = AttrVec::const_iterator;
492 using attr_range = llvm::iterator_range<attr_iterator>;
493
494 attr_range attrs() const {
495 return attr_range(attr_begin(), attr_end());
496 }
497
498 attr_iterator attr_begin() const {
499 return hasAttrs() ? getAttrs().begin() : nullptr;
500 }
501 attr_iterator attr_end() const {
502 return hasAttrs() ? getAttrs().end() : nullptr;
503 }
504
505 template <typename T>
506 void dropAttr() {
507 if (!HasAttrs) return;
508
509 AttrVec &Vec = getAttrs();
510 Vec.erase(std::remove_if(Vec.begin(), Vec.end(), isa<T, Attr*>), Vec.end());
511
512 if (Vec.empty())
513 HasAttrs = false;
514 }
515
516 template <typename T>
517 llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
518 return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>());
519 }
520
521 template <typename T>
522 specific_attr_iterator<T> specific_attr_begin() const {
523 return specific_attr_iterator<T>(attr_begin());
524 }
525
526 template <typename T>
527 specific_attr_iterator<T> specific_attr_end() const {
528 return specific_attr_iterator<T>(attr_end());
529 }
530
531 template<typename T> T *getAttr() const {
532 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
533 }
534
535 template<typename T> bool hasAttr() const {
536 return hasAttrs() && hasSpecificAttr<T>(getAttrs());
537 }
538
539 /// getMaxAlignment - return the maximum alignment specified by attributes
540 /// on this decl, 0 if there are none.
541 unsigned getMaxAlignment() const;
542
543 /// setInvalidDecl - Indicates the Decl had a semantic error. This
544 /// allows for graceful error recovery.
545 void setInvalidDecl(bool Invalid = true);
546 bool isInvalidDecl() const { return (bool) InvalidDecl; }
547
548 /// isImplicit - Indicates whether the declaration was implicitly
549 /// generated by the implementation. If false, this declaration
550 /// was written explicitly in the source code.
551 bool isImplicit() const { return Implicit; }
552 void setImplicit(bool I = true) { Implicit = I; }
553
554 /// \brief Whether *any* (re-)declaration of the entity was used, meaning that
555 /// a definition is required.
556 ///
557 /// \param CheckUsedAttr When true, also consider the "used" attribute
558 /// (in addition to the "used" bit set by \c setUsed()) when determining
559 /// whether the function is used.
560 bool isUsed(bool CheckUsedAttr = true) const;
561
562 /// \brief Set whether the declaration is used, in the sense of odr-use.
563 ///
564 /// This should only be used immediately after creating a declaration.
565 /// It intentionally doesn't notify any listeners.
566 void setIsUsed() { getCanonicalDecl()->Used = true; }
567
568 /// \brief Mark the declaration used, in the sense of odr-use.
569 ///
570 /// This notifies any mutation listeners in addition to setting a bit
571 /// indicating the declaration is used.
572 void markUsed(ASTContext &C);
573
574 /// \brief Whether any declaration of this entity was referenced.
575 bool isReferenced() const;
576
577 /// \brief Whether this declaration was referenced. This should not be relied
578 /// upon for anything other than debugging.
579 bool isThisDeclarationReferenced() const { return Referenced; }
580
581 void setReferenced(bool R = true) { Referenced = R; }
582
583 /// \brief Whether this declaration is a top-level declaration (function,
584 /// global variable, etc.) that is lexically inside an objc container
585 /// definition.
586 bool isTopLevelDeclInObjCContainer() const {
587 return TopLevelDeclInObjCContainer;
588 }
589
590 void setTopLevelDeclInObjCContainer(bool V = true) {
591 TopLevelDeclInObjCContainer = V;
592 }
593
594 /// \brief Looks on this and related declarations for an applicable
595 /// external source symbol attribute.
596 ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const;
597
598 /// \brief Whether this declaration was marked as being private to the
599 /// module in which it was defined.
600 bool isModulePrivate() const {
601 return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate;
602 }
603
604 /// \brief Whether this declaration is exported (by virtue of being lexically
605 /// within an ExportDecl or by being a NamespaceDecl).
606 bool isExported() const;
607
608 /// Return true if this declaration has an attribute which acts as
609 /// definition of the entity, such as 'alias' or 'ifunc'.
610 bool hasDefiningAttr() const;
611
612 /// Return this declaration's defining attribute if it has one.
613 const Attr *getDefiningAttr() const;
614
615protected:
616 /// \brief Specify that this declaration was marked as being private
617 /// to the module in which it was defined.
618 void setModulePrivate() {
619 // The module-private specifier has no effect on unowned declarations.
620 // FIXME: We should track this in some way for source fidelity.
621 if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned)
622 return;
623 setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate);
624 }
625
626 /// \brief Set the owning module ID.
627 void setOwningModuleID(unsigned ID) {
628 assert(isFromASTFile() && "Only works on a deserialized declaration")(static_cast <bool> (isFromASTFile() && "Only works on a deserialized declaration"
) ? void (0) : __assert_fail ("isFromASTFile() && \"Only works on a deserialized declaration\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 628, __extension__ __PRETTY_FUNCTION__))
;
629 *((unsigned*)this - 2) = ID;
630 }
631
632public:
633 /// \brief Determine the availability of the given declaration.
634 ///
635 /// This routine will determine the most restrictive availability of
636 /// the given declaration (e.g., preferring 'unavailable' to
637 /// 'deprecated').
638 ///
639 /// \param Message If non-NULL and the result is not \c
640 /// AR_Available, will be set to a (possibly empty) message
641 /// describing why the declaration has not been introduced, is
642 /// deprecated, or is unavailable.
643 ///
644 /// \param EnclosingVersion The version to compare with. If empty, assume the
645 /// deployment target version.
646 AvailabilityResult
647 getAvailability(std::string *Message = nullptr,
648 VersionTuple EnclosingVersion = VersionTuple()) const;
649
650 /// \brief Retrieve the version of the target platform in which this
651 /// declaration was introduced.
652 ///
653 /// \returns An empty version tuple if this declaration has no 'introduced'
654 /// availability attributes, or the version tuple that's specified in the
655 /// attribute otherwise.
656 VersionTuple getVersionIntroduced() const;
657
658 /// \brief Determine whether this declaration is marked 'deprecated'.
659 ///
660 /// \param Message If non-NULL and the declaration is deprecated,
661 /// this will be set to the message describing why the declaration
662 /// was deprecated (which may be empty).
663 bool isDeprecated(std::string *Message = nullptr) const {
664 return getAvailability(Message) == AR_Deprecated;
665 }
666
667 /// \brief Determine whether this declaration is marked 'unavailable'.
668 ///
669 /// \param Message If non-NULL and the declaration is unavailable,
670 /// this will be set to the message describing why the declaration
671 /// was made unavailable (which may be empty).
672 bool isUnavailable(std::string *Message = nullptr) const {
673 return getAvailability(Message) == AR_Unavailable;
674 }
675
676 /// \brief Determine whether this is a weak-imported symbol.
677 ///
678 /// Weak-imported symbols are typically marked with the
679 /// 'weak_import' attribute, but may also be marked with an
680 /// 'availability' attribute where we're targing a platform prior to
681 /// the introduction of this feature.
682 bool isWeakImported() const;
683
684 /// \brief Determines whether this symbol can be weak-imported,
685 /// e.g., whether it would be well-formed to add the weak_import
686 /// attribute.
687 ///
688 /// \param IsDefinition Set to \c true to indicate that this
689 /// declaration cannot be weak-imported because it has a definition.
690 bool canBeWeakImported(bool &IsDefinition) const;
691
692 /// \brief Determine whether this declaration came from an AST file (such as
693 /// a precompiled header or module) rather than having been parsed.
694 bool isFromASTFile() const { return FromASTFile; }
695
696 /// \brief Retrieve the global declaration ID associated with this
697 /// declaration, which specifies where this Decl was loaded from.
698 unsigned getGlobalID() const {
699 if (isFromASTFile())
700 return *((const unsigned*)this - 1);
701 return 0;
702 }
703
704 /// \brief Retrieve the global ID of the module that owns this particular
705 /// declaration.
706 unsigned getOwningModuleID() const {
707 if (isFromASTFile())
708 return *((const unsigned*)this - 2);
709 return 0;
710 }
711
712private:
713 Module *getOwningModuleSlow() const;
714
715protected:
716 bool hasLocalOwningModuleStorage() const;
717
718public:
719 /// \brief Get the imported owning module, if this decl is from an imported
720 /// (non-local) module.
721 Module *getImportedOwningModule() const {
722 if (!isFromASTFile() || !hasOwningModule())
723 return nullptr;
724
725 return getOwningModuleSlow();
726 }
727
728 /// \brief Get the local owning module, if known. Returns nullptr if owner is
729 /// not yet known or declaration is not from a module.
730 Module *getLocalOwningModule() const {
731 if (isFromASTFile() || !hasOwningModule())
732 return nullptr;
733
734 assert(hasLocalOwningModuleStorage() &&(static_cast <bool> (hasLocalOwningModuleStorage() &&
"owned local decl but no local module storage") ? void (0) :
__assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 735, __extension__ __PRETTY_FUNCTION__))
735 "owned local decl but no local module storage")(static_cast <bool> (hasLocalOwningModuleStorage() &&
"owned local decl but no local module storage") ? void (0) :
__assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 735, __extension__ __PRETTY_FUNCTION__))
;
736 return reinterpret_cast<Module *const *>(this)[-1];
737 }
738 void setLocalOwningModule(Module *M) {
739 assert(!isFromASTFile() && hasOwningModule() &&(static_cast <bool> (!isFromASTFile() && hasOwningModule
() && hasLocalOwningModuleStorage() && "should not have a cached owning module"
) ? void (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 741, __extension__ __PRETTY_FUNCTION__))
740 hasLocalOwningModuleStorage() &&(static_cast <bool> (!isFromASTFile() && hasOwningModule
() && hasLocalOwningModuleStorage() && "should not have a cached owning module"
) ? void (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 741, __extension__ __PRETTY_FUNCTION__))
741 "should not have a cached owning module")(static_cast <bool> (!isFromASTFile() && hasOwningModule
() && hasLocalOwningModuleStorage() && "should not have a cached owning module"
) ? void (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 741, __extension__ __PRETTY_FUNCTION__))
;
742 reinterpret_cast<Module **>(this)[-1] = M;
743 }
744
745 /// Is this declaration owned by some module?
746 bool hasOwningModule() const {
747 return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned;
748 }
749
750 /// Get the module that owns this declaration (for visibility purposes).
751 Module *getOwningModule() const {
752 return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule();
753 }
754
755 /// Get the module that owns this declaration for linkage purposes.
756 /// There only ever is such a module under the C++ Modules TS.
757 ///
758 /// \param IgnoreLinkage Ignore the linkage of the entity; assume that
759 /// all declarations in a global module fragment are unowned.
760 Module *getOwningModuleForLinkage(bool IgnoreLinkage = false) const;
761
762 /// \brief Determine whether this declaration might be hidden from name
763 /// lookup. Note that the declaration might be visible even if this returns
764 /// \c false, if the owning module is visible within the query context.
765 // FIXME: Rename this to make it clearer what it does.
766 bool isHidden() const {
767 return (int)getModuleOwnershipKind() > (int)ModuleOwnershipKind::Visible;
768 }
769
770 /// Set that this declaration is globally visible, even if it came from a
771 /// module that is not visible.
772 void setVisibleDespiteOwningModule() {
773 if (isHidden())
774 setModuleOwnershipKind(ModuleOwnershipKind::Visible);
775 }
776
777 /// \brief Get the kind of module ownership for this declaration.
778 ModuleOwnershipKind getModuleOwnershipKind() const {
779 return NextInContextAndBits.getInt();
780 }
781
782 /// \brief Set whether this declaration is hidden from name lookup.
783 void setModuleOwnershipKind(ModuleOwnershipKind MOK) {
784 assert(!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind
::Unowned && MOK != ModuleOwnershipKind::Unowned &&
!isFromASTFile() && !hasLocalOwningModuleStorage()) &&
"no storage available for owning module for this declaration"
) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 787, __extension__ __PRETTY_FUNCTION__))
785 MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind
::Unowned && MOK != ModuleOwnershipKind::Unowned &&
!isFromASTFile() && !hasLocalOwningModuleStorage()) &&
"no storage available for owning module for this declaration"
) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 787, __extension__ __PRETTY_FUNCTION__))
786 !hasLocalOwningModuleStorage()) &&(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind
::Unowned && MOK != ModuleOwnershipKind::Unowned &&
!isFromASTFile() && !hasLocalOwningModuleStorage()) &&
"no storage available for owning module for this declaration"
) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 787, __extension__ __PRETTY_FUNCTION__))
787 "no storage available for owning module for this declaration")(static_cast <bool> (!(getModuleOwnershipKind() == ModuleOwnershipKind
::Unowned && MOK != ModuleOwnershipKind::Unowned &&
!isFromASTFile() && !hasLocalOwningModuleStorage()) &&
"no storage available for owning module for this declaration"
) ? void (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 787, __extension__ __PRETTY_FUNCTION__))
;
788 NextInContextAndBits.setInt(MOK);
789 }
790
791 unsigned getIdentifierNamespace() const {
792 return IdentifierNamespace;
793 }
794
795 bool isInIdentifierNamespace(unsigned NS) const {
796 return getIdentifierNamespace() & NS;
797 }
798
799 static unsigned getIdentifierNamespaceForKind(Kind DK);
800
801 bool hasTagIdentifierNamespace() const {
802 return isTagIdentifierNamespace(getIdentifierNamespace());
803 }
804
805 static bool isTagIdentifierNamespace(unsigned NS) {
806 // TagDecls have Tag and Type set and may also have TagFriend.
807 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
808 }
809
810 /// getLexicalDeclContext - The declaration context where this Decl was
811 /// lexically declared (LexicalDC). May be different from
812 /// getDeclContext() (SemanticDC).
813 /// e.g.:
814 ///
815 /// namespace A {
816 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
817 /// }
818 /// void A::f(); // SemanticDC == namespace 'A'
819 /// // LexicalDC == global namespace
820 DeclContext *getLexicalDeclContext() {
821 if (isInSemaDC())
822 return getSemanticDC();
823 return getMultipleDC()->LexicalDC;
824 }
825 const DeclContext *getLexicalDeclContext() const {
826 return const_cast<Decl*>(this)->getLexicalDeclContext();
827 }
828
829 /// Determine whether this declaration is declared out of line (outside its
830 /// semantic context).
831 virtual bool isOutOfLine() const;
832
833 /// setDeclContext - Set both the semantic and lexical DeclContext
834 /// to DC.
835 void setDeclContext(DeclContext *DC);
836
837 void setLexicalDeclContext(DeclContext *DC);
838
839 /// Determine whether this declaration is a templated entity (whether it is
840 // within the scope of a template parameter).
841 bool isTemplated() const;
842
843 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
844 /// scoped decl is defined outside the current function or method. This is
845 /// roughly global variables and functions, but also handles enums (which
846 /// could be defined inside or outside a function etc).
847 bool isDefinedOutsideFunctionOrMethod() const {
848 return getParentFunctionOrMethod() == nullptr;
849 }
850
851 /// \brief Returns true if this declaration lexically is inside a function.
852 /// It recognizes non-defining declarations as well as members of local
853 /// classes:
854 /// \code
855 /// void foo() { void bar(); }
856 /// void foo2() { class ABC { void bar(); }; }
857 /// \endcode
858 bool isLexicallyWithinFunctionOrMethod() const;
859
860 /// \brief If this decl is defined inside a function/method/block it returns
861 /// the corresponding DeclContext, otherwise it returns null.
862 const DeclContext *getParentFunctionOrMethod() const;
863 DeclContext *getParentFunctionOrMethod() {
864 return const_cast<DeclContext*>(
865 const_cast<const Decl*>(this)->getParentFunctionOrMethod());
866 }
867
868 /// \brief Retrieves the "canonical" declaration of the given declaration.
869 virtual Decl *getCanonicalDecl() { return this; }
870 const Decl *getCanonicalDecl() const {
871 return const_cast<Decl*>(this)->getCanonicalDecl();
872 }
873
874 /// \brief Whether this particular Decl is a canonical one.
875 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
876
877protected:
878 /// \brief Returns the next redeclaration or itself if this is the only decl.
879 ///
880 /// Decl subclasses that can be redeclared should override this method so that
881 /// Decl::redecl_iterator can iterate over them.
882 virtual Decl *getNextRedeclarationImpl() { return this; }
883
884 /// \brief Implementation of getPreviousDecl(), to be overridden by any
885 /// subclass that has a redeclaration chain.
886 virtual Decl *getPreviousDeclImpl() { return nullptr; }
887
888 /// \brief Implementation of getMostRecentDecl(), to be overridden by any
889 /// subclass that has a redeclaration chain.
890 virtual Decl *getMostRecentDeclImpl() { return this; }
891
892public:
893 /// \brief Iterates through all the redeclarations of the same decl.
894 class redecl_iterator {
895 /// Current - The current declaration.
896 Decl *Current = nullptr;
897 Decl *Starter;
898
899 public:
900 using value_type = Decl *;
901 using reference = const value_type &;
902 using pointer = const value_type *;
903 using iterator_category = std::forward_iterator_tag;
904 using difference_type = std::ptrdiff_t;
905
906 redecl_iterator() = default;
907 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) {}
908
909 reference operator*() const { return Current; }
910 value_type operator->() const { return Current; }
911
912 redecl_iterator& operator++() {
913 assert(Current && "Advancing while iterator has reached end")(static_cast <bool> (Current && "Advancing while iterator has reached end"
) ? void (0) : __assert_fail ("Current && \"Advancing while iterator has reached end\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 913, __extension__ __PRETTY_FUNCTION__))
;
914 // Get either previous decl or latest decl.
915 Decl *Next = Current->getNextRedeclarationImpl();
916 assert(Next && "Should return next redeclaration or itself, never null!")(static_cast <bool> (Next && "Should return next redeclaration or itself, never null!"
) ? void (0) : __assert_fail ("Next && \"Should return next redeclaration or itself, never null!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 916, __extension__ __PRETTY_FUNCTION__))
;
917 Current = (Next != Starter) ? Next : nullptr;
918 return *this;
919 }
920
921 redecl_iterator operator++(int) {
922 redecl_iterator tmp(*this);
923 ++(*this);
924 return tmp;
925 }
926
927 friend bool operator==(redecl_iterator x, redecl_iterator y) {
928 return x.Current == y.Current;
929 }
930
931 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
932 return x.Current != y.Current;
933 }
934 };
935
936 using redecl_range = llvm::iterator_range<redecl_iterator>;
937
938 /// \brief Returns an iterator range for all the redeclarations of the same
939 /// decl. It will iterate at least once (when this decl is the only one).
940 redecl_range redecls() const {
941 return redecl_range(redecls_begin(), redecls_end());
942 }
943
944 redecl_iterator redecls_begin() const {
945 return redecl_iterator(const_cast<Decl *>(this));
946 }
947
948 redecl_iterator redecls_end() const { return redecl_iterator(); }
949
950 /// \brief Retrieve the previous declaration that declares the same entity
951 /// as this declaration, or NULL if there is no previous declaration.
952 Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
953
954 /// \brief Retrieve the most recent declaration that declares the same entity
955 /// as this declaration, or NULL if there is no previous declaration.
956 const Decl *getPreviousDecl() const {
957 return const_cast<Decl *>(this)->getPreviousDeclImpl();
958 }
959
960 /// \brief True if this is the first declaration in its redeclaration chain.
961 bool isFirstDecl() const {
962 return getPreviousDecl() == nullptr;
963 }
964
965 /// \brief Retrieve the most recent declaration that declares the same entity
966 /// as this declaration (which may be this declaration).
967 Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
968
969 /// \brief Retrieve the most recent declaration that declares the same entity
970 /// as this declaration (which may be this declaration).
971 const Decl *getMostRecentDecl() const {
972 return const_cast<Decl *>(this)->getMostRecentDeclImpl();
973 }
974
975 /// getBody - If this Decl represents a declaration for a body of code,
976 /// such as a function or method definition, this method returns the
977 /// top-level Stmt* of that body. Otherwise this method returns null.
978 virtual Stmt* getBody() const { return nullptr; }
979
980 /// \brief Returns true if this \c Decl represents a declaration for a body of
981 /// code, such as a function or method definition.
982 /// Note that \c hasBody can also return true if any redeclaration of this
983 /// \c Decl represents a declaration for a body of code.
984 virtual bool hasBody() const { return getBody() != nullptr; }
985
986 /// getBodyRBrace - Gets the right brace of the body, if a body exists.
987 /// This works whether the body is a CompoundStmt or a CXXTryStmt.
988 SourceLocation getBodyRBrace() const;
989
990 // global temp stats (until we have a per-module visitor)
991 static void add(Kind k);
992 static void EnableStatistics();
993 static void PrintStats();
994
995 /// isTemplateParameter - Determines whether this declaration is a
996 /// template parameter.
997 bool isTemplateParameter() const;
998
999 /// isTemplateParameter - Determines whether this declaration is a
1000 /// template parameter pack.
1001 bool isTemplateParameterPack() const;
1002
1003 /// \brief Whether this declaration is a parameter pack.
1004 bool isParameterPack() const;
1005
1006 /// \brief returns true if this declaration is a template
1007 bool isTemplateDecl() const;
1008
1009 /// \brief Whether this declaration is a function or function template.
1010 bool isFunctionOrFunctionTemplate() const {
1011 return (DeclKind >= Decl::firstFunction &&
1012 DeclKind <= Decl::lastFunction) ||
1013 DeclKind == FunctionTemplate;
1014 }
1015
1016 /// \brief If this is a declaration that describes some template, this
1017 /// method returns that template declaration.
1018 TemplateDecl *getDescribedTemplate() const;
1019
1020 /// \brief Returns the function itself, or the templated function if this is a
1021 /// function template.
1022 FunctionDecl *getAsFunction() LLVM_READONLY__attribute__((__pure__));
1023
1024 const FunctionDecl *getAsFunction() const {
1025 return const_cast<Decl *>(this)->getAsFunction();
1026 }
1027
1028 /// \brief Changes the namespace of this declaration to reflect that it's
1029 /// a function-local extern declaration.
1030 ///
1031 /// These declarations appear in the lexical context of the extern
1032 /// declaration, but in the semantic context of the enclosing namespace
1033 /// scope.
1034 void setLocalExternDecl() {
1035 Decl *Prev = getPreviousDecl();
1036 IdentifierNamespace &= ~IDNS_Ordinary;
1037
1038 // It's OK for the declaration to still have the "invisible friend" flag or
1039 // the "conflicts with tag declarations in this scope" flag for the outer
1040 // scope.
1041 assert((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 &&(static_cast <bool> ((IdentifierNamespace & ~(IDNS_OrdinaryFriend
| IDNS_Tag)) == 0 && "namespace is not ordinary") ? void
(0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 1042, __extension__ __PRETTY_FUNCTION__))
1042 "namespace is not ordinary")(static_cast <bool> ((IdentifierNamespace & ~(IDNS_OrdinaryFriend
| IDNS_Tag)) == 0 && "namespace is not ordinary") ? void
(0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 1042, __extension__ __PRETTY_FUNCTION__))
;
1043
1044 IdentifierNamespace |= IDNS_LocalExtern;
1045 if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
1046 IdentifierNamespace |= IDNS_Ordinary;
1047 }
1048
1049 /// \brief Determine whether this is a block-scope declaration with linkage.
1050 /// This will either be a local variable declaration declared 'extern', or a
1051 /// local function declaration.
1052 bool isLocalExternDecl() {
1053 return IdentifierNamespace & IDNS_LocalExtern;
1054 }
1055
1056 /// \brief Changes the namespace of this declaration to reflect that it's
1057 /// the object of a friend declaration.
1058 ///
1059 /// These declarations appear in the lexical context of the friending
1060 /// class, but in the semantic context of the actual entity. This property
1061 /// applies only to a specific decl object; other redeclarations of the
1062 /// same entity may not (and probably don't) share this property.
1063 void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
1064 unsigned OldNS = IdentifierNamespace;
1065 assert((OldNS & (IDNS_Tag | IDNS_Ordinary |(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) &&
"namespace includes neither ordinary nor tag") ? void (0) : __assert_fail
("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 1068, __extension__ __PRETTY_FUNCTION__))
1066 IDNS_TagFriend | IDNS_OrdinaryFriend |(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) &&
"namespace includes neither ordinary nor tag") ? void (0) : __assert_fail
("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 1068, __extension__ __PRETTY_FUNCTION__))
1067 IDNS_LocalExtern)) &&(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) &&
"namespace includes neither ordinary nor tag") ? void (0) : __assert_fail
("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 1068, __extension__ __PRETTY_FUNCTION__))
1068 "namespace includes neither ordinary nor tag")(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) &&
"namespace includes neither ordinary nor tag") ? void (0) : __assert_fail
("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) && \"namespace includes neither ordinary nor tag\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 1068, __extension__ __PRETTY_FUNCTION__))
;
1069 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 1072, __extension__ __PRETTY_FUNCTION__))
1070 IDNS_TagFriend | IDNS_OrdinaryFriend |(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 1072, __extension__ __PRETTY_FUNCTION__))
1071 IDNS_LocalExtern)) &&(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 1072, __extension__ __PRETTY_FUNCTION__))
1072 "namespace includes other than ordinary or tag")(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern)) && \"namespace includes other than ordinary or tag\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 1072, __extension__ __PRETTY_FUNCTION__))
;
1073
1074 Decl *Prev = getPreviousDecl();
1075 IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
1076
1077 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
1078 IdentifierNamespace |= IDNS_TagFriend;
1079 if (PerformFriendInjection ||
1080 (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
1081 IdentifierNamespace |= IDNS_Tag | IDNS_Type;
1082 }
1083
1084 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend | IDNS_LocalExtern)) {
1085 IdentifierNamespace |= IDNS_OrdinaryFriend;
1086 if (PerformFriendInjection ||
1087 (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
1088 IdentifierNamespace |= IDNS_Ordinary;
1089 }
1090 }
1091
1092 enum FriendObjectKind {
1093 FOK_None, ///< Not a friend object.
1094 FOK_Declared, ///< A friend of a previously-declared entity.
1095 FOK_Undeclared ///< A friend of a previously-undeclared entity.
1096 };
1097
1098 /// \brief Determines whether this declaration is the object of a
1099 /// friend declaration and, if so, what kind.
1100 ///
1101 /// There is currently no direct way to find the associated FriendDecl.
1102 FriendObjectKind getFriendObjectKind() const {
1103 unsigned mask =
1104 (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
1105 if (!mask) return FOK_None;
1106 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
1107 : FOK_Undeclared);
1108 }
1109
1110 /// Specifies that this declaration is a C++ overloaded non-member.
1111 void setNonMemberOperator() {
1112 assert(getKind() == Function || getKind() == FunctionTemplate)(static_cast <bool> (getKind() == Function || getKind()
== FunctionTemplate) ? void (0) : __assert_fail ("getKind() == Function || getKind() == FunctionTemplate"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 1112, __extension__ __PRETTY_FUNCTION__))
;
1113 assert((IdentifierNamespace & IDNS_Ordinary) &&(static_cast <bool> ((IdentifierNamespace & IDNS_Ordinary
) && "visible non-member operators should be in ordinary namespace"
) ? void (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 1114, __extension__ __PRETTY_FUNCTION__))
1114 "visible non-member operators should be in ordinary namespace")(static_cast <bool> ((IdentifierNamespace & IDNS_Ordinary
) && "visible non-member operators should be in ordinary namespace"
) ? void (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 1114, __extension__ __PRETTY_FUNCTION__))
;
1115 IdentifierNamespace |= IDNS_NonMemberOperator;
1116 }
1117
1118 static bool classofKind(Kind K) { return true; }
1119 static DeclContext *castToDeclContext(const Decl *);
1120 static Decl *castFromDeclContext(const DeclContext *);
1121
1122 void print(raw_ostream &Out, unsigned Indentation = 0,
1123 bool PrintInstantiation = false) const;
1124 void print(raw_ostream &Out, const PrintingPolicy &Policy,
1125 unsigned Indentation = 0, bool PrintInstantiation = false) const;
1126 static void printGroup(Decl** Begin, unsigned NumDecls,
1127 raw_ostream &Out, const PrintingPolicy &Policy,
1128 unsigned Indentation = 0);
1129
1130 // Debuggers don't usually respect default arguments.
1131 void dump() const;
1132
1133 // Same as dump(), but forces color printing.
1134 void dumpColor() const;
1135
1136 void dump(raw_ostream &Out, bool Deserialize = false) const;
1137
1138 /// \brief Looks through the Decl's underlying type to extract a FunctionType
1139 /// when possible. Will return null if the type underlying the Decl does not
1140 /// have a FunctionType.
1141 const FunctionType *getFunctionType(bool BlocksToo = true) const;
1142
1143private:
1144 void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
1145 void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
1146 ASTContext &Ctx);
1147
1148protected:
1149 ASTMutationListener *getASTMutationListener() const;
1150};
1151
1152/// \brief Determine whether two declarations declare the same entity.
1153inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
1154 if (!D1 || !D2)
1155 return false;
1156
1157 if (D1 == D2)
1158 return true;
1159
1160 return D1->getCanonicalDecl() == D2->getCanonicalDecl();
1161}
1162
1163/// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
1164/// doing something to a specific decl.
1165class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
1166 const Decl *TheDecl;
1167 SourceLocation Loc;
1168 SourceManager &SM;
1169 const char *Message;
1170
1171public:
1172 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
1173 SourceManager &sm, const char *Msg)
1174 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
1175
1176 void print(raw_ostream &OS) const override;
1177};
1178
1179/// \brief The results of name lookup within a DeclContext. This is either a
1180/// single result (with no stable storage) or a collection of results (with
1181/// stable storage provided by the lookup table).
1182class DeclContextLookupResult {
1183 using ResultTy = ArrayRef<NamedDecl *>;
1184
1185 ResultTy Result;
1186
1187 // If there is only one lookup result, it would be invalidated by
1188 // reallocations of the name table, so store it separately.
1189 NamedDecl *Single = nullptr;
1190
1191 static NamedDecl *const SingleElementDummyList;
1192
1193public:
1194 DeclContextLookupResult() = default;
1195 DeclContextLookupResult(ArrayRef<NamedDecl *> Result)
1196 : Result(Result) {}
1197 DeclContextLookupResult(NamedDecl *Single)
1198 : Result(SingleElementDummyList), Single(Single) {}
1199
1200 class iterator;
1201
1202 using IteratorBase =
1203 llvm::iterator_adaptor_base<iterator, ResultTy::iterator,
1204 std::random_access_iterator_tag,
1205 NamedDecl *const>;
1206
1207 class iterator : public IteratorBase {
1208 value_type SingleElement;
1209
1210 public:
1211 iterator() = default;
1212 explicit iterator(pointer Pos, value_type Single = nullptr)
1213 : IteratorBase(Pos), SingleElement(Single) {}
1214
1215 reference operator*() const {
1216 return SingleElement ? SingleElement : IteratorBase::operator*();
1217 }
1218 };
1219
1220 using const_iterator = iterator;
1221 using pointer = iterator::pointer;
1222 using reference = iterator::reference;
1223
1224 iterator begin() const { return iterator(Result.begin(), Single); }
1225 iterator end() const { return iterator(Result.end(), Single); }
1226
1227 bool empty() const { return Result.empty(); }
1228 pointer data() const { return Single ? &Single : Result.data(); }
1229 size_t size() const { return Single ? 1 : Result.size(); }
1230 reference front() const { return Single ? Single : Result.front(); }
1231 reference back() const { return Single ? Single : Result.back(); }
1232 reference operator[](size_t N) const { return Single ? Single : Result[N]; }
1233
1234 // FIXME: Remove this from the interface
1235 DeclContextLookupResult slice(size_t N) const {
1236 DeclContextLookupResult Sliced = Result.slice(N);
1237 Sliced.Single = Single;
1238 return Sliced;
1239 }
1240};
1241
1242/// DeclContext - This is used only as base class of specific decl types that
1243/// can act as declaration contexts. These decls are (only the top classes
1244/// that directly derive from DeclContext are mentioned, not their subclasses):
1245///
1246/// TranslationUnitDecl
1247/// NamespaceDecl
1248/// FunctionDecl
1249/// TagDecl
1250/// ObjCMethodDecl
1251/// ObjCContainerDecl
1252/// LinkageSpecDecl
1253/// ExportDecl
1254/// BlockDecl
1255/// OMPDeclareReductionDecl
1256class DeclContext {
1257 /// DeclKind - This indicates which class this is.
1258 unsigned DeclKind : 8;
1259
1260 /// \brief Whether this declaration context also has some external
1261 /// storage that contains additional declarations that are lexically
1262 /// part of this context.
1263 mutable bool ExternalLexicalStorage : 1;
1264
1265 /// \brief Whether this declaration context also has some external
1266 /// storage that contains additional declarations that are visible
1267 /// in this context.
1268 mutable bool ExternalVisibleStorage : 1;
1269
1270 /// \brief Whether this declaration context has had external visible
1271 /// storage added since the last lookup. In this case, \c LookupPtr's
1272 /// invariant may not hold and needs to be fixed before we perform
1273 /// another lookup.
1274 mutable bool NeedToReconcileExternalVisibleStorage : 1;
1275
1276 /// \brief If \c true, this context may have local lexical declarations
1277 /// that are missing from the lookup table.
1278 mutable bool HasLazyLocalLexicalLookups : 1;
1279
1280 /// \brief If \c true, the external source may have lexical declarations
1281 /// that are missing from the lookup table.
1282 mutable bool HasLazyExternalLexicalLookups : 1;
1283
1284 /// \brief If \c true, lookups should only return identifier from
1285 /// DeclContext scope (for example TranslationUnit). Used in
1286 /// LookupQualifiedName()
1287 mutable bool UseQualifiedLookup : 1;
1288
1289 /// \brief Pointer to the data structure used to lookup declarations
1290 /// within this context (or a DependentStoredDeclsMap if this is a
1291 /// dependent context). We maintain the invariant that, if the map
1292 /// contains an entry for a DeclarationName (and we haven't lazily
1293 /// omitted anything), then it contains all relevant entries for that
1294 /// name (modulo the hasExternalDecls() flag).
1295 mutable StoredDeclsMap *LookupPtr = nullptr;
1296
1297protected:
1298 friend class ASTDeclReader;
1299 friend class ASTWriter;
1300 friend class ExternalASTSource;
1301
1302 /// FirstDecl - The first declaration stored within this declaration
1303 /// context.
1304 mutable Decl *FirstDecl = nullptr;
1305
1306 /// LastDecl - The last declaration stored within this declaration
1307 /// context. FIXME: We could probably cache this value somewhere
1308 /// outside of the DeclContext, to reduce the size of DeclContext by
1309 /// another pointer.
1310 mutable Decl *LastDecl = nullptr;
1311
1312 /// \brief Build up a chain of declarations.
1313 ///
1314 /// \returns the first/last pair of declarations.
1315 static std::pair<Decl *, Decl *>
1316 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1317
1318 DeclContext(Decl::Kind K)
1319 : DeclKind(K), ExternalLexicalStorage(false),
1320 ExternalVisibleStorage(false),
1321 NeedToReconcileExternalVisibleStorage(false),
1322 HasLazyLocalLexicalLookups(false), HasLazyExternalLexicalLookups(false),
1323 UseQualifiedLookup(false) {}
1324
1325public:
1326 ~DeclContext();
1327
1328 Decl::Kind getDeclKind() const {
1329 return static_cast<Decl::Kind>(DeclKind);
1330 }
1331
1332 const char *getDeclKindName() const;
1333
1334 /// getParent - Returns the containing DeclContext.
1335 DeclContext *getParent() {
1336 return cast<Decl>(this)->getDeclContext();
1337 }
1338 const DeclContext *getParent() const {
1339 return const_cast<DeclContext*>(this)->getParent();
1340 }
1341
1342 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1343 /// different from getParent, e.g.:
1344 ///
1345 /// namespace A {
1346 /// struct S;
1347 /// }
1348 /// struct A::S {}; // getParent() == namespace 'A'
1349 /// // getLexicalParent() == translation unit
1350 ///
1351 DeclContext *getLexicalParent() {
1352 return cast<Decl>(this)->getLexicalDeclContext();
1353 }
1354 const DeclContext *getLexicalParent() const {
1355 return const_cast<DeclContext*>(this)->getLexicalParent();
1356 }
1357
1358 DeclContext *getLookupParent();
1359
1360 const DeclContext *getLookupParent() const {
1361 return const_cast<DeclContext*>(this)->getLookupParent();
1362 }
1363
1364 ASTContext &getParentASTContext() const {
1365 return cast<Decl>(this)->getASTContext();
1366 }
1367
1368 bool isClosure() const {
1369 return DeclKind == Decl::Block;
1370 }
1371
1372 bool isObjCContainer() const {
1373 switch (DeclKind) {
1374 case Decl::ObjCCategory:
1375 case Decl::ObjCCategoryImpl:
1376 case Decl::ObjCImplementation:
1377 case Decl::ObjCInterface:
1378 case Decl::ObjCProtocol:
1379 return true;
1380 }
1381 return false;
1382 }
1383
1384 bool isFunctionOrMethod() const {
1385 switch (DeclKind) {
1386 case Decl::Block:
1387 case Decl::Captured:
1388 case Decl::ObjCMethod:
1389 return true;
1390 default:
1391 return DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction;
1392 }
1393 }
1394
1395 /// \brief Test whether the context supports looking up names.
1396 bool isLookupContext() const {
1397 return !isFunctionOrMethod() && DeclKind != Decl::LinkageSpec &&
1398 DeclKind != Decl::Export;
1399 }
1400
1401 bool isFileContext() const {
1402 return DeclKind == Decl::TranslationUnit || DeclKind == Decl::Namespace;
1403 }
1404
1405 bool isTranslationUnit() const {
1406 return DeclKind == Decl::TranslationUnit;
1407 }
1408
1409 bool isRecord() const {
1410 return DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord;
1411 }
1412
1413 bool isNamespace() const {
1414 return DeclKind == Decl::Namespace;
1415 }
1416
1417 bool isStdNamespace() const;
1418
1419 bool isInlineNamespace() const;
1420
1421 /// \brief Determines whether this context is dependent on a
1422 /// template parameter.
1423 bool isDependentContext() const;
1424
1425 /// isTransparentContext - Determines whether this context is a
1426 /// "transparent" context, meaning that the members declared in this
1427 /// context are semantically declared in the nearest enclosing
1428 /// non-transparent (opaque) context but are lexically declared in
1429 /// this context. For example, consider the enumerators of an
1430 /// enumeration type:
1431 /// @code
1432 /// enum E {
1433 /// Val1
1434 /// };
1435 /// @endcode
1436 /// Here, E is a transparent context, so its enumerator (Val1) will
1437 /// appear (semantically) that it is in the same context of E.
1438 /// Examples of transparent contexts include: enumerations (except for
1439 /// C++0x scoped enums), and C++ linkage specifications.
1440 bool isTransparentContext() const;
1441
1442 /// \brief Determines whether this context or some of its ancestors is a
1443 /// linkage specification context that specifies C linkage.
1444 bool isExternCContext() const;
1445
1446 /// \brief Retrieve the nearest enclosing C linkage specification context.
1447 const LinkageSpecDecl *getExternCContext() const;
1448
1449 /// \brief Determines whether this context or some of its ancestors is a
1450 /// linkage specification context that specifies C++ linkage.
1451 bool isExternCXXContext() const;
1452
1453 /// \brief Determine whether this declaration context is equivalent
1454 /// to the declaration context DC.
1455 bool Equals(const DeclContext *DC) const {
1456 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1457 }
1458
1459 /// \brief Determine whether this declaration context encloses the
1460 /// declaration context DC.
1461 bool Encloses(const DeclContext *DC) const;
1462
1463 /// \brief Find the nearest non-closure ancestor of this context,
1464 /// i.e. the innermost semantic parent of this context which is not
1465 /// a closure. A context may be its own non-closure ancestor.
1466 Decl *getNonClosureAncestor();
1467 const Decl *getNonClosureAncestor() const {
1468 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1469 }
1470
1471 /// getPrimaryContext - There may be many different
1472 /// declarations of the same entity (including forward declarations
1473 /// of classes, multiple definitions of namespaces, etc.), each with
1474 /// a different set of declarations. This routine returns the
1475 /// "primary" DeclContext structure, which will contain the
1476 /// information needed to perform name lookup into this context.
1477 DeclContext *getPrimaryContext();
1478 const DeclContext *getPrimaryContext() const {
1479 return const_cast<DeclContext*>(this)->getPrimaryContext();
1480 }
1481
1482 /// getRedeclContext - Retrieve the context in which an entity conflicts with
1483 /// other entities of the same name, or where it is a redeclaration if the
1484 /// two entities are compatible. This skips through transparent contexts.
1485 DeclContext *getRedeclContext();
1486 const DeclContext *getRedeclContext() const {
1487 return const_cast<DeclContext *>(this)->getRedeclContext();
1488 }
1489
1490 /// \brief Retrieve the nearest enclosing namespace context.
1491 DeclContext *getEnclosingNamespaceContext();
1492 const DeclContext *getEnclosingNamespaceContext() const {
1493 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
1494 }
1495
1496 /// \brief Retrieve the outermost lexically enclosing record context.
1497 RecordDecl *getOuterLexicalRecordContext();
1498 const RecordDecl *getOuterLexicalRecordContext() const {
1499 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
1500 }
1501
1502 /// \brief Test if this context is part of the enclosing namespace set of
1503 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
1504 /// isn't a namespace, this is equivalent to Equals().
1505 ///
1506 /// The enclosing namespace set of a namespace is the namespace and, if it is
1507 /// inline, its enclosing namespace, recursively.
1508 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
1509
1510 /// \brief Collects all of the declaration contexts that are semantically
1511 /// connected to this declaration context.
1512 ///
1513 /// For declaration contexts that have multiple semantically connected but
1514 /// syntactically distinct contexts, such as C++ namespaces, this routine
1515 /// retrieves the complete set of such declaration contexts in source order.
1516 /// For example, given:
1517 ///
1518 /// \code
1519 /// namespace N {
1520 /// int x;
1521 /// }
1522 /// namespace N {
1523 /// int y;
1524 /// }
1525 /// \endcode
1526 ///
1527 /// The \c Contexts parameter will contain both definitions of N.
1528 ///
1529 /// \param Contexts Will be cleared and set to the set of declaration
1530 /// contexts that are semanticaly connected to this declaration context,
1531 /// in source order, including this context (which may be the only result,
1532 /// for non-namespace contexts).
1533 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
1534
1535 /// decl_iterator - Iterates through the declarations stored
1536 /// within this context.
1537 class decl_iterator {
1538 /// Current - The current declaration.
1539 Decl *Current = nullptr;
1540
1541 public:
1542 using value_type = Decl *;
1543 using reference = const value_type &;
1544 using pointer = const value_type *;
1545 using iterator_category = std::forward_iterator_tag;
1546 using difference_type = std::ptrdiff_t;
1547
1548 decl_iterator() = default;
1549 explicit decl_iterator(Decl *C) : Current(C) {}
1550
1551 reference operator*() const { return Current; }
1552
1553 // This doesn't meet the iterator requirements, but it's convenient
1554 value_type operator->() const { return Current; }
1555
1556 decl_iterator& operator++() {
1557 Current = Current->getNextDeclInContext();
1558 return *this;
1559 }
1560
1561 decl_iterator operator++(int) {
1562 decl_iterator tmp(*this);
1563 ++(*this);
1564 return tmp;
1565 }
1566
1567 friend bool operator==(decl_iterator x, decl_iterator y) {
1568 return x.Current == y.Current;
1569 }
1570
1571 friend bool operator!=(decl_iterator x, decl_iterator y) {
1572 return x.Current != y.Current;
1573 }
1574 };
1575
1576 using decl_range = llvm::iterator_range<decl_iterator>;
1577
1578 /// decls_begin/decls_end - Iterate over the declarations stored in
1579 /// this context.
1580 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
1581 decl_iterator decls_begin() const;
1582 decl_iterator decls_end() const { return decl_iterator(); }
1583 bool decls_empty() const;
1584
1585 /// noload_decls_begin/end - Iterate over the declarations stored in this
1586 /// context that are currently loaded; don't attempt to retrieve anything
1587 /// from an external source.
1588 decl_range noload_decls() const {
1589 return decl_range(noload_decls_begin(), noload_decls_end());
1590 }
1591 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
1592 decl_iterator noload_decls_end() const { return decl_iterator(); }
1593
1594 /// specific_decl_iterator - Iterates over a subrange of
1595 /// declarations stored in a DeclContext, providing only those that
1596 /// are of type SpecificDecl (or a class derived from it). This
1597 /// iterator is used, for example, to provide iteration over just
1598 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
1599 template<typename SpecificDecl>
1600 class specific_decl_iterator {
1601 /// Current - The current, underlying declaration iterator, which
1602 /// will either be NULL or will point to a declaration of
1603 /// type SpecificDecl.
1604 DeclContext::decl_iterator Current;
1605
1606 /// SkipToNextDecl - Advances the current position up to the next
1607 /// declaration of type SpecificDecl that also meets the criteria
1608 /// required by Acceptable.
1609 void SkipToNextDecl() {
1610 while (*Current && !isa<SpecificDecl>(*Current))
1611 ++Current;
1612 }
1613
1614 public:
1615 using value_type = SpecificDecl *;
1616 // TODO: Add reference and pointer types (with some appropriate proxy type)
1617 // if we ever have a need for them.
1618 using reference = void;
1619 using pointer = void;
1620 using difference_type =
1621 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
1622 using iterator_category = std::forward_iterator_tag;
1623
1624 specific_decl_iterator() = default;
1625
1626 /// specific_decl_iterator - Construct a new iterator over a
1627 /// subset of the declarations the range [C,
1628 /// end-of-declarations). If A is non-NULL, it is a pointer to a
1629 /// member function of SpecificDecl that should return true for
1630 /// all of the SpecificDecl instances that will be in the subset
1631 /// of iterators. For example, if you want Objective-C instance
1632 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1633 /// &ObjCMethodDecl::isInstanceMethod.
1634 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1635 SkipToNextDecl();
1636 }
1637
1638 value_type operator*() const { return cast<SpecificDecl>(*Current); }
1639
1640 // This doesn't meet the iterator requirements, but it's convenient
1641 value_type operator->() const { return **this; }
1642
1643 specific_decl_iterator& operator++() {
1644 ++Current;
1645 SkipToNextDecl();
1646 return *this;
1647 }
1648
1649 specific_decl_iterator operator++(int) {
1650 specific_decl_iterator tmp(*this);
1651 ++(*this);
1652 return tmp;
1653 }
1654
1655 friend bool operator==(const specific_decl_iterator& x,
1656 const specific_decl_iterator& y) {
1657 return x.Current == y.Current;
1658 }
1659
1660 friend bool operator!=(const specific_decl_iterator& x,
1661 const specific_decl_iterator& y) {
1662 return x.Current != y.Current;
1663 }
1664 };
1665
1666 /// \brief Iterates over a filtered subrange of declarations stored
1667 /// in a DeclContext.
1668 ///
1669 /// This iterator visits only those declarations that are of type
1670 /// SpecificDecl (or a class derived from it) and that meet some
1671 /// additional run-time criteria. This iterator is used, for
1672 /// example, to provide access to the instance methods within an
1673 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
1674 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
1675 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
1676 class filtered_decl_iterator {
1677 /// Current - The current, underlying declaration iterator, which
1678 /// will either be NULL or will point to a declaration of
1679 /// type SpecificDecl.
1680 DeclContext::decl_iterator Current;
1681
1682 /// SkipToNextDecl - Advances the current position up to the next
1683 /// declaration of type SpecificDecl that also meets the criteria
1684 /// required by Acceptable.
1685 void SkipToNextDecl() {
1686 while (*Current &&
1687 (!isa<SpecificDecl>(*Current) ||
1688 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
1689 ++Current;
1690 }
1691
1692 public:
1693 using value_type = SpecificDecl *;
1694 // TODO: Add reference and pointer types (with some appropriate proxy type)
1695 // if we ever have a need for them.
1696 using reference = void;
1697 using pointer = void;
1698 using difference_type =
1699 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
1700 using iterator_category = std::forward_iterator_tag;
1701
1702 filtered_decl_iterator() = default;
1703
1704 /// filtered_decl_iterator - Construct a new iterator over a
1705 /// subset of the declarations the range [C,
1706 /// end-of-declarations). If A is non-NULL, it is a pointer to a
1707 /// member function of SpecificDecl that should return true for
1708 /// all of the SpecificDecl instances that will be in the subset
1709 /// of iterators. For example, if you want Objective-C instance
1710 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
1711 /// &ObjCMethodDecl::isInstanceMethod.
1712 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
1713 SkipToNextDecl();
1714 }
1715
1716 value_type operator*() const { return cast<SpecificDecl>(*Current); }
1717 value_type operator->() const { return cast<SpecificDecl>(*Current); }
1718
1719 filtered_decl_iterator& operator++() {
1720 ++Current;
1721 SkipToNextDecl();
1722 return *this;
1723 }
1724
1725 filtered_decl_iterator operator++(int) {
1726 filtered_decl_iterator tmp(*this);
1727 ++(*this);
1728 return tmp;
1729 }
1730
1731 friend bool operator==(const filtered_decl_iterator& x,
1732 const filtered_decl_iterator& y) {
1733 return x.Current == y.Current;
1734 }
1735
1736 friend bool operator!=(const filtered_decl_iterator& x,
1737 const filtered_decl_iterator& y) {
1738 return x.Current != y.Current;
1739 }
1740 };
1741
1742 /// @brief Add the declaration D into this context.
1743 ///
1744 /// This routine should be invoked when the declaration D has first
1745 /// been declared, to place D into the context where it was
1746 /// (lexically) defined. Every declaration must be added to one
1747 /// (and only one!) context, where it can be visited via
1748 /// [decls_begin(), decls_end()). Once a declaration has been added
1749 /// to its lexical context, the corresponding DeclContext owns the
1750 /// declaration.
1751 ///
1752 /// If D is also a NamedDecl, it will be made visible within its
1753 /// semantic context via makeDeclVisibleInContext.
1754 void addDecl(Decl *D);
1755
1756 /// @brief Add the declaration D into this context, but suppress
1757 /// searches for external declarations with the same name.
1758 ///
1759 /// Although analogous in function to addDecl, this removes an
1760 /// important check. This is only useful if the Decl is being
1761 /// added in response to an external search; in all other cases,
1762 /// addDecl() is the right function to use.
1763 /// See the ASTImporter for use cases.
1764 void addDeclInternal(Decl *D);
1765
1766 /// @brief Add the declaration D to this context without modifying
1767 /// any lookup tables.
1768 ///
1769 /// This is useful for some operations in dependent contexts where
1770 /// the semantic context might not be dependent; this basically
1771 /// only happens with friends.
1772 void addHiddenDecl(Decl *D);
1773
1774 /// @brief Removes a declaration from this context.
1775 void removeDecl(Decl *D);
1776
1777 /// @brief Checks whether a declaration is in this context.
1778 bool containsDecl(Decl *D) const;
1779
1780 using lookup_result = DeclContextLookupResult;
1781 using lookup_iterator = lookup_result::iterator;
1782
1783 /// lookup - Find the declarations (if any) with the given Name in
1784 /// this context. Returns a range of iterators that contains all of
1785 /// the declarations with this name, with object, function, member,
1786 /// and enumerator names preceding any tag name. Note that this
1787 /// routine will not look into parent contexts.
1788 lookup_result lookup(DeclarationName Name) const;
1789
1790 /// \brief Find the declarations with the given name that are visible
1791 /// within this context; don't attempt to retrieve anything from an
1792 /// external source.
1793 lookup_result noload_lookup(DeclarationName Name);
1794
1795 /// \brief A simplistic name lookup mechanism that performs name lookup
1796 /// into this declaration context without consulting the external source.
1797 ///
1798 /// This function should almost never be used, because it subverts the
1799 /// usual relationship between a DeclContext and the external source.
1800 /// See the ASTImporter for the (few, but important) use cases.
1801 ///
1802 /// FIXME: This is very inefficient; replace uses of it with uses of
1803 /// noload_lookup.
1804 void localUncachedLookup(DeclarationName Name,
1805 SmallVectorImpl<NamedDecl *> &Results);
1806
1807 /// @brief Makes a declaration visible within this context.
1808 ///
1809 /// This routine makes the declaration D visible to name lookup
1810 /// within this context and, if this is a transparent context,
1811 /// within its parent contexts up to the first enclosing
1812 /// non-transparent context. Making a declaration visible within a
1813 /// context does not transfer ownership of a declaration, and a
1814 /// declaration can be visible in many contexts that aren't its
1815 /// lexical context.
1816 ///
1817 /// If D is a redeclaration of an existing declaration that is
1818 /// visible from this context, as determined by
1819 /// NamedDecl::declarationReplaces, the previous declaration will be
1820 /// replaced with D.
1821 void makeDeclVisibleInContext(NamedDecl *D);
1822
1823 /// all_lookups_iterator - An iterator that provides a view over the results
1824 /// of looking up every possible name.
1825 class all_lookups_iterator;
1826
1827 using lookups_range = llvm::iterator_range<all_lookups_iterator>;
1828
1829 lookups_range lookups() const;
1830 // Like lookups(), but avoids loading external declarations.
1831 // If PreserveInternalState, avoids building lookup data structures too.
1832 lookups_range noload_lookups(bool PreserveInternalState) const;
1833
1834 /// \brief Iterators over all possible lookups within this context.
1835 all_lookups_iterator lookups_begin() const;
1836 all_lookups_iterator lookups_end() const;
1837
1838 /// \brief Iterators over all possible lookups within this context that are
1839 /// currently loaded; don't attempt to retrieve anything from an external
1840 /// source.
1841 all_lookups_iterator noload_lookups_begin() const;
1842 all_lookups_iterator noload_lookups_end() const;
1843
1844 struct udir_iterator;
1845
1846 using udir_iterator_base =
1847 llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
1848 std::random_access_iterator_tag,
1849 UsingDirectiveDecl *>;
1850
1851 struct udir_iterator : udir_iterator_base {
1852 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
1853
1854 UsingDirectiveDecl *operator*() const;
1855 };
1856
1857 using udir_range = llvm::iterator_range<udir_iterator>;
1858
1859 udir_range using_directives() const;
1860
1861 // These are all defined in DependentDiagnostic.h.
1862 class ddiag_iterator;
1863
1864 using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>;
1865
1866 inline ddiag_range ddiags() const;
1867
1868 // Low-level accessors
1869
1870 /// \brief Mark that there are external lexical declarations that we need
1871 /// to include in our lookup table (and that are not available as external
1872 /// visible lookups). These extra lookup results will be found by walking
1873 /// the lexical declarations of this context. This should be used only if
1874 /// setHasExternalLexicalStorage() has been called on any decl context for
1875 /// which this is the primary context.
1876 void setMustBuildLookupTable() {
1877 assert(this == getPrimaryContext() &&(static_cast <bool> (this == getPrimaryContext() &&
"should only be called on primary context") ? void (0) : __assert_fail
("this == getPrimaryContext() && \"should only be called on primary context\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 1878, __extension__ __PRETTY_FUNCTION__))
1878 "should only be called on primary context")(static_cast <bool> (this == getPrimaryContext() &&
"should only be called on primary context") ? void (0) : __assert_fail
("this == getPrimaryContext() && \"should only be called on primary context\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/DeclBase.h"
, 1878, __extension__ __PRETTY_FUNCTION__))
;
1879 HasLazyExternalLexicalLookups = true;
1880 }
1881
1882 /// \brief Retrieve the internal representation of the lookup structure.
1883 /// This may omit some names if we are lazily building the structure.
1884 StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
1885
1886 /// \brief Ensure the lookup structure is fully-built and return it.
1887 StoredDeclsMap *buildLookup();
1888
1889 /// \brief Whether this DeclContext has external storage containing
1890 /// additional declarations that are lexically in this context.
1891 bool hasExternalLexicalStorage() const { return ExternalLexicalStorage; }
1892
1893 /// \brief State whether this DeclContext has external storage for
1894 /// declarations lexically in this context.
1895 void setHasExternalLexicalStorage(bool ES = true) {
1896 ExternalLexicalStorage = ES;
1897 }
1898
1899 /// \brief Whether this DeclContext has external storage containing
1900 /// additional declarations that are visible in this context.
1901 bool hasExternalVisibleStorage() const { return ExternalVisibleStorage; }
1902
1903 /// \brief State whether this DeclContext has external storage for
1904 /// declarations visible in this context.
1905 void setHasExternalVisibleStorage(bool ES = true) {
1906 ExternalVisibleStorage = ES;
1907 if (ES && LookupPtr)
1908 NeedToReconcileExternalVisibleStorage = true;
1909 }
1910
1911 /// \brief Determine whether the given declaration is stored in the list of
1912 /// declarations lexically within this context.
1913 bool isDeclInLexicalTraversal(const Decl *D) const {
1914 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
1915 D == LastDecl);
1916 }
1917
1918 bool setUseQualifiedLookup(bool use = true) {
1919 bool old_value = UseQualifiedLookup;
1920 UseQualifiedLookup = use;
1921 return old_value;
1922 }
1923
1924 bool shouldUseQualifiedLookup() const {
1925 return UseQualifiedLookup;
1926 }
1927
1928 static bool classof(const Decl *D);
1929 static bool classof(const DeclContext *D) { return true; }
1930
1931 void dumpDeclContext() const;
1932 void dumpLookups() const;
1933 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
1934 bool Deserialize = false) const;
1935
1936private:
1937 friend class DependentDiagnostic;
1938
1939 void reconcileExternalVisibleStorage() const;
1940 bool LoadLexicalDeclsFromExternalStorage() const;
1941
1942 /// @brief Makes a declaration visible within this context, but
1943 /// suppresses searches for external declarations with the same
1944 /// name.
1945 ///
1946 /// Analogous to makeDeclVisibleInContext, but for the exclusive
1947 /// use of addDeclInternal().
1948 void makeDeclVisibleInContextInternal(NamedDecl *D);
1949
1950 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
1951
1952 void loadLazyLocalLexicalLookups();
1953 void buildLookupImpl(DeclContext *DCtx, bool Internal);
1954 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1955 bool Rediscoverable);
1956 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
1957};
1958
1959inline bool Decl::isTemplateParameter() const {
1960 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
1961 getKind() == TemplateTemplateParm;
1962}
1963
1964// Specialization selected when ToTy is not a known subclass of DeclContext.
1965template <class ToTy,
1966 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
1967struct cast_convert_decl_context {
1968 static const ToTy *doit(const DeclContext *Val) {
1969 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
1970 }
1971
1972 static ToTy *doit(DeclContext *Val) {
1973 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
1974 }
1975};
1976
1977// Specialization selected when ToTy is a known subclass of DeclContext.
1978template <class ToTy>
1979struct cast_convert_decl_context<ToTy, true> {
1980 static const ToTy *doit(const DeclContext *Val) {
1981 return static_cast<const ToTy*>(Val);
1982 }
1983
1984 static ToTy *doit(DeclContext *Val) {
1985 return static_cast<ToTy*>(Val);
1986 }
1987};
1988
1989} // namespace clang
1990
1991namespace llvm {
1992
1993/// isa<T>(DeclContext*)
1994template <typename To>
1995struct isa_impl<To, ::clang::DeclContext> {
1996 static bool doit(const ::clang::DeclContext &Val) {
1997 return To::classofKind(Val.getDeclKind());
25
Calling 'DeclContext::getDeclKind'
26
Returning from 'DeclContext::getDeclKind'
27
Calling 'NamespaceDecl::classofKind'
29
Returning from 'NamespaceDecl::classofKind'
1998 }
1999};
2000
2001/// cast<T>(DeclContext*)
2002template<class ToTy>
2003struct cast_convert_val<ToTy,
2004 const ::clang::DeclContext,const ::clang::DeclContext> {
2005 static const ToTy &doit(const ::clang::DeclContext &Val) {
2006 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2007 }
2008};
2009
2010template<class ToTy>
2011struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
2012 static ToTy &doit(::clang::DeclContext &Val) {
2013 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2014 }
2015};
2016
2017template<class ToTy>
2018struct cast_convert_val<ToTy,
2019 const ::clang::DeclContext*, const ::clang::DeclContext*> {
2020 static const ToTy *doit(const ::clang::DeclContext *Val) {
2021 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
47
Calling 'cast_convert_decl_context::doit'
48
Returning from 'cast_convert_decl_context::doit'
2022 }
2023};
2024
2025template<class ToTy>
2026struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
2027 static ToTy *doit(::clang::DeclContext *Val) {
2028 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2029 }
2030};
2031
2032/// Implement cast_convert_val for Decl -> DeclContext conversions.
2033template<class FromTy>
2034struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
2035 static ::clang::DeclContext &doit(const FromTy &Val) {
2036 return *FromTy::castToDeclContext(&Val);
2037 }
2038};
2039
2040template<class FromTy>
2041struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
2042 static ::clang::DeclContext *doit(const FromTy *Val) {
2043 return FromTy::castToDeclContext(Val);
2044 }
2045};
2046
2047template<class FromTy>
2048struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
2049 static const ::clang::DeclContext &doit(const FromTy &Val) {
2050 return *FromTy::castToDeclContext(&Val);
2051 }
2052};
2053
2054template<class FromTy>
2055struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
2056 static const ::clang::DeclContext *doit(const FromTy *Val) {
2057 return FromTy::castToDeclContext(Val);
2058 }
2059};
2060
2061} // namespace llvm
2062
2063#endif // LLVM_CLANG_AST_DECLBASE_H

/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h

1//===- Decl.h - Classes for representing declarations -----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the Decl subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_DECL_H
15#define LLVM_CLANG_AST_DECL_H
16
17#include "clang/AST/APValue.h"
18#include "clang/AST/DeclBase.h"
19#include "clang/AST/DeclarationName.h"
20#include "clang/AST/ExternalASTSource.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/Redeclarable.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/AddressSpaces.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/IdentifierTable.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/OperatorKinds.h"
30#include "clang/Basic/PartialDiagnostic.h"
31#include "clang/Basic/PragmaKinds.h"
32#include "clang/Basic/SourceLocation.h"
33#include "clang/Basic/Specifiers.h"
34#include "clang/Basic/Visibility.h"
35#include "llvm/ADT/APSInt.h"
36#include "llvm/ADT/ArrayRef.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/iterator_range.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/Compiler.h"
44#include "llvm/Support/TrailingObjects.h"
45#include <cassert>
46#include <cstddef>
47#include <cstdint>
48#include <string>
49#include <utility>
50
51namespace clang {
52
53class ASTContext;
54struct ASTTemplateArgumentListInfo;
55class Attr;
56class CompoundStmt;
57class DependentFunctionTemplateSpecializationInfo;
58class EnumDecl;
59class Expr;
60class FunctionTemplateDecl;
61class FunctionTemplateSpecializationInfo;
62class LabelStmt;
63class MemberSpecializationInfo;
64class Module;
65class NamespaceDecl;
66class ParmVarDecl;
67class RecordDecl;
68class Stmt;
69class StringLiteral;
70class TagDecl;
71class TemplateArgumentList;
72class TemplateArgumentListInfo;
73class TemplateParameterList;
74class TypeAliasTemplateDecl;
75class TypeLoc;
76class UnresolvedSetImpl;
77class VarTemplateDecl;
78
79/// A container of type source information.
80///
81/// A client can read the relevant info using TypeLoc wrappers, e.g:
82/// @code
83/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
84/// TL.getStartLoc().print(OS, SrcMgr);
85/// @endcode
86class LLVM_ALIGNAS(8)alignas(8) TypeSourceInfo {
87 // Contains a memory block after the class, used for type source information,
88 // allocated by ASTContext.
89 friend class ASTContext;
90
91 QualType Ty;
92
93 TypeSourceInfo(QualType ty) : Ty(ty) {}
94
95public:
96 /// Return the type wrapped by this type source info.
97 QualType getType() const { return Ty; }
98
99 /// Return the TypeLoc wrapper for the type source info.
100 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
101
102 /// Override the type stored in this TypeSourceInfo. Use with caution!
103 void overrideType(QualType T) { Ty = T; }
104};
105
106/// The top declaration context.
107class TranslationUnitDecl : public Decl, public DeclContext {
108 ASTContext &Ctx;
109
110 /// The (most recently entered) anonymous namespace for this
111 /// translation unit, if one has been created.
112 NamespaceDecl *AnonymousNamespace = nullptr;
113
114 explicit TranslationUnitDecl(ASTContext &ctx);
115
116 virtual void anchor();
117
118public:
119 ASTContext &getASTContext() const { return Ctx; }
120
121 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
122 void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
123
124 static TranslationUnitDecl *Create(ASTContext &C);
125
126 // Implement isa/cast/dyncast/etc.
127 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
128 static bool classofKind(Kind K) { return K == TranslationUnit; }
129 static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
130 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
131 }
132 static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
133 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
134 }
135};
136
137/// Represents a `#pragma comment` line. Always a child of
138/// TranslationUnitDecl.
139class PragmaCommentDecl final
140 : public Decl,
141 private llvm::TrailingObjects<PragmaCommentDecl, char> {
142 friend class ASTDeclReader;
143 friend class ASTDeclWriter;
144 friend TrailingObjects;
145
146 PragmaMSCommentKind CommentKind;
147
148 PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc,
149 PragmaMSCommentKind CommentKind)
150 : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {}
151
152 virtual void anchor();
153
154public:
155 static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC,
156 SourceLocation CommentLoc,
157 PragmaMSCommentKind CommentKind,
158 StringRef Arg);
159 static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID,
160 unsigned ArgSize);
161
162 PragmaMSCommentKind getCommentKind() const { return CommentKind; }
163
164 StringRef getArg() const { return getTrailingObjects<char>(); }
165
166 // Implement isa/cast/dyncast/etc.
167 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
168 static bool classofKind(Kind K) { return K == PragmaComment; }
169};
170
171/// Represents a `#pragma detect_mismatch` line. Always a child of
172/// TranslationUnitDecl.
173class PragmaDetectMismatchDecl final
174 : public Decl,
175 private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> {
176 friend class ASTDeclReader;
177 friend class ASTDeclWriter;
178 friend TrailingObjects;
179
180 size_t ValueStart;
181
182 PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc,
183 size_t ValueStart)
184 : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {}
185
186 virtual void anchor();
187
188public:
189 static PragmaDetectMismatchDecl *Create(const ASTContext &C,
190 TranslationUnitDecl *DC,
191 SourceLocation Loc, StringRef Name,
192 StringRef Value);
193 static PragmaDetectMismatchDecl *
194 CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize);
195
196 StringRef getName() const { return getTrailingObjects<char>(); }
197 StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; }
198
199 // Implement isa/cast/dyncast/etc.
200 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
201 static bool classofKind(Kind K) { return K == PragmaDetectMismatch; }
202};
203
204/// Declaration context for names declared as extern "C" in C++. This
205/// is neither the semantic nor lexical context for such declarations, but is
206/// used to check for conflicts with other extern "C" declarations. Example:
207///
208/// \code
209/// namespace N { extern "C" void f(); } // #1
210/// void N::f() {} // #2
211/// namespace M { extern "C" void f(); } // #3
212/// \endcode
213///
214/// The semantic context of #1 is namespace N and its lexical context is the
215/// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical
216/// context is the TU. However, both declarations are also visible in the
217/// extern "C" context.
218///
219/// The declaration at #3 finds it is a redeclaration of \c N::f through
220/// lookup in the extern "C" context.
221class ExternCContextDecl : public Decl, public DeclContext {
222 explicit ExternCContextDecl(TranslationUnitDecl *TU)
223 : Decl(ExternCContext, TU, SourceLocation()),
224 DeclContext(ExternCContext) {}
225
226 virtual void anchor();
227
228public:
229 static ExternCContextDecl *Create(const ASTContext &C,
230 TranslationUnitDecl *TU);
231
232 // Implement isa/cast/dyncast/etc.
233 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
234 static bool classofKind(Kind K) { return K == ExternCContext; }
235 static DeclContext *castToDeclContext(const ExternCContextDecl *D) {
236 return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D));
237 }
238 static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) {
239 return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC));
240 }
241};
242
243/// This represents a decl that may have a name. Many decls have names such
244/// as ObjCMethodDecl, but not \@class, etc.
245///
246/// Note that not every NamedDecl is actually named (e.g., a struct might
247/// be anonymous), and not every name is an identifier.
248class NamedDecl : public Decl {
249 /// The name of this declaration, which is typically a normal
250 /// identifier but may also be a special kind of name (C++
251 /// constructor, Objective-C selector, etc.)
252 DeclarationName Name;
253
254 virtual void anchor();
255
256private:
257 NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY__attribute__((__pure__));
258
259protected:
260 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
261 : Decl(DK, DC, L), Name(N) {}
262
263public:
264 /// Get the identifier that names this declaration, if there is one.
265 ///
266 /// This will return NULL if this declaration has no name (e.g., for
267 /// an unnamed class) or if the name is a special name (C++ constructor,
268 /// Objective-C selector, etc.).
269 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
270
271 /// Get the name of identifier for this declaration as a StringRef.
272 ///
273 /// This requires that the declaration have a name and that it be a simple
274 /// identifier.
275 StringRef getName() const {
276 assert(Name.isIdentifier() && "Name is not a simple identifier")(static_cast <bool> (Name.isIdentifier() && "Name is not a simple identifier"
) ? void (0) : __assert_fail ("Name.isIdentifier() && \"Name is not a simple identifier\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 276, __extension__ __PRETTY_FUNCTION__))
;
277 return getIdentifier() ? getIdentifier()->getName() : "";
278 }
279
280 /// Get a human-readable name for the declaration, even if it is one of the
281 /// special kinds of names (C++ constructor, Objective-C selector, etc).
282 ///
283 /// Creating this name requires expensive string manipulation, so it should
284 /// be called only when performance doesn't matter. For simple declarations,
285 /// getNameAsCString() should suffice.
286 //
287 // FIXME: This function should be renamed to indicate that it is not just an
288 // alternate form of getName(), and clients should move as appropriate.
289 //
290 // FIXME: Deprecated, move clients to getName().
291 std::string getNameAsString() const { return Name.getAsString(); }
292
293 virtual void printName(raw_ostream &os) const;
294
295 /// Get the actual, stored name of the declaration, which may be a special
296 /// name.
297 DeclarationName getDeclName() const { return Name; }
298
299 /// Set the name of this declaration.
300 void setDeclName(DeclarationName N) { Name = N; }
301
302 /// Returns a human-readable qualified name for this declaration, like
303 /// A::B::i, for i being member of namespace A::B.
304 ///
305 /// If the declaration is not a member of context which can be named (record,
306 /// namespace), it will return the same result as printName().
307 ///
308 /// Creating this name is expensive, so it should be called only when
309 /// performance doesn't matter.
310 void printQualifiedName(raw_ostream &OS) const;
311 void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
312
313 // FIXME: Remove string version.
314 std::string getQualifiedNameAsString() const;
315
316 /// Appends a human-readable name for this declaration into the given stream.
317 ///
318 /// This is the method invoked by Sema when displaying a NamedDecl
319 /// in a diagnostic. It does not necessarily produce the same
320 /// result as printName(); for example, class template
321 /// specializations are printed with their template arguments.
322 virtual void getNameForDiagnostic(raw_ostream &OS,
323 const PrintingPolicy &Policy,
324 bool Qualified) const;
325
326 /// Determine whether this declaration, if known to be well-formed within
327 /// its context, will replace the declaration OldD if introduced into scope.
328 ///
329 /// A declaration will replace another declaration if, for example, it is
330 /// a redeclaration of the same variable or function, but not if it is a
331 /// declaration of a different kind (function vs. class) or an overloaded
332 /// function.
333 ///
334 /// \param IsKnownNewer \c true if this declaration is known to be newer
335 /// than \p OldD (for instance, if this declaration is newly-created).
336 bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
337
338 /// Determine whether this declaration has linkage.
339 bool hasLinkage() const;
340
341 using Decl::isModulePrivate;
342 using Decl::setModulePrivate;
343
344 /// Determine whether this declaration is a C++ class member.
345 bool isCXXClassMember() const {
346 const DeclContext *DC = getDeclContext();
347
348 // C++0x [class.mem]p1:
349 // The enumerators of an unscoped enumeration defined in
350 // the class are members of the class.
351 if (isa<EnumDecl>(DC))
352 DC = DC->getRedeclContext();
353
354 return DC->isRecord();
355 }
356
357 /// Determine whether the given declaration is an instance member of
358 /// a C++ class.
359 bool isCXXInstanceMember() const;
360
361 /// Determine what kind of linkage this entity has.
362 ///
363 /// This is not the linkage as defined by the standard or the codegen notion
364 /// of linkage. It is just an implementation detail that is used to compute
365 /// those.
366 Linkage getLinkageInternal() const;
367
368 /// Get the linkage from a semantic point of view. Entities in
369 /// anonymous namespaces are external (in c++98).
370 Linkage getFormalLinkage() const {
371 return clang::getFormalLinkage(getLinkageInternal());
372 }
373
374 /// True if this decl has external linkage.
375 bool hasExternalFormalLinkage() const {
376 return isExternalFormalLinkage(getLinkageInternal());
377 }
378
379 bool isExternallyVisible() const {
380 return clang::isExternallyVisible(getLinkageInternal());
381 }
382
383 /// Determine whether this declaration can be redeclared in a
384 /// different translation unit.
385 bool isExternallyDeclarable() const {
386 return isExternallyVisible() && !getOwningModuleForLinkage();
387 }
388
389 /// Determines the visibility of this entity.
390 Visibility getVisibility() const {
391 return getLinkageAndVisibility().getVisibility();
392 }
393
394 /// Determines the linkage and visibility of this entity.
395 LinkageInfo getLinkageAndVisibility() const;
396
397 /// Kinds of explicit visibility.
398 enum ExplicitVisibilityKind {
399 /// Do an LV computation for, ultimately, a type.
400 /// Visibility may be restricted by type visibility settings and
401 /// the visibility of template arguments.
402 VisibilityForType,
403
404 /// Do an LV computation for, ultimately, a non-type declaration.
405 /// Visibility may be restricted by value visibility settings and
406 /// the visibility of template arguments.
407 VisibilityForValue
408 };
409
410 /// If visibility was explicitly specified for this
411 /// declaration, return that visibility.
412 Optional<Visibility>
413 getExplicitVisibility(ExplicitVisibilityKind kind) const;
414
415 /// True if the computed linkage is valid. Used for consistency
416 /// checking. Should always return true.
417 bool isLinkageValid() const;
418
419 /// True if something has required us to compute the linkage
420 /// of this declaration.
421 ///
422 /// Language features which can retroactively change linkage (like a
423 /// typedef name for linkage purposes) may need to consider this,
424 /// but hopefully only in transitory ways during parsing.
425 bool hasLinkageBeenComputed() const {
426 return hasCachedLinkage();
427 }
428
429 /// Looks through UsingDecls and ObjCCompatibleAliasDecls for
430 /// the underlying named decl.
431 NamedDecl *getUnderlyingDecl() {
432 // Fast-path the common case.
433 if (this->getKind() != UsingShadow &&
434 this->getKind() != ConstructorUsingShadow &&
435 this->getKind() != ObjCCompatibleAlias &&
436 this->getKind() != NamespaceAlias)
437 return this;
438
439 return getUnderlyingDeclImpl();
440 }
441 const NamedDecl *getUnderlyingDecl() const {
442 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
443 }
444
445 NamedDecl *getMostRecentDecl() {
446 return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
447 }
448 const NamedDecl *getMostRecentDecl() const {
449 return const_cast<NamedDecl*>(this)->getMostRecentDecl();
450 }
451
452 ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
453
454 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
455 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
456};
457
458inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
459 ND.printName(OS);
460 return OS;
461}
462
463/// Represents the declaration of a label. Labels also have a
464/// corresponding LabelStmt, which indicates the position that the label was
465/// defined at. For normal labels, the location of the decl is the same as the
466/// location of the statement. For GNU local labels (__label__), the decl
467/// location is where the __label__ is.
468class LabelDecl : public NamedDecl {
469 LabelStmt *TheStmt;
470 StringRef MSAsmName;
471 bool MSAsmNameResolved = false;
472
473 /// For normal labels, this is the same as the main declaration
474 /// label, i.e., the location of the identifier; for GNU local labels,
475 /// this is the location of the __label__ keyword.
476 SourceLocation LocStart;
477
478 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
479 LabelStmt *S, SourceLocation StartL)
480 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
481
482 void anchor() override;
483
484public:
485 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
486 SourceLocation IdentL, IdentifierInfo *II);
487 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
488 SourceLocation IdentL, IdentifierInfo *II,
489 SourceLocation GnuLabelL);
490 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
491
492 LabelStmt *getStmt() const { return TheStmt; }
493 void setStmt(LabelStmt *T) { TheStmt = T; }
494
495 bool isGnuLocal() const { return LocStart != getLocation(); }
496 void setLocStart(SourceLocation L) { LocStart = L; }
497
498 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
499 return SourceRange(LocStart, getLocation());
500 }
501
502 bool isMSAsmLabel() const { return !MSAsmName.empty(); }
503 bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
504 void setMSAsmLabel(StringRef Name);
505 StringRef getMSAsmLabel() const { return MSAsmName; }
506 void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
507
508 // Implement isa/cast/dyncast/etc.
509 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
510 static bool classofKind(Kind K) { return K == Label; }
511};
512
513/// Represent a C++ namespace.
514class NamespaceDecl : public NamedDecl, public DeclContext,
515 public Redeclarable<NamespaceDecl>
516{
517 /// The starting location of the source range, pointing
518 /// to either the namespace or the inline keyword.
519 SourceLocation LocStart;
520
521 /// The ending location of the source range.
522 SourceLocation RBraceLoc;
523
524 /// A pointer to either the anonymous namespace that lives just inside
525 /// this namespace or to the first namespace in the chain (the latter case
526 /// only when this is not the first in the chain), along with a
527 /// boolean value indicating whether this is an inline namespace.
528 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
529
530 NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
531 SourceLocation StartLoc, SourceLocation IdLoc,
532 IdentifierInfo *Id, NamespaceDecl *PrevDecl);
533
534 using redeclarable_base = Redeclarable<NamespaceDecl>;
535
536 NamespaceDecl *getNextRedeclarationImpl() override;
537 NamespaceDecl *getPreviousDeclImpl() override;
538 NamespaceDecl *getMostRecentDeclImpl() override;
539
540public:
541 friend class ASTDeclReader;
542 friend class ASTDeclWriter;
543
544 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
545 bool Inline, SourceLocation StartLoc,
546 SourceLocation IdLoc, IdentifierInfo *Id,
547 NamespaceDecl *PrevDecl);
548
549 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
550
551 using redecl_range = redeclarable_base::redecl_range;
552 using redecl_iterator = redeclarable_base::redecl_iterator;
553
554 using redeclarable_base::redecls_begin;
555 using redeclarable_base::redecls_end;
556 using redeclarable_base::redecls;
557 using redeclarable_base::getPreviousDecl;
558 using redeclarable_base::getMostRecentDecl;
559 using redeclarable_base::isFirstDecl;
560
561 /// Returns true if this is an anonymous namespace declaration.
562 ///
563 /// For example:
564 /// \code
565 /// namespace {
566 /// ...
567 /// };
568 /// \endcode
569 /// q.v. C++ [namespace.unnamed]
570 bool isAnonymousNamespace() const {
571 return !getIdentifier();
572 }
573
574 /// Returns true if this is an inline namespace declaration.
575 bool isInline() const {
576 return AnonOrFirstNamespaceAndInline.getInt();
577 }
578
579 /// Set whether this is an inline namespace declaration.
580 void setInline(bool Inline) {
581 AnonOrFirstNamespaceAndInline.setInt(Inline);
582 }
583
584 /// Get the original (first) namespace declaration.
585 NamespaceDecl *getOriginalNamespace();
586
587 /// Get the original (first) namespace declaration.
588 const NamespaceDecl *getOriginalNamespace() const;
589
590 /// Return true if this declaration is an original (first) declaration
591 /// of the namespace. This is false for non-original (subsequent) namespace
592 /// declarations and anonymous namespaces.
593 bool isOriginalNamespace() const;
594
595 /// Retrieve the anonymous namespace nested inside this namespace,
596 /// if any.
597 NamespaceDecl *getAnonymousNamespace() const {
598 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
599 }
600
601 void setAnonymousNamespace(NamespaceDecl *D) {
602 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
603 }
604
605 /// Retrieves the canonical declaration of this namespace.
606 NamespaceDecl *getCanonicalDecl() override {
607 return getOriginalNamespace();
608 }
609 const NamespaceDecl *getCanonicalDecl() const {
610 return getOriginalNamespace();
611 }
612
613 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
614 return SourceRange(LocStart, RBraceLoc);
615 }
616
617 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
618 SourceLocation getRBraceLoc() const { return RBraceLoc; }
619 void setLocStart(SourceLocation L) { LocStart = L; }
620 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
621
622 // Implement isa/cast/dyncast/etc.
623 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
624 static bool classofKind(Kind K) { return K == Namespace; }
28
Assuming 'K' is equal to Namespace
625 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
626 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
627 }
628 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
629 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
630 }
631};
632
633/// Represent the declaration of a variable (in which case it is
634/// an lvalue) a function (in which case it is a function designator) or
635/// an enum constant.
636class ValueDecl : public NamedDecl {
637 QualType DeclType;
638
639 void anchor() override;
640
641protected:
642 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
643 DeclarationName N, QualType T)
644 : NamedDecl(DK, DC, L, N), DeclType(T) {}
645
646public:
647 QualType getType() const { return DeclType; }
648 void setType(QualType newType) { DeclType = newType; }
649
650 /// Determine whether this symbol is weakly-imported,
651 /// or declared with the weak or weak-ref attr.
652 bool isWeak() const;
653
654 // Implement isa/cast/dyncast/etc.
655 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
656 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
657};
658
659/// A struct with extended info about a syntactic
660/// name qualifier, to be used for the case of out-of-line declarations.
661struct QualifierInfo {
662 NestedNameSpecifierLoc QualifierLoc;
663
664 /// The number of "outer" template parameter lists.
665 /// The count includes all of the template parameter lists that were matched
666 /// against the template-ids occurring into the NNS and possibly (in the
667 /// case of an explicit specialization) a final "template <>".
668 unsigned NumTemplParamLists = 0;
669
670 /// A new-allocated array of size NumTemplParamLists,
671 /// containing pointers to the "outer" template parameter lists.
672 /// It includes all of the template parameter lists that were matched
673 /// against the template-ids occurring into the NNS and possibly (in the
674 /// case of an explicit specialization) a final "template <>".
675 TemplateParameterList** TemplParamLists = nullptr;
676
677 QualifierInfo() = default;
678 QualifierInfo(const QualifierInfo &) = delete;
679 QualifierInfo& operator=(const QualifierInfo &) = delete;
680
681 /// Sets info about "outer" template parameter lists.
682 void setTemplateParameterListsInfo(ASTContext &Context,
683 ArrayRef<TemplateParameterList *> TPLists);
684};
685
686/// Represents a ValueDecl that came out of a declarator.
687/// Contains type source information through TypeSourceInfo.
688class DeclaratorDecl : public ValueDecl {
689 // A struct representing both a TInfo and a syntactic qualifier,
690 // to be used for the (uncommon) case of out-of-line declarations.
691 struct ExtInfo : public QualifierInfo {
692 TypeSourceInfo *TInfo;
693 };
694
695 llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo;
696
697 /// The start of the source range for this declaration,
698 /// ignoring outer template declarations.
699 SourceLocation InnerLocStart;
700
701 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
702 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
703 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
704
705protected:
706 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
707 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
708 SourceLocation StartL)
709 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {}
710
711public:
712 friend class ASTDeclReader;
713 friend class ASTDeclWriter;
714
715 TypeSourceInfo *getTypeSourceInfo() const {
716 return hasExtInfo()
717 ? getExtInfo()->TInfo
718 : DeclInfo.get<TypeSourceInfo*>();
719 }
720
721 void setTypeSourceInfo(TypeSourceInfo *TI) {
722 if (hasExtInfo())
723 getExtInfo()->TInfo = TI;
724 else
725 DeclInfo = TI;
726 }
727
728 /// Return start of source range ignoring outer template declarations.
729 SourceLocation getInnerLocStart() const { return InnerLocStart; }
730 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
731
732 /// Return start of source range taking into account any outer template
733 /// declarations.
734 SourceLocation getOuterLocStart() const;
735
736 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
737
738 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
739 return getOuterLocStart();
740 }
741
742 /// Retrieve the nested-name-specifier that qualifies the name of this
743 /// declaration, if it was present in the source.
744 NestedNameSpecifier *getQualifier() const {
745 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
746 : nullptr;
747 }
748
749 /// Retrieve the nested-name-specifier (with source-location
750 /// information) that qualifies the name of this declaration, if it was
751 /// present in the source.
752 NestedNameSpecifierLoc getQualifierLoc() const {
753 return hasExtInfo() ? getExtInfo()->QualifierLoc
754 : NestedNameSpecifierLoc();
755 }
756
757 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
758
759 unsigned getNumTemplateParameterLists() const {
760 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
761 }
762
763 TemplateParameterList *getTemplateParameterList(unsigned index) const {
764 assert(index < getNumTemplateParameterLists())(static_cast <bool> (index < getNumTemplateParameterLists
()) ? void (0) : __assert_fail ("index < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 764, __extension__ __PRETTY_FUNCTION__))
;
765 return getExtInfo()->TemplParamLists[index];
766 }
767
768 void setTemplateParameterListsInfo(ASTContext &Context,
769 ArrayRef<TemplateParameterList *> TPLists);
770
771 SourceLocation getTypeSpecStartLoc() const;
772
773 // Implement isa/cast/dyncast/etc.
774 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
775 static bool classofKind(Kind K) {
776 return K >= firstDeclarator && K <= lastDeclarator;
777 }
778};
779
780/// Structure used to store a statement, the constant value to
781/// which it was evaluated (if any), and whether or not the statement
782/// is an integral constant expression (if known).
783struct EvaluatedStmt {
784 /// Whether this statement was already evaluated.
785 bool WasEvaluated : 1;
786
787 /// Whether this statement is being evaluated.
788 bool IsEvaluating : 1;
789
790 /// Whether we already checked whether this statement was an
791 /// integral constant expression.
792 bool CheckedICE : 1;
793
794 /// Whether we are checking whether this statement is an
795 /// integral constant expression.
796 bool CheckingICE : 1;
797
798 /// Whether this statement is an integral constant expression,
799 /// or in C++11, whether the statement is a constant expression. Only
800 /// valid if CheckedICE is true.
801 bool IsICE : 1;
802
803 Stmt *Value;
804 APValue Evaluated;
805
806 EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
807 CheckingICE(false), IsICE(false) {}
808
809};
810
811/// Represents a variable declaration or definition.
812class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
813public:
814 /// Initialization styles.
815 enum InitializationStyle {
816 /// C-style initialization with assignment
817 CInit,
818
819 /// Call-style initialization (C++98)
820 CallInit,
821
822 /// Direct list-initialization (C++11)
823 ListInit
824 };
825
826 /// Kinds of thread-local storage.
827 enum TLSKind {
828 /// Not a TLS variable.
829 TLS_None,
830
831 /// TLS with a known-constant initializer.
832 TLS_Static,
833
834 /// TLS with a dynamic initializer.
835 TLS_Dynamic
836 };
837
838 /// Return the string used to specify the storage class \p SC.
839 ///
840 /// It is illegal to call this function with SC == None.
841 static const char *getStorageClassSpecifierString(StorageClass SC);
842
843protected:
844 // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
845 // have allocated the auxiliary struct of information there.
846 //
847 // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
848 // this as *many* VarDecls are ParmVarDecls that don't have default
849 // arguments. We could save some space by moving this pointer union to be
850 // allocated in trailing space when necessary.
851 using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
852
853 /// The initializer for this variable or, for a ParmVarDecl, the
854 /// C++ default argument.
855 mutable InitType Init;
856
857private:
858 friend class ASTDeclReader;
859 friend class ASTNodeImporter;
860 friend class StmtIteratorBase;
861
862 class VarDeclBitfields {
863 friend class ASTDeclReader;
864 friend class VarDecl;
865
866 unsigned SClass : 3;
867 unsigned TSCSpec : 2;
868 unsigned InitStyle : 2;
869 };
870 enum { NumVarDeclBits = 7 };
871
872protected:
873 enum { NumParameterIndexBits = 8 };
874
875 enum DefaultArgKind {
876 DAK_None,
877 DAK_Unparsed,
878 DAK_Uninstantiated,
879 DAK_Normal
880 };
881
882 class ParmVarDeclBitfields {
883 friend class ASTDeclReader;
884 friend class ParmVarDecl;
885
886 unsigned : NumVarDeclBits;
887
888 /// Whether this parameter inherits a default argument from a
889 /// prior declaration.
890 unsigned HasInheritedDefaultArg : 1;
891
892 /// Describes the kind of default argument for this parameter. By default
893 /// this is none. If this is normal, then the default argument is stored in
894 /// the \c VarDecl initializer expression unless we were unable to parse
895 /// (even an invalid) expression for the default argument.
896 unsigned DefaultArgKind : 2;
897
898 /// Whether this parameter undergoes K&R argument promotion.
899 unsigned IsKNRPromoted : 1;
900
901 /// Whether this parameter is an ObjC method parameter or not.
902 unsigned IsObjCMethodParam : 1;
903
904 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
905 /// Otherwise, the number of function parameter scopes enclosing
906 /// the function parameter scope in which this parameter was
907 /// declared.
908 unsigned ScopeDepthOrObjCQuals : 7;
909
910 /// The number of parameters preceding this parameter in the
911 /// function parameter scope in which it was declared.
912 unsigned ParameterIndex : NumParameterIndexBits;
913 };
914
915 class NonParmVarDeclBitfields {
916 friend class ASTDeclReader;
917 friend class ImplicitParamDecl;
918 friend class VarDecl;
919
920 unsigned : NumVarDeclBits;
921
922 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
923 /// Whether this variable is a definition which was demoted due to
924 /// module merge.
925 unsigned IsThisDeclarationADemotedDefinition : 1;
926
927 /// Whether this variable is the exception variable in a C++ catch
928 /// or an Objective-C @catch statement.
929 unsigned ExceptionVar : 1;
930
931 /// Whether this local variable could be allocated in the return
932 /// slot of its function, enabling the named return value optimization
933 /// (NRVO).
934 unsigned NRVOVariable : 1;
935
936 /// Whether this variable is the for-range-declaration in a C++0x
937 /// for-range statement.
938 unsigned CXXForRangeDecl : 1;
939
940 /// Whether this variable is an ARC pseudo-__strong
941 /// variable; see isARCPseudoStrong() for details.
942 unsigned ARCPseudoStrong : 1;
943
944 /// Whether this variable is (C++1z) inline.
945 unsigned IsInline : 1;
946
947 /// Whether this variable has (C++1z) inline explicitly specified.
948 unsigned IsInlineSpecified : 1;
949
950 /// Whether this variable is (C++0x) constexpr.
951 unsigned IsConstexpr : 1;
952
953 /// Whether this variable is the implicit variable for a lambda
954 /// init-capture.
955 unsigned IsInitCapture : 1;
956
957 /// Whether this local extern variable's previous declaration was
958 /// declared in the same block scope. This controls whether we should merge
959 /// the type of this declaration with its previous declaration.
960 unsigned PreviousDeclInSameBlockScope : 1;
961
962 /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
963 /// something else.
964 unsigned ImplicitParamKind : 3;
965 };
966
967 union {
968 unsigned AllBits;
969 VarDeclBitfields VarDeclBits;
970 ParmVarDeclBitfields ParmVarDeclBits;
971 NonParmVarDeclBitfields NonParmVarDeclBits;
972 };
973
974 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
975 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
976 TypeSourceInfo *TInfo, StorageClass SC);
977
978 using redeclarable_base = Redeclarable<VarDecl>;
979
980 VarDecl *getNextRedeclarationImpl() override {
981 return getNextRedeclaration();
982 }
983
984 VarDecl *getPreviousDeclImpl() override {
985 return getPreviousDecl();
986 }
987
988 VarDecl *getMostRecentDeclImpl() override {
989 return getMostRecentDecl();
990 }
991
992public:
993 using redecl_range = redeclarable_base::redecl_range;
994 using redecl_iterator = redeclarable_base::redecl_iterator;
995
996 using redeclarable_base::redecls_begin;
997 using redeclarable_base::redecls_end;
998 using redeclarable_base::redecls;
999 using redeclarable_base::getPreviousDecl;
1000 using redeclarable_base::getMostRecentDecl;
1001 using redeclarable_base::isFirstDecl;
1002
1003 static VarDecl *Create(ASTContext &C, DeclContext *DC,
1004 SourceLocation StartLoc, SourceLocation IdLoc,
1005 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1006 StorageClass S);
1007
1008 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1009
1010 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1011
1012 /// Returns the storage class as written in the source. For the
1013 /// computed linkage of symbol, see getLinkage.
1014 StorageClass getStorageClass() const {
1015 return (StorageClass) VarDeclBits.SClass;
1016 }
1017 void setStorageClass(StorageClass SC);
1018
1019 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1020 VarDeclBits.TSCSpec = TSC;
1021 assert(VarDeclBits.TSCSpec == TSC && "truncation")(static_cast <bool> (VarDeclBits.TSCSpec == TSC &&
"truncation") ? void (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1021, __extension__ __PRETTY_FUNCTION__))
;
1022 }
1023 ThreadStorageClassSpecifier getTSCSpec() const {
1024 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1025 }
1026 TLSKind getTLSKind() const;
1027
1028 /// Returns true if a variable with function scope is a non-static local
1029 /// variable.
1030 bool hasLocalStorage() const {
1031 if (getStorageClass() == SC_None) {
1032 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1033 // used to describe variables allocated in global memory and which are
1034 // accessed inside a kernel(s) as read-only variables. As such, variables
1035 // in constant address space cannot have local storage.
1036 if (getType().getAddressSpace() == LangAS::opencl_constant)
1037 return false;
1038 // Second check is for C++11 [dcl.stc]p4.
1039 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1040 }
1041
1042 // Global Named Register (GNU extension)
1043 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
1044 return false;
1045
1046 // Return true for: Auto, Register.
1047 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1048
1049 return getStorageClass() >= SC_Auto;
1050 }
1051
1052 /// Returns true if a variable with function scope is a static local
1053 /// variable.
1054 bool isStaticLocal() const {
1055 return (getStorageClass() == SC_Static ||
1056 // C++11 [dcl.stc]p4
1057 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1058 && !isFileVarDecl();
1059 }
1060
1061 /// Returns true if a variable has extern or __private_extern__
1062 /// storage.
1063 bool hasExternalStorage() const {
1064 return getStorageClass() == SC_Extern ||
1065 getStorageClass() == SC_PrivateExtern;
1066 }
1067
1068 /// Returns true for all variables that do not have local storage.
1069 ///
1070 /// This includes all global variables as well as static variables declared
1071 /// within a function.
1072 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1073
1074 /// Get the storage duration of this variable, per C++ [basic.stc].
1075 StorageDuration getStorageDuration() const {
1076 return hasLocalStorage() ? SD_Automatic :
1077 getTSCSpec() ? SD_Thread : SD_Static;
1078 }
1079
1080 /// Compute the language linkage.
1081 LanguageLinkage getLanguageLinkage() const;
1082
1083 /// Determines whether this variable is a variable with external, C linkage.
1084 bool isExternC() const;
1085
1086 /// Determines whether this variable's context is, or is nested within,
1087 /// a C++ extern "C" linkage spec.
1088 bool isInExternCContext() const;
1089
1090 /// Determines whether this variable's context is, or is nested within,
1091 /// a C++ extern "C++" linkage spec.
1092 bool isInExternCXXContext() const;
1093
1094 /// Returns true for local variable declarations other than parameters.
1095 /// Note that this includes static variables inside of functions. It also
1096 /// includes variables inside blocks.
1097 ///
1098 /// void foo() { int x; static int y; extern int z; }
1099 bool isLocalVarDecl() const {
1100 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1101 return false;
1102 if (const DeclContext *DC = getLexicalDeclContext())
1103 return DC->getRedeclContext()->isFunctionOrMethod();
1104 return false;
1105 }
1106
1107 /// Similar to isLocalVarDecl but also includes parameters.
1108 bool isLocalVarDeclOrParm() const {
1109 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1110 }
1111
1112 /// Similar to isLocalVarDecl, but excludes variables declared in blocks.
1113 bool isFunctionOrMethodVarDecl() const {
1114 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1115 return false;
1116 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1117 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1118 }
1119
1120 /// Determines whether this is a static data member.
1121 ///
1122 /// This will only be true in C++, and applies to, e.g., the
1123 /// variable 'x' in:
1124 /// \code
1125 /// struct S {
1126 /// static int x;
1127 /// };
1128 /// \endcode
1129 bool isStaticDataMember() const {
1130 // If it wasn't static, it would be a FieldDecl.
1131 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1132 }
1133
1134 VarDecl *getCanonicalDecl() override;
1135 const VarDecl *getCanonicalDecl() const {
1136 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1137 }
1138
1139 enum DefinitionKind {
1140 /// This declaration is only a declaration.
1141 DeclarationOnly,
1142
1143 /// This declaration is a tentative definition.
1144 TentativeDefinition,
1145
1146 /// This declaration is definitely a definition.
1147 Definition
1148 };
1149
1150 /// Check whether this declaration is a definition. If this could be
1151 /// a tentative definition (in C), don't check whether there's an overriding
1152 /// definition.
1153 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1154 DefinitionKind isThisDeclarationADefinition() const {
1155 return isThisDeclarationADefinition(getASTContext());
1156 }
1157
1158 /// Check whether this variable is defined in this translation unit.
1159 DefinitionKind hasDefinition(ASTContext &) const;
1160 DefinitionKind hasDefinition() const {
1161 return hasDefinition(getASTContext());
1162 }
1163
1164 /// Get the tentative definition that acts as the real definition in a TU.
1165 /// Returns null if there is a proper definition available.
1166 VarDecl *getActingDefinition();
1167 const VarDecl *getActingDefinition() const {
1168 return const_cast<VarDecl*>(this)->getActingDefinition();
1169 }
1170
1171 /// Get the real (not just tentative) definition for this declaration.
1172 VarDecl *getDefinition(ASTContext &);
1173 const VarDecl *getDefinition(ASTContext &C) const {
1174 return const_cast<VarDecl*>(this)->getDefinition(C);
1175 }
1176 VarDecl *getDefinition() {
1177 return getDefinition(getASTContext());
1178 }
1179 const VarDecl *getDefinition() const {
1180 return const_cast<VarDecl*>(this)->getDefinition();
1181 }
1182
1183 /// Determine whether this is or was instantiated from an out-of-line
1184 /// definition of a static data member.
1185 bool isOutOfLine() const override;
1186
1187 /// Returns true for file scoped variable declaration.
1188 bool isFileVarDecl() const {
1189 Kind K = getKind();
1190 if (K == ParmVar || K == ImplicitParam)
1191 return false;
1192
1193 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1194 return true;
1195
1196 if (isStaticDataMember())
1197 return true;
1198
1199 return false;
1200 }
1201
1202 /// Get the initializer for this variable, no matter which
1203 /// declaration it is attached to.
1204 const Expr *getAnyInitializer() const {
1205 const VarDecl *D;
1206 return getAnyInitializer(D);
1207 }
1208
1209 /// Get the initializer for this variable, no matter which
1210 /// declaration it is attached to. Also get that declaration.
1211 const Expr *getAnyInitializer(const VarDecl *&D) const;
1212
1213 bool hasInit() const;
1214 const Expr *getInit() const {
1215 return const_cast<VarDecl *>(this)->getInit();
1216 }
1217 Expr *getInit();
1218
1219 /// Retrieve the address of the initializer expression.
1220 Stmt **getInitAddress();
1221
1222 void setInit(Expr *I);
1223
1224 /// Determine whether this variable's value can be used in a
1225 /// constant expression, according to the relevant language standard.
1226 /// This only checks properties of the declaration, and does not check
1227 /// whether the initializer is in fact a constant expression.
1228 bool isUsableInConstantExpressions(ASTContext &C) const;
1229
1230 EvaluatedStmt *ensureEvaluatedStmt() const;
1231
1232 /// \brief Attempt to evaluate the value of the initializer attached to this
1233 /// declaration, and produce notes explaining why it cannot be evaluated or is
1234 /// not a constant expression. Returns a pointer to the value if evaluation
1235 /// succeeded, 0 otherwise.
1236 APValue *evaluateValue() const;
1237 APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1238
1239 /// \brief Return the already-evaluated value of this variable's
1240 /// initializer, or NULL if the value is not yet known. Returns pointer
1241 /// to untyped APValue if the value could not be evaluated.
1242 APValue *getEvaluatedValue() const;
1243
1244 /// \brief Determines whether it is already known whether the
1245 /// initializer is an integral constant expression or not.
1246 bool isInitKnownICE() const;
1247
1248 /// \brief Determines whether the initializer is an integral constant
1249 /// expression, or in C++11, whether the initializer is a constant
1250 /// expression.
1251 ///
1252 /// \pre isInitKnownICE()
1253 bool isInitICE() const;
1254
1255 /// \brief Determine whether the value of the initializer attached to this
1256 /// declaration is an integral constant expression.
1257 bool checkInitIsICE() const;
1258
1259 void setInitStyle(InitializationStyle Style) {
1260 VarDeclBits.InitStyle = Style;
1261 }
1262
1263 /// \brief The style of initialization for this declaration.
1264 ///
1265 /// C-style initialization is "int x = 1;". Call-style initialization is
1266 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
1267 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor
1268 /// expression for class types. List-style initialization is C++11 syntax,
1269 /// e.g. "int x{1};". Clients can distinguish between different forms of
1270 /// initialization by checking this value. In particular, "int x = {1};" is
1271 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
1272 /// Init expression in all three cases is an InitListExpr.
1273 InitializationStyle getInitStyle() const {
1274 return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
1275 }
1276
1277 /// \brief Whether the initializer is a direct-initializer (list or call).
1278 bool isDirectInit() const {
1279 return getInitStyle() != CInit;
1280 }
1281
1282 /// \brief If this definition should pretend to be a declaration.
1283 bool isThisDeclarationADemotedDefinition() const {
1284 return isa<ParmVarDecl>(this) ? false :
1285 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition;
1286 }
1287
1288 /// \brief This is a definition which should be demoted to a declaration.
1289 ///
1290 /// In some cases (mostly module merging) we can end up with two visible
1291 /// definitions one of which needs to be demoted to a declaration to keep
1292 /// the AST invariants.
1293 void demoteThisDefinitionToDeclaration() {
1294 assert(isThisDeclarationADefinition() && "Not a definition!")(static_cast <bool> (isThisDeclarationADefinition() &&
"Not a definition!") ? void (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1294, __extension__ __PRETTY_FUNCTION__))
;
1295 assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!")(static_cast <bool> (!isa<ParmVarDecl>(this) &&
"Cannot demote ParmVarDecls!") ? void (0) : __assert_fail ("!isa<ParmVarDecl>(this) && \"Cannot demote ParmVarDecls!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1295, __extension__ __PRETTY_FUNCTION__))
;
1296 NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1;
1297 }
1298
1299 /// \brief Determine whether this variable is the exception variable in a
1300 /// C++ catch statememt or an Objective-C \@catch statement.
1301 bool isExceptionVariable() const {
1302 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
1303 }
1304 void setExceptionVariable(bool EV) {
1305 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1305, __extension__ __PRETTY_FUNCTION__))
;
1306 NonParmVarDeclBits.ExceptionVar = EV;
1307 }
1308
1309 /// \brief Determine whether this local variable can be used with the named
1310 /// return value optimization (NRVO).
1311 ///
1312 /// The named return value optimization (NRVO) works by marking certain
1313 /// non-volatile local variables of class type as NRVO objects. These
1314 /// locals can be allocated within the return slot of their containing
1315 /// function, in which case there is no need to copy the object to the
1316 /// return slot when returning from the function. Within the function body,
1317 /// each return that returns the NRVO object will have this variable as its
1318 /// NRVO candidate.
1319 bool isNRVOVariable() const {
1320 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
1321 }
1322 void setNRVOVariable(bool NRVO) {
1323 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1323, __extension__ __PRETTY_FUNCTION__))
;
1324 NonParmVarDeclBits.NRVOVariable = NRVO;
1325 }
1326
1327 /// \brief Determine whether this variable is the for-range-declaration in
1328 /// a C++0x for-range statement.
1329 bool isCXXForRangeDecl() const {
1330 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
1331 }
1332 void setCXXForRangeDecl(bool FRD) {
1333 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1333, __extension__ __PRETTY_FUNCTION__))
;
1334 NonParmVarDeclBits.CXXForRangeDecl = FRD;
1335 }
1336
1337 /// \brief Determine whether this variable is an ARC pseudo-__strong
1338 /// variable. A pseudo-__strong variable has a __strong-qualified
1339 /// type but does not actually retain the object written into it.
1340 /// Generally such variables are also 'const' for safety.
1341 bool isARCPseudoStrong() const {
1342 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ARCPseudoStrong;
1343 }
1344 void setARCPseudoStrong(bool ps) {
1345 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1345, __extension__ __PRETTY_FUNCTION__))
;
1346 NonParmVarDeclBits.ARCPseudoStrong = ps;
1347 }
1348
1349 /// Whether this variable is (C++1z) inline.
1350 bool isInline() const {
1351 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline;
1352 }
1353 bool isInlineSpecified() const {
1354 return isa<ParmVarDecl>(this) ? false
1355 : NonParmVarDeclBits.IsInlineSpecified;
1356 }
1357 void setInlineSpecified() {
1358 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1358, __extension__ __PRETTY_FUNCTION__))
;
1359 NonParmVarDeclBits.IsInline = true;
1360 NonParmVarDeclBits.IsInlineSpecified = true;
1361 }
1362 void setImplicitlyInline() {
1363 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1363, __extension__ __PRETTY_FUNCTION__))
;
1364 NonParmVarDeclBits.IsInline = true;
1365 }
1366
1367 /// Whether this variable is (C++11) constexpr.
1368 bool isConstexpr() const {
1369 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
1370 }
1371 void setConstexpr(bool IC) {
1372 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1372, __extension__ __PRETTY_FUNCTION__))
;
1373 NonParmVarDeclBits.IsConstexpr = IC;
1374 }
1375
1376 /// Whether this variable is the implicit variable for a lambda init-capture.
1377 bool isInitCapture() const {
1378 return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
1379 }
1380 void setInitCapture(bool IC) {
1381 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1381, __extension__ __PRETTY_FUNCTION__))
;
1382 NonParmVarDeclBits.IsInitCapture = IC;
1383 }
1384
1385 /// Whether this local extern variable declaration's previous declaration
1386 /// was declared in the same block scope. Only correct in C++.
1387 bool isPreviousDeclInSameBlockScope() const {
1388 return isa<ParmVarDecl>(this)
1389 ? false
1390 : NonParmVarDeclBits.PreviousDeclInSameBlockScope;
1391 }
1392 void setPreviousDeclInSameBlockScope(bool Same) {
1393 assert(!isa<ParmVarDecl>(this))(static_cast <bool> (!isa<ParmVarDecl>(this)) ? void
(0) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1393, __extension__ __PRETTY_FUNCTION__))
;
1394 NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
1395 }
1396
1397 /// \brief Retrieve the variable declaration from which this variable could
1398 /// be instantiated, if it is an instantiation (rather than a non-template).
1399 VarDecl *getTemplateInstantiationPattern() const;
1400
1401 /// \brief If this variable is an instantiated static data member of a
1402 /// class template specialization, returns the templated static data member
1403 /// from which it was instantiated.
1404 VarDecl *getInstantiatedFromStaticDataMember() const;
1405
1406 /// \brief If this variable is an instantiation of a variable template or a
1407 /// static data member of a class template, determine what kind of
1408 /// template specialization or instantiation this is.
1409 TemplateSpecializationKind getTemplateSpecializationKind() const;
1410
1411 /// \brief If this variable is an instantiation of a variable template or a
1412 /// static data member of a class template, determine its point of
1413 /// instantiation.
1414 SourceLocation getPointOfInstantiation() const;
1415
1416 /// \brief If this variable is an instantiation of a static data member of a
1417 /// class template specialization, retrieves the member specialization
1418 /// information.
1419 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1420
1421 /// \brief For a static data member that was instantiated from a static
1422 /// data member of a class template, set the template specialiation kind.
1423 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1424 SourceLocation PointOfInstantiation = SourceLocation());
1425
1426 /// \brief Specify that this variable is an instantiation of the
1427 /// static data member VD.
1428 void setInstantiationOfStaticDataMember(VarDecl *VD,
1429 TemplateSpecializationKind TSK);
1430
1431 /// \brief Retrieves the variable template that is described by this
1432 /// variable declaration.
1433 ///
1434 /// Every variable template is represented as a VarTemplateDecl and a
1435 /// VarDecl. The former contains template properties (such as
1436 /// the template parameter lists) while the latter contains the
1437 /// actual description of the template's
1438 /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
1439 /// VarDecl that from a VarTemplateDecl, while
1440 /// getDescribedVarTemplate() retrieves the VarTemplateDecl from
1441 /// a VarDecl.
1442 VarTemplateDecl *getDescribedVarTemplate() const;
1443
1444 void setDescribedVarTemplate(VarTemplateDecl *Template);
1445
1446 // Implement isa/cast/dyncast/etc.
1447 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1448 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
1449};
1450
1451class ImplicitParamDecl : public VarDecl {
1452 void anchor() override;
1453
1454public:
1455 /// Defines the kind of the implicit parameter: is this an implicit parameter
1456 /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured
1457 /// context or something else.
1458 enum ImplicitParamKind : unsigned {
1459 /// Parameter for Objective-C 'self' argument
1460 ObjCSelf,
1461
1462 /// Parameter for Objective-C '_cmd' argument
1463 ObjCCmd,
1464
1465 /// Parameter for C++ 'this' argument
1466 CXXThis,
1467
1468 /// Parameter for C++ virtual table pointers
1469 CXXVTT,
1470
1471 /// Parameter for captured context
1472 CapturedContext,
1473
1474 /// Other implicit parameter
1475 Other,
1476 };
1477
1478 /// Create implicit parameter.
1479 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
1480 SourceLocation IdLoc, IdentifierInfo *Id,
1481 QualType T, ImplicitParamKind ParamKind);
1482 static ImplicitParamDecl *Create(ASTContext &C, QualType T,
1483 ImplicitParamKind ParamKind);
1484
1485 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1486
1487 ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
1488 IdentifierInfo *Id, QualType Type,
1489 ImplicitParamKind ParamKind)
1490 : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
1491 /*TInfo=*/nullptr, SC_None) {
1492 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1493 setImplicit();
1494 }
1495
1496 ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind)
1497 : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(),
1498 SourceLocation(), /*Id=*/nullptr, Type,
1499 /*TInfo=*/nullptr, SC_None) {
1500 NonParmVarDeclBits.ImplicitParamKind = ParamKind;
1501 setImplicit();
1502 }
1503
1504 /// Returns the implicit parameter kind.
1505 ImplicitParamKind getParameterKind() const {
1506 return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind);
1507 }
1508
1509 // Implement isa/cast/dyncast/etc.
1510 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1511 static bool classofKind(Kind K) { return K == ImplicitParam; }
1512};
1513
1514/// Represents a parameter to a function.
1515class ParmVarDecl : public VarDecl {
1516public:
1517 enum { MaxFunctionScopeDepth = 255 };
1518 enum { MaxFunctionScopeIndex = 255 };
1519
1520protected:
1521 ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1522 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1523 TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
1524 : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
1525 assert(ParmVarDeclBits.HasInheritedDefaultArg == false)(static_cast <bool> (ParmVarDeclBits.HasInheritedDefaultArg
== false) ? void (0) : __assert_fail ("ParmVarDeclBits.HasInheritedDefaultArg == false"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1525, __extension__ __PRETTY_FUNCTION__))
;
1526 assert(ParmVarDeclBits.DefaultArgKind == DAK_None)(static_cast <bool> (ParmVarDeclBits.DefaultArgKind == DAK_None
) ? void (0) : __assert_fail ("ParmVarDeclBits.DefaultArgKind == DAK_None"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1526, __extension__ __PRETTY_FUNCTION__))
;
1527 assert(ParmVarDeclBits.IsKNRPromoted == false)(static_cast <bool> (ParmVarDeclBits.IsKNRPromoted == false
) ? void (0) : __assert_fail ("ParmVarDeclBits.IsKNRPromoted == false"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1527, __extension__ __PRETTY_FUNCTION__))
;
1528 assert(ParmVarDeclBits.IsObjCMethodParam == false)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam ==
false) ? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam == false"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1528, __extension__ __PRETTY_FUNCTION__))
;
1529 setDefaultArg(DefArg);
1530 }
1531
1532public:
1533 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
1534 SourceLocation StartLoc,
1535 SourceLocation IdLoc, IdentifierInfo *Id,
1536 QualType T, TypeSourceInfo *TInfo,
1537 StorageClass S, Expr *DefArg);
1538
1539 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1540
1541 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1542
1543 void setObjCMethodScopeInfo(unsigned parameterIndex) {
1544 ParmVarDeclBits.IsObjCMethodParam = true;
1545 setParameterIndex(parameterIndex);
1546 }
1547
1548 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
1549 assert(!ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (!ParmVarDeclBits.IsObjCMethodParam
) ? void (0) : __assert_fail ("!ParmVarDeclBits.IsObjCMethodParam"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1549, __extension__ __PRETTY_FUNCTION__))
;
1550
1551 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
1552 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals
== scopeDepth && "truncation!") ? void (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1553, __extension__ __PRETTY_FUNCTION__))
1553 && "truncation!")(static_cast <bool> (ParmVarDeclBits.ScopeDepthOrObjCQuals
== scopeDepth && "truncation!") ? void (0) : __assert_fail
("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1553, __extension__ __PRETTY_FUNCTION__))
;
1554
1555 setParameterIndex(parameterIndex);
1556 }
1557
1558 bool isObjCMethodParameter() const {
1559 return ParmVarDeclBits.IsObjCMethodParam;
1560 }
1561
1562 unsigned getFunctionScopeDepth() const {
1563 if (ParmVarDeclBits.IsObjCMethodParam) return 0;
1564 return ParmVarDeclBits.ScopeDepthOrObjCQuals;
1565 }
1566
1567 /// Returns the index of this parameter in its prototype or method scope.
1568 unsigned getFunctionScopeIndex() const {
1569 return getParameterIndex();
1570 }
1571
1572 ObjCDeclQualifier getObjCDeclQualifier() const {
1573 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
1574 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
1575 }
1576 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
1577 assert(ParmVarDeclBits.IsObjCMethodParam)(static_cast <bool> (ParmVarDeclBits.IsObjCMethodParam)
? void (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1577, __extension__ __PRETTY_FUNCTION__))
;
1578 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
1579 }
1580
1581 /// True if the value passed to this parameter must undergo
1582 /// K&R-style default argument promotion:
1583 ///
1584 /// C99 6.5.2.2.
1585 /// If the expression that denotes the called function has a type
1586 /// that does not include a prototype, the integer promotions are
1587 /// performed on each argument, and arguments that have type float
1588 /// are promoted to double.
1589 bool isKNRPromoted() const {
1590 return ParmVarDeclBits.IsKNRPromoted;
1591 }
1592 void setKNRPromoted(bool promoted) {
1593 ParmVarDeclBits.IsKNRPromoted = promoted;
1594 }
1595
1596 Expr *getDefaultArg();
1597 const Expr *getDefaultArg() const {
1598 return const_cast<ParmVarDecl *>(this)->getDefaultArg();
1599 }
1600
1601 void setDefaultArg(Expr *defarg);
1602
1603 /// \brief Retrieve the source range that covers the entire default
1604 /// argument.
1605 SourceRange getDefaultArgRange() const;
1606 void setUninstantiatedDefaultArg(Expr *arg);
1607 Expr *getUninstantiatedDefaultArg();
1608 const Expr *getUninstantiatedDefaultArg() const {
1609 return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg();
1610 }
1611
1612 /// Determines whether this parameter has a default argument,
1613 /// either parsed or not.
1614 bool hasDefaultArg() const;
1615
1616 /// Determines whether this parameter has a default argument that has not
1617 /// yet been parsed. This will occur during the processing of a C++ class
1618 /// whose member functions have default arguments, e.g.,
1619 /// @code
1620 /// class X {
1621 /// public:
1622 /// void f(int x = 17); // x has an unparsed default argument now
1623 /// }; // x has a regular default argument now
1624 /// @endcode
1625 bool hasUnparsedDefaultArg() const {
1626 return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed;
1627 }
1628
1629 bool hasUninstantiatedDefaultArg() const {
1630 return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated;
1631 }
1632
1633 /// Specify that this parameter has an unparsed default argument.
1634 /// The argument will be replaced with a real default argument via
1635 /// setDefaultArg when the class definition enclosing the function
1636 /// declaration that owns this default argument is completed.
1637 void setUnparsedDefaultArg() {
1638 ParmVarDeclBits.DefaultArgKind = DAK_Unparsed;
1639 }
1640
1641 bool hasInheritedDefaultArg() const {
1642 return ParmVarDeclBits.HasInheritedDefaultArg;
1643 }
1644
1645 void setHasInheritedDefaultArg(bool I = true) {
1646 ParmVarDeclBits.HasInheritedDefaultArg = I;
1647 }
1648
1649 QualType getOriginalType() const;
1650
1651 /// \brief Determine whether this parameter is actually a function
1652 /// parameter pack.
1653 bool isParameterPack() const;
1654
1655 /// Sets the function declaration that owns this
1656 /// ParmVarDecl. Since ParmVarDecls are often created before the
1657 /// FunctionDecls that own them, this routine is required to update
1658 /// the DeclContext appropriately.
1659 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
1660
1661 // Implement isa/cast/dyncast/etc.
1662 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1663 static bool classofKind(Kind K) { return K == ParmVar; }
1664
1665private:
1666 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
1667
1668 void setParameterIndex(unsigned parameterIndex) {
1669 if (parameterIndex >= ParameterIndexSentinel) {
1670 setParameterIndexLarge(parameterIndex);
1671 return;
1672 }
1673
1674 ParmVarDeclBits.ParameterIndex = parameterIndex;
1675 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!")(static_cast <bool> (ParmVarDeclBits.ParameterIndex == parameterIndex
&& "truncation!") ? void (0) : __assert_fail ("ParmVarDeclBits.ParameterIndex == parameterIndex && \"truncation!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 1675, __extension__ __PRETTY_FUNCTION__))
;
1676 }
1677 unsigned getParameterIndex() const {
1678 unsigned d = ParmVarDeclBits.ParameterIndex;
1679 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
1680 }
1681
1682 void setParameterIndexLarge(unsigned parameterIndex);
1683 unsigned getParameterIndexLarge() const;
1684};
1685
1686/// Represents a function declaration or definition.
1687///
1688/// Since a given function can be declared several times in a program,
1689/// there may be several FunctionDecls that correspond to that
1690/// function. Only one of those FunctionDecls will be found when
1691/// traversing the list of declarations in the context of the
1692/// FunctionDecl (e.g., the translation unit); this FunctionDecl
1693/// contains all of the information known about the function. Other,
1694/// previous declarations of the function are available via the
1695/// getPreviousDecl() chain.
1696class FunctionDecl : public DeclaratorDecl, public DeclContext,
1697 public Redeclarable<FunctionDecl> {
1698public:
1699 /// \brief The kind of templated function a FunctionDecl can be.
1700 enum TemplatedKind {
1701 TK_NonTemplate,
1702 TK_FunctionTemplate,
1703 TK_MemberSpecialization,
1704 TK_FunctionTemplateSpecialization,
1705 TK_DependentFunctionTemplateSpecialization
1706 };
1707
1708private:
1709 /// A new[]'d array of pointers to VarDecls for the formal
1710 /// parameters of this function. This is null if a prototype or if there are
1711 /// no formals.
1712 ParmVarDecl **ParamInfo = nullptr;
1713
1714 LazyDeclStmtPtr Body;
1715
1716 // FIXME: This can be packed into the bitfields in DeclContext.
1717 // NOTE: VC++ packs bitfields poorly if the types differ.
1718 unsigned SClass : 3;
1719 unsigned IsInline : 1;
1720 unsigned IsInlineSpecified : 1;
1721
1722protected:
1723 // This is shared by CXXConstructorDecl, CXXConversionDecl, and
1724 // CXXDeductionGuideDecl.
1725 unsigned IsExplicitSpecified : 1;
1726
1727private:
1728 unsigned IsVirtualAsWritten : 1;
1729 unsigned IsPure : 1;
1730 unsigned HasInheritedPrototype : 1;
1731 unsigned HasWrittenPrototype : 1;
1732 unsigned IsDeleted : 1;
1733 unsigned IsTrivial : 1; // sunk from CXXMethodDecl
1734
1735 /// This flag indicates whether this function is trivial for the purpose of
1736 /// calls. This is meaningful only when this function is a copy/move
1737 /// constructor or a destructor.
1738 unsigned IsTrivialForCall : 1;
1739
1740 unsigned IsDefaulted : 1; // sunk from CXXMethoDecl
1741 unsigned IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
1742 unsigned HasImplicitReturnZero : 1;
1743 unsigned IsLateTemplateParsed : 1;
1744 unsigned IsConstexpr : 1;
1745 unsigned InstantiationIsPending : 1;
1746
1747 /// \brief Indicates if the function uses __try.
1748 unsigned UsesSEHTry : 1;
1749
1750 /// \brief Indicates if the function was a definition but its body was
1751 /// skipped.
1752 unsigned HasSkippedBody : 1;
1753
1754 /// Indicates if the function declaration will have a body, once we're done
1755 /// parsing it.
1756 unsigned WillHaveBody : 1;
1757
1758 /// Indicates that this function is a multiversioned function using attribute
1759 /// 'target'.
1760 unsigned IsMultiVersion : 1;
1761
1762protected:
1763 /// [C++17] Only used by CXXDeductionGuideDecl. Declared here to avoid
1764 /// increasing the size of CXXDeductionGuideDecl by the size of an unsigned
1765 /// int as opposed to adding a single bit to FunctionDecl.
1766 /// Indicates that the Deduction Guide is the implicitly generated 'copy
1767 /// deduction candidate' (is used during overload resolution).
1768 unsigned IsCopyDeductionCandidate : 1;
1769
1770private:
1771
1772 /// Store the ODRHash after first calculation.
1773 unsigned HasODRHash : 1;
1774 unsigned ODRHash;
1775
1776 /// \brief End part of this FunctionDecl's source range.
1777 ///
1778 /// We could compute the full range in getSourceRange(). However, when we're
1779 /// dealing with a function definition deserialized from a PCH/AST file,
1780 /// we can only compute the full range once the function body has been
1781 /// de-serialized, so it's far better to have the (sometimes-redundant)
1782 /// EndRangeLoc.
1783 SourceLocation EndRangeLoc;
1784
1785 /// \brief The template or declaration that this declaration
1786 /// describes or was instantiated from, respectively.
1787 ///
1788 /// For non-templates, this value will be NULL. For function
1789 /// declarations that describe a function template, this will be a
1790 /// pointer to a FunctionTemplateDecl. For member functions
1791 /// of class template specializations, this will be a MemberSpecializationInfo
1792 /// pointer containing information about the specialization.
1793 /// For function template specializations, this will be a
1794 /// FunctionTemplateSpecializationInfo, which contains information about
1795 /// the template being specialized and the template arguments involved in
1796 /// that specialization.
1797 llvm::PointerUnion4<FunctionTemplateDecl *,
1798 MemberSpecializationInfo *,
1799 FunctionTemplateSpecializationInfo *,
1800 DependentFunctionTemplateSpecializationInfo *>
1801 TemplateOrSpecialization;
1802
1803 /// Provides source/type location info for the declaration name embedded in
1804 /// the DeclaratorDecl base class.
1805 DeclarationNameLoc DNLoc;
1806
1807 /// \brief Specify that this function declaration is actually a function
1808 /// template specialization.
1809 ///
1810 /// \param C the ASTContext.
1811 ///
1812 /// \param Template the function template that this function template
1813 /// specialization specializes.
1814 ///
1815 /// \param TemplateArgs the template arguments that produced this
1816 /// function template specialization from the template.
1817 ///
1818 /// \param InsertPos If non-NULL, the position in the function template
1819 /// specialization set where the function template specialization data will
1820 /// be inserted.
1821 ///
1822 /// \param TSK the kind of template specialization this is.
1823 ///
1824 /// \param TemplateArgsAsWritten location info of template arguments.
1825 ///
1826 /// \param PointOfInstantiation point at which the function template
1827 /// specialization was first instantiated.
1828 void setFunctionTemplateSpecialization(ASTContext &C,
1829 FunctionTemplateDecl *Template,
1830 const TemplateArgumentList *TemplateArgs,
1831 void *InsertPos,
1832 TemplateSpecializationKind TSK,
1833 const TemplateArgumentListInfo *TemplateArgsAsWritten,
1834 SourceLocation PointOfInstantiation);
1835
1836 /// \brief Specify that this record is an instantiation of the
1837 /// member function FD.
1838 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
1839 TemplateSpecializationKind TSK);
1840
1841 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
1842
1843protected:
1844 FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1845 const DeclarationNameInfo &NameInfo, QualType T,
1846 TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified,
1847 bool isConstexprSpecified)
1848 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
1849 StartLoc),
1850 DeclContext(DK), redeclarable_base(C), SClass(S),
1851 IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
1852 IsExplicitSpecified(false), IsVirtualAsWritten(false), IsPure(false),
1853 HasInheritedPrototype(false), HasWrittenPrototype(true),
1854 IsDeleted(false), IsTrivial(false), IsTrivialForCall(false),
1855 IsDefaulted(false),
1856 IsExplicitlyDefaulted(false), HasImplicitReturnZero(false),
1857 IsLateTemplateParsed(false), IsConstexpr(isConstexprSpecified),
1858 InstantiationIsPending(false), UsesSEHTry(false), HasSkippedBody(false),
1859 WillHaveBody(false), IsMultiVersion(false),
1860 IsCopyDeductionCandidate(false), HasODRHash(false), ODRHash(0),
1861 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {}
1862
1863 using redeclarable_base = Redeclarable<FunctionDecl>;
1864
1865 FunctionDecl *getNextRedeclarationImpl() override {
1866 return getNextRedeclaration();
1867 }
1868
1869 FunctionDecl *getPreviousDeclImpl() override {
1870 return getPreviousDecl();
1871 }
1872
1873 FunctionDecl *getMostRecentDeclImpl() override {
1874 return getMostRecentDecl();
1875 }
1876
1877public:
1878 friend class ASTDeclReader;
1879 friend class ASTDeclWriter;
1880
1881 using redecl_range = redeclarable_base::redecl_range;
1882 using redecl_iterator = redeclarable_base::redecl_iterator;
1883
1884 using redeclarable_base::redecls_begin;
1885 using redeclarable_base::redecls_end;
1886 using redeclarable_base::redecls;
1887 using redeclarable_base::getPreviousDecl;
1888 using redeclarable_base::getMostRecentDecl;
1889 using redeclarable_base::isFirstDecl;
1890
1891 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1892 SourceLocation StartLoc, SourceLocation NLoc,
1893 DeclarationName N, QualType T,
1894 TypeSourceInfo *TInfo,
1895 StorageClass SC,
1896 bool isInlineSpecified = false,
1897 bool hasWrittenPrototype = true,
1898 bool isConstexprSpecified = false) {
1899 DeclarationNameInfo NameInfo(N, NLoc);
1900 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
1901 SC,
1902 isInlineSpecified, hasWrittenPrototype,
1903 isConstexprSpecified);
1904 }
1905
1906 static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
1907 SourceLocation StartLoc,
1908 const DeclarationNameInfo &NameInfo,
1909 QualType T, TypeSourceInfo *TInfo,
1910 StorageClass SC,
1911 bool isInlineSpecified,
1912 bool hasWrittenPrototype,
1913 bool isConstexprSpecified = false);
1914
1915 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1916
1917 DeclarationNameInfo getNameInfo() const {
1918 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
1919 }
1920
1921 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1922 bool Qualified) const override;
1923
1924 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
1925
1926 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1927
1928 /// \brief Returns true if the function has a body (definition). The
1929 /// function body might be in any of the (re-)declarations of this
1930 /// function. The variant that accepts a FunctionDecl pointer will
1931 /// set that function declaration to the actual declaration
1932 /// containing the body (if there is one).
1933 bool hasBody(const FunctionDecl *&Definition) const;
1934
1935 bool hasBody() const override {
1936 const FunctionDecl* Definition;
1937 return hasBody(Definition);
1938 }
1939
1940 /// Returns whether the function has a trivial body that does not require any
1941 /// specific codegen.
1942 bool hasTrivialBody() const;
1943
1944 /// Returns true if the function is defined at all, including a deleted
1945 /// definition. Except for the behavior when the function is deleted, behaves
1946 /// like hasBody.
1947 bool isDefined(const FunctionDecl *&Definition) const;
1948
1949 virtual bool isDefined() const {
1950 const FunctionDecl* Definition;
1951 return isDefined(Definition);
1952 }
1953
1954 /// \brief Get the definition for this declaration.
1955 FunctionDecl *getDefinition() {
1956 const FunctionDecl *Definition;
1957 if (isDefined(Definition))
1958 return const_cast<FunctionDecl *>(Definition);
1959 return nullptr;
1960 }
1961 const FunctionDecl *getDefinition() const {
1962 return const_cast<FunctionDecl *>(this)->getDefinition();
1963 }
1964
1965 /// Retrieve the body (definition) of the function. The function body might be
1966 /// in any of the (re-)declarations of this function. The variant that accepts
1967 /// a FunctionDecl pointer will set that function declaration to the actual
1968 /// declaration containing the body (if there is one).
1969 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid
1970 /// unnecessary AST de-serialization of the body.
1971 Stmt *getBody(const FunctionDecl *&Definition) const;
1972
1973 Stmt *getBody() const override {
1974 const FunctionDecl* Definition;
1975 return getBody(Definition);
1976 }
1977
1978 /// Returns whether this specific declaration of the function is also a
1979 /// definition that does not contain uninstantiated body.
1980 ///
1981 /// This does not determine whether the function has been defined (e.g., in a
1982 /// previous definition); for that information, use isDefined.
1983 bool isThisDeclarationADefinition() const {
1984 return IsDeleted || IsDefaulted || Body || HasSkippedBody ||
1985 IsLateTemplateParsed || WillHaveBody || hasDefiningAttr();
1986 }
1987
1988 /// Returns whether this specific declaration of the function has a body -
1989 /// that is, if it is a non-deleted definition.
1990 bool doesThisDeclarationHaveABody() const {
1991 return Body || IsLateTemplateParsed;
1992 }
1993
1994 void setBody(Stmt *B);
1995 void setLazyBody(uint64_t Offset) { Body = Offset; }
1996
1997 /// Whether this function is variadic.
1998 bool isVariadic() const;
1999
2000 /// Whether this function is marked as virtual explicitly.
2001 bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
2002 void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
2003
2004 /// Whether this virtual function is pure, i.e. makes the containing class
2005 /// abstract.
2006 bool isPure() const { return IsPure; }
2007 void setPure(bool P = true);
2008
2009 /// Whether this templated function will be late parsed.
2010 bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
2011 void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
2012
2013 /// Whether this function is "trivial" in some specialized C++ senses.
2014 /// Can only be true for default constructors, copy constructors,
2015 /// copy assignment operators, and destructors. Not meaningful until
2016 /// the class has been fully built by Sema.
2017 bool isTrivial() const { return IsTrivial; }
2018 void setTrivial(bool IT) { IsTrivial = IT; }
2019
2020 bool isTrivialForCall() const { return IsTrivialForCall; }
2021 void setTrivialForCall(bool IT) { IsTrivialForCall = IT; }
2022
2023 /// Whether this function is defaulted per C++0x. Only valid for
2024 /// special member functions.
2025 bool isDefaulted() const { return IsDefaulted; }
2026 void setDefaulted(bool D = true) { IsDefaulted = D; }
2027
2028 /// Whether this function is explicitly defaulted per C++0x. Only valid
2029 /// for special member functions.
2030 bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
2031 void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
2032
2033 /// Whether falling off this function implicitly returns null/zero.
2034 /// If a more specific implicit return value is required, front-ends
2035 /// should synthesize the appropriate return statements.
2036 bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
2037 void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
2038
2039 /// \brief Whether this function has a prototype, either because one
2040 /// was explicitly written or because it was "inherited" by merging
2041 /// a declaration without a prototype with a declaration that has a
2042 /// prototype.
2043 bool hasPrototype() const {
2044 return HasWrittenPrototype || HasInheritedPrototype;
2045 }
2046
2047 bool hasWrittenPrototype() const { return HasWrittenPrototype; }
2048
2049 /// \brief Whether this function inherited its prototype from a
2050 /// previous declaration.
2051 bool hasInheritedPrototype() const { return HasInheritedPrototype; }
2052 void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
2053
2054 /// Whether this is a (C++11) constexpr function or constexpr constructor.
2055 bool isConstexpr() const { return IsConstexpr; }
2056 void setConstexpr(bool IC) { IsConstexpr = IC; }
2057
2058 /// \brief Whether the instantiation of this function is pending.
2059 /// This bit is set when the decision to instantiate this function is made
2060 /// and unset if and when the function body is created. That leaves out
2061 /// cases where instantiation did not happen because the template definition
2062 /// was not seen in this TU. This bit remains set in those cases, under the
2063 /// assumption that the instantiation will happen in some other TU.
2064 bool instantiationIsPending() const { return InstantiationIsPending; }
2065 void setInstantiationIsPending(bool IC) { InstantiationIsPending = IC; }
2066
2067 /// \brief Indicates the function uses __try.
2068 bool usesSEHTry() const { return UsesSEHTry; }
2069 void setUsesSEHTry(bool UST) { UsesSEHTry = UST; }
2070
2071 /// \brief Whether this function has been deleted.
2072 ///
2073 /// A function that is "deleted" (via the C++0x "= delete" syntax)
2074 /// acts like a normal function, except that it cannot actually be
2075 /// called or have its address taken. Deleted functions are
2076 /// typically used in C++ overload resolution to attract arguments
2077 /// whose type or lvalue/rvalue-ness would permit the use of a
2078 /// different overload that would behave incorrectly. For example,
2079 /// one might use deleted functions to ban implicit conversion from
2080 /// a floating-point number to an Integer type:
2081 ///
2082 /// @code
2083 /// struct Integer {
2084 /// Integer(long); // construct from a long
2085 /// Integer(double) = delete; // no construction from float or double
2086 /// Integer(long double) = delete; // no construction from long double
2087 /// };
2088 /// @endcode
2089 // If a function is deleted, its first declaration must be.
2090 bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
2091 bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
2092 void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
2093
2094 /// \brief Determines whether this function is "main", which is the
2095 /// entry point into an executable program.
2096 bool isMain() const;
2097
2098 /// \brief Determines whether this function is a MSVCRT user defined entry
2099 /// point.
2100 bool isMSVCRTEntryPoint() const;
2101
2102 /// \brief Determines whether this operator new or delete is one
2103 /// of the reserved global placement operators:
2104 /// void *operator new(size_t, void *);
2105 /// void *operator new[](size_t, void *);
2106 /// void operator delete(void *, void *);
2107 /// void operator delete[](void *, void *);
2108 /// These functions have special behavior under [new.delete.placement]:
2109 /// These functions are reserved, a C++ program may not define
2110 /// functions that displace the versions in the Standard C++ library.
2111 /// The provisions of [basic.stc.dynamic] do not apply to these
2112 /// reserved placement forms of operator new and operator delete.
2113 ///
2114 /// This function must be an allocation or deallocation function.
2115 bool isReservedGlobalPlacementOperator() const;
2116
2117 /// \brief Determines whether this function is one of the replaceable
2118 /// global allocation functions:
2119 /// void *operator new(size_t);
2120 /// void *operator new(size_t, const std::nothrow_t &) noexcept;
2121 /// void *operator new[](size_t);
2122 /// void *operator new[](size_t, const std::nothrow_t &) noexcept;
2123 /// void operator delete(void *) noexcept;
2124 /// void operator delete(void *, std::size_t) noexcept; [C++1y]
2125 /// void operator delete(void *, const std::nothrow_t &) noexcept;
2126 /// void operator delete[](void *) noexcept;
2127 /// void operator delete[](void *, std::size_t) noexcept; [C++1y]
2128 /// void operator delete[](void *, const std::nothrow_t &) noexcept;
2129 /// These functions have special behavior under C++1y [expr.new]:
2130 /// An implementation is allowed to omit a call to a replaceable global
2131 /// allocation function. [...]
2132 ///
2133 /// If this function is an aligned allocation/deallocation function, return
2134 /// true through IsAligned.
2135 bool isReplaceableGlobalAllocationFunction(bool *IsAligned = nullptr) const;
2136
2137 /// \brief Determine whether this is a destroying operator delete.
2138 bool isDestroyingOperatorDelete() const;
2139
2140 /// Compute the language linkage.
2141 LanguageLinkage getLanguageLinkage() const;
2142
2143 /// \brief Determines whether this function is a function with
2144 /// external, C linkage.
2145 bool isExternC() const;
2146
2147 /// \brief Determines whether this function's context is, or is nested within,
2148 /// a C++ extern "C" linkage spec.
2149 bool isInExternCContext() const;
2150
2151 /// \brief Determines whether this function's context is, or is nested within,
2152 /// a C++ extern "C++" linkage spec.
2153 bool isInExternCXXContext() const;
2154
2155 /// \brief Determines whether this is a global function.
2156 bool isGlobal() const;
2157
2158 /// \brief Determines whether this function is known to be 'noreturn', through
2159 /// an attribute on its declaration or its type.
2160 bool isNoReturn() const;
2161
2162 /// \brief True if the function was a definition but its body was skipped.
2163 bool hasSkippedBody() const { return HasSkippedBody; }
2164 void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; }
2165
2166 /// True if this function will eventually have a body, once it's fully parsed.
2167 bool willHaveBody() const { return WillHaveBody; }
2168 void setWillHaveBody(bool V = true) { WillHaveBody = V; }
2169
2170 /// True if this function is considered a multiversioned function.
2171 bool isMultiVersion() const { return getCanonicalDecl()->IsMultiVersion; }
2172
2173 /// Sets the multiversion state for this declaration and all of its
2174 /// redeclarations.
2175 void setIsMultiVersion(bool V = true) {
2176 getCanonicalDecl()->IsMultiVersion = V;
2177 }
2178
2179 void setPreviousDeclaration(FunctionDecl * PrevDecl);
2180
2181 FunctionDecl *getCanonicalDecl() override;
2182 const FunctionDecl *getCanonicalDecl() const {
2183 return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
2184 }
2185
2186 unsigned getBuiltinID() const;
2187
2188 // ArrayRef interface to parameters.
2189 ArrayRef<ParmVarDecl *> parameters() const {
2190 return {ParamInfo, getNumParams()};
2191 }
2192 MutableArrayRef<ParmVarDecl *> parameters() {
2193 return {ParamInfo, getNumParams()};
2194 }
2195
2196 // Iterator access to formal parameters.
2197 using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator;
2198 using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator;
2199
2200 bool param_empty() const { return parameters().empty(); }
2201 param_iterator param_begin() { return parameters().begin(); }
2202 param_iterator param_end() { return parameters().end(); }
2203 param_const_iterator param_begin() const { return parameters().begin(); }
2204 param_const_iterator param_end() const { return parameters().end(); }
2205 size_t param_size() const { return parameters().size(); }
2206
2207 /// Return the number of parameters this function must have based on its
2208 /// FunctionType. This is the length of the ParamInfo array after it has been
2209 /// created.
2210 unsigned getNumParams() const;
2211
2212 const ParmVarDecl *getParamDecl(unsigned i) const {
2213 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 2213, __extension__ __PRETTY_FUNCTION__))
;
2214 return ParamInfo[i];
2215 }
2216 ParmVarDecl *getParamDecl(unsigned i) {
2217 assert(i < getNumParams() && "Illegal param #")(static_cast <bool> (i < getNumParams() && "Illegal param #"
) ? void (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 2217, __extension__ __PRETTY_FUNCTION__))
;
2218 return ParamInfo[i];
2219 }
2220 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
2221 setParams(getASTContext(), NewParamInfo);
2222 }
2223
2224 /// Returns the minimum number of arguments needed to call this function. This
2225 /// may be fewer than the number of function parameters, if some of the
2226 /// parameters have default arguments (in C++).
2227 unsigned getMinRequiredArguments() const;
2228
2229 QualType getReturnType() const {
2230 assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!")(static_cast <bool> (getType()->getAs<FunctionType
>() && "Expected a FunctionType!") ? void (0) : __assert_fail
("getType()->getAs<FunctionType>() && \"Expected a FunctionType!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 2230, __extension__ __PRETTY_FUNCTION__))
;
2231 return getType()->getAs<FunctionType>()->getReturnType();
2232 }
2233
2234 /// \brief Attempt to compute an informative source range covering the
2235 /// function return type. This may omit qualifiers and other information with
2236 /// limited representation in the AST.
2237 SourceRange getReturnTypeSourceRange() const;
2238
2239 /// \brief Attempt to compute an informative source range covering the
2240 /// function exception specification, if any.
2241 SourceRange getExceptionSpecSourceRange() const;
2242
2243 /// \brief Determine the type of an expression that calls this function.
2244 QualType getCallResultType() const {
2245 assert(getType()->getAs<FunctionType>() && "Expected a FunctionType!")(static_cast <bool> (getType()->getAs<FunctionType
>() && "Expected a FunctionType!") ? void (0) : __assert_fail
("getType()->getAs<FunctionType>() && \"Expected a FunctionType!\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 2245, __extension__ __PRETTY_FUNCTION__))
;
2246 return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
2247 }
2248
2249 /// \brief Returns the WarnUnusedResultAttr that is either declared on this
2250 /// function, or its return type declaration.
2251 const Attr *getUnusedResultAttr() const;
2252
2253 /// \brief Returns true if this function or its return type has the
2254 /// warn_unused_result attribute.
2255 bool hasUnusedResultAttr() const { return getUnusedResultAttr() != nullptr; }
2256
2257 /// \brief Returns the storage class as written in the source. For the
2258 /// computed linkage of symbol, see getLinkage.
2259 StorageClass getStorageClass() const { return StorageClass(SClass); }
2260
2261 /// \brief Determine whether the "inline" keyword was specified for this
2262 /// function.
2263 bool isInlineSpecified() const { return IsInlineSpecified; }
2264
2265 /// Set whether the "inline" keyword was specified for this function.
2266 void setInlineSpecified(bool I) {
2267 IsInlineSpecified = I;
2268 IsInline = I;
2269 }
2270
2271 /// Flag that this function is implicitly inline.
2272 void setImplicitlyInline() {
2273 IsInline = true;
2274 }
2275
2276 /// \brief Determine whether this function should be inlined, because it is
2277 /// either marked "inline" or "constexpr" or is a member function of a class
2278 /// that was defined in the class body.
2279 bool isInlined() const { return IsInline; }
2280
2281 bool isInlineDefinitionExternallyVisible() const;
2282
2283 bool isMSExternInline() const;
2284
2285 bool doesDeclarationForceExternallyVisibleDefinition() const;
2286
2287 /// Whether this function declaration represents an C++ overloaded
2288 /// operator, e.g., "operator+".
2289 bool isOverloadedOperator() const {
2290 return getOverloadedOperator() != OO_None;
2291 }
2292
2293 OverloadedOperatorKind getOverloadedOperator() const;
2294
2295 const IdentifierInfo *getLiteralIdentifier() const;
2296
2297 /// \brief If this function is an instantiation of a member function
2298 /// of a class template specialization, retrieves the function from
2299 /// which it was instantiated.
2300 ///
2301 /// This routine will return non-NULL for (non-templated) member
2302 /// functions of class templates and for instantiations of function
2303 /// templates. For example, given:
2304 ///
2305 /// \code
2306 /// template<typename T>
2307 /// struct X {
2308 /// void f(T);
2309 /// };
2310 /// \endcode
2311 ///
2312 /// The declaration for X<int>::f is a (non-templated) FunctionDecl
2313 /// whose parent is the class template specialization X<int>. For
2314 /// this declaration, getInstantiatedFromFunction() will return
2315 /// the FunctionDecl X<T>::A. When a complete definition of
2316 /// X<int>::A is required, it will be instantiated from the
2317 /// declaration returned by getInstantiatedFromMemberFunction().
2318 FunctionDecl *getInstantiatedFromMemberFunction() const;
2319
2320 /// \brief What kind of templated function this is.
2321 TemplatedKind getTemplatedKind() const;
2322
2323 /// \brief If this function is an instantiation of a member function of a
2324 /// class template specialization, retrieves the member specialization
2325 /// information.
2326 MemberSpecializationInfo *getMemberSpecializationInfo() const;
2327
2328 /// \brief Specify that this record is an instantiation of the
2329 /// member function FD.
2330 void setInstantiationOfMemberFunction(FunctionDecl *FD,
2331 TemplateSpecializationKind TSK) {
2332 setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
2333 }
2334
2335 /// \brief Retrieves the function template that is described by this
2336 /// function declaration.
2337 ///
2338 /// Every function template is represented as a FunctionTemplateDecl
2339 /// and a FunctionDecl (or something derived from FunctionDecl). The
2340 /// former contains template properties (such as the template
2341 /// parameter lists) while the latter contains the actual
2342 /// description of the template's
2343 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
2344 /// FunctionDecl that describes the function template,
2345 /// getDescribedFunctionTemplate() retrieves the
2346 /// FunctionTemplateDecl from a FunctionDecl.
2347 FunctionTemplateDecl *getDescribedFunctionTemplate() const;
2348
2349 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template);
2350
2351 /// \brief Determine whether this function is a function template
2352 /// specialization.
2353 bool isFunctionTemplateSpecialization() const {
2354 return getPrimaryTemplate() != nullptr;
2355 }
2356
2357 /// \brief Retrieve the class scope template pattern that this function
2358 /// template specialization is instantiated from.
2359 FunctionDecl *getClassScopeSpecializationPattern() const;
2360
2361 /// \brief If this function is actually a function template specialization,
2362 /// retrieve information about this function template specialization.
2363 /// Otherwise, returns NULL.
2364 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const;
2365
2366 /// \brief Determines whether this function is a function template
2367 /// specialization or a member of a class template specialization that can
2368 /// be implicitly instantiated.
2369 bool isImplicitlyInstantiable() const;
2370
2371 /// \brief Determines if the given function was instantiated from a
2372 /// function template.
2373 bool isTemplateInstantiation() const;
2374
2375 /// \brief Retrieve the function declaration from which this function could
2376 /// be instantiated, if it is an instantiation (rather than a non-template
2377 /// or a specialization, for example).
2378 FunctionDecl *getTemplateInstantiationPattern() const;
2379
2380 /// \brief Retrieve the primary template that this function template
2381 /// specialization either specializes or was instantiated from.
2382 ///
2383 /// If this function declaration is not a function template specialization,
2384 /// returns NULL.
2385 FunctionTemplateDecl *getPrimaryTemplate() const;
2386
2387 /// \brief Retrieve the template arguments used to produce this function
2388 /// template specialization from the primary template.
2389 ///
2390 /// If this function declaration is not a function template specialization,
2391 /// returns NULL.
2392 const TemplateArgumentList *getTemplateSpecializationArgs() const;
2393
2394 /// \brief Retrieve the template argument list as written in the sources,
2395 /// if any.
2396 ///
2397 /// If this function declaration is not a function template specialization
2398 /// or if it had no explicit template argument list, returns NULL.
2399 /// Note that it an explicit template argument list may be written empty,
2400 /// e.g., template<> void foo<>(char* s);
2401 const ASTTemplateArgumentListInfo*
2402 getTemplateSpecializationArgsAsWritten() const;
2403
2404 /// \brief Specify that this function declaration is actually a function
2405 /// template specialization.
2406 ///
2407 /// \param Template the function template that this function template
2408 /// specialization specializes.
2409 ///
2410 /// \param TemplateArgs the template arguments that produced this
2411 /// function template specialization from the template.
2412 ///
2413 /// \param InsertPos If non-NULL, the position in the function template
2414 /// specialization set where the function template specialization data will
2415 /// be inserted.
2416 ///
2417 /// \param TSK the kind of template specialization this is.
2418 ///
2419 /// \param TemplateArgsAsWritten location info of template arguments.
2420 ///
2421 /// \param PointOfInstantiation point at which the function template
2422 /// specialization was first instantiated.
2423 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
2424 const TemplateArgumentList *TemplateArgs,
2425 void *InsertPos,
2426 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
2427 const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
2428 SourceLocation PointOfInstantiation = SourceLocation()) {
2429 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
2430 InsertPos, TSK, TemplateArgsAsWritten,
2431 PointOfInstantiation);
2432 }
2433
2434 /// \brief Specifies that this function declaration is actually a
2435 /// dependent function template specialization.
2436 void setDependentTemplateSpecialization(ASTContext &Context,
2437 const UnresolvedSetImpl &Templates,
2438 const TemplateArgumentListInfo &TemplateArgs);
2439
2440 DependentFunctionTemplateSpecializationInfo *
2441 getDependentSpecializationInfo() const;
2442
2443 /// \brief Determine what kind of template instantiation this function
2444 /// represents.
2445 TemplateSpecializationKind getTemplateSpecializationKind() const;
2446
2447 /// \brief Determine what kind of template instantiation this function
2448 /// represents.
2449 void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2450 SourceLocation PointOfInstantiation = SourceLocation());
2451
2452 /// \brief Retrieve the (first) point of instantiation of a function template
2453 /// specialization or a member of a class template specialization.
2454 ///
2455 /// \returns the first point of instantiation, if this function was
2456 /// instantiated from a template; otherwise, returns an invalid source
2457 /// location.
2458 SourceLocation getPointOfInstantiation() const;
2459
2460 /// \brief Determine whether this is or was instantiated from an out-of-line
2461 /// definition of a member function.
2462 bool isOutOfLine() const override;
2463
2464 /// \brief Identify a memory copying or setting function.
2465 /// If the given function is a memory copy or setting function, returns
2466 /// the corresponding Builtin ID. If the function is not a memory function,
2467 /// returns 0.
2468 unsigned getMemoryFunctionKind() const;
2469
2470 /// \brief Returns ODRHash of the function. This value is calculated and
2471 /// stored on first call, then the stored value returned on the other calls.
2472 unsigned getODRHash();
2473
2474 // Implement isa/cast/dyncast/etc.
2475 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2476 static bool classofKind(Kind K) {
2477 return K >= firstFunction && K <= lastFunction;
2478 }
2479 static DeclContext *castToDeclContext(const FunctionDecl *D) {
2480 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
2481 }
2482 static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
2483 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
2484 }
2485};
2486
2487/// Represents a member of a struct/union/class.
2488class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
2489 unsigned BitField : 1;
2490 unsigned Mutable : 1;
2491 mutable unsigned CachedFieldIndex : 30;
2492
2493 /// The kinds of value we can store in InitializerOrBitWidth.
2494 ///
2495 /// Note that this is compatible with InClassInitStyle except for
2496 /// ISK_CapturedVLAType.
2497 enum InitStorageKind {
2498 /// If the pointer is null, there's nothing special. Otherwise,
2499 /// this is a bitfield and the pointer is the Expr* storing the
2500 /// bit-width.
2501 ISK_NoInit = (unsigned) ICIS_NoInit,
2502
2503 /// The pointer is an (optional due to delayed parsing) Expr*
2504 /// holding the copy-initializer.
2505 ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
2506
2507 /// The pointer is an (optional due to delayed parsing) Expr*
2508 /// holding the list-initializer.
2509 ISK_InClassListInit = (unsigned) ICIS_ListInit,
2510
2511 /// The pointer is a VariableArrayType* that's been captured;
2512 /// the enclosing context is a lambda or captured statement.
2513 ISK_CapturedVLAType,
2514 };
2515
2516 /// If this is a bitfield with a default member initializer, this
2517 /// structure is used to represent the two expressions.
2518 struct InitAndBitWidth {
2519 Expr *Init;
2520 Expr *BitWidth;
2521 };
2522
2523 /// \brief Storage for either the bit-width, the in-class initializer, or
2524 /// both (via InitAndBitWidth), or the captured variable length array bound.
2525 ///
2526 /// If the storage kind is ISK_InClassCopyInit or
2527 /// ISK_InClassListInit, but the initializer is null, then this
2528 /// field has an in-class initializer that has not yet been parsed
2529 /// and attached.
2530 // FIXME: Tail-allocate this to reduce the size of FieldDecl in the
2531 // overwhelmingly common case that we have none of these things.
2532 llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
2533
2534protected:
2535 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
2536 SourceLocation IdLoc, IdentifierInfo *Id,
2537 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2538 InClassInitStyle InitStyle)
2539 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2540 BitField(false), Mutable(Mutable), CachedFieldIndex(0),
2541 InitStorage(nullptr, (InitStorageKind) InitStyle) {
2542 if (BW)
2543 setBitWidth(BW);
2544 }
2545
2546public:
2547 friend class ASTDeclReader;
2548 friend class ASTDeclWriter;
2549
2550 static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
2551 SourceLocation StartLoc, SourceLocation IdLoc,
2552 IdentifierInfo *Id, QualType T,
2553 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2554 InClassInitStyle InitStyle);
2555
2556 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2557
2558 /// Returns the index of this field within its record,
2559 /// as appropriate for passing to ASTRecordLayout::getFieldOffset.
2560 unsigned getFieldIndex() const;
2561
2562 /// Determines whether this field is mutable (C++ only).
2563 bool isMutable() const { return Mutable; }
2564
2565 /// Determines whether this field is a bitfield.
2566 bool isBitField() const { return BitField; }
2567
2568 /// Determines whether this is an unnamed bitfield.
2569 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
2570
2571 /// Determines whether this field is a
2572 /// representative for an anonymous struct or union. Such fields are
2573 /// unnamed and are implicitly generated by the implementation to
2574 /// store the data for the anonymous union or struct.
2575 bool isAnonymousStructOrUnion() const;
2576
2577 Expr *getBitWidth() const {
2578 if (!BitField)
2579 return nullptr;
2580 void *Ptr = InitStorage.getPointer();
2581 if (getInClassInitStyle())
2582 return static_cast<InitAndBitWidth*>(Ptr)->BitWidth;
2583 return static_cast<Expr*>(Ptr);
2584 }
2585
2586 unsigned getBitWidthValue(const ASTContext &Ctx) const;
2587
2588 /// Set the bit-field width for this member.
2589 // Note: used by some clients (i.e., do not remove it).
2590 void setBitWidth(Expr *Width) {
2591 assert(!hasCapturedVLAType() && !BitField &&(static_cast <bool> (!hasCapturedVLAType() && !
BitField && "bit width or captured type already set")
? void (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 2592, __extension__ __PRETTY_FUNCTION__))
2592 "bit width or captured type already set")(static_cast <bool> (!hasCapturedVLAType() && !
BitField && "bit width or captured type already set")
? void (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 2592, __extension__ __PRETTY_FUNCTION__))
;
2593 assert(Width && "no bit width specified")(static_cast <bool> (Width && "no bit width specified"
) ? void (0) : __assert_fail ("Width && \"no bit width specified\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 2593, __extension__ __PRETTY_FUNCTION__))
;
2594 InitStorage.setPointer(
2595 InitStorage.getInt()
2596 ? new (getASTContext())
2597 InitAndBitWidth{getInClassInitializer(), Width}
2598 : static_cast<void*>(Width));
2599 BitField = true;
2600 }
2601
2602 /// Remove the bit-field width from this member.
2603 // Note: used by some clients (i.e., do not remove it).
2604 void removeBitWidth() {
2605 assert(isBitField() && "no bitfield width to remove")(static_cast <bool> (isBitField() && "no bitfield width to remove"
) ? void (0) : __assert_fail ("isBitField() && \"no bitfield width to remove\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 2605, __extension__ __PRETTY_FUNCTION__))
;
2606 InitStorage.setPointer(getInClassInitializer());
2607 BitField = false;
2608 }
2609
2610 /// Get the kind of (C++11) default member initializer that this field has.
2611 InClassInitStyle getInClassInitStyle() const {
2612 InitStorageKind storageKind = InitStorage.getInt();
2613 return (storageKind == ISK_CapturedVLAType
2614 ? ICIS_NoInit : (InClassInitStyle) storageKind);
2615 }
2616
2617 /// Determine whether this member has a C++11 default member initializer.
2618 bool hasInClassInitializer() const {
2619 return getInClassInitStyle() != ICIS_NoInit;
2620 }
2621
2622 /// Get the C++11 default member initializer for this member, or null if one
2623 /// has not been set. If a valid declaration has a default member initializer,
2624 /// but this returns null, then we have not parsed and attached it yet.
2625 Expr *getInClassInitializer() const {
2626 if (!hasInClassInitializer())
2627 return nullptr;
2628 void *Ptr = InitStorage.getPointer();
2629 if (BitField)
2630 return static_cast<InitAndBitWidth*>(Ptr)->Init;
2631 return static_cast<Expr*>(Ptr);
2632 }
2633
2634 /// Set the C++11 in-class initializer for this member.
2635 void setInClassInitializer(Expr *Init) {
2636 assert(hasInClassInitializer() && !getInClassInitializer())(static_cast <bool> (hasInClassInitializer() &&
!getInClassInitializer()) ? void (0) : __assert_fail ("hasInClassInitializer() && !getInClassInitializer()"
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 2636, __extension__ __PRETTY_FUNCTION__))
;
2637 if (BitField)
2638 static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init;
2639 else
2640 InitStorage.setPointer(Init);
2641 }
2642
2643 /// Remove the C++11 in-class initializer from this member.
2644 void removeInClassInitializer() {
2645 assert(hasInClassInitializer() && "no initializer to remove")(static_cast <bool> (hasInClassInitializer() &&
"no initializer to remove") ? void (0) : __assert_fail ("hasInClassInitializer() && \"no initializer to remove\""
, "/build/llvm-toolchain-snapshot-7~svn325118/tools/clang/include/clang/AST/Decl.h"
, 2645, __extension__ __PRETTY_FUNCTION__))
;
2646 InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit);
2647 }
2648
2649 /// \brief Determine whether this member captures the variable length array
2650 /// type.
2651 bool hasCapturedVLAType() const {
2652 return InitStorage.getInt() == ISK_CapturedVLAType;
2653 }
2654
2655 /// \brief Get the captured variable length array type.
2656 const VariableArrayType *getCapturedVLAType() const {
2657 return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
2658 InitStorage.getPointer())
2659 : nullptr;
2660 }
2661
2662 /// \brief Set the captured variable length array type for this field.
2663 void setCapturedVLAType(const VariableArrayType *VLAType);
2664
2665 /// Returns the parent of this field declaration, which
2666 /// is the struct in which this field is defined.
2667 const RecordDecl *getParent() const {
2668 return cast<RecordDecl>(getDeclContext());
2669 }
2670
2671 RecordDecl *getParent() {
2672 return cast<RecordDecl>(getDeclContext());
2673 }
2674
2675 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2676
2677 /// Retrieves the canonical declaration of this field.
2678 FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
2679 const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
2680
2681 // Implement isa/cast/dyncast/etc.
2682 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2683 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
2684};
2685
2686/// An instance of this object exists for each enum constant
2687/// that is defined. For example, in "enum X {a,b}", each of a/b are
2688/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
2689/// TagType for the X EnumDecl.
2690class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
2691 Stmt *Init; // an integer constant expression
2692 llvm::APSInt Val; // The value.
2693
2694protected:
2695 EnumConstantDecl(DeclContext *DC, SourceLocation L,
2696 IdentifierInfo *Id, QualType T, Expr *E,
2697 const llvm::APSInt &V)
2698 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
2699
2700public:
2701 friend class StmtIteratorBase;
2702
2703 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
2704 SourceLocation L, IdentifierInfo *Id,
2705 QualType T, Expr *E,
2706 const llvm::APSInt &V);
2707 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2708
2709 const Expr *getInitExpr() const { return (const Expr*) Init; }
2710 Expr *getInitExpr() { return (Expr*) Init; }
2711 const llvm::APSInt &getInitVal() const { return Val; }
2712
2713 void setInitExpr(Expr *E) { Init = (Stmt*) E; }
2714 void setInitVal(const llvm::APSInt &V) { Val = V; }
2715
2716 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
2717
2718 /// Retrieves the canonical declaration of this enumerator.
2719 EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
2720 const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
2721
2722 // Implement isa/cast/dyncast/etc.
2723 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2724 static bool classofKind(Kind K) { return K == EnumConstant; }
2725};
2726
2727/// Represents a field injected from an anonymous union/struct into the parent
2728/// scope. These are always implicit.
2729class IndirectFieldDecl : public ValueDecl,
2730 public Mergeable<IndirectFieldDecl> {
2731 NamedDecl **Chaining;
2732 unsigned ChainingSize;
2733
2734 IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2735 DeclarationName N, QualType T,
2736 MutableArrayRef<NamedDecl *> CH);
2737
2738 void anchor() override;
2739
2740public:
2741 friend class ASTDeclReader;
2742
2743 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
2744 SourceLocation L, IdentifierInfo *Id,
2745 QualType T, llvm::MutableArrayRef<NamedDecl *> CH);
2746
2747 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2748
2749 using chain_iterator = ArrayRef<NamedDecl *>::const_iterator;
2750
2751 ArrayRef<NamedDecl *> chain() const {
2752 return llvm::makeArrayRef(Chaining, ChainingSize);
2753 }
2754 chain_iterator chain_begin() const { return chain().begin(); }
2755 chain_iterator chain_end() const { return chain().end(); }
2756
2757 unsigned getChainingSize() const { return ChainingSize; }
2758
2759 FieldDecl *getAnonField() const {
2760 assert(chain().size() >= 2)(static_cast <bool> (chain().size() >= 2) ? void (0)
: __assert_fail ("chain().size() >=