Bug Summary

File:lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp
Warning:line 130, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name CxxModuleHandler.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -isystem /usr/include/libxml2 -D HAVE_ROUND -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/lldb/source/Plugins/ExpressionParser/Clang -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/lldb/source/Plugins/ExpressionParser/Clang -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/lldb/include -I tools/lldb/include -I include -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/llvm/include -I /usr/include/python3.9 -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/clang/include -I tools/lldb/../clang/include -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/lldb/source -I tools/lldb/source -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-deprecated-declarations -Wno-unknown-pragmas -Wno-strict-aliasing -Wno-deprecated-register -Wno-vla-extension -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-19-134126-35450-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp

/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp

1//===-- CxxModuleHandler.cpp ----------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "Plugins/ExpressionParser/Clang/CxxModuleHandler.h"
10#include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
11
12#include "lldb/Utility/Log.h"
13#include "clang/Sema/Lookup.h"
14#include "llvm/Support/Error.h"
15
16using namespace lldb_private;
17using namespace clang;
18
19CxxModuleHandler::CxxModuleHandler(ASTImporter &importer, ASTContext *target)
20 : m_importer(&importer),
21 m_sema(TypeSystemClang::GetASTContext(target)->getSema()) {
22
23 std::initializer_list<const char *> supported_names = {
24 // containers
25 "array",
26 "deque",
27 "forward_list",
28 "list",
29 "queue",
30 "stack",
31 "vector",
32 // pointers
33 "shared_ptr",
34 "unique_ptr",
35 "weak_ptr",
36 // iterator
37 "move_iterator",
38 "__wrap_iter",
39 // utility
40 "allocator",
41 "pair",
42 };
43 m_supported_templates.insert(supported_names.begin(), supported_names.end());
44}
45
46/// Builds a list of scopes that point into the given context.
47///
48/// \param sema The sema that will be using the scopes.
49/// \param ctxt The context that the scope should look into.
50/// \param result A list of scopes. The scopes need to be freed by the caller
51/// (except the TUScope which is owned by the sema).
52static void makeScopes(Sema &sema, DeclContext *ctxt,
53 std::vector<Scope *> &result) {
54 // FIXME: The result should be a list of unique_ptrs, but the TUScope makes
55 // this currently impossible as it's owned by the Sema.
56
57 if (auto parent = ctxt->getParent()) {
58 makeScopes(sema, parent, result);
59
60 Scope *scope =
61 new Scope(result.back(), Scope::DeclScope, sema.getDiagnostics());
62 scope->setEntity(ctxt);
63 result.push_back(scope);
64 } else
65 result.push_back(sema.TUScope);
66}
67
68/// Uses the Sema to look up the given name in the given DeclContext.
69static std::unique_ptr<LookupResult>
70emulateLookupInCtxt(Sema &sema, llvm::StringRef name, DeclContext *ctxt) {
71 IdentifierInfo &ident = sema.getASTContext().Idents.get(name);
72
73 std::unique_ptr<LookupResult> lookup_result;
74 lookup_result = std::make_unique<LookupResult>(sema, DeclarationName(&ident),
75 SourceLocation(),
76 Sema::LookupOrdinaryName);
77
78 // Usually during parsing we already encountered the scopes we would use. But
79 // here don't have these scopes so we have to emulate the behavior of the
80 // Sema during parsing.
81 std::vector<Scope *> scopes;
82 makeScopes(sema, ctxt, scopes);
83
84 // Now actually perform the lookup with the sema.
85 sema.LookupName(*lookup_result, scopes.back());
86
87 // Delete all the allocated scopes beside the translation unit scope (which
88 // has depth 0).
89 for (Scope *s : scopes)
90 if (s->getDepth() != 0)
91 delete s;
92
93 return lookup_result;
94}
95
96/// Error class for handling problems when finding a certain DeclContext.
97struct MissingDeclContext : public llvm::ErrorInfo<MissingDeclContext> {
98
99 static char ID;
100
101 MissingDeclContext(DeclContext *context, std::string error)
102 : m_context(context), m_error(error) {}
103
104 DeclContext *m_context;
105 std::string m_error;
106
107 void log(llvm::raw_ostream &OS) const override {
108 OS << llvm::formatv("error when reconstructing context of kind {0}:{1}",
109 m_context->getDeclKindName(), m_error);
110 }
111
112 std::error_code convertToErrorCode() const override {
113 return llvm::inconvertibleErrorCode();
114 }
115};
116
117char MissingDeclContext::ID = 0;
118
119/// Given a foreign decl context, this function finds the equivalent local
120/// decl context in the ASTContext of the given Sema. Potentially deserializes
121/// decls from the 'std' module if necessary.
122static llvm::Expected<DeclContext *>
123getEqualLocalDeclContext(Sema &sema, DeclContext *foreign_ctxt) {
124
125 // Inline namespaces don't matter for lookups, so let's skip them.
126 while (foreign_ctxt && foreign_ctxt->isInlineNamespace())
34
Assuming 'foreign_ctxt' is null
127 foreign_ctxt = foreign_ctxt->getParent();
128
129 // If the foreign context is the TU, we just return the local TU.
130 if (foreign_ctxt->isTranslationUnit())
35
Called C++ object pointer is null
131 return sema.getASTContext().getTranslationUnitDecl();
132
133 // Recursively find/build the parent DeclContext.
134 llvm::Expected<DeclContext *> parent =
135 getEqualLocalDeclContext(sema, foreign_ctxt->getParent());
136 if (!parent)
137 return parent;
138
139 // We currently only support building namespaces.
140 if (foreign_ctxt->isNamespace()) {
141 NamedDecl *ns = llvm::dyn_cast<NamedDecl>(foreign_ctxt);
142 llvm::StringRef ns_name = ns->getName();
143
144 auto lookup_result = emulateLookupInCtxt(sema, ns_name, *parent);
145 for (NamedDecl *named_decl : *lookup_result) {
146 if (DeclContext *DC = llvm::dyn_cast<DeclContext>(named_decl))
147 return DC->getPrimaryContext();
148 }
149 return llvm::make_error<MissingDeclContext>(
150 foreign_ctxt,
151 "Couldn't find namespace " + ns->getQualifiedNameAsString());
152 }
153
154 return llvm::make_error<MissingDeclContext>(foreign_ctxt, "Unknown context ");
155}
156
157/// Returns true iff tryInstantiateStdTemplate supports instantiating a template
158/// with the given template arguments.
159static bool templateArgsAreSupported(ArrayRef<TemplateArgument> a) {
160 for (const TemplateArgument &arg : a) {
10
Assuming '__begin1' is equal to '__end1'
161 switch (arg.getKind()) {
162 case TemplateArgument::Type:
163 case TemplateArgument::Integral:
164 break;
165 default:
166 // TemplateArgument kind hasn't been handled yet.
167 return false;
168 }
169 }
170 return true;
11
Returning the value 1, which participates in a condition later
171}
172
173/// Constructor function for Clang declarations. Ensures that the created
174/// declaration is registered with the ASTImporter.
175template <typename T, typename... Args>
176T *createDecl(ASTImporter &importer, Decl *from_d, Args &&... args) {
177 T *to_d = T::Create(std::forward<Args>(args)...);
178 importer.RegisterImportedDecl(from_d, to_d);
179 return to_d;
180}
181
182llvm::Optional<Decl *> CxxModuleHandler::tryInstantiateStdTemplate(Decl *d) {
183 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS(1u << 8));
184
185 // If we don't have a template to instiantiate, then there is nothing to do.
186 auto td = dyn_cast<ClassTemplateSpecializationDecl>(d);
3
Assuming 'd' is a 'ClassTemplateSpecializationDecl'
187 if (!td
3.1
'td' is non-null
3.1
'td' is non-null
3.1
'td' is non-null
)
4
Taking false branch
188 return llvm::None;
189
190 // We only care about templates in the std namespace.
191 if (!td->getDeclContext()->isStdNamespace())
5
Assuming the condition is false
6
Taking false branch
192 return llvm::None;
193
194 // We have a list of supported template names.
195 if (!m_supported_templates.contains(td->getName()))
7
Assuming the condition is false
8
Taking false branch
196 return llvm::None;
197
198 // Early check if we even support instantiating this template. We do this
199 // before we import anything into the target AST.
200 auto &foreign_args = td->getTemplateInstantiationArgs();
201 if (!templateArgsAreSupported(foreign_args.asArray()))
9
Calling 'templateArgsAreSupported'
12
Returning from 'templateArgsAreSupported'
13
Taking false branch
202 return llvm::None;
203
204 // Find the local DeclContext that corresponds to the DeclContext of our
205 // decl we want to import.
206 llvm::Expected<DeclContext *> to_context =
207 getEqualLocalDeclContext(*m_sema, td->getDeclContext());
14
Calling 'Decl::getDeclContext'
31
Returning from 'Decl::getDeclContext'
32
Passing value via 2nd parameter 'foreign_ctxt'
33
Calling 'getEqualLocalDeclContext'
208 if (!to_context) {
209 LLDB_LOG_ERROR(log, to_context.takeError(),do { ::lldb_private::Log *log_private = (log); ::llvm::Error error_private
= (to_context.takeError()); if (log_private && error_private
) { log_private->FormatError(::std::move(error_private), "lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp"
, __func__, "Got error while searching equal local DeclContext for decl "
"'{1}':\n{0}", td->getName()); } else ::llvm::consumeError
(::std::move(error_private)); } while (0)
210 "Got error while searching equal local DeclContext for decl "do { ::lldb_private::Log *log_private = (log); ::llvm::Error error_private
= (to_context.takeError()); if (log_private && error_private
) { log_private->FormatError(::std::move(error_private), "lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp"
, __func__, "Got error while searching equal local DeclContext for decl "
"'{1}':\n{0}", td->getName()); } else ::llvm::consumeError
(::std::move(error_private)); } while (0)
211 "'{1}':\n{0}",do { ::lldb_private::Log *log_private = (log); ::llvm::Error error_private
= (to_context.takeError()); if (log_private && error_private
) { log_private->FormatError(::std::move(error_private), "lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp"
, __func__, "Got error while searching equal local DeclContext for decl "
"'{1}':\n{0}", td->getName()); } else ::llvm::consumeError
(::std::move(error_private)); } while (0)
212 td->getName())do { ::lldb_private::Log *log_private = (log); ::llvm::Error error_private
= (to_context.takeError()); if (log_private && error_private
) { log_private->FormatError(::std::move(error_private), "lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp"
, __func__, "Got error while searching equal local DeclContext for decl "
"'{1}':\n{0}", td->getName()); } else ::llvm::consumeError
(::std::move(error_private)); } while (0)
;
213 return llvm::None;
214 }
215
216 // Look up the template in our local context.
217 std::unique_ptr<LookupResult> lookup =
218 emulateLookupInCtxt(*m_sema, td->getName(), *to_context);
219
220 ClassTemplateDecl *new_class_template = nullptr;
221 for (auto LD : *lookup) {
222 if ((new_class_template = dyn_cast<ClassTemplateDecl>(LD)))
223 break;
224 }
225 if (!new_class_template)
226 return llvm::None;
227
228 // Import the foreign template arguments.
229 llvm::SmallVector<TemplateArgument, 4> imported_args;
230
231 // If this logic is changed, also update templateArgsAreSupported.
232 for (const TemplateArgument &arg : foreign_args.asArray()) {
233 switch (arg.getKind()) {
234 case TemplateArgument::Type: {
235 llvm::Expected<QualType> type = m_importer->Import(arg.getAsType());
236 if (!type) {
237 LLDB_LOG_ERROR(log, type.takeError(), "Couldn't import type: {0}")do { ::lldb_private::Log *log_private = (log); ::llvm::Error error_private
= (type.takeError()); if (log_private && error_private
) { log_private->FormatError(::std::move(error_private), "lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp"
, __func__, "Couldn't import type: {0}"); } else ::llvm::consumeError
(::std::move(error_private)); } while (0)
;
238 return llvm::None;
239 }
240 imported_args.push_back(TemplateArgument(*type));
241 break;
242 }
243 case TemplateArgument::Integral: {
244 llvm::APSInt integral = arg.getAsIntegral();
245 llvm::Expected<QualType> type =
246 m_importer->Import(arg.getIntegralType());
247 if (!type) {
248 LLDB_LOG_ERROR(log, type.takeError(), "Couldn't import type: {0}")do { ::lldb_private::Log *log_private = (log); ::llvm::Error error_private
= (type.takeError()); if (log_private && error_private
) { log_private->FormatError(::std::move(error_private), "lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp"
, __func__, "Couldn't import type: {0}"); } else ::llvm::consumeError
(::std::move(error_private)); } while (0)
;
249 return llvm::None;
250 }
251 imported_args.push_back(
252 TemplateArgument(d->getASTContext(), integral, *type));
253 break;
254 }
255 default:
256 assert(false && "templateArgsAreSupported not updated?")(static_cast <bool> (false && "templateArgsAreSupported not updated?"
) ? void (0) : __assert_fail ("false && \"templateArgsAreSupported not updated?\""
, "lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp"
, 256, __extension__ __PRETTY_FUNCTION__))
;
257 }
258 }
259
260 // Find the class template specialization declaration that
261 // corresponds to these arguments.
262 void *InsertPos = nullptr;
263 ClassTemplateSpecializationDecl *result =
264 new_class_template->findSpecialization(imported_args, InsertPos);
265
266 if (result) {
267 // We found an existing specialization in the module that fits our arguments
268 // so we can treat it as the result and register it with the ASTImporter.
269 m_importer->RegisterImportedDecl(d, result);
270 return result;
271 }
272
273 // Instantiate the template.
274 result = createDecl<ClassTemplateSpecializationDecl>(
275 *m_importer, d, m_sema->getASTContext(),
276 new_class_template->getTemplatedDecl()->getTagKind(),
277 new_class_template->getDeclContext(),
278 new_class_template->getTemplatedDecl()->getLocation(),
279 new_class_template->getLocation(), new_class_template, imported_args,
280 nullptr);
281
282 new_class_template->AddSpecialization(result, InsertPos);
283 if (new_class_template->isOutOfLine())
284 result->setLexicalDeclContext(
285 new_class_template->getLexicalDeclContext());
286 return result;
287}
288
289llvm::Optional<Decl *> CxxModuleHandler::Import(Decl *d) {
290 if (!isValid())
1
Taking false branch
291 return {};
292
293 return tryInstantiateStdTemplate(d);
2
Calling 'CxxModuleHandler::tryInstantiateStdTemplate'
294}

/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/clang/include/clang/AST/DeclBase.h

1//===- DeclBase.h - Base Classes for representing declarations --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Decl and DeclContext interfaces.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_DECLBASE_H
14#define LLVM_CLANG_AST_DECLBASE_H
15
16#include "clang/AST/ASTDumperUtils.h"
17#include "clang/AST/AttrIterator.h"
18#include "clang/AST/DeclarationName.h"
19#include "clang/Basic/IdentifierTable.h"
20#include "clang/Basic/LLVM.h"
21#include "clang/Basic/SourceLocation.h"
22#include "clang/Basic/Specifiers.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 "llvm/Support/VersionTuple.h"
32#include <algorithm>
33#include <cassert>
34#include <cstddef>
35#include <iterator>
36#include <string>
37#include <type_traits>
38#include <utility>
39
40namespace clang {
41
42class ASTContext;
43class ASTMutationListener;
44class Attr;
45class BlockDecl;
46class DeclContext;
47class ExternalSourceSymbolAttr;
48class FunctionDecl;
49class FunctionType;
50class IdentifierInfo;
51enum Linkage : unsigned char;
52class LinkageSpecDecl;
53class Module;
54class NamedDecl;
55class ObjCContainerDecl;
56class ObjCMethodDecl;
57struct PrintingPolicy;
58class RecordDecl;
59class SourceManager;
60class Stmt;
61class StoredDeclsMap;
62class TemplateDecl;
63class TemplateParameterList;
64class TranslationUnitDecl;
65class UsingDirectiveDecl;
66
67/// Captures the result of checking the availability of a
68/// declaration.
69enum AvailabilityResult {
70 AR_Available = 0,
71 AR_NotYetIntroduced,
72 AR_Deprecated,
73 AR_Unavailable
74};
75
76/// Decl - This represents one declaration (or definition), e.g. a variable,
77/// typedef, function, struct, etc.
78///
79/// Note: There are objects tacked on before the *beginning* of Decl
80/// (and its subclasses) in its Decl::operator new(). Proper alignment
81/// of all subclasses (not requiring more than the alignment of Decl) is
82/// asserted in DeclBase.cpp.
83class alignas(8) Decl {
84public:
85 /// Lists the kind of concrete classes of Decl.
86 enum Kind {
87#define DECL(DERIVED, BASE) DERIVED,
88#define ABSTRACT_DECL(DECL)
89#define DECL_RANGE(BASE, START, END) \
90 first##BASE = START, last##BASE = END,
91#define LAST_DECL_RANGE(BASE, START, END) \
92 first##BASE = START, last##BASE = END
93#include "clang/AST/DeclNodes.inc"
94 };
95
96 /// A placeholder type used to construct an empty shell of a
97 /// decl-derived type that will be filled in later (e.g., by some
98 /// deserialization method).
99 struct EmptyShell {};
100
101 /// IdentifierNamespace - The different namespaces in which
102 /// declarations may appear. According to C99 6.2.3, there are
103 /// four namespaces, labels, tags, members and ordinary
104 /// identifiers. C++ describes lookup completely differently:
105 /// certain lookups merely "ignore" certain kinds of declarations,
106 /// usually based on whether the declaration is of a type, etc.
107 ///
108 /// These are meant as bitmasks, so that searches in
109 /// C++ can look into the "tag" namespace during ordinary lookup.
110 ///
111 /// Decl currently provides 15 bits of IDNS bits.
112 enum IdentifierNamespace {
113 /// Labels, declared with 'x:' and referenced with 'goto x'.
114 IDNS_Label = 0x0001,
115
116 /// Tags, declared with 'struct foo;' and referenced with
117 /// 'struct foo'. All tags are also types. This is what
118 /// elaborated-type-specifiers look for in C.
119 /// This also contains names that conflict with tags in the
120 /// same scope but that are otherwise ordinary names (non-type
121 /// template parameters and indirect field declarations).
122 IDNS_Tag = 0x0002,
123
124 /// Types, declared with 'struct foo', typedefs, etc.
125 /// This is what elaborated-type-specifiers look for in C++,
126 /// but note that it's ill-formed to find a non-tag.
127 IDNS_Type = 0x0004,
128
129 /// Members, declared with object declarations within tag
130 /// definitions. In C, these can only be found by "qualified"
131 /// lookup in member expressions. In C++, they're found by
132 /// normal lookup.
133 IDNS_Member = 0x0008,
134
135 /// Namespaces, declared with 'namespace foo {}'.
136 /// Lookup for nested-name-specifiers find these.
137 IDNS_Namespace = 0x0010,
138
139 /// Ordinary names. In C, everything that's not a label, tag,
140 /// member, or function-local extern ends up here.
141 IDNS_Ordinary = 0x0020,
142
143 /// Objective C \@protocol.
144 IDNS_ObjCProtocol = 0x0040,
145
146 /// This declaration is a friend function. A friend function
147 /// declaration is always in this namespace but may also be in
148 /// IDNS_Ordinary if it was previously declared.
149 IDNS_OrdinaryFriend = 0x0080,
150
151 /// This declaration is a friend class. A friend class
152 /// declaration is always in this namespace but may also be in
153 /// IDNS_Tag|IDNS_Type if it was previously declared.
154 IDNS_TagFriend = 0x0100,
155
156 /// This declaration is a using declaration. A using declaration
157 /// *introduces* a number of other declarations into the current
158 /// scope, and those declarations use the IDNS of their targets,
159 /// but the actual using declarations go in this namespace.
160 IDNS_Using = 0x0200,
161
162 /// This declaration is a C++ operator declared in a non-class
163 /// context. All such operators are also in IDNS_Ordinary.
164 /// C++ lexical operator lookup looks for these.
165 IDNS_NonMemberOperator = 0x0400,
166
167 /// This declaration is a function-local extern declaration of a
168 /// variable or function. This may also be IDNS_Ordinary if it
169 /// has been declared outside any function. These act mostly like
170 /// invisible friend declarations, but are also visible to unqualified
171 /// lookup within the scope of the declaring function.
172 IDNS_LocalExtern = 0x0800,
173
174 /// This declaration is an OpenMP user defined reduction construction.
175 IDNS_OMPReduction = 0x1000,
176
177 /// This declaration is an OpenMP user defined mapper.
178 IDNS_OMPMapper = 0x2000,
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 /// 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*>(); }
16
Calling 'PointerUnion::is'
18
Returning from 'PointerUnion::is'
19
Returning the value 1, which participates in a condition later
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*>();
23
Calling 'PointerUnion::get'
27
Returning from 'PointerUnion::get'
28
Returning pointer
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 /// Whether this declaration was "used", meaning that a definition is
292 /// required.
293 unsigned Used : 1;
294
295 /// 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 /// 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 /// Whether statistic collection is enabled.
307 static bool StatisticsEnabled;
308
309protected:
310 friend class ASTDeclReader;
311 friend class ASTDeclWriter;
312 friend class ASTNodeImporter;
313 friend class ASTReader;
314 friend class CXXClassMemberWrapper;
315 friend class LinkageComputer;
316 template<typename decl_type> friend class Redeclarable;
317
318 /// Access - Used by C++ decls for the access specifier.
319 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
320 unsigned Access : 2;
321
322 /// Whether this declaration was loaded from an AST file.
323 unsigned FromASTFile : 1;
324
325 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
326 unsigned IdentifierNamespace : 14;
327
328 /// If 0, we have not computed the linkage of this declaration.
329 /// Otherwise, it is the linkage + 1.
330 mutable unsigned CacheValidAndLinkage : 3;
331
332 /// Allocate memory for a deserialized declaration.
333 ///
334 /// This routine must be used to allocate memory for any declaration that is
335 /// deserialized from a module file.
336 ///
337 /// \param Size The size of the allocated object.
338 /// \param Ctx The context in which we will allocate memory.
339 /// \param ID The global ID of the deserialized declaration.
340 /// \param Extra The amount of extra space to allocate after the object.
341 void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
342 std::size_t Extra = 0);
343
344 /// Allocate memory for a non-deserialized declaration.
345 void *operator new(std::size_t Size, const ASTContext &Ctx,
346 DeclContext *Parent, std::size_t Extra = 0);
347
348private:
349 bool AccessDeclContextCheck() const;
350
351 /// Get the module ownership kind to use for a local lexical child of \p DC,
352 /// which may be either a local or (rarely) an imported declaration.
353 static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) {
354 if (DC) {
355 auto *D = cast<Decl>(DC);
356 auto MOK = D->getModuleOwnershipKind();
357 if (MOK != ModuleOwnershipKind::Unowned &&
358 (!D->isFromASTFile() || D->hasLocalOwningModuleStorage()))
359 return MOK;
360 // If D is not local and we have no local module storage, then we don't
361 // need to track module ownership at all.
362 }
363 return ModuleOwnershipKind::Unowned;
364 }
365
366public:
367 Decl() = delete;
368 Decl(const Decl&) = delete;
369 Decl(Decl &&) = delete;
370 Decl &operator=(const Decl&) = delete;
371 Decl &operator=(Decl&&) = delete;
372
373protected:
374 Decl(Kind DK, DeclContext *DC, SourceLocation L)
375 : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)),
376 DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false),
377 Implicit(false), Used(false), Referenced(false),
378 TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0),
379 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
380 CacheValidAndLinkage(0) {
381 if (StatisticsEnabled) add(DK);
382 }
383
384 Decl(Kind DK, EmptyShell Empty)
385 : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false),
386 Used(false), Referenced(false), TopLevelDeclInObjCContainer(false),
387 Access(AS_none), FromASTFile(0),
388 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
389 CacheValidAndLinkage(0) {
390 if (StatisticsEnabled) add(DK);
391 }
392
393 virtual ~Decl();
394
395 /// Update a potentially out-of-date declaration.
396 void updateOutOfDate(IdentifierInfo &II) const;
397
398 Linkage getCachedLinkage() const {
399 return Linkage(CacheValidAndLinkage - 1);
400 }
401
402 void setCachedLinkage(Linkage L) const {
403 CacheValidAndLinkage = L + 1;
404 }
405
406 bool hasCachedLinkage() const {
407 return CacheValidAndLinkage;
408 }
409
410public:
411 /// Source range that this declaration covers.
412 virtual SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
413 return SourceRange(getLocation(), getLocation());
414 }
415
416 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
417 return getSourceRange().getBegin();
418 }
419
420 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
421 return getSourceRange().getEnd();
422 }
423
424 SourceLocation getLocation() const { return Loc; }
425 void setLocation(SourceLocation L) { Loc = L; }
426
427 Kind getKind() const { return static_cast<Kind>(DeclKind); }
428 const char *getDeclKindName() const;
429
430 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
431 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
432
433 DeclContext *getDeclContext() {
434 if (isInSemaDC())
15
Calling 'Decl::isInSemaDC'
20
Returning from 'Decl::isInSemaDC'
21
Taking true branch
435 return getSemanticDC();
22
Calling 'Decl::getSemanticDC'
29
Returning from 'Decl::getSemanticDC'
30
Returning pointer
436 return getMultipleDC()->SemanticDC;
437 }
438 const DeclContext *getDeclContext() const {
439 return const_cast<Decl*>(this)->getDeclContext();
440 }
441
442 /// Find the innermost non-closure ancestor of this declaration,
443 /// walking up through blocks, lambdas, etc. If that ancestor is
444 /// not a code context (!isFunctionOrMethod()), returns null.
445 ///
446 /// A declaration may be its own non-closure context.
447 Decl *getNonClosureContext();
448 const Decl *getNonClosureContext() const {
449 return const_cast<Decl*>(this)->getNonClosureContext();
450 }
451
452 TranslationUnitDecl *getTranslationUnitDecl();
453 const TranslationUnitDecl *getTranslationUnitDecl() const {
454 return const_cast<Decl*>(this)->getTranslationUnitDecl();
455 }
456
457 bool isInAnonymousNamespace() const;
458
459 bool isInStdNamespace() const;
460
461 ASTContext &getASTContext() const LLVM_READONLY__attribute__((__pure__));
462
463 /// Helper to get the language options from the ASTContext.
464 /// Defined out of line to avoid depending on ASTContext.h.
465 const LangOptions &getLangOpts() const LLVM_READONLY__attribute__((__pure__));
466
467 void setAccess(AccessSpecifier AS) {
468 Access = AS;
469 assert(AccessDeclContextCheck())(static_cast <bool> (AccessDeclContextCheck()) ? void (
0) : __assert_fail ("AccessDeclContextCheck()", "clang/include/clang/AST/DeclBase.h"
, 469, __extension__ __PRETTY_FUNCTION__))
;
470 }
471
472 AccessSpecifier getAccess() const {
473 assert(AccessDeclContextCheck())(static_cast <bool> (AccessDeclContextCheck()) ? void (
0) : __assert_fail ("AccessDeclContextCheck()", "clang/include/clang/AST/DeclBase.h"
, 473, __extension__ __PRETTY_FUNCTION__))
;
474 return AccessSpecifier(Access);
475 }
476
477 /// Retrieve the access specifier for this declaration, even though
478 /// it may not yet have been properly set.
479 AccessSpecifier getAccessUnsafe() const {
480 return AccessSpecifier(Access);
481 }
482
483 bool hasAttrs() const { return HasAttrs; }
484
485 void setAttrs(const AttrVec& Attrs) {
486 return setAttrsImpl(Attrs, getASTContext());
487 }
488
489 AttrVec &getAttrs() {
490 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
491 }
492
493 const AttrVec &getAttrs() const;
494 void dropAttrs();
495 void addAttr(Attr *A);
496
497 using attr_iterator = AttrVec::const_iterator;
498 using attr_range = llvm::iterator_range<attr_iterator>;
499
500 attr_range attrs() const {
501 return attr_range(attr_begin(), attr_end());
502 }
503
504 attr_iterator attr_begin() const {
505 return hasAttrs() ? getAttrs().begin() : nullptr;
506 }
507 attr_iterator attr_end() const {
508 return hasAttrs() ? getAttrs().end() : nullptr;
509 }
510
511 template <typename T>
512 void dropAttr() {
513 if (!HasAttrs) return;
514
515 AttrVec &Vec = getAttrs();
516 llvm::erase_if(Vec, [](Attr *A) { return isa<T>(A); });
517
518 if (Vec.empty())
519 HasAttrs = false;
520 }
521
522 template <typename T>
523 llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
524 return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>());
525 }
526
527 template <typename T>
528 specific_attr_iterator<T> specific_attr_begin() const {
529 return specific_attr_iterator<T>(attr_begin());
530 }
531
532 template <typename T>
533 specific_attr_iterator<T> specific_attr_end() const {
534 return specific_attr_iterator<T>(attr_end());
535 }
536
537 template<typename T> T *getAttr() const {
538 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
539 }
540
541 template<typename T> bool hasAttr() const {
542 return hasAttrs() && hasSpecificAttr<T>(getAttrs());
543 }
544
545 /// getMaxAlignment - return the maximum alignment specified by attributes
546 /// on this decl, 0 if there are none.
547 unsigned getMaxAlignment() const;
548
549 /// setInvalidDecl - Indicates the Decl had a semantic error. This
550 /// allows for graceful error recovery.
551 void setInvalidDecl(bool Invalid = true);
552 bool isInvalidDecl() const { return (bool) InvalidDecl; }
553
554 /// isImplicit - Indicates whether the declaration was implicitly
555 /// generated by the implementation. If false, this declaration
556 /// was written explicitly in the source code.
557 bool isImplicit() const { return Implicit; }
558 void setImplicit(bool I = true) { Implicit = I; }
559
560 /// Whether *any* (re-)declaration of the entity was used, meaning that
561 /// a definition is required.
562 ///
563 /// \param CheckUsedAttr When true, also consider the "used" attribute
564 /// (in addition to the "used" bit set by \c setUsed()) when determining
565 /// whether the function is used.
566 bool isUsed(bool CheckUsedAttr = true) const;
567
568 /// Set whether the declaration is used, in the sense of odr-use.
569 ///
570 /// This should only be used immediately after creating a declaration.
571 /// It intentionally doesn't notify any listeners.
572 void setIsUsed() { getCanonicalDecl()->Used = true; }
573
574 /// Mark the declaration used, in the sense of odr-use.
575 ///
576 /// This notifies any mutation listeners in addition to setting a bit
577 /// indicating the declaration is used.
578 void markUsed(ASTContext &C);
579
580 /// Whether any declaration of this entity was referenced.
581 bool isReferenced() const;
582
583 /// Whether this declaration was referenced. This should not be relied
584 /// upon for anything other than debugging.
585 bool isThisDeclarationReferenced() const { return Referenced; }
586
587 void setReferenced(bool R = true) { Referenced = R; }
588
589 /// Whether this declaration is a top-level declaration (function,
590 /// global variable, etc.) that is lexically inside an objc container
591 /// definition.
592 bool isTopLevelDeclInObjCContainer() const {
593 return TopLevelDeclInObjCContainer;
594 }
595
596 void setTopLevelDeclInObjCContainer(bool V = true) {
597 TopLevelDeclInObjCContainer = V;
598 }
599
600 /// Looks on this and related declarations for an applicable
601 /// external source symbol attribute.
602 ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const;
603
604 /// Whether this declaration was marked as being private to the
605 /// module in which it was defined.
606 bool isModulePrivate() const {
607 return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate;
608 }
609
610 /// Return true if this declaration has an attribute which acts as
611 /// definition of the entity, such as 'alias' or 'ifunc'.
612 bool hasDefiningAttr() const;
613
614 /// Return this declaration's defining attribute if it has one.
615 const Attr *getDefiningAttr() const;
616
617protected:
618 /// Specify that this declaration was marked as being private
619 /// to the module in which it was defined.
620 void setModulePrivate() {
621 // The module-private specifier has no effect on unowned declarations.
622 // FIXME: We should track this in some way for source fidelity.
623 if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned)
624 return;
625 setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate);
626 }
627
628public:
629 /// Set the FromASTFile flag. This indicates that this declaration
630 /// was deserialized and not parsed from source code and enables
631 /// features such as module ownership information.
632 void setFromASTFile() {
633 FromASTFile = true;
634 }
635
636 /// Set the owning module ID. This may only be called for
637 /// deserialized Decls.
638 void setOwningModuleID(unsigned ID) {
639 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\""
, "clang/include/clang/AST/DeclBase.h", 639, __extension__ __PRETTY_FUNCTION__
))
;
640 *((unsigned*)this - 2) = ID;
641 }
642
643public:
644 /// Determine the availability of the given declaration.
645 ///
646 /// This routine will determine the most restrictive availability of
647 /// the given declaration (e.g., preferring 'unavailable' to
648 /// 'deprecated').
649 ///
650 /// \param Message If non-NULL and the result is not \c
651 /// AR_Available, will be set to a (possibly empty) message
652 /// describing why the declaration has not been introduced, is
653 /// deprecated, or is unavailable.
654 ///
655 /// \param EnclosingVersion The version to compare with. If empty, assume the
656 /// deployment target version.
657 ///
658 /// \param RealizedPlatform If non-NULL and the availability result is found
659 /// in an available attribute it will set to the platform which is written in
660 /// the available attribute.
661 AvailabilityResult
662 getAvailability(std::string *Message = nullptr,
663 VersionTuple EnclosingVersion = VersionTuple(),
664 StringRef *RealizedPlatform = nullptr) const;
665
666 /// Retrieve the version of the target platform in which this
667 /// declaration was introduced.
668 ///
669 /// \returns An empty version tuple if this declaration has no 'introduced'
670 /// availability attributes, or the version tuple that's specified in the
671 /// attribute otherwise.
672 VersionTuple getVersionIntroduced() const;
673
674 /// Determine whether this declaration is marked 'deprecated'.
675 ///
676 /// \param Message If non-NULL and the declaration is deprecated,
677 /// this will be set to the message describing why the declaration
678 /// was deprecated (which may be empty).
679 bool isDeprecated(std::string *Message = nullptr) const {
680 return getAvailability(Message) == AR_Deprecated;
681 }
682
683 /// Determine whether this declaration is marked 'unavailable'.
684 ///
685 /// \param Message If non-NULL and the declaration is unavailable,
686 /// this will be set to the message describing why the declaration
687 /// was made unavailable (which may be empty).
688 bool isUnavailable(std::string *Message = nullptr) const {
689 return getAvailability(Message) == AR_Unavailable;
690 }
691
692 /// Determine whether this is a weak-imported symbol.
693 ///
694 /// Weak-imported symbols are typically marked with the
695 /// 'weak_import' attribute, but may also be marked with an
696 /// 'availability' attribute where we're targing a platform prior to
697 /// the introduction of this feature.
698 bool isWeakImported() const;
699
700 /// Determines whether this symbol can be weak-imported,
701 /// e.g., whether it would be well-formed to add the weak_import
702 /// attribute.
703 ///
704 /// \param IsDefinition Set to \c true to indicate that this
705 /// declaration cannot be weak-imported because it has a definition.
706 bool canBeWeakImported(bool &IsDefinition) const;
707
708 /// Determine whether this declaration came from an AST file (such as
709 /// a precompiled header or module) rather than having been parsed.
710 bool isFromASTFile() const { return FromASTFile; }
711
712 /// Retrieve the global declaration ID associated with this
713 /// declaration, which specifies where this Decl was loaded from.
714 unsigned getGlobalID() const {
715 if (isFromASTFile())
716 return *((const unsigned*)this - 1);
717 return 0;
718 }
719
720 /// Retrieve the global ID of the module that owns this particular
721 /// declaration.
722 unsigned getOwningModuleID() const {
723 if (isFromASTFile())
724 return *((const unsigned*)this - 2);
725 return 0;
726 }
727
728private:
729 Module *getOwningModuleSlow() const;
730
731protected:
732 bool hasLocalOwningModuleStorage() const;
733
734public:
735 /// Get the imported owning module, if this decl is from an imported
736 /// (non-local) module.
737 Module *getImportedOwningModule() const {
738 if (!isFromASTFile() || !hasOwningModule())
739 return nullptr;
740
741 return getOwningModuleSlow();
742 }
743
744 /// Get the local owning module, if known. Returns nullptr if owner is
745 /// not yet known or declaration is not from a module.
746 Module *getLocalOwningModule() const {
747 if (isFromASTFile() || !hasOwningModule())
748 return nullptr;
749
750 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\""
, "clang/include/clang/AST/DeclBase.h", 751, __extension__ __PRETTY_FUNCTION__
))
751 "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\""
, "clang/include/clang/AST/DeclBase.h", 751, __extension__ __PRETTY_FUNCTION__
))
;
752 return reinterpret_cast<Module *const *>(this)[-1];
753 }
754 void setLocalOwningModule(Module *M) {
755 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\""
, "clang/include/clang/AST/DeclBase.h", 757, __extension__ __PRETTY_FUNCTION__
))
756 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\""
, "clang/include/clang/AST/DeclBase.h", 757, __extension__ __PRETTY_FUNCTION__
))
757 "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\""
, "clang/include/clang/AST/DeclBase.h", 757, __extension__ __PRETTY_FUNCTION__
))
;
758 reinterpret_cast<Module **>(this)[-1] = M;
759 }
760
761 /// Is this declaration owned by some module?
762 bool hasOwningModule() const {
763 return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned;
764 }
765
766 /// Get the module that owns this declaration (for visibility purposes).
767 Module *getOwningModule() const {
768 return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule();
769 }
770
771 /// Get the module that owns this declaration for linkage purposes.
772 /// There only ever is such a module under the C++ Modules TS.
773 ///
774 /// \param IgnoreLinkage Ignore the linkage of the entity; assume that
775 /// all declarations in a global module fragment are unowned.
776 Module *getOwningModuleForLinkage(bool IgnoreLinkage = false) const;
777
778 /// Determine whether this declaration is definitely visible to name lookup,
779 /// independent of whether the owning module is visible.
780 /// Note: The declaration may be visible even if this returns \c false if the
781 /// owning module is visible within the query context. This is a low-level
782 /// helper function; most code should be calling Sema::isVisible() instead.
783 bool isUnconditionallyVisible() const {
784 return (int)getModuleOwnershipKind() <= (int)ModuleOwnershipKind::Visible;
785 }
786
787 /// Set that this declaration is globally visible, even if it came from a
788 /// module that is not visible.
789 void setVisibleDespiteOwningModule() {
790 if (!isUnconditionallyVisible())
791 setModuleOwnershipKind(ModuleOwnershipKind::Visible);
792 }
793
794 /// Get the kind of module ownership for this declaration.
795 ModuleOwnershipKind getModuleOwnershipKind() const {
796 return NextInContextAndBits.getInt();
797 }
798
799 /// Set whether this declaration is hidden from name lookup.
800 void setModuleOwnershipKind(ModuleOwnershipKind MOK) {
801 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\""
, "clang/include/clang/AST/DeclBase.h", 804, __extension__ __PRETTY_FUNCTION__
))
802 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\""
, "clang/include/clang/AST/DeclBase.h", 804, __extension__ __PRETTY_FUNCTION__
))
803 !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\""
, "clang/include/clang/AST/DeclBase.h", 804, __extension__ __PRETTY_FUNCTION__
))
804 "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\""
, "clang/include/clang/AST/DeclBase.h", 804, __extension__ __PRETTY_FUNCTION__
))
;
805 NextInContextAndBits.setInt(MOK);
806 }
807
808 unsigned getIdentifierNamespace() const {
809 return IdentifierNamespace;
810 }
811
812 bool isInIdentifierNamespace(unsigned NS) const {
813 return getIdentifierNamespace() & NS;
814 }
815
816 static unsigned getIdentifierNamespaceForKind(Kind DK);
817
818 bool hasTagIdentifierNamespace() const {
819 return isTagIdentifierNamespace(getIdentifierNamespace());
820 }
821
822 static bool isTagIdentifierNamespace(unsigned NS) {
823 // TagDecls have Tag and Type set and may also have TagFriend.
824 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
825 }
826
827 /// getLexicalDeclContext - The declaration context where this Decl was
828 /// lexically declared (LexicalDC). May be different from
829 /// getDeclContext() (SemanticDC).
830 /// e.g.:
831 ///
832 /// namespace A {
833 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
834 /// }
835 /// void A::f(); // SemanticDC == namespace 'A'
836 /// // LexicalDC == global namespace
837 DeclContext *getLexicalDeclContext() {
838 if (isInSemaDC())
839 return getSemanticDC();
840 return getMultipleDC()->LexicalDC;
841 }
842 const DeclContext *getLexicalDeclContext() const {
843 return const_cast<Decl*>(this)->getLexicalDeclContext();
844 }
845
846 /// Determine whether this declaration is declared out of line (outside its
847 /// semantic context).
848 virtual bool isOutOfLine() const;
849
850 /// setDeclContext - Set both the semantic and lexical DeclContext
851 /// to DC.
852 void setDeclContext(DeclContext *DC);
853
854 void setLexicalDeclContext(DeclContext *DC);
855
856 /// Determine whether this declaration is a templated entity (whether it is
857 // within the scope of a template parameter).
858 bool isTemplated() const;
859
860 /// Determine the number of levels of template parameter surrounding this
861 /// declaration.
862 unsigned getTemplateDepth() const;
863
864 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
865 /// scoped decl is defined outside the current function or method. This is
866 /// roughly global variables and functions, but also handles enums (which
867 /// could be defined inside or outside a function etc).
868 bool isDefinedOutsideFunctionOrMethod() const {
869 return getParentFunctionOrMethod() == nullptr;
870 }
871
872 /// Determine whether a substitution into this declaration would occur as
873 /// part of a substitution into a dependent local scope. Such a substitution
874 /// transitively substitutes into all constructs nested within this
875 /// declaration.
876 ///
877 /// This recognizes non-defining declarations as well as members of local
878 /// classes and lambdas:
879 /// \code
880 /// template<typename T> void foo() { void bar(); }
881 /// template<typename T> void foo2() { class ABC { void bar(); }; }
882 /// template<typename T> inline int x = [](){ return 0; }();
883 /// \endcode
884 bool isInLocalScopeForInstantiation() const;
885
886 /// If this decl is defined inside a function/method/block it returns
887 /// the corresponding DeclContext, otherwise it returns null.
888 const DeclContext *getParentFunctionOrMethod() const;
889 DeclContext *getParentFunctionOrMethod() {
890 return const_cast<DeclContext*>(
891 const_cast<const Decl*>(this)->getParentFunctionOrMethod());
892 }
893
894 /// Retrieves the "canonical" declaration of the given declaration.
895 virtual Decl *getCanonicalDecl() { return this; }
896 const Decl *getCanonicalDecl() const {
897 return const_cast<Decl*>(this)->getCanonicalDecl();
898 }
899
900 /// Whether this particular Decl is a canonical one.
901 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
902
903protected:
904 /// Returns the next redeclaration or itself if this is the only decl.
905 ///
906 /// Decl subclasses that can be redeclared should override this method so that
907 /// Decl::redecl_iterator can iterate over them.
908 virtual Decl *getNextRedeclarationImpl() { return this; }
909
910 /// Implementation of getPreviousDecl(), to be overridden by any
911 /// subclass that has a redeclaration chain.
912 virtual Decl *getPreviousDeclImpl() { return nullptr; }
913
914 /// Implementation of getMostRecentDecl(), to be overridden by any
915 /// subclass that has a redeclaration chain.
916 virtual Decl *getMostRecentDeclImpl() { return this; }
917
918public:
919 /// Iterates through all the redeclarations of the same decl.
920 class redecl_iterator {
921 /// Current - The current declaration.
922 Decl *Current = nullptr;
923 Decl *Starter;
924
925 public:
926 using value_type = Decl *;
927 using reference = const value_type &;
928 using pointer = const value_type *;
929 using iterator_category = std::forward_iterator_tag;
930 using difference_type = std::ptrdiff_t;
931
932 redecl_iterator() = default;
933 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) {}
934
935 reference operator*() const { return Current; }
936 value_type operator->() const { return Current; }
937
938 redecl_iterator& operator++() {
939 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\""
, "clang/include/clang/AST/DeclBase.h", 939, __extension__ __PRETTY_FUNCTION__
))
;
940 // Get either previous decl or latest decl.
941 Decl *Next = Current->getNextRedeclarationImpl();
942 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!\""
, "clang/include/clang/AST/DeclBase.h", 942, __extension__ __PRETTY_FUNCTION__
))
;
943 Current = (Next != Starter) ? Next : nullptr;
944 return *this;
945 }
946
947 redecl_iterator operator++(int) {
948 redecl_iterator tmp(*this);
949 ++(*this);
950 return tmp;
951 }
952
953 friend bool operator==(redecl_iterator x, redecl_iterator y) {
954 return x.Current == y.Current;
955 }
956
957 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
958 return x.Current != y.Current;
959 }
960 };
961
962 using redecl_range = llvm::iterator_range<redecl_iterator>;
963
964 /// Returns an iterator range for all the redeclarations of the same
965 /// decl. It will iterate at least once (when this decl is the only one).
966 redecl_range redecls() const {
967 return redecl_range(redecls_begin(), redecls_end());
968 }
969
970 redecl_iterator redecls_begin() const {
971 return redecl_iterator(const_cast<Decl *>(this));
972 }
973
974 redecl_iterator redecls_end() const { return redecl_iterator(); }
975
976 /// Retrieve the previous declaration that declares the same entity
977 /// as this declaration, or NULL if there is no previous declaration.
978 Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
979
980 /// Retrieve the previous declaration that declares the same entity
981 /// as this declaration, or NULL if there is no previous declaration.
982 const Decl *getPreviousDecl() const {
983 return const_cast<Decl *>(this)->getPreviousDeclImpl();
984 }
985
986 /// True if this is the first declaration in its redeclaration chain.
987 bool isFirstDecl() const {
988 return getPreviousDecl() == nullptr;
989 }
990
991 /// Retrieve the most recent declaration that declares the same entity
992 /// as this declaration (which may be this declaration).
993 Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
994
995 /// Retrieve the most recent declaration that declares the same entity
996 /// as this declaration (which may be this declaration).
997 const Decl *getMostRecentDecl() const {
998 return const_cast<Decl *>(this)->getMostRecentDeclImpl();
999 }
1000
1001 /// getBody - If this Decl represents a declaration for a body of code,
1002 /// such as a function or method definition, this method returns the
1003 /// top-level Stmt* of that body. Otherwise this method returns null.
1004 virtual Stmt* getBody() const { return nullptr; }
1005
1006 /// Returns true if this \c Decl represents a declaration for a body of
1007 /// code, such as a function or method definition.
1008 /// Note that \c hasBody can also return true if any redeclaration of this
1009 /// \c Decl represents a declaration for a body of code.
1010 virtual bool hasBody() const { return getBody() != nullptr; }
1011
1012 /// getBodyRBrace - Gets the right brace of the body, if a body exists.
1013 /// This works whether the body is a CompoundStmt or a CXXTryStmt.
1014 SourceLocation getBodyRBrace() const;
1015
1016 // global temp stats (until we have a per-module visitor)
1017 static void add(Kind k);
1018 static void EnableStatistics();
1019 static void PrintStats();
1020
1021 /// isTemplateParameter - Determines whether this declaration is a
1022 /// template parameter.
1023 bool isTemplateParameter() const;
1024
1025 /// isTemplateParameter - Determines whether this declaration is a
1026 /// template parameter pack.
1027 bool isTemplateParameterPack() const;
1028
1029 /// Whether this declaration is a parameter pack.
1030 bool isParameterPack() const;
1031
1032 /// returns true if this declaration is a template
1033 bool isTemplateDecl() const;
1034
1035 /// Whether this declaration is a function or function template.
1036 bool isFunctionOrFunctionTemplate() const {
1037 return (DeclKind >= Decl::firstFunction &&
1038 DeclKind <= Decl::lastFunction) ||
1039 DeclKind == FunctionTemplate;
1040 }
1041
1042 /// If this is a declaration that describes some template, this
1043 /// method returns that template declaration.
1044 ///
1045 /// Note that this returns nullptr for partial specializations, because they
1046 /// are not modeled as TemplateDecls. Use getDescribedTemplateParams to handle
1047 /// those cases.
1048 TemplateDecl *getDescribedTemplate() const;
1049
1050 /// If this is a declaration that describes some template or partial
1051 /// specialization, this returns the corresponding template parameter list.
1052 const TemplateParameterList *getDescribedTemplateParams() const;
1053
1054 /// Returns the function itself, or the templated function if this is a
1055 /// function template.
1056 FunctionDecl *getAsFunction() LLVM_READONLY__attribute__((__pure__));
1057
1058 const FunctionDecl *getAsFunction() const {
1059 return const_cast<Decl *>(this)->getAsFunction();
1060 }
1061
1062 /// Changes the namespace of this declaration to reflect that it's
1063 /// a function-local extern declaration.
1064 ///
1065 /// These declarations appear in the lexical context of the extern
1066 /// declaration, but in the semantic context of the enclosing namespace
1067 /// scope.
1068 void setLocalExternDecl() {
1069 Decl *Prev = getPreviousDecl();
1070 IdentifierNamespace &= ~IDNS_Ordinary;
1071
1072 // It's OK for the declaration to still have the "invisible friend" flag or
1073 // the "conflicts with tag declarations in this scope" flag for the outer
1074 // scope.
1075 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\""
, "clang/include/clang/AST/DeclBase.h", 1076, __extension__ __PRETTY_FUNCTION__
))
1076 "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\""
, "clang/include/clang/AST/DeclBase.h", 1076, __extension__ __PRETTY_FUNCTION__
))
;
1077
1078 IdentifierNamespace |= IDNS_LocalExtern;
1079 if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
1080 IdentifierNamespace |= IDNS_Ordinary;
1081 }
1082
1083 /// Determine whether this is a block-scope declaration with linkage.
1084 /// This will either be a local variable declaration declared 'extern', or a
1085 /// local function declaration.
1086 bool isLocalExternDecl() {
1087 return IdentifierNamespace & IDNS_LocalExtern;
1088 }
1089
1090 /// Changes the namespace of this declaration to reflect that it's
1091 /// the object of a friend declaration.
1092 ///
1093 /// These declarations appear in the lexical context of the friending
1094 /// class, but in the semantic context of the actual entity. This property
1095 /// applies only to a specific decl object; other redeclarations of the
1096 /// same entity may not (and probably don't) share this property.
1097 void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
1098 unsigned OldNS = IdentifierNamespace;
1099 assert((OldNS & (IDNS_Tag | IDNS_Ordinary |(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes neither ordinary nor tag") ?
void (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "clang/include/clang/AST/DeclBase.h", 1102, __extension__ __PRETTY_FUNCTION__
))
1100 IDNS_TagFriend | IDNS_OrdinaryFriend |(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes neither ordinary nor tag") ?
void (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "clang/include/clang/AST/DeclBase.h", 1102, __extension__ __PRETTY_FUNCTION__
))
1101 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes neither ordinary nor tag") ?
void (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "clang/include/clang/AST/DeclBase.h", 1102, __extension__ __PRETTY_FUNCTION__
))
1102 "namespace includes neither ordinary nor tag")(static_cast <bool> ((OldNS & (IDNS_Tag | IDNS_Ordinary
| IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes neither ordinary nor tag") ?
void (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\""
, "clang/include/clang/AST/DeclBase.h", 1102, __extension__ __PRETTY_FUNCTION__
))
;
1103 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
| IDNS_NonMemberOperator)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "clang/include/clang/AST/DeclBase.h", 1106, __extension__ __PRETTY_FUNCTION__
))
1104 IDNS_TagFriend | IDNS_OrdinaryFriend |(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
| IDNS_NonMemberOperator)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "clang/include/clang/AST/DeclBase.h", 1106, __extension__ __PRETTY_FUNCTION__
))
1105 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
| IDNS_NonMemberOperator)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "clang/include/clang/AST/DeclBase.h", 1106, __extension__ __PRETTY_FUNCTION__
))
1106 "namespace includes other than ordinary or tag")(static_cast <bool> (!(OldNS & ~(IDNS_Tag | IDNS_Ordinary
| IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern
| IDNS_NonMemberOperator)) && "namespace includes other than ordinary or tag"
) ? void (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\""
, "clang/include/clang/AST/DeclBase.h", 1106, __extension__ __PRETTY_FUNCTION__
))
;
1107
1108 Decl *Prev = getPreviousDecl();
1109 IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
1110
1111 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
1112 IdentifierNamespace |= IDNS_TagFriend;
1113 if (PerformFriendInjection ||
1114 (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
1115 IdentifierNamespace |= IDNS_Tag | IDNS_Type;
1116 }
1117
1118 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend |
1119 IDNS_LocalExtern | IDNS_NonMemberOperator)) {
1120 IdentifierNamespace |= IDNS_OrdinaryFriend;
1121 if (PerformFriendInjection ||
1122 (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
1123 IdentifierNamespace |= IDNS_Ordinary;
1124 }
1125 }
1126
1127 enum FriendObjectKind {
1128 FOK_None, ///< Not a friend object.
1129 FOK_Declared, ///< A friend of a previously-declared entity.
1130 FOK_Undeclared ///< A friend of a previously-undeclared entity.
1131 };
1132
1133 /// Determines whether this declaration is the object of a
1134 /// friend declaration and, if so, what kind.
1135 ///
1136 /// There is currently no direct way to find the associated FriendDecl.
1137 FriendObjectKind getFriendObjectKind() const {
1138 unsigned mask =
1139 (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
1140 if (!mask) return FOK_None;
1141 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
1142 : FOK_Undeclared);
1143 }
1144
1145 /// Specifies that this declaration is a C++ overloaded non-member.
1146 void setNonMemberOperator() {
1147 assert(getKind() == Function || getKind() == FunctionTemplate)(static_cast <bool> (getKind() == Function || getKind()
== FunctionTemplate) ? void (0) : __assert_fail ("getKind() == Function || getKind() == FunctionTemplate"
, "clang/include/clang/AST/DeclBase.h", 1147, __extension__ __PRETTY_FUNCTION__
))
;
1148 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\""
, "clang/include/clang/AST/DeclBase.h", 1149, __extension__ __PRETTY_FUNCTION__
))
1149 "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\""
, "clang/include/clang/AST/DeclBase.h", 1149, __extension__ __PRETTY_FUNCTION__
))
;
1150 IdentifierNamespace |= IDNS_NonMemberOperator;
1151 }
1152
1153 static bool classofKind(Kind K) { return true; }
1154 static DeclContext *castToDeclContext(const Decl *);
1155 static Decl *castFromDeclContext(const DeclContext *);
1156
1157 void print(raw_ostream &Out, unsigned Indentation = 0,
1158 bool PrintInstantiation = false) const;
1159 void print(raw_ostream &Out, const PrintingPolicy &Policy,
1160 unsigned Indentation = 0, bool PrintInstantiation = false) const;
1161 static void printGroup(Decl** Begin, unsigned NumDecls,
1162 raw_ostream &Out, const PrintingPolicy &Policy,
1163 unsigned Indentation = 0);
1164
1165 // Debuggers don't usually respect default arguments.
1166 void dump() const;
1167
1168 // Same as dump(), but forces color printing.
1169 void dumpColor() const;
1170
1171 void dump(raw_ostream &Out, bool Deserialize = false,
1172 ASTDumpOutputFormat OutputFormat = ADOF_Default) const;
1173
1174 /// \return Unique reproducible object identifier
1175 int64_t getID() const;
1176
1177 /// Looks through the Decl's underlying type to extract a FunctionType
1178 /// when possible. Will return null if the type underlying the Decl does not
1179 /// have a FunctionType.
1180 const FunctionType *getFunctionType(bool BlocksToo = true) const;
1181
1182private:
1183 void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
1184 void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
1185 ASTContext &Ctx);
1186
1187protected:
1188 ASTMutationListener *getASTMutationListener() const;
1189};
1190
1191/// Determine whether two declarations declare the same entity.
1192inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
1193 if (!D1 || !D2)
1194 return false;
1195
1196 if (D1 == D2)
1197 return true;
1198
1199 return D1->getCanonicalDecl() == D2->getCanonicalDecl();
1200}
1201
1202/// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
1203/// doing something to a specific decl.
1204class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
1205 const Decl *TheDecl;
1206 SourceLocation Loc;
1207 SourceManager &SM;
1208 const char *Message;
1209
1210public:
1211 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
1212 SourceManager &sm, const char *Msg)
1213 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
1214
1215 void print(raw_ostream &OS) const override;
1216};
1217} // namespace clang
1218
1219// Required to determine the layout of the PointerUnion<NamedDecl*> before
1220// seeing the NamedDecl definition being first used in DeclListNode::operator*.
1221namespace llvm {
1222 template <> struct PointerLikeTypeTraits<::clang::NamedDecl *> {
1223 static inline void *getAsVoidPointer(::clang::NamedDecl *P) { return P; }
1224 static inline ::clang::NamedDecl *getFromVoidPointer(void *P) {
1225 return static_cast<::clang::NamedDecl *>(P);
1226 }
1227 static constexpr int NumLowBitsAvailable = 3;
1228 };
1229}
1230
1231namespace clang {
1232/// A list storing NamedDecls in the lookup tables.
1233class DeclListNode {
1234 friend class ASTContext; // allocate, deallocate nodes.
1235 friend class StoredDeclsList;
1236public:
1237 using Decls = llvm::PointerUnion<NamedDecl*, DeclListNode*>;
1238 class iterator {
1239 friend class DeclContextLookupResult;
1240 friend class StoredDeclsList;
1241
1242 Decls Ptr;
1243 iterator(Decls Node) : Ptr(Node) { }
1244 public:
1245 using difference_type = ptrdiff_t;
1246 using value_type = NamedDecl*;
1247 using pointer = void;
1248 using reference = value_type;
1249 using iterator_category = std::forward_iterator_tag;
1250
1251 iterator() = default;
1252
1253 reference operator*() const {
1254 assert(Ptr && "dereferencing end() iterator")(static_cast <bool> (Ptr && "dereferencing end() iterator"
) ? void (0) : __assert_fail ("Ptr && \"dereferencing end() iterator\""
, "clang/include/clang/AST/DeclBase.h", 1254, __extension__ __PRETTY_FUNCTION__
))
;
1255 if (DeclListNode *CurNode = Ptr.dyn_cast<DeclListNode*>())
1256 return CurNode->D;
1257 return Ptr.get<NamedDecl*>();
1258 }
1259 void operator->() const { } // Unsupported.
1260 bool operator==(const iterator &X) const { return Ptr == X.Ptr; }
1261 bool operator!=(const iterator &X) const { return Ptr != X.Ptr; }
1262 inline iterator &operator++() { // ++It
1263 assert(!Ptr.isNull() && "Advancing empty iterator")(static_cast <bool> (!Ptr.isNull() && "Advancing empty iterator"
) ? void (0) : __assert_fail ("!Ptr.isNull() && \"Advancing empty iterator\""
, "clang/include/clang/AST/DeclBase.h", 1263, __extension__ __PRETTY_FUNCTION__
))
;
1264
1265 if (DeclListNode *CurNode = Ptr.dyn_cast<DeclListNode*>())
1266 Ptr = CurNode->Rest;
1267 else
1268 Ptr = nullptr;
1269 return *this;
1270 }
1271 iterator operator++(int) { // It++
1272 iterator temp = *this;
1273 ++(*this);
1274 return temp;
1275 }
1276 // Enables the pattern for (iterator I =..., E = I.end(); I != E; ++I)
1277 iterator end() { return iterator(); }
1278 };
1279private:
1280 NamedDecl *D = nullptr;
1281 Decls Rest = nullptr;
1282 DeclListNode(NamedDecl *ND) : D(ND) {}
1283};
1284
1285/// The results of name lookup within a DeclContext.
1286class DeclContextLookupResult {
1287 using Decls = DeclListNode::Decls;
1288
1289 /// When in collection form, this is what the Data pointer points to.
1290 Decls Result;
1291
1292public:
1293 DeclContextLookupResult() = default;
1294 DeclContextLookupResult(Decls Result) : Result(Result) {}
1295
1296 using iterator = DeclListNode::iterator;
1297 using const_iterator = iterator;
1298 using reference = iterator::reference;
1299
1300 iterator begin() { return iterator(Result); }
1301 iterator end() { return iterator(); }
1302 const_iterator begin() const {
1303 return const_cast<DeclContextLookupResult*>(this)->begin();
1304 }
1305 const_iterator end() const { return iterator(); }
1306
1307 bool empty() const { return Result.isNull(); }
1308 bool isSingleResult() const { return Result.dyn_cast<NamedDecl*>(); }
1309 reference front() const { return *begin(); }
1310
1311 // Find the first declaration of the given type in the list. Note that this
1312 // is not in general the earliest-declared declaration, and should only be
1313 // used when it's not possible for there to be more than one match or where
1314 // it doesn't matter which one is found.
1315 template<class T> T *find_first() const {
1316 for (auto *D : *this)
1317 if (T *Decl = dyn_cast<T>(D))
1318 return Decl;
1319
1320 return nullptr;
1321 }
1322};
1323
1324/// DeclContext - This is used only as base class of specific decl types that
1325/// can act as declaration contexts. These decls are (only the top classes
1326/// that directly derive from DeclContext are mentioned, not their subclasses):
1327///
1328/// TranslationUnitDecl
1329/// ExternCContext
1330/// NamespaceDecl
1331/// TagDecl
1332/// OMPDeclareReductionDecl
1333/// OMPDeclareMapperDecl
1334/// FunctionDecl
1335/// ObjCMethodDecl
1336/// ObjCContainerDecl
1337/// LinkageSpecDecl
1338/// ExportDecl
1339/// BlockDecl
1340/// CapturedDecl
1341class DeclContext {
1342 /// For makeDeclVisibleInContextImpl
1343 friend class ASTDeclReader;
1344 /// For reconcileExternalVisibleStorage, CreateStoredDeclsMap,
1345 /// hasNeedToReconcileExternalVisibleStorage
1346 friend class ExternalASTSource;
1347 /// For CreateStoredDeclsMap
1348 friend class DependentDiagnostic;
1349 /// For hasNeedToReconcileExternalVisibleStorage,
1350 /// hasLazyLocalLexicalLookups, hasLazyExternalLexicalLookups
1351 friend class ASTWriter;
1352
1353 // We use uint64_t in the bit-fields below since some bit-fields
1354 // cross the unsigned boundary and this breaks the packing.
1355
1356 /// Stores the bits used by DeclContext.
1357 /// If modified NumDeclContextBit, the ctor of DeclContext and the accessor
1358 /// methods in DeclContext should be updated appropriately.
1359 class DeclContextBitfields {
1360 friend class DeclContext;
1361 /// DeclKind - This indicates which class this is.
1362 uint64_t DeclKind : 7;
1363
1364 /// Whether this declaration context also has some external
1365 /// storage that contains additional declarations that are lexically
1366 /// part of this context.
1367 mutable uint64_t ExternalLexicalStorage : 1;
1368
1369 /// Whether this declaration context also has some external
1370 /// storage that contains additional declarations that are visible
1371 /// in this context.
1372 mutable uint64_t ExternalVisibleStorage : 1;
1373
1374 /// Whether this declaration context has had externally visible
1375 /// storage added since the last lookup. In this case, \c LookupPtr's
1376 /// invariant may not hold and needs to be fixed before we perform
1377 /// another lookup.
1378 mutable uint64_t NeedToReconcileExternalVisibleStorage : 1;
1379
1380 /// If \c true, this context may have local lexical declarations
1381 /// that are missing from the lookup table.
1382 mutable uint64_t HasLazyLocalLexicalLookups : 1;
1383
1384 /// If \c true, the external source may have lexical declarations
1385 /// that are missing from the lookup table.
1386 mutable uint64_t HasLazyExternalLexicalLookups : 1;
1387
1388 /// If \c true, lookups should only return identifier from
1389 /// DeclContext scope (for example TranslationUnit). Used in
1390 /// LookupQualifiedName()
1391 mutable uint64_t UseQualifiedLookup : 1;
1392 };
1393
1394 /// Number of bits in DeclContextBitfields.
1395 enum { NumDeclContextBits = 13 };
1396
1397 /// Stores the bits used by TagDecl.
1398 /// If modified NumTagDeclBits and the accessor
1399 /// methods in TagDecl should be updated appropriately.
1400 class TagDeclBitfields {
1401 friend class TagDecl;
1402 /// For the bits in DeclContextBitfields
1403 uint64_t : NumDeclContextBits;
1404
1405 /// The TagKind enum.
1406 uint64_t TagDeclKind : 3;
1407
1408 /// True if this is a definition ("struct foo {};"), false if it is a
1409 /// declaration ("struct foo;"). It is not considered a definition
1410 /// until the definition has been fully processed.
1411 uint64_t IsCompleteDefinition : 1;
1412
1413 /// True if this is currently being defined.
1414 uint64_t IsBeingDefined : 1;
1415
1416 /// True if this tag declaration is "embedded" (i.e., defined or declared
1417 /// for the very first time) in the syntax of a declarator.
1418 uint64_t IsEmbeddedInDeclarator : 1;
1419
1420 /// True if this tag is free standing, e.g. "struct foo;".
1421 uint64_t IsFreeStanding : 1;
1422
1423 /// Indicates whether it is possible for declarations of this kind
1424 /// to have an out-of-date definition.
1425 ///
1426 /// This option is only enabled when modules are enabled.
1427 uint64_t MayHaveOutOfDateDef : 1;
1428
1429 /// Has the full definition of this type been required by a use somewhere in
1430 /// the TU.
1431 uint64_t IsCompleteDefinitionRequired : 1;
1432 };
1433
1434 /// Number of non-inherited bits in TagDeclBitfields.
1435 enum { NumTagDeclBits = 9 };
1436
1437 /// Stores the bits used by EnumDecl.
1438 /// If modified NumEnumDeclBit and the accessor
1439 /// methods in EnumDecl should be updated appropriately.
1440 class EnumDeclBitfields {
1441 friend class EnumDecl;
1442 /// For the bits in DeclContextBitfields.
1443 uint64_t : NumDeclContextBits;
1444 /// For the bits in TagDeclBitfields.
1445 uint64_t : NumTagDeclBits;
1446
1447 /// Width in bits required to store all the non-negative
1448 /// enumerators of this enum.
1449 uint64_t NumPositiveBits : 8;
1450
1451 /// Width in bits required to store all the negative
1452 /// enumerators of this enum.
1453 uint64_t NumNegativeBits : 8;
1454
1455 /// True if this tag declaration is a scoped enumeration. Only
1456 /// possible in C++11 mode.
1457 uint64_t IsScoped : 1;
1458
1459 /// If this tag declaration is a scoped enum,
1460 /// then this is true if the scoped enum was declared using the class
1461 /// tag, false if it was declared with the struct tag. No meaning is
1462 /// associated if this tag declaration is not a scoped enum.
1463 uint64_t IsScopedUsingClassTag : 1;
1464
1465 /// True if this is an enumeration with fixed underlying type. Only
1466 /// possible in C++11, Microsoft extensions, or Objective C mode.
1467 uint64_t IsFixed : 1;
1468
1469 /// True if a valid hash is stored in ODRHash.
1470 uint64_t HasODRHash : 1;
1471 };
1472
1473 /// Number of non-inherited bits in EnumDeclBitfields.
1474 enum { NumEnumDeclBits = 20 };
1475
1476 /// Stores the bits used by RecordDecl.
1477 /// If modified NumRecordDeclBits and the accessor
1478 /// methods in RecordDecl should be updated appropriately.
1479 class RecordDeclBitfields {
1480 friend class RecordDecl;
1481 /// For the bits in DeclContextBitfields.
1482 uint64_t : NumDeclContextBits;
1483 /// For the bits in TagDeclBitfields.
1484 uint64_t : NumTagDeclBits;
1485
1486 /// This is true if this struct ends with a flexible
1487 /// array member (e.g. int X[]) or if this union contains a struct that does.
1488 /// If so, this cannot be contained in arrays or other structs as a member.
1489 uint64_t HasFlexibleArrayMember : 1;
1490
1491 /// Whether this is the type of an anonymous struct or union.
1492 uint64_t AnonymousStructOrUnion : 1;
1493
1494 /// This is true if this struct has at least one member
1495 /// containing an Objective-C object pointer type.
1496 uint64_t HasObjectMember : 1;
1497
1498 /// This is true if struct has at least one member of
1499 /// 'volatile' type.
1500 uint64_t HasVolatileMember : 1;
1501
1502 /// Whether the field declarations of this record have been loaded
1503 /// from external storage. To avoid unnecessary deserialization of
1504 /// methods/nested types we allow deserialization of just the fields
1505 /// when needed.
1506 mutable uint64_t LoadedFieldsFromExternalStorage : 1;
1507
1508 /// Basic properties of non-trivial C structs.
1509 uint64_t NonTrivialToPrimitiveDefaultInitialize : 1;
1510 uint64_t NonTrivialToPrimitiveCopy : 1;
1511 uint64_t NonTrivialToPrimitiveDestroy : 1;
1512
1513 /// The following bits indicate whether this is or contains a C union that
1514 /// is non-trivial to default-initialize, destruct, or copy. These bits
1515 /// imply the associated basic non-triviality predicates declared above.
1516 uint64_t HasNonTrivialToPrimitiveDefaultInitializeCUnion : 1;
1517 uint64_t HasNonTrivialToPrimitiveDestructCUnion : 1;
1518 uint64_t HasNonTrivialToPrimitiveCopyCUnion : 1;
1519
1520 /// Indicates whether this struct is destroyed in the callee.
1521 uint64_t ParamDestroyedInCallee : 1;
1522
1523 /// Represents the way this type is passed to a function.
1524 uint64_t ArgPassingRestrictions : 2;
1525 };
1526
1527 /// Number of non-inherited bits in RecordDeclBitfields.
1528 enum { NumRecordDeclBits = 14 };
1529
1530 /// Stores the bits used by OMPDeclareReductionDecl.
1531 /// If modified NumOMPDeclareReductionDeclBits and the accessor
1532 /// methods in OMPDeclareReductionDecl should be updated appropriately.
1533 class OMPDeclareReductionDeclBitfields {
1534 friend class OMPDeclareReductionDecl;
1535 /// For the bits in DeclContextBitfields
1536 uint64_t : NumDeclContextBits;
1537
1538 /// Kind of initializer,
1539 /// function call or omp_priv<init_expr> initializtion.
1540 uint64_t InitializerKind : 2;
1541 };
1542
1543 /// Number of non-inherited bits in OMPDeclareReductionDeclBitfields.
1544 enum { NumOMPDeclareReductionDeclBits = 2 };
1545
1546 /// Stores the bits used by FunctionDecl.
1547 /// If modified NumFunctionDeclBits and the accessor
1548 /// methods in FunctionDecl and CXXDeductionGuideDecl
1549 /// (for IsCopyDeductionCandidate) should be updated appropriately.
1550 class FunctionDeclBitfields {
1551 friend class FunctionDecl;
1552 /// For IsCopyDeductionCandidate
1553 friend class CXXDeductionGuideDecl;
1554 /// For the bits in DeclContextBitfields.
1555 uint64_t : NumDeclContextBits;
1556
1557 uint64_t SClass : 3;
1558 uint64_t IsInline : 1;
1559 uint64_t IsInlineSpecified : 1;
1560
1561 uint64_t IsVirtualAsWritten : 1;
1562 uint64_t IsPure : 1;
1563 uint64_t HasInheritedPrototype : 1;
1564 uint64_t HasWrittenPrototype : 1;
1565 uint64_t IsDeleted : 1;
1566 /// Used by CXXMethodDecl
1567 uint64_t IsTrivial : 1;
1568
1569 /// This flag indicates whether this function is trivial for the purpose of
1570 /// calls. This is meaningful only when this function is a copy/move
1571 /// constructor or a destructor.
1572 uint64_t IsTrivialForCall : 1;
1573
1574 uint64_t IsDefaulted : 1;
1575 uint64_t IsExplicitlyDefaulted : 1;
1576 uint64_t HasDefaultedFunctionInfo : 1;
1577 uint64_t HasImplicitReturnZero : 1;
1578 uint64_t IsLateTemplateParsed : 1;
1579
1580 /// Kind of contexpr specifier as defined by ConstexprSpecKind.
1581 uint64_t ConstexprKind : 2;
1582 uint64_t InstantiationIsPending : 1;
1583
1584 /// Indicates if the function uses __try.
1585 uint64_t UsesSEHTry : 1;
1586
1587 /// Indicates if the function was a definition
1588 /// but its body was skipped.
1589 uint64_t HasSkippedBody : 1;
1590
1591 /// Indicates if the function declaration will
1592 /// have a body, once we're done parsing it.
1593 uint64_t WillHaveBody : 1;
1594
1595 /// Indicates that this function is a multiversioned
1596 /// function using attribute 'target'.
1597 uint64_t IsMultiVersion : 1;
1598
1599 /// [C++17] Only used by CXXDeductionGuideDecl. Indicates that
1600 /// the Deduction Guide is the implicitly generated 'copy
1601 /// deduction candidate' (is used during overload resolution).
1602 uint64_t IsCopyDeductionCandidate : 1;
1603
1604 /// Store the ODRHash after first calculation.
1605 uint64_t HasODRHash : 1;
1606
1607 /// Indicates if the function uses Floating Point Constrained Intrinsics
1608 uint64_t UsesFPIntrin : 1;
1609 };
1610
1611 /// Number of non-inherited bits in FunctionDeclBitfields.
1612 enum { NumFunctionDeclBits = 27 };
1613
1614 /// Stores the bits used by CXXConstructorDecl. If modified
1615 /// NumCXXConstructorDeclBits and the accessor
1616 /// methods in CXXConstructorDecl should be updated appropriately.
1617 class CXXConstructorDeclBitfields {
1618 friend class CXXConstructorDecl;
1619 /// For the bits in DeclContextBitfields.
1620 uint64_t : NumDeclContextBits;
1621 /// For the bits in FunctionDeclBitfields.
1622 uint64_t : NumFunctionDeclBits;
1623
1624 /// 24 bits to fit in the remaining available space.
1625 /// Note that this makes CXXConstructorDeclBitfields take
1626 /// exactly 64 bits and thus the width of NumCtorInitializers
1627 /// will need to be shrunk if some bit is added to NumDeclContextBitfields,
1628 /// NumFunctionDeclBitfields or CXXConstructorDeclBitfields.
1629 uint64_t NumCtorInitializers : 21;
1630 uint64_t IsInheritingConstructor : 1;
1631
1632 /// Whether this constructor has a trail-allocated explicit specifier.
1633 uint64_t HasTrailingExplicitSpecifier : 1;
1634 /// If this constructor does't have a trail-allocated explicit specifier.
1635 /// Whether this constructor is explicit specified.
1636 uint64_t IsSimpleExplicit : 1;
1637 };
1638
1639 /// Number of non-inherited bits in CXXConstructorDeclBitfields.
1640 enum {
1641 NumCXXConstructorDeclBits = 64 - NumDeclContextBits - NumFunctionDeclBits
1642 };
1643
1644 /// Stores the bits used by ObjCMethodDecl.
1645 /// If modified NumObjCMethodDeclBits and the accessor
1646 /// methods in ObjCMethodDecl should be updated appropriately.
1647 class ObjCMethodDeclBitfields {
1648 friend class ObjCMethodDecl;
1649
1650 /// For the bits in DeclContextBitfields.
1651 uint64_t : NumDeclContextBits;
1652
1653 /// The conventional meaning of this method; an ObjCMethodFamily.
1654 /// This is not serialized; instead, it is computed on demand and
1655 /// cached.
1656 mutable uint64_t Family : ObjCMethodFamilyBitWidth;
1657
1658 /// instance (true) or class (false) method.
1659 uint64_t IsInstance : 1;
1660 uint64_t IsVariadic : 1;
1661
1662 /// True if this method is the getter or setter for an explicit property.
1663 uint64_t IsPropertyAccessor : 1;
1664
1665 /// True if this method is a synthesized property accessor stub.
1666 uint64_t IsSynthesizedAccessorStub : 1;
1667
1668 /// Method has a definition.
1669 uint64_t IsDefined : 1;
1670
1671 /// Method redeclaration in the same interface.
1672 uint64_t IsRedeclaration : 1;
1673
1674 /// Is redeclared in the same interface.
1675 mutable uint64_t HasRedeclaration : 1;
1676
1677 /// \@required/\@optional
1678 uint64_t DeclImplementation : 2;
1679
1680 /// in, inout, etc.
1681 uint64_t objcDeclQualifier : 7;
1682
1683 /// Indicates whether this method has a related result type.
1684 uint64_t RelatedResultType : 1;
1685
1686 /// Whether the locations of the selector identifiers are in a
1687 /// "standard" position, a enum SelectorLocationsKind.
1688 uint64_t SelLocsKind : 2;
1689
1690 /// Whether this method overrides any other in the class hierarchy.
1691 ///
1692 /// A method is said to override any method in the class's
1693 /// base classes, its protocols, or its categories' protocols, that has
1694 /// the same selector and is of the same kind (class or instance).
1695 /// A method in an implementation is not considered as overriding the same
1696 /// method in the interface or its categories.
1697 uint64_t IsOverriding : 1;
1698
1699 /// Indicates if the method was a definition but its body was skipped.
1700 uint64_t HasSkippedBody : 1;
1701 };
1702
1703 /// Number of non-inherited bits in ObjCMethodDeclBitfields.
1704 enum { NumObjCMethodDeclBits = 24 };
1705
1706 /// Stores the bits used by ObjCContainerDecl.
1707 /// If modified NumObjCContainerDeclBits and the accessor
1708 /// methods in ObjCContainerDecl should be updated appropriately.
1709 class ObjCContainerDeclBitfields {
1710 friend class ObjCContainerDecl;
1711 /// For the bits in DeclContextBitfields
1712 uint32_t : NumDeclContextBits;
1713
1714 // Not a bitfield but this saves space.
1715 // Note that ObjCContainerDeclBitfields is full.
1716 SourceLocation AtStart;
1717 };
1718
1719 /// Number of non-inherited bits in ObjCContainerDeclBitfields.
1720 /// Note that here we rely on the fact that SourceLocation is 32 bits
1721 /// wide. We check this with the static_assert in the ctor of DeclContext.
1722 enum { NumObjCContainerDeclBits = 64 - NumDeclContextBits };
1723
1724 /// Stores the bits used by LinkageSpecDecl.
1725 /// If modified NumLinkageSpecDeclBits and the accessor
1726 /// methods in LinkageSpecDecl should be updated appropriately.
1727 class LinkageSpecDeclBitfields {
1728 friend class LinkageSpecDecl;
1729 /// For the bits in DeclContextBitfields.
1730 uint64_t : NumDeclContextBits;
1731
1732 /// The language for this linkage specification with values
1733 /// in the enum LinkageSpecDecl::LanguageIDs.
1734 uint64_t Language : 3;
1735
1736 /// True if this linkage spec has braces.
1737 /// This is needed so that hasBraces() returns the correct result while the
1738 /// linkage spec body is being parsed. Once RBraceLoc has been set this is
1739 /// not used, so it doesn't need to be serialized.
1740 uint64_t HasBraces : 1;
1741 };
1742
1743 /// Number of non-inherited bits in LinkageSpecDeclBitfields.
1744 enum { NumLinkageSpecDeclBits = 4 };
1745
1746 /// Stores the bits used by BlockDecl.
1747 /// If modified NumBlockDeclBits and the accessor
1748 /// methods in BlockDecl should be updated appropriately.
1749 class BlockDeclBitfields {
1750 friend class BlockDecl;
1751 /// For the bits in DeclContextBitfields.
1752 uint64_t : NumDeclContextBits;
1753
1754 uint64_t IsVariadic : 1;
1755 uint64_t CapturesCXXThis : 1;
1756 uint64_t BlockMissingReturnType : 1;
1757 uint64_t IsConversionFromLambda : 1;
1758
1759 /// A bit that indicates this block is passed directly to a function as a
1760 /// non-escaping parameter.
1761 uint64_t DoesNotEscape : 1;
1762
1763 /// A bit that indicates whether it's possible to avoid coying this block to
1764 /// the heap when it initializes or is assigned to a local variable with
1765 /// automatic storage.
1766 uint64_t CanAvoidCopyToHeap : 1;
1767 };
1768
1769 /// Number of non-inherited bits in BlockDeclBitfields.
1770 enum { NumBlockDeclBits = 5 };
1771
1772 /// Pointer to the data structure used to lookup declarations
1773 /// within this context (or a DependentStoredDeclsMap if this is a
1774 /// dependent context). We maintain the invariant that, if the map
1775 /// contains an entry for a DeclarationName (and we haven't lazily
1776 /// omitted anything), then it contains all relevant entries for that
1777 /// name (modulo the hasExternalDecls() flag).
1778 mutable StoredDeclsMap *LookupPtr = nullptr;
1779
1780protected:
1781 /// This anonymous union stores the bits belonging to DeclContext and classes
1782 /// deriving from it. The goal is to use otherwise wasted
1783 /// space in DeclContext to store data belonging to derived classes.
1784 /// The space saved is especially significient when pointers are aligned
1785 /// to 8 bytes. In this case due to alignment requirements we have a
1786 /// little less than 8 bytes free in DeclContext which we can use.
1787 /// We check that none of the classes in this union is larger than
1788 /// 8 bytes with static_asserts in the ctor of DeclContext.
1789 union {
1790 DeclContextBitfields DeclContextBits;
1791 TagDeclBitfields TagDeclBits;
1792 EnumDeclBitfields EnumDeclBits;
1793 RecordDeclBitfields RecordDeclBits;
1794 OMPDeclareReductionDeclBitfields OMPDeclareReductionDeclBits;
1795 FunctionDeclBitfields FunctionDeclBits;
1796 CXXConstructorDeclBitfields CXXConstructorDeclBits;
1797 ObjCMethodDeclBitfields ObjCMethodDeclBits;
1798 ObjCContainerDeclBitfields ObjCContainerDeclBits;
1799 LinkageSpecDeclBitfields LinkageSpecDeclBits;
1800 BlockDeclBitfields BlockDeclBits;
1801
1802 static_assert(sizeof(DeclContextBitfields) <= 8,
1803 "DeclContextBitfields is larger than 8 bytes!");
1804 static_assert(sizeof(TagDeclBitfields) <= 8,
1805 "TagDeclBitfields is larger than 8 bytes!");
1806 static_assert(sizeof(EnumDeclBitfields) <= 8,
1807 "EnumDeclBitfields is larger than 8 bytes!");
1808 static_assert(sizeof(RecordDeclBitfields) <= 8,
1809 "RecordDeclBitfields is larger than 8 bytes!");
1810 static_assert(sizeof(OMPDeclareReductionDeclBitfields) <= 8,
1811 "OMPDeclareReductionDeclBitfields is larger than 8 bytes!");
1812 static_assert(sizeof(FunctionDeclBitfields) <= 8,
1813 "FunctionDeclBitfields is larger than 8 bytes!");
1814 static_assert(sizeof(CXXConstructorDeclBitfields) <= 8,
1815 "CXXConstructorDeclBitfields is larger than 8 bytes!");
1816 static_assert(sizeof(ObjCMethodDeclBitfields) <= 8,
1817 "ObjCMethodDeclBitfields is larger than 8 bytes!");
1818 static_assert(sizeof(ObjCContainerDeclBitfields) <= 8,
1819 "ObjCContainerDeclBitfields is larger than 8 bytes!");
1820 static_assert(sizeof(LinkageSpecDeclBitfields) <= 8,
1821 "LinkageSpecDeclBitfields is larger than 8 bytes!");
1822 static_assert(sizeof(BlockDeclBitfields) <= 8,
1823 "BlockDeclBitfields is larger than 8 bytes!");
1824 };
1825
1826 /// FirstDecl - The first declaration stored within this declaration
1827 /// context.
1828 mutable Decl *FirstDecl = nullptr;
1829
1830 /// LastDecl - The last declaration stored within this declaration
1831 /// context. FIXME: We could probably cache this value somewhere
1832 /// outside of the DeclContext, to reduce the size of DeclContext by
1833 /// another pointer.
1834 mutable Decl *LastDecl = nullptr;
1835
1836 /// Build up a chain of declarations.
1837 ///
1838 /// \returns the first/last pair of declarations.
1839 static std::pair<Decl *, Decl *>
1840 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1841
1842 DeclContext(Decl::Kind K);
1843
1844public:
1845 ~DeclContext();
1846
1847 Decl::Kind getDeclKind() const {
1848 return static_cast<Decl::Kind>(DeclContextBits.DeclKind);
1849 }
1850
1851 const char *getDeclKindName() const;
1852
1853 /// getParent - Returns the containing DeclContext.
1854 DeclContext *getParent() {
1855 return cast<Decl>(this)->getDeclContext();
1856 }
1857 const DeclContext *getParent() const {
1858 return const_cast<DeclContext*>(this)->getParent();
1859 }
1860
1861 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1862 /// different from getParent, e.g.:
1863 ///
1864 /// namespace A {
1865 /// struct S;
1866 /// }
1867 /// struct A::S {}; // getParent() == namespace 'A'
1868 /// // getLexicalParent() == translation unit
1869 ///
1870 DeclContext *getLexicalParent() {
1871 return cast<Decl>(this)->getLexicalDeclContext();
1872 }
1873 const DeclContext *getLexicalParent() const {
1874 return const_cast<DeclContext*>(this)->getLexicalParent();
1875 }
1876
1877 DeclContext *getLookupParent();
1878
1879 const DeclContext *getLookupParent() const {
1880 return const_cast<DeclContext*>(this)->getLookupParent();
1881 }
1882
1883 ASTContext &getParentASTContext() const {
1884 return cast<Decl>(this)->getASTContext();
1885 }
1886
1887 bool isClosure() const { return getDeclKind() == Decl::Block; }
1888
1889 /// Return this DeclContext if it is a BlockDecl. Otherwise, return the
1890 /// innermost enclosing BlockDecl or null if there are no enclosing blocks.
1891 const BlockDecl *getInnermostBlockDecl() const;
1892
1893 bool isObjCContainer() const {
1894 switch (getDeclKind()) {
1895 case Decl::ObjCCategory:
1896 case Decl::ObjCCategoryImpl:
1897 case Decl::ObjCImplementation:
1898 case Decl::ObjCInterface:
1899 case Decl::ObjCProtocol:
1900 return true;
1901 default:
1902 return false;
1903 }
1904 }
1905
1906 bool isFunctionOrMethod() const {
1907 switch (getDeclKind()) {
1908 case Decl::Block:
1909 case Decl::Captured:
1910 case Decl::ObjCMethod:
1911 return true;
1912 default:
1913 return getDeclKind() >= Decl::firstFunction &&
1914 getDeclKind() <= Decl::lastFunction;
1915 }
1916 }
1917
1918 /// Test whether the context supports looking up names.
1919 bool isLookupContext() const {
1920 return !isFunctionOrMethod() && getDeclKind() != Decl::LinkageSpec &&
1921 getDeclKind() != Decl::Export;
1922 }
1923
1924 bool isFileContext() const {
1925 return getDeclKind() == Decl::TranslationUnit ||
1926 getDeclKind() == Decl::Namespace;
1927 }
1928
1929 bool isTranslationUnit() const {
1930 return getDeclKind() == Decl::TranslationUnit;
1931 }
1932
1933 bool isRecord() const {
1934 return getDeclKind() >= Decl::firstRecord &&
1935 getDeclKind() <= Decl::lastRecord;
1936 }
1937
1938 bool isNamespace() const { return getDeclKind() == Decl::Namespace; }
1939
1940 bool isStdNamespace() const;
1941
1942 bool isInlineNamespace() const;
1943
1944 /// Determines whether this context is dependent on a
1945 /// template parameter.
1946 bool isDependentContext() const;
1947
1948 /// isTransparentContext - Determines whether this context is a
1949 /// "transparent" context, meaning that the members declared in this
1950 /// context are semantically declared in the nearest enclosing
1951 /// non-transparent (opaque) context but are lexically declared in
1952 /// this context. For example, consider the enumerators of an
1953 /// enumeration type:
1954 /// @code
1955 /// enum E {
1956 /// Val1
1957 /// };
1958 /// @endcode
1959 /// Here, E is a transparent context, so its enumerator (Val1) will
1960 /// appear (semantically) that it is in the same context of E.
1961 /// Examples of transparent contexts include: enumerations (except for
1962 /// C++0x scoped enums), and C++ linkage specifications.
1963 bool isTransparentContext() const;
1964
1965 /// Determines whether this context or some of its ancestors is a
1966 /// linkage specification context that specifies C linkage.
1967 bool isExternCContext() const;
1968
1969 /// Retrieve the nearest enclosing C linkage specification context.
1970 const LinkageSpecDecl *getExternCContext() const;
1971
1972 /// Determines whether this context or some of its ancestors is a
1973 /// linkage specification context that specifies C++ linkage.
1974 bool isExternCXXContext() const;
1975
1976 /// Determine whether this declaration context is equivalent
1977 /// to the declaration context DC.
1978 bool Equals(const DeclContext *DC) const {
1979 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1980 }
1981
1982 /// Determine whether this declaration context encloses the
1983 /// declaration context DC.
1984 bool Encloses(const DeclContext *DC) const;
1985
1986 /// Find the nearest non-closure ancestor of this context,
1987 /// i.e. the innermost semantic parent of this context which is not
1988 /// a closure. A context may be its own non-closure ancestor.
1989 Decl *getNonClosureAncestor();
1990 const Decl *getNonClosureAncestor() const {
1991 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1992 }
1993
1994 // Retrieve the nearest context that is not a transparent context.
1995 DeclContext *getNonTransparentContext();
1996 const DeclContext *getNonTransparentContext() const {
1997 return const_cast<DeclContext *>(this)->getNonTransparentContext();
1998 }
1999
2000 /// getPrimaryContext - There may be many different
2001 /// declarations of the same entity (including forward declarations
2002 /// of classes, multiple definitions of namespaces, etc.), each with
2003 /// a different set of declarations. This routine returns the
2004 /// "primary" DeclContext structure, which will contain the
2005 /// information needed to perform name lookup into this context.
2006 DeclContext *getPrimaryContext();
2007 const DeclContext *getPrimaryContext() const {
2008 return const_cast<DeclContext*>(this)->getPrimaryContext();
2009 }
2010
2011 /// getRedeclContext - Retrieve the context in which an entity conflicts with
2012 /// other entities of the same name, or where it is a redeclaration if the
2013 /// two entities are compatible. This skips through transparent contexts.
2014 DeclContext *getRedeclContext();
2015 const DeclContext *getRedeclContext() const {
2016 return const_cast<DeclContext *>(this)->getRedeclContext();
2017 }
2018
2019 /// Retrieve the nearest enclosing namespace context.
2020 DeclContext *getEnclosingNamespaceContext();
2021 const DeclContext *getEnclosingNamespaceContext() const {
2022 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
2023 }
2024
2025 /// Retrieve the outermost lexically enclosing record context.
2026 RecordDecl *getOuterLexicalRecordContext();
2027 const RecordDecl *getOuterLexicalRecordContext() const {
2028 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
2029 }
2030
2031 /// Test if this context is part of the enclosing namespace set of
2032 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
2033 /// isn't a namespace, this is equivalent to Equals().
2034 ///
2035 /// The enclosing namespace set of a namespace is the namespace and, if it is
2036 /// inline, its enclosing namespace, recursively.
2037 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
2038
2039 /// Collects all of the declaration contexts that are semantically
2040 /// connected to this declaration context.
2041 ///
2042 /// For declaration contexts that have multiple semantically connected but
2043 /// syntactically distinct contexts, such as C++ namespaces, this routine
2044 /// retrieves the complete set of such declaration contexts in source order.
2045 /// For example, given:
2046 ///
2047 /// \code
2048 /// namespace N {
2049 /// int x;
2050 /// }
2051 /// namespace N {
2052 /// int y;
2053 /// }
2054 /// \endcode
2055 ///
2056 /// The \c Contexts parameter will contain both definitions of N.
2057 ///
2058 /// \param Contexts Will be cleared and set to the set of declaration
2059 /// contexts that are semanticaly connected to this declaration context,
2060 /// in source order, including this context (which may be the only result,
2061 /// for non-namespace contexts).
2062 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
2063
2064 /// decl_iterator - Iterates through the declarations stored
2065 /// within this context.
2066 class decl_iterator {
2067 /// Current - The current declaration.
2068 Decl *Current = nullptr;
2069
2070 public:
2071 using value_type = Decl *;
2072 using reference = const value_type &;
2073 using pointer = const value_type *;
2074 using iterator_category = std::forward_iterator_tag;
2075 using difference_type = std::ptrdiff_t;
2076
2077 decl_iterator() = default;
2078 explicit decl_iterator(Decl *C) : Current(C) {}
2079
2080 reference operator*() const { return Current; }
2081
2082 // This doesn't meet the iterator requirements, but it's convenient
2083 value_type operator->() const { return Current; }
2084
2085 decl_iterator& operator++() {
2086 Current = Current->getNextDeclInContext();
2087 return *this;
2088 }
2089
2090 decl_iterator operator++(int) {
2091 decl_iterator tmp(*this);
2092 ++(*this);
2093 return tmp;
2094 }
2095
2096 friend bool operator==(decl_iterator x, decl_iterator y) {
2097 return x.Current == y.Current;
2098 }
2099
2100 friend bool operator!=(decl_iterator x, decl_iterator y) {
2101 return x.Current != y.Current;
2102 }
2103 };
2104
2105 using decl_range = llvm::iterator_range<decl_iterator>;
2106
2107 /// decls_begin/decls_end - Iterate over the declarations stored in
2108 /// this context.
2109 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
2110 decl_iterator decls_begin() const;
2111 decl_iterator decls_end() const { return decl_iterator(); }
2112 bool decls_empty() const;
2113
2114 /// noload_decls_begin/end - Iterate over the declarations stored in this
2115 /// context that are currently loaded; don't attempt to retrieve anything
2116 /// from an external source.
2117 decl_range noload_decls() const {
2118 return decl_range(noload_decls_begin(), noload_decls_end());
2119 }
2120 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
2121 decl_iterator noload_decls_end() const { return decl_iterator(); }
2122
2123 /// specific_decl_iterator - Iterates over a subrange of
2124 /// declarations stored in a DeclContext, providing only those that
2125 /// are of type SpecificDecl (or a class derived from it). This
2126 /// iterator is used, for example, to provide iteration over just
2127 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
2128 template<typename SpecificDecl>
2129 class specific_decl_iterator {
2130 /// Current - The current, underlying declaration iterator, which
2131 /// will either be NULL or will point to a declaration of
2132 /// type SpecificDecl.
2133 DeclContext::decl_iterator Current;
2134
2135 /// SkipToNextDecl - Advances the current position up to the next
2136 /// declaration of type SpecificDecl that also meets the criteria
2137 /// required by Acceptable.
2138 void SkipToNextDecl() {
2139 while (*Current && !isa<SpecificDecl>(*Current))
2140 ++Current;
2141 }
2142
2143 public:
2144 using value_type = SpecificDecl *;
2145 // TODO: Add reference and pointer types (with some appropriate proxy type)
2146 // if we ever have a need for them.
2147 using reference = void;
2148 using pointer = void;
2149 using difference_type =
2150 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2151 using iterator_category = std::forward_iterator_tag;
2152
2153 specific_decl_iterator() = default;
2154
2155 /// specific_decl_iterator - Construct a new iterator over a
2156 /// subset of the declarations the range [C,
2157 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2158 /// member function of SpecificDecl that should return true for
2159 /// all of the SpecificDecl instances that will be in the subset
2160 /// of iterators. For example, if you want Objective-C instance
2161 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2162 /// &ObjCMethodDecl::isInstanceMethod.
2163 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2164 SkipToNextDecl();
2165 }
2166
2167 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2168
2169 // This doesn't meet the iterator requirements, but it's convenient
2170 value_type operator->() const { return **this; }
2171
2172 specific_decl_iterator& operator++() {
2173 ++Current;
2174 SkipToNextDecl();
2175 return *this;
2176 }
2177
2178 specific_decl_iterator operator++(int) {
2179 specific_decl_iterator tmp(*this);
2180 ++(*this);
2181 return tmp;
2182 }
2183
2184 friend bool operator==(const specific_decl_iterator& x,
2185 const specific_decl_iterator& y) {
2186 return x.Current == y.Current;
2187 }
2188
2189 friend bool operator!=(const specific_decl_iterator& x,
2190 const specific_decl_iterator& y) {
2191 return x.Current != y.Current;
2192 }
2193 };
2194
2195 /// Iterates over a filtered subrange of declarations stored
2196 /// in a DeclContext.
2197 ///
2198 /// This iterator visits only those declarations that are of type
2199 /// SpecificDecl (or a class derived from it) and that meet some
2200 /// additional run-time criteria. This iterator is used, for
2201 /// example, to provide access to the instance methods within an
2202 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
2203 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
2204 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
2205 class filtered_decl_iterator {
2206 /// Current - The current, underlying declaration iterator, which
2207 /// will either be NULL or will point to a declaration of
2208 /// type SpecificDecl.
2209 DeclContext::decl_iterator Current;
2210
2211 /// SkipToNextDecl - Advances the current position up to the next
2212 /// declaration of type SpecificDecl that also meets the criteria
2213 /// required by Acceptable.
2214 void SkipToNextDecl() {
2215 while (*Current &&
2216 (!isa<SpecificDecl>(*Current) ||
2217 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
2218 ++Current;
2219 }
2220
2221 public:
2222 using value_type = SpecificDecl *;
2223 // TODO: Add reference and pointer types (with some appropriate proxy type)
2224 // if we ever have a need for them.
2225 using reference = void;
2226 using pointer = void;
2227 using difference_type =
2228 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2229 using iterator_category = std::forward_iterator_tag;
2230
2231 filtered_decl_iterator() = default;
2232
2233 /// filtered_decl_iterator - Construct a new iterator over a
2234 /// subset of the declarations the range [C,
2235 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2236 /// member function of SpecificDecl that should return true for
2237 /// all of the SpecificDecl instances that will be in the subset
2238 /// of iterators. For example, if you want Objective-C instance
2239 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2240 /// &ObjCMethodDecl::isInstanceMethod.
2241 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2242 SkipToNextDecl();
2243 }
2244
2245 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2246 value_type operator->() const { return cast<SpecificDecl>(*Current); }
2247
2248 filtered_decl_iterator& operator++() {
2249 ++Current;
2250 SkipToNextDecl();
2251 return *this;
2252 }
2253
2254 filtered_decl_iterator operator++(int) {
2255 filtered_decl_iterator tmp(*this);
2256 ++(*this);
2257 return tmp;
2258 }
2259
2260 friend bool operator==(const filtered_decl_iterator& x,
2261 const filtered_decl_iterator& y) {
2262 return x.Current == y.Current;
2263 }
2264
2265 friend bool operator!=(const filtered_decl_iterator& x,
2266 const filtered_decl_iterator& y) {
2267 return x.Current != y.Current;
2268 }
2269 };
2270
2271 /// Add the declaration D into this context.
2272 ///
2273 /// This routine should be invoked when the declaration D has first
2274 /// been declared, to place D into the context where it was
2275 /// (lexically) defined. Every declaration must be added to one
2276 /// (and only one!) context, where it can be visited via
2277 /// [decls_begin(), decls_end()). Once a declaration has been added
2278 /// to its lexical context, the corresponding DeclContext owns the
2279 /// declaration.
2280 ///
2281 /// If D is also a NamedDecl, it will be made visible within its
2282 /// semantic context via makeDeclVisibleInContext.
2283 void addDecl(Decl *D);
2284
2285 /// Add the declaration D into this context, but suppress
2286 /// searches for external declarations with the same name.
2287 ///
2288 /// Although analogous in function to addDecl, this removes an
2289 /// important check. This is only useful if the Decl is being
2290 /// added in response to an external search; in all other cases,
2291 /// addDecl() is the right function to use.
2292 /// See the ASTImporter for use cases.
2293 void addDeclInternal(Decl *D);
2294
2295 /// Add the declaration D to this context without modifying
2296 /// any lookup tables.
2297 ///
2298 /// This is useful for some operations in dependent contexts where
2299 /// the semantic context might not be dependent; this basically
2300 /// only happens with friends.
2301 void addHiddenDecl(Decl *D);
2302
2303 /// Removes a declaration from this context.
2304 void removeDecl(Decl *D);
2305
2306 /// Checks whether a declaration is in this context.
2307 bool containsDecl(Decl *D) const;
2308
2309 /// Checks whether a declaration is in this context.
2310 /// This also loads the Decls from the external source before the check.
2311 bool containsDeclAndLoad(Decl *D) const;
2312
2313 using lookup_result = DeclContextLookupResult;
2314 using lookup_iterator = lookup_result::iterator;
2315
2316 /// lookup - Find the declarations (if any) with the given Name in
2317 /// this context. Returns a range of iterators that contains all of
2318 /// the declarations with this name, with object, function, member,
2319 /// and enumerator names preceding any tag name. Note that this
2320 /// routine will not look into parent contexts.
2321 lookup_result lookup(DeclarationName Name) const;
2322
2323 /// Find the declarations with the given name that are visible
2324 /// within this context; don't attempt to retrieve anything from an
2325 /// external source.
2326 lookup_result noload_lookup(DeclarationName Name);
2327
2328 /// A simplistic name lookup mechanism that performs name lookup
2329 /// into this declaration context without consulting the external source.
2330 ///
2331 /// This function should almost never be used, because it subverts the
2332 /// usual relationship between a DeclContext and the external source.
2333 /// See the ASTImporter for the (few, but important) use cases.
2334 ///
2335 /// FIXME: This is very inefficient; replace uses of it with uses of
2336 /// noload_lookup.
2337 void localUncachedLookup(DeclarationName Name,
2338 SmallVectorImpl<NamedDecl *> &Results);
2339
2340 /// Makes a declaration visible within this context.
2341 ///
2342 /// This routine makes the declaration D visible to name lookup
2343 /// within this context and, if this is a transparent context,
2344 /// within its parent contexts up to the first enclosing
2345 /// non-transparent context. Making a declaration visible within a
2346 /// context does not transfer ownership of a declaration, and a
2347 /// declaration can be visible in many contexts that aren't its
2348 /// lexical context.
2349 ///
2350 /// If D is a redeclaration of an existing declaration that is
2351 /// visible from this context, as determined by
2352 /// NamedDecl::declarationReplaces, the previous declaration will be
2353 /// replaced with D.
2354 void makeDeclVisibleInContext(NamedDecl *D);
2355
2356 /// all_lookups_iterator - An iterator that provides a view over the results
2357 /// of looking up every possible name.
2358 class all_lookups_iterator;
2359
2360 using lookups_range = llvm::iterator_range<all_lookups_iterator>;
2361
2362 lookups_range lookups() const;
2363 // Like lookups(), but avoids loading external declarations.
2364 // If PreserveInternalState, avoids building lookup data structures too.
2365 lookups_range noload_lookups(bool PreserveInternalState) const;
2366
2367 /// Iterators over all possible lookups within this context.
2368 all_lookups_iterator lookups_begin() const;
2369 all_lookups_iterator lookups_end() const;
2370
2371 /// Iterators over all possible lookups within this context that are
2372 /// currently loaded; don't attempt to retrieve anything from an external
2373 /// source.
2374 all_lookups_iterator noload_lookups_begin() const;
2375 all_lookups_iterator noload_lookups_end() const;
2376
2377 struct udir_iterator;
2378
2379 using udir_iterator_base =
2380 llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
2381 typename lookup_iterator::iterator_category,
2382 UsingDirectiveDecl *>;
2383
2384 struct udir_iterator : udir_iterator_base {
2385 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
2386
2387 UsingDirectiveDecl *operator*() const;
2388 };
2389
2390 using udir_range = llvm::iterator_range<udir_iterator>;
2391
2392 udir_range using_directives() const;
2393
2394 // These are all defined in DependentDiagnostic.h.
2395 class ddiag_iterator;
2396
2397 using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>;
2398
2399 inline ddiag_range ddiags() const;
2400
2401 // Low-level accessors
2402
2403 /// Mark that there are external lexical declarations that we need
2404 /// to include in our lookup table (and that are not available as external
2405 /// visible lookups). These extra lookup results will be found by walking
2406 /// the lexical declarations of this context. This should be used only if
2407 /// setHasExternalLexicalStorage() has been called on any decl context for
2408 /// which this is the primary context.
2409 void setMustBuildLookupTable() {
2410 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\""
, "clang/include/clang/AST/DeclBase.h", 2411, __extension__ __PRETTY_FUNCTION__
))
2411 "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\""
, "clang/include/clang/AST/DeclBase.h", 2411, __extension__ __PRETTY_FUNCTION__
))
;
2412 DeclContextBits.HasLazyExternalLexicalLookups = true;
2413 }
2414
2415 /// Retrieve the internal representation of the lookup structure.
2416 /// This may omit some names if we are lazily building the structure.
2417 StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
2418
2419 /// Ensure the lookup structure is fully-built and return it.
2420 StoredDeclsMap *buildLookup();
2421
2422 /// Whether this DeclContext has external storage containing
2423 /// additional declarations that are lexically in this context.
2424 bool hasExternalLexicalStorage() const {
2425 return DeclContextBits.ExternalLexicalStorage;
2426 }
2427
2428 /// State whether this DeclContext has external storage for
2429 /// declarations lexically in this context.
2430 void setHasExternalLexicalStorage(bool ES = true) const {
2431 DeclContextBits.ExternalLexicalStorage = ES;
2432 }
2433
2434 /// Whether this DeclContext has external storage containing
2435 /// additional declarations that are visible in this context.
2436 bool hasExternalVisibleStorage() const {
2437 return DeclContextBits.ExternalVisibleStorage;
2438 }
2439
2440 /// State whether this DeclContext has external storage for
2441 /// declarations visible in this context.
2442 void setHasExternalVisibleStorage(bool ES = true) const {
2443 DeclContextBits.ExternalVisibleStorage = ES;
2444 if (ES && LookupPtr)
2445 DeclContextBits.NeedToReconcileExternalVisibleStorage = true;
2446 }
2447
2448 /// Determine whether the given declaration is stored in the list of
2449 /// declarations lexically within this context.
2450 bool isDeclInLexicalTraversal(const Decl *D) const {
2451 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
2452 D == LastDecl);
2453 }
2454
2455 bool setUseQualifiedLookup(bool use = true) const {
2456 bool old_value = DeclContextBits.UseQualifiedLookup;
2457 DeclContextBits.UseQualifiedLookup = use;
2458 return old_value;
2459 }
2460
2461 bool shouldUseQualifiedLookup() const {
2462 return DeclContextBits.UseQualifiedLookup;
2463 }
2464
2465 static bool classof(const Decl *D);
2466 static bool classof(const DeclContext *D) { return true; }
2467
2468 void dumpDeclContext() const;
2469 void dumpLookups() const;
2470 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
2471 bool Deserialize = false) const;
2472
2473private:
2474 /// Whether this declaration context has had externally visible
2475 /// storage added since the last lookup. In this case, \c LookupPtr's
2476 /// invariant may not hold and needs to be fixed before we perform
2477 /// another lookup.
2478 bool hasNeedToReconcileExternalVisibleStorage() const {
2479 return DeclContextBits.NeedToReconcileExternalVisibleStorage;
2480 }
2481
2482 /// State that this declaration context has had externally visible
2483 /// storage added since the last lookup. In this case, \c LookupPtr's
2484 /// invariant may not hold and needs to be fixed before we perform
2485 /// another lookup.
2486 void setNeedToReconcileExternalVisibleStorage(bool Need = true) const {
2487 DeclContextBits.NeedToReconcileExternalVisibleStorage = Need;
2488 }
2489
2490 /// If \c true, this context may have local lexical declarations
2491 /// that are missing from the lookup table.
2492 bool hasLazyLocalLexicalLookups() const {
2493 return DeclContextBits.HasLazyLocalLexicalLookups;
2494 }
2495
2496 /// If \c true, this context may have local lexical declarations
2497 /// that are missing from the lookup table.
2498 void setHasLazyLocalLexicalLookups(bool HasLLLL = true) const {
2499 DeclContextBits.HasLazyLocalLexicalLookups = HasLLLL;
2500 }
2501
2502 /// If \c true, the external source may have lexical declarations
2503 /// that are missing from the lookup table.
2504 bool hasLazyExternalLexicalLookups() const {
2505 return DeclContextBits.HasLazyExternalLexicalLookups;
2506 }
2507
2508 /// If \c true, the external source may have lexical declarations
2509 /// that are missing from the lookup table.
2510 void setHasLazyExternalLexicalLookups(bool HasLELL = true) const {
2511 DeclContextBits.HasLazyExternalLexicalLookups = HasLELL;
2512 }
2513
2514 void reconcileExternalVisibleStorage() const;
2515 bool LoadLexicalDeclsFromExternalStorage() const;
2516
2517 /// Makes a declaration visible within this context, but
2518 /// suppresses searches for external declarations with the same
2519 /// name.
2520 ///
2521 /// Analogous to makeDeclVisibleInContext, but for the exclusive
2522 /// use of addDeclInternal().
2523 void makeDeclVisibleInContextInternal(NamedDecl *D);
2524
2525 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
2526
2527 void loadLazyLocalLexicalLookups();
2528 void buildLookupImpl(DeclContext *DCtx, bool Internal);
2529 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
2530 bool Rediscoverable);
2531 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
2532};
2533
2534inline bool Decl::isTemplateParameter() const {
2535 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
2536 getKind() == TemplateTemplateParm;
2537}
2538
2539// Specialization selected when ToTy is not a known subclass of DeclContext.
2540template <class ToTy,
2541 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
2542struct cast_convert_decl_context {
2543 static const ToTy *doit(const DeclContext *Val) {
2544 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
2545 }
2546
2547 static ToTy *doit(DeclContext *Val) {
2548 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
2549 }
2550};
2551
2552// Specialization selected when ToTy is a known subclass of DeclContext.
2553template <class ToTy>
2554struct cast_convert_decl_context<ToTy, true> {
2555 static const ToTy *doit(const DeclContext *Val) {
2556 return static_cast<const ToTy*>(Val);
2557 }
2558
2559 static ToTy *doit(DeclContext *Val) {
2560 return static_cast<ToTy*>(Val);
2561 }
2562};
2563
2564} // namespace clang
2565
2566namespace llvm {
2567
2568/// isa<T>(DeclContext*)
2569template <typename To>
2570struct isa_impl<To, ::clang::DeclContext> {
2571 static bool doit(const ::clang::DeclContext &Val) {
2572 return To::classofKind(Val.getDeclKind());
2573 }
2574};
2575
2576/// cast<T>(DeclContext*)
2577template<class ToTy>
2578struct cast_convert_val<ToTy,
2579 const ::clang::DeclContext,const ::clang::DeclContext> {
2580 static const ToTy &doit(const ::clang::DeclContext &Val) {
2581 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2582 }
2583};
2584
2585template<class ToTy>
2586struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
2587 static ToTy &doit(::clang::DeclContext &Val) {
2588 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2589 }
2590};
2591
2592template<class ToTy>
2593struct cast_convert_val<ToTy,
2594 const ::clang::DeclContext*, const ::clang::DeclContext*> {
2595 static const ToTy *doit(const ::clang::DeclContext *Val) {
2596 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2597 }
2598};
2599
2600template<class ToTy>
2601struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
2602 static ToTy *doit(::clang::DeclContext *Val) {
2603 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2604 }
2605};
2606
2607/// Implement cast_convert_val for Decl -> DeclContext conversions.
2608template<class FromTy>
2609struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
2610 static ::clang::DeclContext &doit(const FromTy &Val) {
2611 return *FromTy::castToDeclContext(&Val);
2612 }
2613};
2614
2615template<class FromTy>
2616struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
2617 static ::clang::DeclContext *doit(const FromTy *Val) {
2618 return FromTy::castToDeclContext(Val);
2619 }
2620};
2621
2622template<class FromTy>
2623struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
2624 static const ::clang::DeclContext &doit(const FromTy &Val) {
2625 return *FromTy::castToDeclContext(&Val);
2626 }
2627};
2628
2629template<class FromTy>
2630struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
2631 static const ::clang::DeclContext *doit(const FromTy *Val) {
2632 return FromTy::castToDeclContext(Val);
2633 }
2634};
2635
2636} // namespace llvm
2637
2638#endif // LLVM_CLANG_AST_DECLBASE_H

/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/llvm/include/llvm/ADT/PointerUnion.h

1//===- llvm/ADT/PointerUnion.h - Discriminated Union of 2 Ptrs --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the PointerUnion class, which is a discriminated union of
10// pointer types.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ADT_POINTERUNION_H
15#define LLVM_ADT_POINTERUNION_H
16
17#include "llvm/ADT/DenseMapInfo.h"
18#include "llvm/ADT/PointerIntPair.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/Support/PointerLikeTypeTraits.h"
21#include <algorithm>
22#include <cassert>
23#include <cstddef>
24#include <cstdint>
25
26namespace llvm {
27
28namespace pointer_union_detail {
29 /// Determine the number of bits required to store integers with values < n.
30 /// This is ceil(log2(n)).
31 constexpr int bitsRequired(unsigned n) {
32 return n > 1 ? 1 + bitsRequired((n + 1) / 2) : 0;
33 }
34
35 template <typename... Ts> constexpr int lowBitsAvailable() {
36 return std::min<int>({PointerLikeTypeTraits<Ts>::NumLowBitsAvailable...});
37 }
38
39 /// Find the first type in a list of types.
40 template <typename T, typename...> struct GetFirstType {
41 using type = T;
42 };
43
44 /// Provide PointerLikeTypeTraits for void* that is used by PointerUnion
45 /// for the template arguments.
46 template <typename ...PTs> class PointerUnionUIntTraits {
47 public:
48 static inline void *getAsVoidPointer(void *P) { return P; }
49 static inline void *getFromVoidPointer(void *P) { return P; }
50 static constexpr int NumLowBitsAvailable = lowBitsAvailable<PTs...>();
51 };
52
53 template <typename Derived, typename ValTy, int I, typename ...Types>
54 class PointerUnionMembers;
55
56 template <typename Derived, typename ValTy, int I>
57 class PointerUnionMembers<Derived, ValTy, I> {
58 protected:
59 ValTy Val;
60 PointerUnionMembers() = default;
61 PointerUnionMembers(ValTy Val) : Val(Val) {}
62
63 friend struct PointerLikeTypeTraits<Derived>;
64 };
65
66 template <typename Derived, typename ValTy, int I, typename Type,
67 typename ...Types>
68 class PointerUnionMembers<Derived, ValTy, I, Type, Types...>
69 : public PointerUnionMembers<Derived, ValTy, I + 1, Types...> {
70 using Base = PointerUnionMembers<Derived, ValTy, I + 1, Types...>;
71 public:
72 using Base::Base;
73 PointerUnionMembers() = default;
74 PointerUnionMembers(Type V)
75 : Base(ValTy(const_cast<void *>(
76 PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
77 I)) {}
78
79 using Base::operator=;
80 Derived &operator=(Type V) {
81 this->Val = ValTy(
82 const_cast<void *>(PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
83 I);
84 return static_cast<Derived &>(*this);
85 };
86 };
87}
88
89/// A discriminated union of two or more pointer types, with the discriminator
90/// in the low bit of the pointer.
91///
92/// This implementation is extremely efficient in space due to leveraging the
93/// low bits of the pointer, while exposing a natural and type-safe API.
94///
95/// Common use patterns would be something like this:
96/// PointerUnion<int*, float*> P;
97/// P = (int*)0;
98/// printf("%d %d", P.is<int*>(), P.is<float*>()); // prints "1 0"
99/// X = P.get<int*>(); // ok.
100/// Y = P.get<float*>(); // runtime assertion failure.
101/// Z = P.get<double*>(); // compile time failure.
102/// P = (float*)0;
103/// Y = P.get<float*>(); // ok.
104/// X = P.get<int*>(); // runtime assertion failure.
105/// PointerUnion<int*, int*> Q; // compile time failure.
106template <typename... PTs>
107class PointerUnion
108 : public pointer_union_detail::PointerUnionMembers<
109 PointerUnion<PTs...>,
110 PointerIntPair<
111 void *, pointer_union_detail::bitsRequired(sizeof...(PTs)), int,
112 pointer_union_detail::PointerUnionUIntTraits<PTs...>>,
113 0, PTs...> {
114 static_assert(TypesAreDistinct<PTs...>::value,
115 "PointerUnion alternative types cannot be repeated");
116 // The first type is special because we want to directly cast a pointer to a
117 // default-initialized union to a pointer to the first type. But we don't
118 // want PointerUnion to be a 'template <typename First, typename ...Rest>'
119 // because it's much more convenient to have a name for the whole pack. So
120 // split off the first type here.
121 using First = TypeAtIndex<0, PTs...>;
122 using Base = typename PointerUnion::PointerUnionMembers;
123
124public:
125 PointerUnion() = default;
126
127 PointerUnion(std::nullptr_t) : PointerUnion() {}
128 using Base::Base;
129
130 /// Test if the pointer held in the union is null, regardless of
131 /// which type it is.
132 bool isNull() const { return !this->Val.getPointer(); }
133
134 explicit operator bool() const { return !isNull(); }
135
136 /// Test if the Union currently holds the type matching T.
137 template <typename T> bool is() const {
138 return this->Val.getInt() == FirstIndexOfType<T, PTs...>::value;
17
Returning the value 1, which participates in a condition later
139 }
140
141 /// Returns the value of the specified pointer type.
142 ///
143 /// If the specified pointer type is incorrect, assert.
144 template <typename T> T get() const {
145 assert(is<T>() && "Invalid accessor called")(static_cast <bool> (is<T>() && "Invalid accessor called"
) ? void (0) : __assert_fail ("is<T>() && \"Invalid accessor called\""
, "llvm/include/llvm/ADT/PointerUnion.h", 145, __extension__ __PRETTY_FUNCTION__
))
;
24
'?' condition is true
146 return PointerLikeTypeTraits<T>::getFromVoidPointer(this->Val.getPointer());
25
Passing value via 1st parameter 'P'
26
Returning pointer
147 }
148
149 /// Returns the current pointer if it is of the specified pointer type,
150 /// otherwise returns null.
151 template <typename T> T dyn_cast() const {
152 if (is<T>())
153 return get<T>();
154 return T();
155 }
156
157 /// If the union is set to the first pointer type get an address pointing to
158 /// it.
159 First const *getAddrOfPtr1() const {
160 return const_cast<PointerUnion *>(this)->getAddrOfPtr1();
161 }
162
163 /// If the union is set to the first pointer type get an address pointing to
164 /// it.
165 First *getAddrOfPtr1() {
166 assert(is<First>() && "Val is not the first pointer")(static_cast <bool> (is<First>() && "Val is not the first pointer"
) ? void (0) : __assert_fail ("is<First>() && \"Val is not the first pointer\""
, "llvm/include/llvm/ADT/PointerUnion.h", 166, __extension__ __PRETTY_FUNCTION__
))
;
167 assert((static_cast <bool> (PointerLikeTypeTraits<First>
::getAsVoidPointer(get<First>()) == this->Val.getPointer
() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? void (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "llvm/include/llvm/ADT/PointerUnion.h", 170, __extension__ __PRETTY_FUNCTION__
))
168 PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) ==(static_cast <bool> (PointerLikeTypeTraits<First>
::getAsVoidPointer(get<First>()) == this->Val.getPointer
() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? void (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "llvm/include/llvm/ADT/PointerUnion.h", 170, __extension__ __PRETTY_FUNCTION__
))
169 this->Val.getPointer() &&(static_cast <bool> (PointerLikeTypeTraits<First>
::getAsVoidPointer(get<First>()) == this->Val.getPointer
() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? void (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "llvm/include/llvm/ADT/PointerUnion.h", 170, __extension__ __PRETTY_FUNCTION__
))
170 "Can't get the address because PointerLikeTypeTraits changes the ptr")(static_cast <bool> (PointerLikeTypeTraits<First>
::getAsVoidPointer(get<First>()) == this->Val.getPointer
() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? void (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "llvm/include/llvm/ADT/PointerUnion.h", 170, __extension__ __PRETTY_FUNCTION__
))
;
171 return const_cast<First *>(
172 reinterpret_cast<const First *>(this->Val.getAddrOfPointer()));
173 }
174
175 /// Assignment from nullptr which just clears the union.
176 const PointerUnion &operator=(std::nullptr_t) {
177 this->Val.initWithPointer(nullptr);
178 return *this;
179 }
180
181 /// Assignment from elements of the union.
182 using Base::operator=;
183
184 void *getOpaqueValue() const { return this->Val.getOpaqueValue(); }
185 static inline PointerUnion getFromOpaqueValue(void *VP) {
186 PointerUnion V;
187 V.Val = decltype(V.Val)::getFromOpaqueValue(VP);
188 return V;
189 }
190};
191
192template <typename ...PTs>
193bool operator==(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
194 return lhs.getOpaqueValue() == rhs.getOpaqueValue();
195}
196
197template <typename ...PTs>
198bool operator!=(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
199 return lhs.getOpaqueValue() != rhs.getOpaqueValue();
200}
201
202template <typename ...PTs>
203bool operator<(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
204 return lhs.getOpaqueValue() < rhs.getOpaqueValue();
205}
206
207// Teach SmallPtrSet that PointerUnion is "basically a pointer", that has
208// # low bits available = min(PT1bits,PT2bits)-1.
209template <typename ...PTs>
210struct PointerLikeTypeTraits<PointerUnion<PTs...>> {
211 static inline void *getAsVoidPointer(const PointerUnion<PTs...> &P) {
212 return P.getOpaqueValue();
213 }
214
215 static inline PointerUnion<PTs...> getFromVoidPointer(void *P) {
216 return PointerUnion<PTs...>::getFromOpaqueValue(P);
217 }
218
219 // The number of bits available are the min of the pointer types minus the
220 // bits needed for the discriminator.
221 static constexpr int NumLowBitsAvailable = PointerLikeTypeTraits<decltype(
222 PointerUnion<PTs...>::Val)>::NumLowBitsAvailable;
223};
224
225// Teach DenseMap how to use PointerUnions as keys.
226template <typename ...PTs> struct DenseMapInfo<PointerUnion<PTs...>> {
227 using Union = PointerUnion<PTs...>;
228 using FirstInfo =
229 DenseMapInfo<typename pointer_union_detail::GetFirstType<PTs...>::type>;
230
231 static inline Union getEmptyKey() { return Union(FirstInfo::getEmptyKey()); }
232
233 static inline Union getTombstoneKey() {
234 return Union(FirstInfo::getTombstoneKey());
235 }
236
237 static unsigned getHashValue(const Union &UnionVal) {
238 intptr_t key = (intptr_t)UnionVal.getOpaqueValue();
239 return DenseMapInfo<intptr_t>::getHashValue(key);
240 }
241
242 static bool isEqual(const Union &LHS, const Union &RHS) {
243 return LHS == RHS;
244 }
245};
246
247} // end namespace llvm
248
249#endif // LLVM_ADT_POINTERUNION_H