Bug Summary

File:build/source/lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp
Warning:line 132, 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/source/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-17/lib/clang/17 -isystem /usr/include/libxml2 -I tools/lldb/source/Plugins/ExpressionParser/Clang -I /build/source/lldb/source/Plugins/ExpressionParser/Clang -I /build/source/lldb/include -I tools/lldb/include -I include -I /build/source/llvm/include -I /usr/include/python3.9 -I /build/source/clang/include -I tools/lldb/../clang/include -I /build/source/lldb/source -I tools/lldb/source -D HAVE_ROUND -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -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-17/lib/clang/17/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/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/source/= -source-date-epoch 1675682001 -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/source/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/= -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-2023-02-06-130241-16458-1 -x c++ /build/source/lldb/source/Plugins/ExpressionParser/Clang/CxxModuleHandler.cpp

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

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

/build/source/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/source/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/Support/Compiler.h"
18#include "llvm/Support/type_traits.h"
19#include <cassert>
20#include <memory>
21#include <optional>
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, std::optional<From>> {
267 static inline bool isPossible(const std::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 std::optional<T> casting. This means that if you
363/// have a value type, you can cast it to another value type and have dyn_cast
364/// return an std::optional<T>.
365template <typename To, typename From, typename Derived = void>
366struct OptionalValueCast
367 : public CastIsPossible<To, From>,
368 public DefaultDoCastIfPossible<
369 std::optional<To>, From,
370 detail::SelfType<Derived, OptionalValueCast<To, From>>> {
371 static inline std::optional<To> castFailed() { return std::optional<To>{}; }
372
373 static inline std::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 std::optional<From>. It's assumed that if
537/// the input is std::optional<From> that the output can be std::optional<To>.
538/// If that's not the case, specialize CastInfo for your use case.
539template <typename To, typename From>
540struct CastInfo<To, std::optional<From>> : public OptionalValueCast<To, From> {
541};
542
543/// isa<X> - Return true if the parameter to the template is an instance of one
544/// of the template type arguments. Used like this:
545///
546/// if (isa<Type>(myVal)) { ... }
547/// if (isa<Type0, Type1, Type2>(myVal)) { ... }
548template <typename To, typename From>
549[[nodiscard]] inline bool isa(const From &Val) {
550 return CastInfo<To, const From>::isPossible(Val);
551}
552
553template <typename First, typename Second, typename... Rest, typename From>
554[[nodiscard]] inline bool isa(const From &Val) {
555 return isa<First>(Val) || isa<Second, Rest...>(Val);
556}
557
558/// cast<X> - Return the argument parameter cast to the specified type. This
559/// casting operator asserts that the type is correct, so it does not return
560/// null on failure. It does not allow a null argument (use cast_if_present for
561/// that). It is typically used like this:
562///
563/// cast<Instruction>(myVal)->getParent()
564
565template <typename To, typename From>
566[[nodiscard]] inline decltype(auto) cast(const From &Val) {
567 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", 567, __extension__ __PRETTY_FUNCTION__
))
;
17
Assuming 'Val' is a 'class clang::DeclContext *&'
18
'?' condition is true
568 return CastInfo<To, const From>::doCast(Val);
19
Returning pointer
569}
570
571template <typename To, typename From>
572[[nodiscard]] inline decltype(auto) cast(From &Val) {
573 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", 573, __extension__ __PRETTY_FUNCTION__
))
;
574 return CastInfo<To, From>::doCast(Val);
575}
576
577template <typename To, typename From>
578[[nodiscard]] inline decltype(auto) cast(From *Val) {
579 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", 579, __extension__ __PRETTY_FUNCTION__
))
;
580 return CastInfo<To, From *>::doCast(Val);
581}
582
583template <typename To, typename From>
584[[nodiscard]] inline decltype(auto) cast(std::unique_ptr<From> &&Val) {
585 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", 585, __extension__ __PRETTY_FUNCTION__
))
;
586 return CastInfo<To, std::unique_ptr<From>>::doCast(std::move(Val));
587}
588
589//===----------------------------------------------------------------------===//
590// ValueIsPresent
591//===----------------------------------------------------------------------===//
592
593template <typename T>
594constexpr bool IsNullable =
595 std::is_pointer_v<T> || std::is_constructible_v<T, std::nullptr_t>;
596
597/// ValueIsPresent provides a way to check if a value is, well, present. For
598/// pointers, this is the equivalent of checking against nullptr, for Optionals
599/// this is the equivalent of checking hasValue(). It also provides a method for
600/// unwrapping a value (think calling .value() on an optional).
601
602// Generic values can't *not* be present.
603template <typename T, typename Enable = void> struct ValueIsPresent {
604 using UnwrappedType = T;
605 static inline bool isPresent(const T &t) { return true; }
606 static inline decltype(auto) unwrapValue(T &t) { return t; }
607};
608
609// Optional provides its own way to check if something is present.
610template <typename T> struct ValueIsPresent<std::optional<T>> {
611 using UnwrappedType = T;
612 static inline bool isPresent(const std::optional<T> &t) {
613 return t.has_value();
614 }
615 static inline decltype(auto) unwrapValue(std::optional<T> &t) { return *t; }
616};
617
618// If something is "nullable" then we just compare it to nullptr to see if it
619// exists.
620template <typename T>
621struct ValueIsPresent<T, std::enable_if_t<IsNullable<T>>> {
622 using UnwrappedType = T;
623 static inline bool isPresent(const T &t) { return t != T(nullptr); }
624 static inline decltype(auto) unwrapValue(T &t) { return t; }
625};
626
627namespace detail {
628// Convenience function we can use to check if a value is present. Because of
629// simplify_type, we have to call it on the simplified type for now.
630template <typename T> inline bool isPresent(const T &t) {
631 return ValueIsPresent<typename simplify_type<T>::SimpleType>::isPresent(
632 simplify_type<T>::getSimplifiedValue(const_cast<T &>(t)));
633}
634
635// Convenience function we can use to unwrap a value.
636template <typename T> inline decltype(auto) unwrapValue(T &t) {
637 return ValueIsPresent<T>::unwrapValue(t);
638}
639} // namespace detail
640
641/// dyn_cast<X> - Return the argument parameter cast to the specified type. This
642/// casting operator returns null if the argument is of the wrong type, so it
643/// can be used to test for a type as well as cast if successful. The value
644/// passed in must be present, if not, use dyn_cast_if_present. This should be
645/// used in the context of an if statement like this:
646///
647/// if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... }
648
649template <typename To, typename From>
650[[nodiscard]] inline decltype(auto) dyn_cast(const From &Val) {
651 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", 651, __extension__ __PRETTY_FUNCTION__
))
;
652 return CastInfo<To, const From>::doCastIfPossible(Val);
653}
654
655template <typename To, typename From>
656[[nodiscard]] inline decltype(auto) dyn_cast(From &Val) {
657 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", 657, __extension__ __PRETTY_FUNCTION__
))
;
658 return CastInfo<To, From>::doCastIfPossible(Val);
659}
660
661template <typename To, typename From>
662[[nodiscard]] inline decltype(auto) dyn_cast(From *Val) {
663 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", 663, __extension__ __PRETTY_FUNCTION__
))
;
664 return CastInfo<To, From *>::doCastIfPossible(Val);
665}
666
667template <typename To, typename From>
668[[nodiscard]] inline decltype(auto) dyn_cast(std::unique_ptr<From> &&Val) {
669 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", 669, __extension__ __PRETTY_FUNCTION__
))
;
670 return CastInfo<To, std::unique_ptr<From>>::doCastIfPossible(
671 std::forward<std::unique_ptr<From> &&>(Val));
672}
673
674/// isa_and_present<X> - Functionally identical to isa, except that a null value
675/// is accepted.
676template <typename... X, class Y>
677[[nodiscard]] inline bool isa_and_present(const Y &Val) {
678 if (!detail::isPresent(Val))
679 return false;
680 return isa<X...>(Val);
681}
682
683template <typename... X, class Y>
684[[nodiscard]] inline bool isa_and_nonnull(const Y &Val) {
685 return isa_and_present<X...>(Val);
686}
687
688/// cast_if_present<X> - Functionally identical to cast, except that a null
689/// value is accepted.
690template <class X, class Y>
691[[nodiscard]] inline auto cast_if_present(const Y &Val) {
692 if (!detail::isPresent(Val))
693 return CastInfo<X, const Y>::castFailed();
694 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", 694, __extension__ __PRETTY_FUNCTION__
))
;
695 return cast<X>(detail::unwrapValue(Val));
696}
697
698template <class X, class Y> [[nodiscard]] inline auto cast_if_present(Y &Val) {
699 if (!detail::isPresent(Val))
700 return CastInfo<X, Y>::castFailed();
701 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", 701, __extension__ __PRETTY_FUNCTION__
))
;
702 return cast<X>(detail::unwrapValue(Val));
703}
704
705template <class X, class Y> [[nodiscard]] inline auto cast_if_present(Y *Val) {
706 if (!detail::isPresent(Val))
707 return CastInfo<X, Y *>::castFailed();
708 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", 708, __extension__ __PRETTY_FUNCTION__
))
;
709 return cast<X>(detail::unwrapValue(Val));
710}
711
712template <class X, class Y>
713[[nodiscard]] inline auto cast_if_present(std::unique_ptr<Y> &&Val) {
714 if (!detail::isPresent(Val))
715 return UniquePtrCast<X, Y>::castFailed();
716 return UniquePtrCast<X, Y>::doCast(std::move(Val));
717}
718
719// Provide a forwarding from cast_or_null to cast_if_present for current
720// users. This is deprecated and will be removed in a future patch, use
721// cast_if_present instead.
722template <class X, class Y> auto cast_or_null(const Y &Val) {
723 return cast_if_present<X>(Val);
724}
725
726template <class X, class Y> auto cast_or_null(Y &Val) {
727 return cast_if_present<X>(Val);
728}
729
730template <class X, class Y> auto cast_or_null(Y *Val) {
731 return cast_if_present<X>(Val);
732}
733
734template <class X, class Y> auto cast_or_null(std::unique_ptr<Y> &&Val) {
735 return cast_if_present<X>(std::move(Val));
736}
737
738/// dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a
739/// null (or none in the case of optionals) value is accepted.
740template <class X, class Y> auto dyn_cast_if_present(const Y &Val) {
741 if (!detail::isPresent(Val))
742 return CastInfo<X, const Y>::castFailed();
743 return CastInfo<X, const Y>::doCastIfPossible(detail::unwrapValue(Val));
744}
745
746template <class X, class Y> auto dyn_cast_if_present(Y &Val) {
747 if (!detail::isPresent(Val))
748 return CastInfo<X, Y>::castFailed();
749 return CastInfo<X, Y>::doCastIfPossible(detail::unwrapValue(Val));
750}
751
752template <class X, class Y> auto dyn_cast_if_present(Y *Val) {
753 if (!detail::isPresent(Val))
754 return CastInfo<X, Y *>::castFailed();
755 return CastInfo<X, Y *>::doCastIfPossible(detail::unwrapValue(Val));
756}
757
758// Forwards to dyn_cast_if_present to avoid breaking current users. This is
759// deprecated and will be removed in a future patch, use
760// cast_if_present instead.
761template <class X, class Y> auto dyn_cast_or_null(const Y &Val) {
762 return dyn_cast_if_present<X>(Val);
763}
764
765template <class X, class Y> auto dyn_cast_or_null(Y &Val) {
766 return dyn_cast_if_present<X>(Val);
767}
768
769template <class X, class Y> auto dyn_cast_or_null(Y *Val) {
770 return dyn_cast_if_present<X>(Val);
771}
772
773/// unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>,
774/// taking ownership of the input pointer iff isa<X>(Val) is true. If the
775/// cast is successful, From refers to nullptr on exit and the casted value
776/// is returned. If the cast is unsuccessful, the function returns nullptr
777/// and From is unchanged.
778template <class X, class Y>
779[[nodiscard]] inline typename CastInfo<X, std::unique_ptr<Y>>::CastResultType
780unique_dyn_cast(std::unique_ptr<Y> &Val) {
781 if (!isa<X>(Val))
782 return nullptr;
783 return cast<X>(std::move(Val));
784}
785
786template <class X, class Y>
787[[nodiscard]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val) {
788 return unique_dyn_cast<X, Y>(Val);
789}
790
791// unique_dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast,
792// except that a null value is accepted.
793template <class X, class Y>
794[[nodiscard]] inline typename CastInfo<X, std::unique_ptr<Y>>::CastResultType
795unique_dyn_cast_or_null(std::unique_ptr<Y> &Val) {
796 if (!Val)
797 return nullptr;
798 return unique_dyn_cast<X, Y>(Val);
799}
800
801template <class X, class Y>
802[[nodiscard]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val) {
803 return unique_dyn_cast_or_null<X, Y>(Val);
804}
805
806} // end namespace llvm
807
808#endif // LLVM_SUPPORT_CASTING_H