Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp
Warning:line 131, 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-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-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-16/lib/clang/16.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-16~++20221003111214+1fa2019828ca/lldb/source/Plugins/ExpressionParser/Clang -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/lldb/include -I tools/lldb/include -I include -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/include -I /usr/include/python3.9 -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/include -I tools/lldb/../clang/include -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/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-16/lib/clang/16.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-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -O2 -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-misleading-indentation -Wno-deprecated-declarations -Wno-unknown-pragmas -Wno-strict-aliasing -Wno-stringop-truncation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -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-10-03-140002-15933-1 -x c++ /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp

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

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

/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/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/// \file
10/// This file defines the PointerUnion class, which is a discriminated union of
11/// pointer types.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ADT_POINTERUNION_H
16#define LLVM_ADT_POINTERUNION_H
17
18#include "llvm/ADT/DenseMapInfo.h"
19#include "llvm/ADT/PointerIntPair.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/Support/Casting.h"
22#include "llvm/Support/PointerLikeTypeTraits.h"
23#include <algorithm>
24#include <cassert>
25#include <cstddef>
26#include <cstdint>
27
28namespace llvm {
29
30namespace pointer_union_detail {
31 /// Determine the number of bits required to store integers with values < n.
32 /// This is ceil(log2(n)).
33 constexpr int bitsRequired(unsigned n) {
34 return n > 1 ? 1 + bitsRequired((n + 1) / 2) : 0;
35 }
36
37 template <typename... Ts> constexpr int lowBitsAvailable() {
38 return std::min<int>({PointerLikeTypeTraits<Ts>::NumLowBitsAvailable...});
39 }
40
41 /// Find the first type in a list of types.
42 template <typename T, typename...> struct GetFirstType {
43 using type = T;
44 };
45
46 /// Provide PointerLikeTypeTraits for void* that is used by PointerUnion
47 /// for the template arguments.
48 template <typename ...PTs> class PointerUnionUIntTraits {
49 public:
50 static inline void *getAsVoidPointer(void *P) { return P; }
51 static inline void *getFromVoidPointer(void *P) { return P; }
52 static constexpr int NumLowBitsAvailable = lowBitsAvailable<PTs...>();
53 };
54
55 template <typename Derived, typename ValTy, int I, typename ...Types>
56 class PointerUnionMembers;
57
58 template <typename Derived, typename ValTy, int I>
59 class PointerUnionMembers<Derived, ValTy, I> {
60 protected:
61 ValTy Val;
62 PointerUnionMembers() = default;
63 PointerUnionMembers(ValTy Val) : Val(Val) {}
64
65 friend struct PointerLikeTypeTraits<Derived>;
66 };
67
68 template <typename Derived, typename ValTy, int I, typename Type,
69 typename ...Types>
70 class PointerUnionMembers<Derived, ValTy, I, Type, Types...>
71 : public PointerUnionMembers<Derived, ValTy, I + 1, Types...> {
72 using Base = PointerUnionMembers<Derived, ValTy, I + 1, Types...>;
73 public:
74 using Base::Base;
75 PointerUnionMembers() = default;
76 PointerUnionMembers(Type V)
77 : Base(ValTy(const_cast<void *>(
78 PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
79 I)) {}
80
81 using Base::operator=;
82 Derived &operator=(Type V) {
83 this->Val = ValTy(
84 const_cast<void *>(PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
85 I);
86 return static_cast<Derived &>(*this);
87 };
88 };
89}
90
91// This is a forward declaration of CastInfoPointerUnionImpl
92// Refer to its definition below for further details
93template <typename... PTs> struct CastInfoPointerUnionImpl;
94/// A discriminated union of two or more pointer types, with the discriminator
95/// in the low bit of the pointer.
96///
97/// This implementation is extremely efficient in space due to leveraging the
98/// low bits of the pointer, while exposing a natural and type-safe API.
99///
100/// Common use patterns would be something like this:
101/// PointerUnion<int*, float*> P;
102/// P = (int*)0;
103/// printf("%d %d", P.is<int*>(), P.is<float*>()); // prints "1 0"
104/// X = P.get<int*>(); // ok.
105/// Y = P.get<float*>(); // runtime assertion failure.
106/// Z = P.get<double*>(); // compile time failure.
107/// P = (float*)0;
108/// Y = P.get<float*>(); // ok.
109/// X = P.get<int*>(); // runtime assertion failure.
110/// PointerUnion<int*, int*> Q; // compile time failure.
111template <typename... PTs>
112class PointerUnion
113 : public pointer_union_detail::PointerUnionMembers<
114 PointerUnion<PTs...>,
115 PointerIntPair<
116 void *, pointer_union_detail::bitsRequired(sizeof...(PTs)), int,
117 pointer_union_detail::PointerUnionUIntTraits<PTs...>>,
118 0, PTs...> {
119 static_assert(TypesAreDistinct<PTs...>::value,
120 "PointerUnion alternative types cannot be repeated");
121 // The first type is special because we want to directly cast a pointer to a
122 // default-initialized union to a pointer to the first type. But we don't
123 // want PointerUnion to be a 'template <typename First, typename ...Rest>'
124 // because it's much more convenient to have a name for the whole pack. So
125 // split off the first type here.
126 using First = TypeAtIndex<0, PTs...>;
127 using Base = typename PointerUnion::PointerUnionMembers;
128
129 /// This is needed to give the CastInfo implementation below access
130 /// to protected members.
131 /// Refer to its definition for further details.
132 friend struct CastInfoPointerUnionImpl<PTs...>;
133
134public:
135 PointerUnion() = default;
136
137 PointerUnion(std::nullptr_t) : PointerUnion() {}
138 using Base::Base;
139
140 /// Test if the pointer held in the union is null, regardless of
141 /// which type it is.
142 bool isNull() const { return !this->Val.getPointer(); }
143
144 explicit operator bool() const { return !isNull(); }
145
146 // FIXME: Replace the uses of is(), get() and dyn_cast() with
147 // isa<T>, cast<T> and the llvm::dyn_cast<T>
148
149 /// Test if the Union currently holds the type matching T.
150 template <typename T> inline bool is() const { return isa<T>(*this); }
151
152 /// Returns the value of the specified pointer type.
153 ///
154 /// If the specified pointer type is incorrect, assert.
155 template <typename T> inline T get() const {
156 assert(isa<T>(*this) && "Invalid accessor called")(static_cast <bool> (isa<T>(*this) && "Invalid accessor called"
) ? void (0) : __assert_fail ("isa<T>(*this) && \"Invalid accessor called\""
, "llvm/include/llvm/ADT/PointerUnion.h", 156, __extension__ __PRETTY_FUNCTION__
))
;
14
Assuming the object is a 'class clang::DeclContext *&'
15
'?' condition is true
157 return cast<T>(*this);
16
Calling 'cast<clang::DeclContext *, llvm::PointerUnion<clang::DeclContext *, clang::Decl::MultipleDC *>>'
20
Returning from 'cast<clang::DeclContext *, llvm::PointerUnion<clang::DeclContext *, clang::Decl::MultipleDC *>>'
21
Returning pointer
158 }
159
160 /// Returns the current pointer if it is of the specified pointer type,
161 /// otherwise returns null.
162 template <typename T> inline T dyn_cast() const {
163 return llvm::dyn_cast_if_present<T>(*this);
164 }
165
166 /// If the union is set to the first pointer type get an address pointing to
167 /// it.
168 First const *getAddrOfPtr1() const {
169 return const_cast<PointerUnion *>(this)->getAddrOfPtr1();
170 }
171
172 /// If the union is set to the first pointer type get an address pointing to
173 /// it.
174 First *getAddrOfPtr1() {
175 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", 175, __extension__ __PRETTY_FUNCTION__
))
;
176 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", 179, __extension__ __PRETTY_FUNCTION__
))
177 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", 179, __extension__ __PRETTY_FUNCTION__
))
178 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", 179, __extension__ __PRETTY_FUNCTION__
))
179 "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", 179, __extension__ __PRETTY_FUNCTION__
))
;
180 return const_cast<First *>(
181 reinterpret_cast<const First *>(this->Val.getAddrOfPointer()));
182 }
183
184 /// Assignment from nullptr which just clears the union.
185 const PointerUnion &operator=(std::nullptr_t) {
186 this->Val.initWithPointer(nullptr);
187 return *this;
188 }
189
190 /// Assignment from elements of the union.
191 using Base::operator=;
192
193 void *getOpaqueValue() const { return this->Val.getOpaqueValue(); }
194 static inline PointerUnion getFromOpaqueValue(void *VP) {
195 PointerUnion V;
196 V.Val = decltype(V.Val)::getFromOpaqueValue(VP);
197 return V;
198 }
199};
200
201template <typename ...PTs>
202bool operator==(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
203 return lhs.getOpaqueValue() == rhs.getOpaqueValue();
204}
205
206template <typename ...PTs>
207bool operator!=(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
208 return lhs.getOpaqueValue() != rhs.getOpaqueValue();
209}
210
211template <typename ...PTs>
212bool operator<(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
213 return lhs.getOpaqueValue() < rhs.getOpaqueValue();
214}
215
216/// We can't (at least, at this moment with C++14) declare CastInfo
217/// as a friend of PointerUnion like this:
218/// ```
219/// template<typename To>
220/// friend struct CastInfo<To, PointerUnion<PTs...>>;
221/// ```
222/// The compiler complains 'Partial specialization cannot be declared as a
223/// friend'.
224/// So we define this struct to be a bridge between CastInfo and
225/// PointerUnion.
226template <typename... PTs> struct CastInfoPointerUnionImpl {
227 using From = PointerUnion<PTs...>;
228
229 template <typename To> static inline bool isPossible(From &F) {
230 return F.Val.getInt() == FirstIndexOfType<To, PTs...>::value;
231 }
232
233 template <typename To> static To doCast(From &F) {
234 assert(isPossible<To>(F) && "cast to an incompatible type !")(static_cast <bool> (isPossible<To>(F) &&
"cast to an incompatible type !") ? void (0) : __assert_fail
("isPossible<To>(F) && \"cast to an incompatible type !\""
, "llvm/include/llvm/ADT/PointerUnion.h", 234, __extension__ __PRETTY_FUNCTION__
))
;
235 return PointerLikeTypeTraits<To>::getFromVoidPointer(F.Val.getPointer());
236 }
237};
238
239// Specialization of CastInfo for PointerUnion
240template <typename To, typename... PTs>
241struct CastInfo<To, PointerUnion<PTs...>>
242 : public DefaultDoCastIfPossible<To, PointerUnion<PTs...>,
243 CastInfo<To, PointerUnion<PTs...>>> {
244 using From = PointerUnion<PTs...>;
245 using Impl = CastInfoPointerUnionImpl<PTs...>;
246
247 static inline bool isPossible(From &f) {
248 return Impl::template isPossible<To>(f);
249 }
250
251 static To doCast(From &f) { return Impl::template doCast<To>(f); }
252
253 static inline To castFailed() { return To(); }
254};
255
256template <typename To, typename... PTs>
257struct CastInfo<To, const PointerUnion<PTs...>>
258 : public ConstStrippingForwardingCast<To, const PointerUnion<PTs...>,
259 CastInfo<To, PointerUnion<PTs...>>> {
260};
261
262// Teach SmallPtrSet that PointerUnion is "basically a pointer", that has
263// # low bits available = min(PT1bits,PT2bits)-1.
264template <typename ...PTs>
265struct PointerLikeTypeTraits<PointerUnion<PTs...>> {
266 static inline void *getAsVoidPointer(const PointerUnion<PTs...> &P) {
267 return P.getOpaqueValue();
268 }
269
270 static inline PointerUnion<PTs...> getFromVoidPointer(void *P) {
271 return PointerUnion<PTs...>::getFromOpaqueValue(P);
272 }
273
274 // The number of bits available are the min of the pointer types minus the
275 // bits needed for the discriminator.
276 static constexpr int NumLowBitsAvailable = PointerLikeTypeTraits<decltype(
277 PointerUnion<PTs...>::Val)>::NumLowBitsAvailable;
278};
279
280// Teach DenseMap how to use PointerUnions as keys.
281template <typename ...PTs> struct DenseMapInfo<PointerUnion<PTs...>> {
282 using Union = PointerUnion<PTs...>;
283 using FirstInfo =
284 DenseMapInfo<typename pointer_union_detail::GetFirstType<PTs...>::type>;
285
286 static inline Union getEmptyKey() { return Union(FirstInfo::getEmptyKey()); }
287
288 static inline Union getTombstoneKey() {
289 return Union(FirstInfo::getTombstoneKey());
290 }
291
292 static unsigned getHashValue(const Union &UnionVal) {
293 intptr_t key = (intptr_t)UnionVal.getOpaqueValue();
294 return DenseMapInfo<intptr_t>::getHashValue(key);
295 }
296
297 static bool isEqual(const Union &LHS, const Union &RHS) {
298 return LHS == RHS;
299 }
300};
301
302} // end namespace llvm
303
304#endif // LLVM_ADT_POINTERUNION_H

/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/include/llvm/Support/Casting.h

1//===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- 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 isa<X>(), cast<X>(), dyn_cast<X>(),
10// cast_if_present<X>(), and dyn_cast_if_present<X>() templates.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_SUPPORT_CASTING_H
15#define LLVM_SUPPORT_CASTING_H
16
17#include "llvm/ADT/Optional.h"
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/type_traits.h"
20#include <cassert>
21#include <memory>
22#include <type_traits>
23
24namespace llvm {
25
26//===----------------------------------------------------------------------===//
27// simplify_type
28//===----------------------------------------------------------------------===//
29
30/// Define a template that can be specialized by smart pointers to reflect the
31/// fact that they are automatically dereferenced, and are not involved with the
32/// template selection process... the default implementation is a noop.
33// TODO: rename this and/or replace it with other cast traits.
34template <typename From> struct simplify_type {
35 using SimpleType = From; // The real type this represents...
36
37 // An accessor to get the real value...
38 static SimpleType &getSimplifiedValue(From &Val) { return Val; }
39};
40
41template <typename From> struct simplify_type<const From> {
42 using NonConstSimpleType = typename simplify_type<From>::SimpleType;
43 using SimpleType = typename add_const_past_pointer<NonConstSimpleType>::type;
44 using RetType =
45 typename add_lvalue_reference_if_not_pointer<SimpleType>::type;
46
47 static RetType getSimplifiedValue(const From &Val) {
48 return simplify_type<From>::getSimplifiedValue(const_cast<From &>(Val));
49 }
50};
51
52// TODO: add this namespace once everyone is switched to using the new
53// interface.
54// namespace detail {
55
56//===----------------------------------------------------------------------===//
57// isa_impl
58//===----------------------------------------------------------------------===//
59
60// The core of the implementation of isa<X> is here; To and From should be
61// the names of classes. This template can be specialized to customize the
62// implementation of isa<> without rewriting it from scratch.
63template <typename To, typename From, typename Enabler = void> struct isa_impl {
64 static inline bool doit(const From &Val) { return To::classof(&Val); }
65};
66
67// Always allow upcasts, and perform no dynamic check for them.
68template <typename To, typename From>
69struct isa_impl<To, From, std::enable_if_t<std::is_base_of<To, From>::value>> {
70 static inline bool doit(const From &) { return true; }
71};
72
73template <typename To, typename From> struct isa_impl_cl {
74 static inline bool doit(const From &Val) {
75 return isa_impl<To, From>::doit(Val);
76 }
77};
78
79template <typename To, typename From> struct isa_impl_cl<To, const From> {
80 static inline bool doit(const From &Val) {
81 return isa_impl<To, From>::doit(Val);
82 }
83};
84
85template <typename To, typename From>
86struct isa_impl_cl<To, const std::unique_ptr<From>> {
87 static inline bool doit(const std::unique_ptr<From> &Val) {
88 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "llvm/include/llvm/Support/Casting.h", 88, __extension__ __PRETTY_FUNCTION__
))
;
89 return isa_impl_cl<To, From>::doit(*Val);
90 }
91};
92
93template <typename To, typename From> struct isa_impl_cl<To, From *> {
94 static inline bool doit(const From *Val) {
95 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "llvm/include/llvm/Support/Casting.h", 95, __extension__ __PRETTY_FUNCTION__
))
;
96 return isa_impl<To, From>::doit(*Val);
97 }
98};
99
100template <typename To, typename From> struct isa_impl_cl<To, From *const> {
101 static inline bool doit(const From *Val) {
102 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "llvm/include/llvm/Support/Casting.h", 102, __extension__ __PRETTY_FUNCTION__
))
;
103 return isa_impl<To, From>::doit(*Val);
104 }
105};
106
107template <typename To, typename From> struct isa_impl_cl<To, const From *> {
108 static inline bool doit(const From *Val) {
109 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "llvm/include/llvm/Support/Casting.h", 109, __extension__ __PRETTY_FUNCTION__
))
;
110 return isa_impl<To, From>::doit(*Val);
111 }
112};
113
114template <typename To, typename From>
115struct isa_impl_cl<To, const From *const> {
116 static inline bool doit(const From *Val) {
117 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "llvm/include/llvm/Support/Casting.h", 117, __extension__ __PRETTY_FUNCTION__
))
;
118 return isa_impl<To, From>::doit(*Val);
119 }
120};
121
122template <typename To, typename From, typename SimpleFrom>
123struct isa_impl_wrap {
124 // When From != SimplifiedType, we can simplify the type some more by using
125 // the simplify_type template.
126 static bool doit(const From &Val) {
127 return isa_impl_wrap<To, SimpleFrom,
128 typename simplify_type<SimpleFrom>::SimpleType>::
129 doit(simplify_type<const From>::getSimplifiedValue(Val));
130 }
131};
132
133template <typename To, typename FromTy>
134struct isa_impl_wrap<To, FromTy, FromTy> {
135 // When From == SimpleType, we are as simple as we are going to get.
136 static bool doit(const FromTy &Val) {
137 return isa_impl_cl<To, FromTy>::doit(Val);
138 }
139};
140
141//===----------------------------------------------------------------------===//
142// cast_retty + cast_retty_impl
143//===----------------------------------------------------------------------===//
144
145template <class To, class From> struct cast_retty;
146
147// Calculate what type the 'cast' function should return, based on a requested
148// type of To and a source type of From.
149template <class To, class From> struct cast_retty_impl {
150 using ret_type = To &; // Normal case, return Ty&
151};
152template <class To, class From> struct cast_retty_impl<To, const From> {
153 using ret_type = const To &; // Normal case, return Ty&
154};
155
156template <class To, class From> struct cast_retty_impl<To, From *> {
157 using ret_type = To *; // Pointer arg case, return Ty*
158};
159
160template <class To, class From> struct cast_retty_impl<To, const From *> {
161 using ret_type = const To *; // Constant pointer arg case, return const Ty*
162};
163
164template <class To, class From> struct cast_retty_impl<To, const From *const> {
165 using ret_type = const To *; // Constant pointer arg case, return const Ty*
166};
167
168template <class To, class From>
169struct cast_retty_impl<To, std::unique_ptr<From>> {
170private:
171 using PointerType = typename cast_retty_impl<To, From *>::ret_type;
172 using ResultType = std::remove_pointer_t<PointerType>;
173
174public:
175 using ret_type = std::unique_ptr<ResultType>;
176};
177
178template <class To, class From, class SimpleFrom> struct cast_retty_wrap {
179 // When the simplified type and the from type are not the same, use the type
180 // simplifier to reduce the type, then reuse cast_retty_impl to get the
181 // resultant type.
182 using ret_type = typename cast_retty<To, SimpleFrom>::ret_type;
183};
184
185template <class To, class FromTy> struct cast_retty_wrap<To, FromTy, FromTy> {
186 // When the simplified type is equal to the from type, use it directly.
187 using ret_type = typename cast_retty_impl<To, FromTy>::ret_type;
188};
189
190template <class To, class From> struct cast_retty {
191 using ret_type = typename cast_retty_wrap<
192 To, From, typename simplify_type<From>::SimpleType>::ret_type;
193};
194
195//===----------------------------------------------------------------------===//
196// cast_convert_val
197//===----------------------------------------------------------------------===//
198
199// Ensure the non-simple values are converted using the simplify_type template
200// that may be specialized by smart pointers...
201//
202template <class To, class From, class SimpleFrom> struct cast_convert_val {
203 // This is not a simple type, use the template to simplify it...
204 static typename cast_retty<To, From>::ret_type doit(const From &Val) {
205 return cast_convert_val<To, SimpleFrom,
206 typename simplify_type<SimpleFrom>::SimpleType>::
207 doit(simplify_type<From>::getSimplifiedValue(const_cast<From &>(Val)));
208 }
209};
210
211template <class To, class FromTy> struct cast_convert_val<To, FromTy, FromTy> {
212 // If it's a reference, switch to a pointer to do the cast and then deref it.
213 static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) {
214 return *(std::remove_reference_t<typename cast_retty<To, FromTy>::ret_type>
215 *)&const_cast<FromTy &>(Val);
216 }
217};
218
219template <class To, class FromTy>
220struct cast_convert_val<To, FromTy *, FromTy *> {
221 // If it's a pointer, we can use c-style casting directly.
222 static typename cast_retty<To, FromTy *>::ret_type doit(const FromTy *Val) {
223 return (typename cast_retty<To, FromTy *>::ret_type) const_cast<FromTy *>(
224 Val);
225 }
226};
227
228//===----------------------------------------------------------------------===//
229// is_simple_type
230//===----------------------------------------------------------------------===//
231
232template <class X> struct is_simple_type {
233 static const bool value =
234 std::is_same<X, typename simplify_type<X>::SimpleType>::value;
235};
236
237// } // namespace detail
238
239//===----------------------------------------------------------------------===//
240// CastIsPossible
241//===----------------------------------------------------------------------===//
242
243/// This struct provides a way to check if a given cast is possible. It provides
244/// a static function called isPossible that is used to check if a cast can be
245/// performed. It should be overridden like this:
246///
247/// template<> struct CastIsPossible<foo, bar> {
248/// static inline bool isPossible(const bar &b) {
249/// return bar.isFoo();
250/// }
251/// };
252template <typename To, typename From, typename Enable = void>
253struct CastIsPossible {
254 static inline bool isPossible(const From &f) {
255 return isa_impl_wrap<
256 To, const From,
257 typename simplify_type<const From>::SimpleType>::doit(f);
258 }
259};
260
261// Needed for optional unwrapping. This could be implemented with isa_impl, but
262// we want to implement things in the new method and move old implementations
263// over. In fact, some of the isa_impl templates should be moved over to
264// CastIsPossible.
265template <typename To, typename From>
266struct CastIsPossible<To, Optional<From>> {
267 static inline bool isPossible(const Optional<From> &f) {
268 assert(f && "CastIsPossible::isPossible called on a nullopt!")(static_cast <bool> (f && "CastIsPossible::isPossible called on a nullopt!"
) ? void (0) : __assert_fail ("f && \"CastIsPossible::isPossible called on a nullopt!\""
, "llvm/include/llvm/Support/Casting.h", 268, __extension__ __PRETTY_FUNCTION__
))
;
269 return isa_impl_wrap<
270 To, const From,
271 typename simplify_type<const From>::SimpleType>::doit(*f);
272 }
273};
274
275/// Upcasting (from derived to base) and casting from a type to itself should
276/// always be possible.
277template <typename To, typename From>
278struct CastIsPossible<To, From,
279 std::enable_if_t<std::is_base_of<To, From>::value>> {
280 static inline bool isPossible(const From &f) { return true; }
281};
282
283//===----------------------------------------------------------------------===//
284// Cast traits
285//===----------------------------------------------------------------------===//
286
287/// All of these cast traits are meant to be implementations for useful casts
288/// that users may want to use that are outside the standard behavior. An
289/// example of how to use a special cast called `CastTrait` is:
290///
291/// template<> struct CastInfo<foo, bar> : public CastTrait<foo, bar> {};
292///
293/// Essentially, if your use case falls directly into one of the use cases
294/// supported by a given cast trait, simply inherit your special CastInfo
295/// directly from one of these to avoid having to reimplement the boilerplate
296/// `isPossible/castFailed/doCast/doCastIfPossible`. A cast trait can also
297/// provide a subset of those functions.
298
299/// This cast trait just provides castFailed for the specified `To` type to make
300/// CastInfo specializations more declarative. In order to use this, the target
301/// result type must be `To` and `To` must be constructible from `nullptr`.
302template <typename To> struct NullableValueCastFailed {
303 static To castFailed() { return To(nullptr); }
304};
305
306/// This cast trait just provides the default implementation of doCastIfPossible
307/// to make CastInfo specializations more declarative. The `Derived` template
308/// parameter *must* be provided for forwarding castFailed and doCast.
309template <typename To, typename From, typename Derived>
310struct DefaultDoCastIfPossible {
311 static To doCastIfPossible(From f) {
312 if (!Derived::isPossible(f))
313 return Derived::castFailed();
314 return Derived::doCast(f);
315 }
316};
317
318namespace detail {
319/// A helper to derive the type to use with `Self` for cast traits, when the
320/// provided CRTP derived type is allowed to be void.
321template <typename OptionalDerived, typename Default>
322using SelfType = std::conditional_t<std::is_same<OptionalDerived, void>::value,
323 Default, OptionalDerived>;
324} // namespace detail
325
326/// This cast trait provides casting for the specific case of casting to a
327/// value-typed object from a pointer-typed object. Note that `To` must be
328/// nullable/constructible from a pointer to `From` to use this cast.
329template <typename To, typename From, typename Derived = void>
330struct ValueFromPointerCast
331 : public CastIsPossible<To, From *>,
332 public NullableValueCastFailed<To>,
333 public DefaultDoCastIfPossible<
334 To, From *,
335 detail::SelfType<Derived, ValueFromPointerCast<To, From>>> {
336 static inline To doCast(From *f) { return To(f); }
337};
338
339/// This cast trait provides std::unique_ptr casting. It has the semantics of
340/// moving the contents of the input unique_ptr into the output unique_ptr
341/// during the cast. It's also a good example of how to implement a move-only
342/// cast.
343template <typename To, typename From, typename Derived = void>
344struct UniquePtrCast : public CastIsPossible<To, From *> {
345 using Self = detail::SelfType<Derived, UniquePtrCast<To, From>>;
346 using CastResultType = std::unique_ptr<
347 std::remove_reference_t<typename cast_retty<To, From>::ret_type>>;
348
349 static inline CastResultType doCast(std::unique_ptr<From> &&f) {
350 return CastResultType((typename CastResultType::element_type *)f.release());
351 }
352
353 static inline CastResultType castFailed() { return CastResultType(nullptr); }
354
355 static inline CastResultType doCastIfPossible(std::unique_ptr<From> &&f) {
356 if (!Self::isPossible(f))
357 return castFailed();
358 return doCast(f);
359 }
360};
361
362/// This cast trait provides Optional<T> casting. This means that if you have a
363/// value type, you can cast it to another value type and have dyn_cast return
364/// an Optional<T>.
365template <typename To, typename From, typename Derived = void>
366struct OptionalValueCast
367 : public CastIsPossible<To, From>,
368 public DefaultDoCastIfPossible<
369 Optional<To>, From,
370 detail::SelfType<Derived, OptionalValueCast<To, From>>> {
371 static inline Optional<To> castFailed() { return Optional<To>{}; }
372
373 static inline Optional<To> doCast(const From &f) { return To(f); }
374};
375
376/// Provides a cast trait that strips `const` from types to make it easier to
377/// implement a const-version of a non-const cast. It just removes boilerplate
378/// and reduces the amount of code you as the user need to implement. You can
379/// use it like this:
380///
381/// template<> struct CastInfo<foo, bar> {
382/// ...verbose implementation...
383/// };
384///
385/// template<> struct CastInfo<foo, const bar> : public
386/// ConstStrippingForwardingCast<foo, const bar, CastInfo<foo, bar>> {};
387///
388template <typename To, typename From, typename ForwardTo>
389struct ConstStrippingForwardingCast {
390 // Remove the pointer if it exists, then we can get rid of consts/volatiles.
391 using DecayedFrom = std::remove_cv_t<std::remove_pointer_t<From>>;
392 // Now if it's a pointer, add it back. Otherwise, we want a ref.
393 using NonConstFrom = std::conditional_t<std::is_pointer<From>::value,
394 DecayedFrom *, DecayedFrom &>;
395
396 static inline bool isPossible(const From &f) {
397 return ForwardTo::isPossible(const_cast<NonConstFrom>(f));
398 }
399
400 static inline decltype(auto) castFailed() { return ForwardTo::castFailed(); }
401
402 static inline decltype(auto) doCast(const From &f) {
403 return ForwardTo::doCast(const_cast<NonConstFrom>(f));
404 }
405
406 static inline decltype(auto) doCastIfPossible(const From &f) {
407 return ForwardTo::doCastIfPossible(const_cast<NonConstFrom>(f));
408 }
409};
410
411/// Provides a cast trait that uses a defined pointer to pointer cast as a base
412/// for reference-to-reference casts. Note that it does not provide castFailed
413/// and doCastIfPossible because a pointer-to-pointer cast would likely just
414/// return `nullptr` which could cause nullptr dereference. You can use it like
415/// this:
416///
417/// template <> struct CastInfo<foo, bar *> { ... verbose implementation... };
418///
419/// template <>
420/// struct CastInfo<foo, bar>
421/// : public ForwardToPointerCast<foo, bar, CastInfo<foo, bar *>> {};
422///
423template <typename To, typename From, typename ForwardTo>
424struct ForwardToPointerCast {
425 static inline bool isPossible(const From &f) {
426 return ForwardTo::isPossible(&f);
427 }
428
429 static inline decltype(auto) doCast(const From &f) {
430 return *ForwardTo::doCast(&f);
431 }
432};
433
434//===----------------------------------------------------------------------===//
435// CastInfo
436//===----------------------------------------------------------------------===//
437
438/// This struct provides a method for customizing the way a cast is performed.
439/// It inherits from CastIsPossible, to support the case of declaring many
440/// CastIsPossible specializations without having to specialize the full
441/// CastInfo.
442///
443/// In order to specialize different behaviors, specify different functions in
444/// your CastInfo specialization.
445/// For isa<> customization, provide:
446///
447/// `static bool isPossible(const From &f)`
448///
449/// For cast<> customization, provide:
450///
451/// `static To doCast(const From &f)`
452///
453/// For dyn_cast<> and the *_if_present<> variants' customization, provide:
454///
455/// `static To castFailed()` and `static To doCastIfPossible(const From &f)`
456///
457/// Your specialization might look something like this:
458///
459/// template<> struct CastInfo<foo, bar> : public CastIsPossible<foo, bar> {
460/// static inline foo doCast(const bar &b) {
461/// return foo(const_cast<bar &>(b));
462/// }
463/// static inline foo castFailed() { return foo(); }
464/// static inline foo doCastIfPossible(const bar &b) {
465/// if (!CastInfo<foo, bar>::isPossible(b))
466/// return castFailed();
467/// return doCast(b);
468/// }
469/// };
470
471// The default implementations of CastInfo don't use cast traits for now because
472// we need to specify types all over the place due to the current expected
473// casting behavior and the way cast_retty works. New use cases can and should
474// take advantage of the cast traits whenever possible!
475
476template <typename To, typename From, typename Enable = void>
477struct CastInfo : public CastIsPossible<To, From> {
478 using Self = CastInfo<To, From, Enable>;
479
480 using CastReturnType = typename cast_retty<To, From>::ret_type;
481
482 static inline CastReturnType doCast(const From &f) {
483 return cast_convert_val<
484 To, From,
485 typename simplify_type<From>::SimpleType>::doit(const_cast<From &>(f));
486 }
487
488 // This assumes that you can construct the cast return type from `nullptr`.
489 // This is largely to support legacy use cases - if you don't want this
490 // behavior you should specialize CastInfo for your use case.
491 static inline CastReturnType castFailed() { return CastReturnType(nullptr); }
492
493 static inline CastReturnType doCastIfPossible(const From &f) {
494 if (!Self::isPossible(f))
495 return castFailed();
496 return doCast(f);
497 }
498};
499
500/// This struct provides an overload for CastInfo where From has simplify_type
501/// defined. This simply forwards to the appropriate CastInfo with the
502/// simplified type/value, so you don't have to implement both.
503template <typename To, typename From>
504struct CastInfo<To, From, std::enable_if_t<!is_simple_type<From>::value>> {
505 using Self = CastInfo<To, From>;
506 using SimpleFrom = typename simplify_type<From>::SimpleType;
507 using SimplifiedSelf = CastInfo<To, SimpleFrom>;
508
509 static inline bool isPossible(From &f) {
510 return SimplifiedSelf::isPossible(
511 simplify_type<From>::getSimplifiedValue(f));
512 }
513
514 static inline decltype(auto) doCast(From &f) {
515 return SimplifiedSelf::doCast(simplify_type<From>::getSimplifiedValue(f));
516 }
517
518 static inline decltype(auto) castFailed() {
519 return SimplifiedSelf::castFailed();
520 }
521
522 static inline decltype(auto) doCastIfPossible(From &f) {
523 return SimplifiedSelf::doCastIfPossible(
524 simplify_type<From>::getSimplifiedValue(f));
525 }
526};
527
528//===----------------------------------------------------------------------===//
529// Pre-specialized CastInfo
530//===----------------------------------------------------------------------===//
531
532/// Provide a CastInfo specialized for std::unique_ptr.
533template <typename To, typename From>
534struct CastInfo<To, std::unique_ptr<From>> : public UniquePtrCast<To, From> {};
535
536/// Provide a CastInfo specialized for Optional<From>. It's assumed that if the
537/// input is Optional<From> that the output can be Optional<To>. If that's not
538/// the case, specialize CastInfo for your use case.
539template <typename To, typename From>
540struct CastInfo<To, Optional<From>> : public OptionalValueCast<To, From> {};
541
542/// isa<X> - Return true if the parameter to the template is an instance of one
543/// of the template type arguments. Used like this:
544///
545/// if (isa<Type>(myVal)) { ... }
546/// if (isa<Type0, Type1, Type2>(myVal)) { ... }
547template <typename To, typename From>
548[[nodiscard]] inline bool isa(const From &Val) {
549 return CastInfo<To, const From>::isPossible(Val);
550}
551
552template <typename First, typename Second, typename... Rest, typename From>
553[[nodiscard]] inline bool isa(const From &Val) {
554 return isa<First>(Val) || isa<Second, Rest...>(Val);
555}
556
557/// cast<X> - Return the argument parameter cast to the specified type. This
558/// casting operator asserts that the type is correct, so it does not return
559/// null on failure. It does not allow a null argument (use cast_if_present for
560/// that). It is typically used like this:
561///
562/// cast<Instruction>(myVal)->getParent()
563
564template <typename To, typename From>
565[[nodiscard]] inline decltype(auto) cast(const From &Val) {
566 assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<To>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<To>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 566, __extension__ __PRETTY_FUNCTION__
))
;
17
Assuming 'Val' is a 'class clang::DeclContext *&'
18
'?' condition is true
567 return CastInfo<To, const From>::doCast(Val);
19
Returning pointer
568}
569
570template <typename To, typename From>
571[[nodiscard]] inline decltype(auto) cast(From &Val) {
572 assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<To>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<To>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 572, __extension__ __PRETTY_FUNCTION__
))
;
573 return CastInfo<To, From>::doCast(Val);
574}
575
576template <typename To, typename From>
577[[nodiscard]] inline decltype(auto) cast(From *Val) {
578 assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<To>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<To>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 578, __extension__ __PRETTY_FUNCTION__
))
;
579 return CastInfo<To, From *>::doCast(Val);
580}
581
582template <typename To, typename From>
583[[nodiscard]] inline decltype(auto) cast(std::unique_ptr<From> &&Val) {
584 assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<To>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<To>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 584, __extension__ __PRETTY_FUNCTION__
))
;
585 return CastInfo<To, std::unique_ptr<From>>::doCast(std::move(Val));
586}
587
588//===----------------------------------------------------------------------===//
589// ValueIsPresent
590//===----------------------------------------------------------------------===//
591
592template <typename T>
593constexpr bool IsNullable =
594 std::is_pointer_v<T> || std::is_constructible_v<T, std::nullptr_t>;
595
596/// ValueIsPresent provides a way to check if a value is, well, present. For
597/// pointers, this is the equivalent of checking against nullptr, for Optionals
598/// this is the equivalent of checking hasValue(). It also provides a method for
599/// unwrapping a value (think calling .value() on an optional).
600
601// Generic values can't *not* be present.
602template <typename T, typename Enable = void> struct ValueIsPresent {
603 using UnwrappedType = T;
604 static inline bool isPresent(const T &t) { return true; }
605 static inline decltype(auto) unwrapValue(T &t) { return t; }
606};
607
608// Optional provides its own way to check if something is present.
609template <typename T> struct ValueIsPresent<Optional<T>> {
610 using UnwrappedType = T;
611 static inline bool isPresent(const Optional<T> &t) { return t.has_value(); }
612 static inline decltype(auto) unwrapValue(Optional<T> &t) { return t.value(); }
613};
614
615// If something is "nullable" then we just compare it to nullptr to see if it
616// exists.
617template <typename T>
618struct ValueIsPresent<T, std::enable_if_t<IsNullable<T>>> {
619 using UnwrappedType = T;
620 static inline bool isPresent(const T &t) { return t != T(nullptr); }
621 static inline decltype(auto) unwrapValue(T &t) { return t; }
622};
623
624namespace detail {
625// Convenience function we can use to check if a value is present. Because of
626// simplify_type, we have to call it on the simplified type for now.
627template <typename T> inline bool isPresent(const T &t) {
628 return ValueIsPresent<typename simplify_type<T>::SimpleType>::isPresent(
629 simplify_type<T>::getSimplifiedValue(const_cast<T &>(t)));
630}
631
632// Convenience function we can use to unwrap a value.
633template <typename T> inline decltype(auto) unwrapValue(T &t) {
634 return ValueIsPresent<T>::unwrapValue(t);
635}
636} // namespace detail
637
638/// dyn_cast<X> - Return the argument parameter cast to the specified type. This
639/// casting operator returns null if the argument is of the wrong type, so it
640/// can be used to test for a type as well as cast if successful. The value
641/// passed in must be present, if not, use dyn_cast_if_present. This should be
642/// used in the context of an if statement like this:
643///
644/// if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... }
645
646template <typename To, typename From>
647[[nodiscard]] inline decltype(auto) dyn_cast(const From &Val) {
648 assert(detail::isPresent(Val) && "dyn_cast on a non-existent value")(static_cast <bool> (detail::isPresent(Val) && "dyn_cast on a non-existent value"
) ? void (0) : __assert_fail ("detail::isPresent(Val) && \"dyn_cast on a non-existent value\""
, "llvm/include/llvm/Support/Casting.h", 648, __extension__ __PRETTY_FUNCTION__
))
;
649 return CastInfo<To, const From>::doCastIfPossible(Val);
650}
651
652template <typename To, typename From>
653[[nodiscard]] inline decltype(auto) dyn_cast(From &Val) {
654 assert(detail::isPresent(Val) && "dyn_cast on a non-existent value")(static_cast <bool> (detail::isPresent(Val) && "dyn_cast on a non-existent value"
) ? void (0) : __assert_fail ("detail::isPresent(Val) && \"dyn_cast on a non-existent value\""
, "llvm/include/llvm/Support/Casting.h", 654, __extension__ __PRETTY_FUNCTION__
))
;
655 return CastInfo<To, From>::doCastIfPossible(Val);
656}
657
658template <typename To, typename From>
659[[nodiscard]] inline decltype(auto) dyn_cast(From *Val) {
660 assert(detail::isPresent(Val) && "dyn_cast on a non-existent value")(static_cast <bool> (detail::isPresent(Val) && "dyn_cast on a non-existent value"
) ? void (0) : __assert_fail ("detail::isPresent(Val) && \"dyn_cast on a non-existent value\""
, "llvm/include/llvm/Support/Casting.h", 660, __extension__ __PRETTY_FUNCTION__
))
;
661 return CastInfo<To, From *>::doCastIfPossible(Val);
662}
663
664template <typename To, typename From>
665[[nodiscard]] inline decltype(auto) dyn_cast(std::unique_ptr<From> &&Val) {
666 assert(detail::isPresent(Val) && "dyn_cast on a non-existent value")(static_cast <bool> (detail::isPresent(Val) && "dyn_cast on a non-existent value"
) ? void (0) : __assert_fail ("detail::isPresent(Val) && \"dyn_cast on a non-existent value\""
, "llvm/include/llvm/Support/Casting.h", 666, __extension__ __PRETTY_FUNCTION__
))
;
667 return CastInfo<To, std::unique_ptr<From>>::doCastIfPossible(
668 std::forward<std::unique_ptr<From> &&>(Val));
669}
670
671/// isa_and_present<X> - Functionally identical to isa, except that a null value
672/// is accepted.
673template <typename... X, class Y>
674[[nodiscard]] inline bool isa_and_present(const Y &Val) {
675 if (!detail::isPresent(Val))
676 return false;
677 return isa<X...>(Val);
678}
679
680template <typename... X, class Y>
681[[nodiscard]] inline bool isa_and_nonnull(const Y &Val) {
682 return isa_and_present<X...>(Val);
683}
684
685/// cast_if_present<X> - Functionally identical to cast, except that a null
686/// value is accepted.
687template <class X, class Y>
688[[nodiscard]] inline auto cast_if_present(const Y &Val) {
689 if (!detail::isPresent(Val))
690 return CastInfo<X, const Y>::castFailed();
691 assert(isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_if_present<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 691, __extension__ __PRETTY_FUNCTION__
))
;
692 return cast<X>(detail::unwrapValue(Val));
693}
694
695template <class X, class Y> [[nodiscard]] inline auto cast_if_present(Y &Val) {
696 if (!detail::isPresent(Val))
697 return CastInfo<X, Y>::castFailed();
698 assert(isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_if_present<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 698, __extension__ __PRETTY_FUNCTION__
))
;
699 return cast<X>(detail::unwrapValue(Val));
700}
701
702template <class X, class Y> [[nodiscard]] inline auto cast_if_present(Y *Val) {
703 if (!detail::isPresent(Val))
704 return CastInfo<X, Y *>::castFailed();
705 assert(isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_if_present<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 705, __extension__ __PRETTY_FUNCTION__
))
;
706 return cast<X>(detail::unwrapValue(Val));
707}
708
709template <class X, class Y>
710[[nodiscard]] inline auto cast_if_present(std::unique_ptr<Y> &&Val) {
711 if (!detail::isPresent(Val))
712 return UniquePtrCast<X, Y>::castFailed();
713 return UniquePtrCast<X, Y>::doCast(std::move(Val));
714}
715
716// Provide a forwarding from cast_or_null to cast_if_present for current
717// users. This is deprecated and will be removed in a future patch, use
718// cast_if_present instead.
719template <class X, class Y> auto cast_or_null(const Y &Val) {
720 return cast_if_present<X>(Val);
721}
722
723template <class X, class Y> auto cast_or_null(Y &Val) {
724 return cast_if_present<X>(Val);
725}
726
727template <class X, class Y> auto cast_or_null(Y *Val) {
728 return cast_if_present<X>(Val);
729}
730
731template <class X, class Y> auto cast_or_null(std::unique_ptr<Y> &&Val) {
732 return cast_if_present<X>(std::move(Val));
733}
734
735/// dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a
736/// null (or none in the case of optionals) value is accepted.
737template <class X, class Y> auto dyn_cast_if_present(const Y &Val) {
738 if (!detail::isPresent(Val))
739 return CastInfo<X, const Y>::castFailed();
740 return CastInfo<X, const Y>::doCastIfPossible(detail::unwrapValue(Val));
741}
742
743template <class X, class Y> auto dyn_cast_if_present(Y &Val) {
744 if (!detail::isPresent(Val))
745 return CastInfo<X, Y>::castFailed();
746 return CastInfo<X, Y>::doCastIfPossible(detail::unwrapValue(Val));
747}
748
749template <class X, class Y> auto dyn_cast_if_present(Y *Val) {
750 if (!detail::isPresent(Val))
751 return CastInfo<X, Y *>::castFailed();
752 return CastInfo<X, Y *>::doCastIfPossible(detail::unwrapValue(Val));
753}
754
755// Forwards to dyn_cast_if_present to avoid breaking current users. This is
756// deprecated and will be removed in a future patch, use
757// cast_if_present instead.
758template <class X, class Y> auto dyn_cast_or_null(const Y &Val) {
759 return dyn_cast_if_present<X>(Val);
760}
761
762template <class X, class Y> auto dyn_cast_or_null(Y &Val) {
763 return dyn_cast_if_present<X>(Val);
764}
765
766template <class X, class Y> auto dyn_cast_or_null(Y *Val) {
767 return dyn_cast_if_present<X>(Val);
768}
769
770/// unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>,
771/// taking ownership of the input pointer iff isa<X>(Val) is true. If the
772/// cast is successful, From refers to nullptr on exit and the casted value
773/// is returned. If the cast is unsuccessful, the function returns nullptr
774/// and From is unchanged.
775template <class X, class Y>
776[[nodiscard]] inline typename CastInfo<X, std::unique_ptr<Y>>::CastResultType
777unique_dyn_cast(std::unique_ptr<Y> &Val) {
778 if (!isa<X>(Val))
779 return nullptr;
780 return cast<X>(std::move(Val));
781}
782
783template <class X, class Y>
784[[nodiscard]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val) {
785 return unique_dyn_cast<X, Y>(Val);
786}
787
788// unique_dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast,
789// except that a null value is accepted.
790template <class X, class Y>
791[[nodiscard]] inline typename CastInfo<X, std::unique_ptr<Y>>::CastResultType
792unique_dyn_cast_or_null(std::unique_ptr<Y> &Val) {
793 if (!Val)
794 return nullptr;
795 return unique_dyn_cast<X, Y>(Val);
796}
797
798template <class X, class Y>
799[[nodiscard]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val) {
800 return unique_dyn_cast_or_null<X, Y>(Val);
801}
802
803} // end namespace llvm
804
805#endif // LLVM_SUPPORT_CASTING_H