blob: 4d25bf375641e3a4d1a608c1823b7fb5a5ee5dbc [file] [log] [blame]
//===-- ClangASTContext.cpp -------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "lldb/Symbol/ClangASTContext.h"
#include "llvm/Support/FormatAdapters.h"
#include "llvm/Support/FormatVariadic.h"
#include <mutex>
#include <string>
#include <vector>
// Clang headers like to use NDEBUG inside of them to enable/disable debug
// related features using "#ifndef NDEBUG" preprocessor blocks to do one thing
// or another. This is bad because it means that if clang was built in release
// mode, it assumes that you are building in release mode which is not always
// the case. You can end up with functions that are defined as empty in header
// files when NDEBUG is not defined, and this can cause link errors with the
// clang .a files that you have since you might be missing functions in the .a
// file. So we have to define NDEBUG when including clang headers to avoid any
// mismatches. This is covered by rdar://problem/8691220
#if !defined(NDEBUG) && !defined(LLVM_NDEBUG_OFF)
#define LLDB_DEFINED_NDEBUG_FOR_CLANG
#define NDEBUG
// Need to include assert.h so it is as clang would expect it to be (disabled)
#include <assert.h>
#endif
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTImporter.h"
#include "clang/AST/Attr.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/Type.h"
#include "clang/AST/VTableBuilder.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/FileSystemOptions.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Frontend/FrontendOptions.h"
#include "clang/Frontend/LangStandard.h"
#include "clang/Sema/Sema.h"
#ifdef LLDB_DEFINED_NDEBUG_FOR_CLANG
#undef NDEBUG
#undef LLDB_DEFINED_NDEBUG_FOR_CLANG
// Need to re-include assert.h so it is as _we_ would expect it to be (enabled)
#include <assert.h>
#endif
#include "llvm/Support/Signals.h"
#include "llvm/Support/Threading.h"
#include "Plugins/ExpressionParser/Clang/ClangFunctionCaller.h"
#include "Plugins/ExpressionParser/Clang/ClangUserExpression.h"
#include "Plugins/ExpressionParser/Clang/ClangUtilityFunction.h"
#include "lldb/Utility/ArchSpec.h"
#include "lldb/Utility/Flags.h"
#include "lldb/Core/DumpDataExtractor.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/StreamFile.h"
#include "lldb/Core/ThreadSafeDenseMap.h"
#include "lldb/Core/UniqueCStringMap.h"
#include "lldb/Symbol/ClangASTContext.h"
#include "lldb/Symbol/ClangASTImporter.h"
#include "lldb/Symbol/ClangExternalASTSourceCallbacks.h"
#include "lldb/Symbol/ClangExternalASTSourceCommon.h"
#include "lldb/Symbol/ClangUtil.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Symbol/SymbolFile.h"
#include "lldb/Symbol/VerifyDecl.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/Language.h"
#include "lldb/Target/ObjCLanguageRuntime.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/Target.h"
#include "lldb/Utility/DataExtractor.h"
#include "lldb/Utility/LLDBAssert.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/RegularExpression.h"
#include "lldb/Utility/Scalar.h"
#include "Plugins/SymbolFile/DWARF/DWARFASTParserClang.h"
#include "Plugins/SymbolFile/PDB/PDBASTParser.h"
#include <stdio.h>
#include <mutex>
using namespace lldb;
using namespace lldb_private;
using namespace llvm;
using namespace clang;
namespace {
static inline bool
ClangASTContextSupportsLanguage(lldb::LanguageType language) {
return language == eLanguageTypeUnknown || // Clang is the default type system
Language::LanguageIsC(language) ||
Language::LanguageIsCPlusPlus(language) ||
Language::LanguageIsObjC(language) ||
Language::LanguageIsPascal(language) ||
// Use Clang for Rust until there is a proper language plugin for it
language == eLanguageTypeRust ||
language == eLanguageTypeExtRenderScript ||
// Use Clang for D until there is a proper language plugin for it
language == eLanguageTypeD ||
// Open Dylan compiler debug info is designed to be Clang-compatible
language == eLanguageTypeDylan;
}
// Checks whether m1 is an overload of m2 (as opposed to an override). This is
// called by addOverridesForMethod to distinguish overrides (which share a
// vtable entry) from overloads (which require distinct entries).
bool isOverload(clang::CXXMethodDecl *m1, clang::CXXMethodDecl *m2) {
// FIXME: This should detect covariant return types, but currently doesn't.
lldbassert(&m1->getASTContext() == &m2->getASTContext() &&
"Methods should have the same AST context");
clang::ASTContext &context = m1->getASTContext();
const auto *m1Type = llvm::cast<clang::FunctionProtoType>(
context.getCanonicalType(m1->getType()));
const auto *m2Type = llvm::cast<clang::FunctionProtoType>(
context.getCanonicalType(m2->getType()));
auto compareArgTypes = [&context](const clang::QualType &m1p,
const clang::QualType &m2p) {
return context.hasSameType(m1p.getUnqualifiedType(),
m2p.getUnqualifiedType());
};
// FIXME: In C++14 and later, we can just pass m2Type->param_type_end()
// as a fourth parameter to std::equal().
return (m1->getNumParams() != m2->getNumParams()) ||
!std::equal(m1Type->param_type_begin(), m1Type->param_type_end(),
m2Type->param_type_begin(), compareArgTypes);
}
// If decl is a virtual method, walk the base classes looking for methods that
// decl overrides. This table of overridden methods is used by IRGen to
// determine the vtable layout for decl's parent class.
void addOverridesForMethod(clang::CXXMethodDecl *decl) {
if (!decl->isVirtual())
return;
clang::CXXBasePaths paths;
auto find_overridden_methods =
[decl](const clang::CXXBaseSpecifier *specifier,
clang::CXXBasePath &path) {
if (auto *base_record = llvm::dyn_cast<clang::CXXRecordDecl>(
specifier->getType()->getAs<clang::RecordType>()->getDecl())) {
clang::DeclarationName name = decl->getDeclName();
// If this is a destructor, check whether the base class destructor is
// virtual.
if (name.getNameKind() == clang::DeclarationName::CXXDestructorName)
if (auto *baseDtorDecl = base_record->getDestructor()) {
if (baseDtorDecl->isVirtual()) {
path.Decls = baseDtorDecl;
return true;
} else
return false;
}
// Otherwise, search for name in the base class.
for (path.Decls = base_record->lookup(name); !path.Decls.empty();
path.Decls = path.Decls.slice(1)) {
if (auto *method_decl =
llvm::dyn_cast<clang::CXXMethodDecl>(path.Decls.front()))
if (method_decl->isVirtual() && !isOverload(decl, method_decl)) {
path.Decls = method_decl;
return true;
}
}
}
return false;
};
if (decl->getParent()->lookupInBases(find_overridden_methods, paths)) {
for (auto *overridden_decl : paths.found_decls())
decl->addOverriddenMethod(
llvm::cast<clang::CXXMethodDecl>(overridden_decl));
}
}
}
static lldb::addr_t GetVTableAddress(Process &process,
VTableContextBase &vtable_ctx,
ValueObject &valobj,
const ASTRecordLayout &record_layout) {
// Retrieve type info
CompilerType pointee_type;
CompilerType this_type(valobj.GetCompilerType());
uint32_t type_info = this_type.GetTypeInfo(&pointee_type);
if (!type_info)
return LLDB_INVALID_ADDRESS;
// Check if it's a pointer or reference
bool ptr_or_ref = false;
if (type_info & (eTypeIsPointer | eTypeIsReference)) {
ptr_or_ref = true;
type_info = pointee_type.GetTypeInfo();
}
// We process only C++ classes
const uint32_t cpp_class = eTypeIsClass | eTypeIsCPlusPlus;
if ((type_info & cpp_class) != cpp_class)
return LLDB_INVALID_ADDRESS;
// Calculate offset to VTable pointer
lldb::offset_t vbtable_ptr_offset =
vtable_ctx.isMicrosoft() ? record_layout.getVBPtrOffset().getQuantity()
: 0;
if (ptr_or_ref) {
// We have a pointer / ref to object, so read
// VTable pointer from process memory
if (valobj.GetAddressTypeOfChildren() != eAddressTypeLoad)
return LLDB_INVALID_ADDRESS;
auto vbtable_ptr_addr = valobj.GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
if (vbtable_ptr_addr == LLDB_INVALID_ADDRESS)
return LLDB_INVALID_ADDRESS;
vbtable_ptr_addr += vbtable_ptr_offset;
Status err;
return process.ReadPointerFromMemory(vbtable_ptr_addr, err);
}
// We have an object already read from process memory,
// so just extract VTable pointer from it
DataExtractor data;
Status err;
auto size = valobj.GetData(data, err);
if (err.Fail() || vbtable_ptr_offset + data.GetAddressByteSize() > size)
return LLDB_INVALID_ADDRESS;
return data.GetPointer(&vbtable_ptr_offset);
}
static int64_t ReadVBaseOffsetFromVTable(Process &process,
VTableContextBase &vtable_ctx,
lldb::addr_t vtable_ptr,
const CXXRecordDecl *cxx_record_decl,
const CXXRecordDecl *base_class_decl) {
if (vtable_ctx.isMicrosoft()) {
clang::MicrosoftVTableContext &msoft_vtable_ctx =
static_cast<clang::MicrosoftVTableContext &>(vtable_ctx);
// Get the index into the virtual base table. The
// index is the index in uint32_t from vbtable_ptr
const unsigned vbtable_index =
msoft_vtable_ctx.getVBTableIndex(cxx_record_decl, base_class_decl);
const lldb::addr_t base_offset_addr = vtable_ptr + vbtable_index * 4;
Status err;
return process.ReadSignedIntegerFromMemory(base_offset_addr, 4, INT64_MAX,
err);
}
clang::ItaniumVTableContext &itanium_vtable_ctx =
static_cast<clang::ItaniumVTableContext &>(vtable_ctx);
clang::CharUnits base_offset_offset =
itanium_vtable_ctx.getVirtualBaseOffsetOffset(cxx_record_decl,
base_class_decl);
const lldb::addr_t base_offset_addr =
vtable_ptr + base_offset_offset.getQuantity();
const uint32_t base_offset_size = process.GetAddressByteSize();
Status err;
return process.ReadSignedIntegerFromMemory(base_offset_addr, base_offset_size,
INT64_MAX, err);
}
static bool GetVBaseBitOffset(VTableContextBase &vtable_ctx,
ValueObject &valobj,
const ASTRecordLayout &record_layout,
const CXXRecordDecl *cxx_record_decl,
const CXXRecordDecl *base_class_decl,
int32_t &bit_offset) {
ExecutionContext exe_ctx(valobj.GetExecutionContextRef());
Process *process = exe_ctx.GetProcessPtr();
if (!process)
return false;
lldb::addr_t vtable_ptr =
GetVTableAddress(*process, vtable_ctx, valobj, record_layout);
if (vtable_ptr == LLDB_INVALID_ADDRESS)
return false;
auto base_offset = ReadVBaseOffsetFromVTable(
*process, vtable_ctx, vtable_ptr, cxx_record_decl, base_class_decl);
if (base_offset == INT64_MAX)
return false;
bit_offset = base_offset * 8;
return true;
}
typedef lldb_private::ThreadSafeDenseMap<clang::ASTContext *, ClangASTContext *>
ClangASTMap;
static ClangASTMap &GetASTMap() {
static ClangASTMap *g_map_ptr = nullptr;
static llvm::once_flag g_once_flag;
llvm::call_once(g_once_flag, []() {
g_map_ptr = new ClangASTMap(); // leaked on purpose to avoid spins
});
return *g_map_ptr;
}
bool ClangASTContext::IsOperator(const char *name,
clang::OverloadedOperatorKind &op_kind) {
if (name == nullptr || name[0] == '\0')
return false;
#define OPERATOR_PREFIX "operator"
#define OPERATOR_PREFIX_LENGTH (sizeof(OPERATOR_PREFIX) - 1)
const char *post_op_name = nullptr;
bool no_space = true;
if (::strncmp(name, OPERATOR_PREFIX, OPERATOR_PREFIX_LENGTH))
return false;
post_op_name = name + OPERATOR_PREFIX_LENGTH;
if (post_op_name[0] == ' ') {
post_op_name++;
no_space = false;
}
#undef OPERATOR_PREFIX
#undef OPERATOR_PREFIX_LENGTH
// This is an operator, set the overloaded operator kind to invalid in case
// this is a conversion operator...
op_kind = clang::NUM_OVERLOADED_OPERATORS;
switch (post_op_name[0]) {
default:
if (no_space)
return false;
break;
case 'n':
if (no_space)
return false;
if (strcmp(post_op_name, "new") == 0)
op_kind = clang::OO_New;
else if (strcmp(post_op_name, "new[]") == 0)
op_kind = clang::OO_Array_New;
break;
case 'd':
if (no_space)
return false;
if (strcmp(post_op_name, "delete") == 0)
op_kind = clang::OO_Delete;
else if (strcmp(post_op_name, "delete[]") == 0)
op_kind = clang::OO_Array_Delete;
break;
case '+':
if (post_op_name[1] == '\0')
op_kind = clang::OO_Plus;
else if (post_op_name[2] == '\0') {
if (post_op_name[1] == '=')
op_kind = clang::OO_PlusEqual;
else if (post_op_name[1] == '+')
op_kind = clang::OO_PlusPlus;
}
break;
case '-':
if (post_op_name[1] == '\0')
op_kind = clang::OO_Minus;
else if (post_op_name[2] == '\0') {
switch (post_op_name[1]) {
case '=':
op_kind = clang::OO_MinusEqual;
break;
case '-':
op_kind = clang::OO_MinusMinus;
break;
case '>':
op_kind = clang::OO_Arrow;
break;
}
} else if (post_op_name[3] == '\0') {
if (post_op_name[2] == '*')
op_kind = clang::OO_ArrowStar;
break;
}
break;
case '*':
if (post_op_name[1] == '\0')
op_kind = clang::OO_Star;
else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
op_kind = clang::OO_StarEqual;
break;
case '/':
if (post_op_name[1] == '\0')
op_kind = clang::OO_Slash;
else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
op_kind = clang::OO_SlashEqual;
break;
case '%':
if (post_op_name[1] == '\0')
op_kind = clang::OO_Percent;
else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
op_kind = clang::OO_PercentEqual;
break;
case '^':
if (post_op_name[1] == '\0')
op_kind = clang::OO_Caret;
else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
op_kind = clang::OO_CaretEqual;
break;
case '&':
if (post_op_name[1] == '\0')
op_kind = clang::OO_Amp;
else if (post_op_name[2] == '\0') {
switch (post_op_name[1]) {
case '=':
op_kind = clang::OO_AmpEqual;
break;
case '&':
op_kind = clang::OO_AmpAmp;
break;
}
}
break;
case '|':
if (post_op_name[1] == '\0')
op_kind = clang::OO_Pipe;
else if (post_op_name[2] == '\0') {
switch (post_op_name[1]) {
case '=':
op_kind = clang::OO_PipeEqual;
break;
case '|':
op_kind = clang::OO_PipePipe;
break;
}
}
break;
case '~':
if (post_op_name[1] == '\0')
op_kind = clang::OO_Tilde;
break;
case '!':
if (post_op_name[1] == '\0')
op_kind = clang::OO_Exclaim;
else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
op_kind = clang::OO_ExclaimEqual;
break;
case '=':
if (post_op_name[1] == '\0')
op_kind = clang::OO_Equal;
else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
op_kind = clang::OO_EqualEqual;
break;
case '<':
if (post_op_name[1] == '\0')
op_kind = clang::OO_Less;
else if (post_op_name[2] == '\0') {
switch (post_op_name[1]) {
case '<':
op_kind = clang::OO_LessLess;
break;
case '=':
op_kind = clang::OO_LessEqual;
break;
}
} else if (post_op_name[3] == '\0') {
if (post_op_name[2] == '=')
op_kind = clang::OO_LessLessEqual;
}
break;
case '>':
if (post_op_name[1] == '\0')
op_kind = clang::OO_Greater;
else if (post_op_name[2] == '\0') {
switch (post_op_name[1]) {
case '>':
op_kind = clang::OO_GreaterGreater;
break;
case '=':
op_kind = clang::OO_GreaterEqual;
break;
}
} else if (post_op_name[1] == '>' && post_op_name[2] == '=' &&
post_op_name[3] == '\0') {
op_kind = clang::OO_GreaterGreaterEqual;
}
break;
case ',':
if (post_op_name[1] == '\0')
op_kind = clang::OO_Comma;
break;
case '(':
if (post_op_name[1] == ')' && post_op_name[2] == '\0')
op_kind = clang::OO_Call;
break;
case '[':
if (post_op_name[1] == ']' && post_op_name[2] == '\0')
op_kind = clang::OO_Subscript;
break;
}
return true;
}
clang::AccessSpecifier
ClangASTContext::ConvertAccessTypeToAccessSpecifier(AccessType access) {
switch (access) {
default:
break;
case eAccessNone:
return AS_none;
case eAccessPublic:
return AS_public;
case eAccessPrivate:
return AS_private;
case eAccessProtected:
return AS_protected;
}
return AS_none;
}
static void ParseLangArgs(LangOptions &Opts, InputKind IK, const char *triple) {
// FIXME: Cleanup per-file based stuff.
// Set some properties which depend solely on the input kind; it would be
// nice to move these to the language standard, and have the driver resolve
// the input kind + language standard.
if (IK.getLanguage() == InputKind::Asm) {
Opts.AsmPreprocessor = 1;
} else if (IK.isObjectiveC()) {
Opts.ObjC = 1;
}
LangStandard::Kind LangStd = LangStandard::lang_unspecified;
if (LangStd == LangStandard::lang_unspecified) {
// Based on the base language, pick one.
switch (IK.getLanguage()) {
case InputKind::Unknown:
case InputKind::LLVM_IR:
case InputKind::RenderScript:
llvm_unreachable("Invalid input kind!");
case InputKind::OpenCL:
LangStd = LangStandard::lang_opencl10;
break;
case InputKind::CUDA:
LangStd = LangStandard::lang_cuda;
break;
case InputKind::Asm:
case InputKind::C:
case InputKind::ObjC:
LangStd = LangStandard::lang_gnu99;
break;
case InputKind::CXX:
case InputKind::ObjCXX:
LangStd = LangStandard::lang_gnucxx98;
break;
case InputKind::HIP:
LangStd = LangStandard::lang_hip;
break;
}
}
const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
Opts.LineComment = Std.hasLineComments();
Opts.C99 = Std.isC99();
Opts.CPlusPlus = Std.isCPlusPlus();
Opts.CPlusPlus11 = Std.isCPlusPlus11();
Opts.Digraphs = Std.hasDigraphs();
Opts.GNUMode = Std.isGNUMode();
Opts.GNUInline = !Std.isC99();
Opts.HexFloats = Std.hasHexFloats();
Opts.ImplicitInt = Std.hasImplicitInt();
Opts.WChar = true;
// OpenCL has some additional defaults.
if (LangStd == LangStandard::lang_opencl10) {
Opts.OpenCL = 1;
Opts.AltiVec = 1;
Opts.CXXOperatorNames = 1;
Opts.LaxVectorConversions = 1;
}
// OpenCL and C++ both have bool, true, false keywords.
Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
Opts.setValueVisibilityMode(DefaultVisibility);
// Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs is
// specified, or -std is set to a conforming mode.
Opts.Trigraphs = !Opts.GNUMode;
Opts.CharIsSigned = ArchSpec(triple).CharIsSignedByDefault();
Opts.OptimizeSize = 0;
// FIXME: Eliminate this dependency.
// unsigned Opt =
// Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags);
// Opts.Optimize = Opt != 0;
unsigned Opt = 0;
// This is the __NO_INLINE__ define, which just depends on things like the
// optimization level and -fno-inline, not actually whether the backend has
// inlining enabled.
//
// FIXME: This is affected by other options (-fno-inline).
Opts.NoInlineDefine = !Opt;
}
ClangASTContext::ClangASTContext(const char *target_triple)
: TypeSystem(TypeSystem::eKindClang), m_target_triple(), m_ast_up(),
m_language_options_up(), m_source_manager_up(), m_diagnostics_engine_up(),
m_target_options_rp(), m_target_info_up(), m_identifier_table_up(),
m_selector_table_up(), m_builtins_up(), m_callback_tag_decl(nullptr),
m_callback_objc_decl(nullptr), m_callback_baton(nullptr),
m_pointer_byte_size(0), m_ast_owned(false) {
if (target_triple && target_triple[0])
SetTargetTriple(target_triple);
}
// Destructor
ClangASTContext::~ClangASTContext() { Finalize(); }
ConstString ClangASTContext::GetPluginNameStatic() {
return ConstString("clang");
}
ConstString ClangASTContext::GetPluginName() {
return ClangASTContext::GetPluginNameStatic();
}
uint32_t ClangASTContext::GetPluginVersion() { return 1; }
lldb::TypeSystemSP ClangASTContext::CreateInstance(lldb::LanguageType language,
lldb_private::Module *module,
Target *target) {
if (ClangASTContextSupportsLanguage(language)) {
ArchSpec arch;
if (module)
arch = module->GetArchitecture();
else if (target)
arch = target->GetArchitecture();
if (arch.IsValid()) {
ArchSpec fixed_arch = arch;
// LLVM wants this to be set to iOS or MacOSX; if we're working on
// a bare-boards type image, change the triple for llvm's benefit.
if (fixed_arch.GetTriple().getVendor() == llvm::Triple::Apple &&
fixed_arch.GetTriple().getOS() == llvm::Triple::UnknownOS) {
if (fixed_arch.GetTriple().getArch() == llvm::Triple::arm ||
fixed_arch.GetTriple().getArch() == llvm::Triple::aarch64 ||
fixed_arch.GetTriple().getArch() == llvm::Triple::thumb) {
fixed_arch.GetTriple().setOS(llvm::Triple::IOS);
} else {
fixed_arch.GetTriple().setOS(llvm::Triple::MacOSX);
}
}
if (module) {
std::shared_ptr<ClangASTContext> ast_sp(new ClangASTContext);
if (ast_sp) {
ast_sp->SetArchitecture(fixed_arch);
}
return ast_sp;
} else if (target && target->IsValid()) {
std::shared_ptr<ClangASTContextForExpressions> ast_sp(
new ClangASTContextForExpressions(*target));
if (ast_sp) {
ast_sp->SetArchitecture(fixed_arch);
ast_sp->m_scratch_ast_source_up.reset(
new ClangASTSource(target->shared_from_this()));
lldbassert(ast_sp->getFileManager());
ast_sp->m_scratch_ast_source_up->InstallASTContext(
*ast_sp->getASTContext(), *ast_sp->getFileManager(), true);
llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> proxy_ast_source(
ast_sp->m_scratch_ast_source_up->CreateProxy());
ast_sp->SetExternalSource(proxy_ast_source);
return ast_sp;
}
}
}
}
return lldb::TypeSystemSP();
}
void ClangASTContext::EnumerateSupportedLanguages(
std::set<lldb::LanguageType> &languages_for_types,
std::set<lldb::LanguageType> &languages_for_expressions) {
static std::vector<lldb::LanguageType> s_supported_languages_for_types(
{lldb::eLanguageTypeC89, lldb::eLanguageTypeC, lldb::eLanguageTypeC11,
lldb::eLanguageTypeC_plus_plus, lldb::eLanguageTypeC99,
lldb::eLanguageTypeObjC, lldb::eLanguageTypeObjC_plus_plus,
lldb::eLanguageTypeC_plus_plus_03, lldb::eLanguageTypeC_plus_plus_11,
lldb::eLanguageTypeC11, lldb::eLanguageTypeC_plus_plus_14});
static std::vector<lldb::LanguageType> s_supported_languages_for_expressions(
{lldb::eLanguageTypeC_plus_plus, lldb::eLanguageTypeObjC_plus_plus,
lldb::eLanguageTypeC_plus_plus_03, lldb::eLanguageTypeC_plus_plus_11,
lldb::eLanguageTypeC_plus_plus_14});
languages_for_types.insert(s_supported_languages_for_types.begin(),
s_supported_languages_for_types.end());
languages_for_expressions.insert(
s_supported_languages_for_expressions.begin(),
s_supported_languages_for_expressions.end());
}
void ClangASTContext::Initialize() {
PluginManager::RegisterPlugin(GetPluginNameStatic(),
"clang base AST context plug-in",
CreateInstance, EnumerateSupportedLanguages);
}
void ClangASTContext::Terminate() {
PluginManager::UnregisterPlugin(CreateInstance);
}
void ClangASTContext::Finalize() {
if (m_ast_up) {
GetASTMap().Erase(m_ast_up.get());
if (!m_ast_owned)
m_ast_up.release();
}
m_builtins_up.reset();
m_selector_table_up.reset();
m_identifier_table_up.reset();
m_target_info_up.reset();
m_target_options_rp.reset();
m_diagnostics_engine_up.reset();
m_source_manager_up.reset();
m_language_options_up.reset();
m_ast_up.reset();
m_scratch_ast_source_up.reset();
}
void ClangASTContext::Clear() {
m_ast_up.reset();
m_language_options_up.reset();
m_source_manager_up.reset();
m_diagnostics_engine_up.reset();
m_target_options_rp.reset();
m_target_info_up.reset();
m_identifier_table_up.reset();
m_selector_table_up.reset();
m_builtins_up.reset();
m_pointer_byte_size = 0;
}
void ClangASTContext::setSema(Sema *s) {
// Ensure that the new sema actually belongs to our ASTContext.
assert(s == nullptr || &s->getASTContext() == m_ast_up.get());
m_sema = s;
}
const char *ClangASTContext::GetTargetTriple() {
return m_target_triple.c_str();
}
void ClangASTContext::SetTargetTriple(const char *target_triple) {
Clear();
m_target_triple.assign(target_triple);
}
void ClangASTContext::SetArchitecture(const ArchSpec &arch) {
SetTargetTriple(arch.GetTriple().str().c_str());
}
bool ClangASTContext::HasExternalSource() {
ASTContext *ast = getASTContext();
if (ast)
return ast->getExternalSource() != nullptr;
return false;
}
void ClangASTContext::SetExternalSource(
llvm::IntrusiveRefCntPtr<ExternalASTSource> &ast_source_up) {
ASTContext *ast = getASTContext();
if (ast) {
ast->setExternalSource(ast_source_up);
ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(true);
}
}
void ClangASTContext::RemoveExternalSource() {
ASTContext *ast = getASTContext();
if (ast) {
llvm::IntrusiveRefCntPtr<ExternalASTSource> empty_ast_source_up;
ast->setExternalSource(empty_ast_source_up);
ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(false);
}
}
void ClangASTContext::setASTContext(clang::ASTContext *ast_ctx) {
if (!m_ast_owned) {
m_ast_up.release();
}
m_ast_owned = false;
m_ast_up.reset(ast_ctx);
GetASTMap().Insert(ast_ctx, this);
}
ASTContext *ClangASTContext::getASTContext() {
if (m_ast_up == nullptr) {
m_ast_owned = true;
m_ast_up.reset(new ASTContext(*getLanguageOptions(), *getSourceManager(),
*getIdentifierTable(), *getSelectorTable(),
*getBuiltinContext()));
m_ast_up->getDiagnostics().setClient(getDiagnosticConsumer(), false);
// This can be NULL if we don't know anything about the architecture or if
// the target for an architecture isn't enabled in the llvm/clang that we
// built
TargetInfo *target_info = getTargetInfo();
if (target_info)
m_ast_up->InitBuiltinTypes(*target_info);
if ((m_callback_tag_decl || m_callback_objc_decl) && m_callback_baton) {
m_ast_up->getTranslationUnitDecl()->setHasExternalLexicalStorage();
// m_ast_up->getTranslationUnitDecl()->setHasExternalVisibleStorage();
}
GetASTMap().Insert(m_ast_up.get(), this);
llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source_up(
new ClangExternalASTSourceCallbacks(
ClangASTContext::CompleteTagDecl,
ClangASTContext::CompleteObjCInterfaceDecl, nullptr,
ClangASTContext::LayoutRecordType, this));
SetExternalSource(ast_source_up);
}
return m_ast_up.get();
}
ClangASTContext *ClangASTContext::GetASTContext(clang::ASTContext *ast) {
ClangASTContext *clang_ast = GetASTMap().Lookup(ast);
return clang_ast;
}
Builtin::Context *ClangASTContext::getBuiltinContext() {
if (m_builtins_up == nullptr)
m_builtins_up.reset(new Builtin::Context());
return m_builtins_up.get();
}
IdentifierTable *ClangASTContext::getIdentifierTable() {
if (m_identifier_table_up == nullptr)
m_identifier_table_up.reset(
new IdentifierTable(*ClangASTContext::getLanguageOptions(), nullptr));
return m_identifier_table_up.get();
}
LangOptions *ClangASTContext::getLanguageOptions() {
if (m_language_options_up == nullptr) {
m_language_options_up.reset(new LangOptions());
ParseLangArgs(*m_language_options_up, InputKind::ObjCXX, GetTargetTriple());
// InitializeLangOptions(*m_language_options_up, InputKind::ObjCXX);
}
return m_language_options_up.get();
}
SelectorTable *ClangASTContext::getSelectorTable() {
if (m_selector_table_up == nullptr)
m_selector_table_up.reset(new SelectorTable());
return m_selector_table_up.get();
}
clang::FileManager *ClangASTContext::getFileManager() {
if (m_file_manager_up == nullptr) {
clang::FileSystemOptions file_system_options;
m_file_manager_up.reset(new clang::FileManager(
file_system_options, FileSystem::Instance().GetVirtualFileSystem()));
}
return m_file_manager_up.get();
}
clang::SourceManager *ClangASTContext::getSourceManager() {
if (m_source_manager_up == nullptr)
m_source_manager_up.reset(
new clang::SourceManager(*getDiagnosticsEngine(), *getFileManager()));
return m_source_manager_up.get();
}
clang::DiagnosticsEngine *ClangASTContext::getDiagnosticsEngine() {
if (m_diagnostics_engine_up == nullptr) {
llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_id_sp(new DiagnosticIDs());
m_diagnostics_engine_up.reset(
new DiagnosticsEngine(diag_id_sp, new DiagnosticOptions()));
}
return m_diagnostics_engine_up.get();
}
clang::MangleContext *ClangASTContext::getMangleContext() {
if (m_mangle_ctx_up == nullptr)
m_mangle_ctx_up.reset(getASTContext()->createMangleContext());
return m_mangle_ctx_up.get();
}
class NullDiagnosticConsumer : public DiagnosticConsumer {
public:
NullDiagnosticConsumer() {
m_log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
}
void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
const clang::Diagnostic &info) override {
if (m_log) {
llvm::SmallVector<char, 32> diag_str(10);
info.FormatDiagnostic(diag_str);
diag_str.push_back('\0');
m_log->Printf("Compiler diagnostic: %s\n", diag_str.data());
}
}
DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
return new NullDiagnosticConsumer();
}
private:
Log *m_log;
};
DiagnosticConsumer *ClangASTContext::getDiagnosticConsumer() {
if (m_diagnostic_consumer_up == nullptr)
m_diagnostic_consumer_up.reset(new NullDiagnosticConsumer);
return m_diagnostic_consumer_up.get();
}
std::shared_ptr<clang::TargetOptions> &ClangASTContext::getTargetOptions() {
if (m_target_options_rp == nullptr && !m_target_triple.empty()) {
m_target_options_rp = std::make_shared<clang::TargetOptions>();
if (m_target_options_rp != nullptr)
m_target_options_rp->Triple = m_target_triple;
}
return m_target_options_rp;
}
TargetInfo *ClangASTContext::getTargetInfo() {
// target_triple should be something like "x86_64-apple-macosx"
if (m_target_info_up == nullptr && !m_target_triple.empty())
m_target_info_up.reset(TargetInfo::CreateTargetInfo(*getDiagnosticsEngine(),
getTargetOptions()));
return m_target_info_up.get();
}
#pragma mark Basic Types
static inline bool QualTypeMatchesBitSize(const uint64_t bit_size,
ASTContext *ast, QualType qual_type) {
uint64_t qual_type_bit_size = ast->getTypeSize(qual_type);
return qual_type_bit_size == bit_size;
}
CompilerType
ClangASTContext::GetBuiltinTypeForEncodingAndBitSize(Encoding encoding,
size_t bit_size) {
return ClangASTContext::GetBuiltinTypeForEncodingAndBitSize(
getASTContext(), encoding, bit_size);
}
CompilerType ClangASTContext::GetBuiltinTypeForEncodingAndBitSize(
ASTContext *ast, Encoding encoding, uint32_t bit_size) {
if (!ast)
return CompilerType();
switch (encoding) {
case eEncodingInvalid:
if (QualTypeMatchesBitSize(bit_size, ast, ast->VoidPtrTy))
return CompilerType(ast, ast->VoidPtrTy);
break;
case eEncodingUint:
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedCharTy))
return CompilerType(ast, ast->UnsignedCharTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedShortTy))
return CompilerType(ast, ast->UnsignedShortTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedIntTy))
return CompilerType(ast, ast->UnsignedIntTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongTy))
return CompilerType(ast, ast->UnsignedLongTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongLongTy))
return CompilerType(ast, ast->UnsignedLongLongTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedInt128Ty))
return CompilerType(ast, ast->UnsignedInt128Ty);
break;
case eEncodingSint:
if (QualTypeMatchesBitSize(bit_size, ast, ast->SignedCharTy))
return CompilerType(ast, ast->SignedCharTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->ShortTy))
return CompilerType(ast, ast->ShortTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->IntTy))
return CompilerType(ast, ast->IntTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->LongTy))
return CompilerType(ast, ast->LongTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->LongLongTy))
return CompilerType(ast, ast->LongLongTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->Int128Ty))
return CompilerType(ast, ast->Int128Ty);
break;
case eEncodingIEEE754:
if (QualTypeMatchesBitSize(bit_size, ast, ast->FloatTy))
return CompilerType(ast, ast->FloatTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->DoubleTy))
return CompilerType(ast, ast->DoubleTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->LongDoubleTy))
return CompilerType(ast, ast->LongDoubleTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->HalfTy))
return CompilerType(ast, ast->HalfTy);
break;
case eEncodingVector:
// Sanity check that bit_size is a multiple of 8's.
if (bit_size && !(bit_size & 0x7u))
return CompilerType(
ast, ast->getExtVectorType(ast->UnsignedCharTy, bit_size / 8));
break;
}
return CompilerType();
}
lldb::BasicType
ClangASTContext::GetBasicTypeEnumeration(ConstString name) {
if (name) {
typedef UniqueCStringMap<lldb::BasicType> TypeNameToBasicTypeMap;
static TypeNameToBasicTypeMap g_type_map;
static llvm::once_flag g_once_flag;
llvm::call_once(g_once_flag, []() {
// "void"
g_type_map.Append(ConstString("void"), eBasicTypeVoid);
// "char"
g_type_map.Append(ConstString("char"), eBasicTypeChar);
g_type_map.Append(ConstString("signed char"), eBasicTypeSignedChar);
g_type_map.Append(ConstString("unsigned char"), eBasicTypeUnsignedChar);
g_type_map.Append(ConstString("wchar_t"), eBasicTypeWChar);
g_type_map.Append(ConstString("signed wchar_t"), eBasicTypeSignedWChar);
g_type_map.Append(ConstString("unsigned wchar_t"),
eBasicTypeUnsignedWChar);
// "short"
g_type_map.Append(ConstString("short"), eBasicTypeShort);
g_type_map.Append(ConstString("short int"), eBasicTypeShort);
g_type_map.Append(ConstString("unsigned short"), eBasicTypeUnsignedShort);
g_type_map.Append(ConstString("unsigned short int"),
eBasicTypeUnsignedShort);
// "int"
g_type_map.Append(ConstString("int"), eBasicTypeInt);
g_type_map.Append(ConstString("signed int"), eBasicTypeInt);
g_type_map.Append(ConstString("unsigned int"), eBasicTypeUnsignedInt);
g_type_map.Append(ConstString("unsigned"), eBasicTypeUnsignedInt);
// "long"
g_type_map.Append(ConstString("long"), eBasicTypeLong);
g_type_map.Append(ConstString("long int"), eBasicTypeLong);
g_type_map.Append(ConstString("unsigned long"), eBasicTypeUnsignedLong);
g_type_map.Append(ConstString("unsigned long int"),
eBasicTypeUnsignedLong);
// "long long"
g_type_map.Append(ConstString("long long"), eBasicTypeLongLong);
g_type_map.Append(ConstString("long long int"), eBasicTypeLongLong);
g_type_map.Append(ConstString("unsigned long long"),
eBasicTypeUnsignedLongLong);
g_type_map.Append(ConstString("unsigned long long int"),
eBasicTypeUnsignedLongLong);
// "int128"
g_type_map.Append(ConstString("__int128_t"), eBasicTypeInt128);
g_type_map.Append(ConstString("__uint128_t"), eBasicTypeUnsignedInt128);
// Miscellaneous
g_type_map.Append(ConstString("bool"), eBasicTypeBool);
g_type_map.Append(ConstString("float"), eBasicTypeFloat);
g_type_map.Append(ConstString("double"), eBasicTypeDouble);
g_type_map.Append(ConstString("long double"), eBasicTypeLongDouble);
g_type_map.Append(ConstString("id"), eBasicTypeObjCID);
g_type_map.Append(ConstString("SEL"), eBasicTypeObjCSel);
g_type_map.Append(ConstString("nullptr"), eBasicTypeNullPtr);
g_type_map.Sort();
});
return g_type_map.Find(name, eBasicTypeInvalid);
}
return eBasicTypeInvalid;
}
CompilerType ClangASTContext::GetBasicType(ASTContext *ast,
ConstString name) {
if (ast) {
lldb::BasicType basic_type = ClangASTContext::GetBasicTypeEnumeration(name);
return ClangASTContext::GetBasicType(ast, basic_type);
}
return CompilerType();
}
uint32_t ClangASTContext::GetPointerByteSize() {
if (m_pointer_byte_size == 0)
if (auto size = GetBasicType(lldb::eBasicTypeVoid)
.GetPointerType()
.GetByteSize(nullptr))
m_pointer_byte_size = *size;
return m_pointer_byte_size;
}
CompilerType ClangASTContext::GetBasicType(lldb::BasicType basic_type) {
return GetBasicType(getASTContext(), basic_type);
}
CompilerType ClangASTContext::GetBasicType(ASTContext *ast,
lldb::BasicType basic_type) {
if (!ast)
return CompilerType();
lldb::opaque_compiler_type_t clang_type =
GetOpaqueCompilerType(ast, basic_type);
if (clang_type)
return CompilerType(GetASTContext(ast), clang_type);
return CompilerType();
}
CompilerType ClangASTContext::GetBuiltinTypeForDWARFEncodingAndBitSize(
const char *type_name, uint32_t dw_ate, uint32_t bit_size) {
ASTContext *ast = getASTContext();
#define streq(a, b) strcmp(a, b) == 0
assert(ast != nullptr);
if (ast) {
switch (dw_ate) {
default:
break;
case DW_ATE_address:
if (QualTypeMatchesBitSize(bit_size, ast, ast->VoidPtrTy))
return CompilerType(ast, ast->VoidPtrTy);
break;
case DW_ATE_boolean:
if (QualTypeMatchesBitSize(bit_size, ast, ast->BoolTy))
return CompilerType(ast, ast->BoolTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedCharTy))
return CompilerType(ast, ast->UnsignedCharTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedShortTy))
return CompilerType(ast, ast->UnsignedShortTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedIntTy))
return CompilerType(ast, ast->UnsignedIntTy);
break;
case DW_ATE_lo_user:
// This has been seen to mean DW_AT_complex_integer
if (type_name) {
if (::strstr(type_name, "complex")) {
CompilerType complex_int_clang_type =
GetBuiltinTypeForDWARFEncodingAndBitSize("int", DW_ATE_signed,
bit_size / 2);
return CompilerType(ast, ast->getComplexType(ClangUtil::GetQualType(
complex_int_clang_type)));
}
}
break;
case DW_ATE_complex_float:
if (QualTypeMatchesBitSize(bit_size, ast, ast->FloatComplexTy))
return CompilerType(ast, ast->FloatComplexTy);
else if (QualTypeMatchesBitSize(bit_size, ast, ast->DoubleComplexTy))
return CompilerType(ast, ast->DoubleComplexTy);
else if (QualTypeMatchesBitSize(bit_size, ast, ast->LongDoubleComplexTy))
return CompilerType(ast, ast->LongDoubleComplexTy);
else {
CompilerType complex_float_clang_type =
GetBuiltinTypeForDWARFEncodingAndBitSize("float", DW_ATE_float,
bit_size / 2);
return CompilerType(ast, ast->getComplexType(ClangUtil::GetQualType(
complex_float_clang_type)));
}
break;
case DW_ATE_float:
if (streq(type_name, "float") &&
QualTypeMatchesBitSize(bit_size, ast, ast->FloatTy))
return CompilerType(ast, ast->FloatTy);
if (streq(type_name, "double") &&
QualTypeMatchesBitSize(bit_size, ast, ast->DoubleTy))
return CompilerType(ast, ast->DoubleTy);
if (streq(type_name, "long double") &&
QualTypeMatchesBitSize(bit_size, ast, ast->LongDoubleTy))
return CompilerType(ast, ast->LongDoubleTy);
// Fall back to not requiring a name match
if (QualTypeMatchesBitSize(bit_size, ast, ast->FloatTy))
return CompilerType(ast, ast->FloatTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->DoubleTy))
return CompilerType(ast, ast->DoubleTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->LongDoubleTy))
return CompilerType(ast, ast->LongDoubleTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->HalfTy))
return CompilerType(ast, ast->HalfTy);
break;
case DW_ATE_signed:
if (type_name) {
if (streq(type_name, "wchar_t") &&
QualTypeMatchesBitSize(bit_size, ast, ast->WCharTy) &&
(getTargetInfo() &&
TargetInfo::isTypeSigned(getTargetInfo()->getWCharType())))
return CompilerType(ast, ast->WCharTy);
if (streq(type_name, "void") &&
QualTypeMatchesBitSize(bit_size, ast, ast->VoidTy))
return CompilerType(ast, ast->VoidTy);
if (strstr(type_name, "long long") &&
QualTypeMatchesBitSize(bit_size, ast, ast->LongLongTy))
return CompilerType(ast, ast->LongLongTy);
if (strstr(type_name, "long") &&
QualTypeMatchesBitSize(bit_size, ast, ast->LongTy))
return CompilerType(ast, ast->LongTy);
if (strstr(type_name, "short") &&
QualTypeMatchesBitSize(bit_size, ast, ast->ShortTy))
return CompilerType(ast, ast->ShortTy);
if (strstr(type_name, "char")) {
if (QualTypeMatchesBitSize(bit_size, ast, ast->CharTy))
return CompilerType(ast, ast->CharTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->SignedCharTy))
return CompilerType(ast, ast->SignedCharTy);
}
if (strstr(type_name, "int")) {
if (QualTypeMatchesBitSize(bit_size, ast, ast->IntTy))
return CompilerType(ast, ast->IntTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->Int128Ty))
return CompilerType(ast, ast->Int128Ty);
}
}
// We weren't able to match up a type name, just search by size
if (QualTypeMatchesBitSize(bit_size, ast, ast->CharTy))
return CompilerType(ast, ast->CharTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->ShortTy))
return CompilerType(ast, ast->ShortTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->IntTy))
return CompilerType(ast, ast->IntTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->LongTy))
return CompilerType(ast, ast->LongTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->LongLongTy))
return CompilerType(ast, ast->LongLongTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->Int128Ty))
return CompilerType(ast, ast->Int128Ty);
break;
case DW_ATE_signed_char:
if (ast->getLangOpts().CharIsSigned && type_name &&
streq(type_name, "char")) {
if (QualTypeMatchesBitSize(bit_size, ast, ast->CharTy))
return CompilerType(ast, ast->CharTy);
}
if (QualTypeMatchesBitSize(bit_size, ast, ast->SignedCharTy))
return CompilerType(ast, ast->SignedCharTy);
break;
case DW_ATE_unsigned:
if (type_name) {
if (streq(type_name, "wchar_t")) {
if (QualTypeMatchesBitSize(bit_size, ast, ast->WCharTy)) {
if (!(getTargetInfo() &&
TargetInfo::isTypeSigned(getTargetInfo()->getWCharType())))
return CompilerType(ast, ast->WCharTy);
}
}
if (strstr(type_name, "long long")) {
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongLongTy))
return CompilerType(ast, ast->UnsignedLongLongTy);
} else if (strstr(type_name, "long")) {
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongTy))
return CompilerType(ast, ast->UnsignedLongTy);
} else if (strstr(type_name, "short")) {
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedShortTy))
return CompilerType(ast, ast->UnsignedShortTy);
} else if (strstr(type_name, "char")) {
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedCharTy))
return CompilerType(ast, ast->UnsignedCharTy);
} else if (strstr(type_name, "int")) {
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedIntTy))
return CompilerType(ast, ast->UnsignedIntTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedInt128Ty))
return CompilerType(ast, ast->UnsignedInt128Ty);
}
}
// We weren't able to match up a type name, just search by size
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedCharTy))
return CompilerType(ast, ast->UnsignedCharTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedShortTy))
return CompilerType(ast, ast->UnsignedShortTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedIntTy))
return CompilerType(ast, ast->UnsignedIntTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongTy))
return CompilerType(ast, ast->UnsignedLongTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedLongLongTy))
return CompilerType(ast, ast->UnsignedLongLongTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedInt128Ty))
return CompilerType(ast, ast->UnsignedInt128Ty);
break;
case DW_ATE_unsigned_char:
if (!ast->getLangOpts().CharIsSigned && type_name &&
streq(type_name, "char")) {
if (QualTypeMatchesBitSize(bit_size, ast, ast->CharTy))
return CompilerType(ast, ast->CharTy);
}
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedCharTy))
return CompilerType(ast, ast->UnsignedCharTy);
if (QualTypeMatchesBitSize(bit_size, ast, ast->UnsignedShortTy))
return CompilerType(ast, ast->UnsignedShortTy);
break;
case DW_ATE_imaginary_float:
break;
case DW_ATE_UTF:
if (type_name) {
if (streq(type_name, "char16_t")) {
return CompilerType(ast, ast->Char16Ty);
} else if (streq(type_name, "char32_t")) {
return CompilerType(ast, ast->Char32Ty);
}
}
break;
}
}
// This assert should fire for anything that we don't catch above so we know
// to fix any issues we run into.
if (type_name) {
Host::SystemLog(Host::eSystemLogError, "error: need to add support for "
"DW_TAG_base_type '%s' encoded with "
"DW_ATE = 0x%x, bit_size = %u\n",
type_name, dw_ate, bit_size);
} else {
Host::SystemLog(Host::eSystemLogError, "error: need to add support for "
"DW_TAG_base_type encoded with "
"DW_ATE = 0x%x, bit_size = %u\n",
dw_ate, bit_size);
}
return CompilerType();
}
CompilerType ClangASTContext::GetUnknownAnyType(clang::ASTContext *ast) {
if (ast)
return CompilerType(ast, ast->UnknownAnyTy);
return CompilerType();
}
CompilerType ClangASTContext::GetCStringType(bool is_const) {
ASTContext *ast = getASTContext();
QualType char_type(ast->CharTy);
if (is_const)
char_type.addConst();
return CompilerType(ast, ast->getPointerType(char_type));
}
clang::DeclContext *
ClangASTContext::GetTranslationUnitDecl(clang::ASTContext *ast) {
return ast->getTranslationUnitDecl();
}
clang::Decl *ClangASTContext::CopyDecl(ASTContext *dst_ast, ASTContext *src_ast,
clang::Decl *source_decl) {
FileSystemOptions file_system_options;
FileManager file_manager(file_system_options);
ASTImporter importer(*dst_ast, file_manager, *src_ast, file_manager, false);
return importer.Import(source_decl);
}
bool ClangASTContext::AreTypesSame(CompilerType type1, CompilerType type2,
bool ignore_qualifiers) {
ClangASTContext *ast =
llvm::dyn_cast_or_null<ClangASTContext>(type1.GetTypeSystem());
if (!ast || ast != type2.GetTypeSystem())
return false;
if (type1.GetOpaqueQualType() == type2.GetOpaqueQualType())
return true;
QualType type1_qual = ClangUtil::GetQualType(type1);
QualType type2_qual = ClangUtil::GetQualType(type2);
if (ignore_qualifiers) {
type1_qual = type1_qual.getUnqualifiedType();
type2_qual = type2_qual.getUnqualifiedType();
}
return ast->getASTContext()->hasSameType(type1_qual, type2_qual);
}
CompilerType ClangASTContext::GetTypeForDecl(clang::NamedDecl *decl) {
if (clang::ObjCInterfaceDecl *interface_decl =
llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl))
return GetTypeForDecl(interface_decl);
if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl))
return GetTypeForDecl(tag_decl);
return CompilerType();
}
CompilerType ClangASTContext::GetTypeForDecl(TagDecl *decl) {
// No need to call the getASTContext() accessor (which can create the AST if
// it isn't created yet, because we can't have created a decl in this
// AST if our AST didn't already exist...
ASTContext *ast = &decl->getASTContext();
if (ast)
return CompilerType(ast, ast->getTagDeclType(decl));
return CompilerType();
}
CompilerType ClangASTContext::GetTypeForDecl(ObjCInterfaceDecl *decl) {
// No need to call the getASTContext() accessor (which can create the AST if
// it isn't created yet, because we can't have created a decl in this
// AST if our AST didn't already exist...
ASTContext *ast = &decl->getASTContext();
if (ast)
return CompilerType(ast, ast->getObjCInterfaceType(decl));
return CompilerType();
}
#pragma mark Structure, Unions, Classes
CompilerType ClangASTContext::CreateRecordType(DeclContext *decl_ctx,
AccessType access_type,
const char *name, int kind,
LanguageType language,
ClangASTMetadata *metadata) {
ASTContext *ast = getASTContext();
assert(ast != nullptr);
if (decl_ctx == nullptr)
decl_ctx = ast->getTranslationUnitDecl();
if (language == eLanguageTypeObjC ||
language == eLanguageTypeObjC_plus_plus) {
bool isForwardDecl = true;
bool isInternal = false;
return CreateObjCClass(name, decl_ctx, isForwardDecl, isInternal, metadata);
}
// NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
// we will need to update this code. I was told to currently always use the
// CXXRecordDecl class since we often don't know from debug information if
// something is struct or a class, so we default to always use the more
// complete definition just in case.
bool is_anonymous = (!name) || (!name[0]);
CXXRecordDecl *decl = CXXRecordDecl::Create(
*ast, (TagDecl::TagKind)kind, decl_ctx, SourceLocation(),
SourceLocation(), is_anonymous ? nullptr : &ast->Idents.get(name));
if (is_anonymous)
decl->setAnonymousStructOrUnion(true);
if (decl) {
if (metadata)
SetMetadata(ast, decl, *metadata);
if (access_type != eAccessNone)
decl->setAccess(ConvertAccessTypeToAccessSpecifier(access_type));
if (decl_ctx)
decl_ctx->addDecl(decl);
return CompilerType(ast, ast->getTagDeclType(decl));
}
return CompilerType();
}
namespace {
bool IsValueParam(const clang::TemplateArgument &argument) {
return argument.getKind() == TemplateArgument::Integral;
}
}
static TemplateParameterList *CreateTemplateParameterList(
ASTContext *ast,
const ClangASTContext::TemplateParameterInfos &template_param_infos,
llvm::SmallVector<NamedDecl *, 8> &template_param_decls) {
const bool parameter_pack = false;
const bool is_typename = false;
const unsigned depth = 0;
const size_t num_template_params = template_param_infos.args.size();
DeclContext *const decl_context =
ast->getTranslationUnitDecl(); // Is this the right decl context?,
for (size_t i = 0; i < num_template_params; ++i) {
const char *name = template_param_infos.names[i];
IdentifierInfo *identifier_info = nullptr;
if (name && name[0])
identifier_info = &ast->Idents.get(name);
if (IsValueParam(template_param_infos.args[i])) {
template_param_decls.push_back(NonTypeTemplateParmDecl::Create(
*ast, decl_context,
SourceLocation(), SourceLocation(), depth, i, identifier_info,
template_param_infos.args[i].getIntegralType(), parameter_pack,
nullptr));
} else {
template_param_decls.push_back(TemplateTypeParmDecl::Create(
*ast, decl_context,
SourceLocation(), SourceLocation(), depth, i, identifier_info,
is_typename, parameter_pack));
}
}
if (template_param_infos.packed_args) {
IdentifierInfo *identifier_info = nullptr;
if (template_param_infos.pack_name && template_param_infos.pack_name[0])
identifier_info = &ast->Idents.get(template_param_infos.pack_name);
const bool parameter_pack_true = true;
if (!template_param_infos.packed_args->args.empty() &&
IsValueParam(template_param_infos.packed_args->args[0])) {
template_param_decls.push_back(NonTypeTemplateParmDecl::Create(
*ast, decl_context, SourceLocation(), SourceLocation(), depth,
num_template_params, identifier_info,
template_param_infos.packed_args->args[0].getIntegralType(),
parameter_pack_true, nullptr));
} else {
template_param_decls.push_back(TemplateTypeParmDecl::Create(
*ast, decl_context, SourceLocation(), SourceLocation(), depth,
num_template_params, identifier_info, is_typename,
parameter_pack_true));
}
}
clang::Expr *const requires_clause = nullptr; // TODO: Concepts
TemplateParameterList *template_param_list = TemplateParameterList::Create(
*ast, SourceLocation(), SourceLocation(), template_param_decls,
SourceLocation(), requires_clause);
return template_param_list;
}
clang::FunctionTemplateDecl *ClangASTContext::CreateFunctionTemplateDecl(
clang::DeclContext *decl_ctx, clang::FunctionDecl *func_decl,
const char *name, const TemplateParameterInfos &template_param_infos) {
// /// Create a function template node.
ASTContext *ast = getASTContext();
llvm::SmallVector<NamedDecl *, 8> template_param_decls;
TemplateParameterList *template_param_list = CreateTemplateParameterList(
ast, template_param_infos, template_param_decls);
FunctionTemplateDecl *func_tmpl_decl = FunctionTemplateDecl::Create(
*ast, decl_ctx, func_decl->getLocation(), func_decl->getDeclName(),
template_param_list, func_decl);
for (size_t i = 0, template_param_decl_count = template_param_decls.size();
i < template_param_decl_count; ++i) {
// TODO: verify which decl context we should put template_param_decls into..
template_param_decls[i]->setDeclContext(func_decl);
}
return func_tmpl_decl;
}
void ClangASTContext::CreateFunctionTemplateSpecializationInfo(
FunctionDecl *func_decl, clang::FunctionTemplateDecl *func_tmpl_decl,
const TemplateParameterInfos &infos) {
TemplateArgumentList template_args(TemplateArgumentList::OnStack, infos.args);
func_decl->setFunctionTemplateSpecialization(func_tmpl_decl, &template_args,
nullptr);
}
ClassTemplateDecl *ClangASTContext::CreateClassTemplateDecl(
DeclContext *decl_ctx, lldb::AccessType access_type, const char *class_name,
int kind, const TemplateParameterInfos &template_param_infos) {
ASTContext *ast = getASTContext();
ClassTemplateDecl *class_template_decl = nullptr;
if (decl_ctx == nullptr)
decl_ctx = ast->getTranslationUnitDecl();
IdentifierInfo &identifier_info = ast->Idents.get(class_name);
DeclarationName decl_name(&identifier_info);
clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
for (NamedDecl *decl : result) {
class_template_decl = dyn_cast<clang::ClassTemplateDecl>(decl);
if (class_template_decl)
return class_template_decl;
}
llvm::SmallVector<NamedDecl *, 8> template_param_decls;
TemplateParameterList *template_param_list = CreateTemplateParameterList(
ast, template_param_infos, template_param_decls);
CXXRecordDecl *template_cxx_decl = CXXRecordDecl::Create(
*ast, (TagDecl::TagKind)kind,
decl_ctx, // What decl context do we use here? TU? The actual decl
// context?
SourceLocation(), SourceLocation(), &identifier_info);
for (size_t i = 0, template_param_decl_count = template_param_decls.size();
i < template_param_decl_count; ++i) {
template_param_decls[i]->setDeclContext(template_cxx_decl);
}
// With templated classes, we say that a class is templated with
// specializations, but that the bare class has no functions.
// template_cxx_decl->startDefinition();
// template_cxx_decl->completeDefinition();
class_template_decl = ClassTemplateDecl::Create(
*ast,
decl_ctx, // What decl context do we use here? TU? The actual decl
// context?
SourceLocation(), decl_name, template_param_list, template_cxx_decl);
template_cxx_decl->setDescribedClassTemplate(class_template_decl);
if (class_template_decl) {
if (access_type != eAccessNone)
class_template_decl->setAccess(
ConvertAccessTypeToAccessSpecifier(access_type));
// if (TagDecl *ctx_tag_decl = dyn_cast<TagDecl>(decl_ctx))
// CompleteTagDeclarationDefinition(GetTypeForDecl(ctx_tag_decl));
decl_ctx->addDecl(class_template_decl);
#ifdef LLDB_CONFIGURATION_DEBUG
VerifyDecl(class_template_decl);
#endif
}
return class_template_decl;
}
TemplateTemplateParmDecl *
ClangASTContext::CreateTemplateTemplateParmDecl(const char *template_name) {
ASTContext *ast = getASTContext();
auto *decl_ctx = ast->getTranslationUnitDecl();
IdentifierInfo &identifier_info = ast->Idents.get(template_name);
llvm::SmallVector<NamedDecl *, 8> template_param_decls;
ClangASTContext::TemplateParameterInfos template_param_infos;
TemplateParameterList *template_param_list = CreateTemplateParameterList(
ast, template_param_infos, template_param_decls);
// LLDB needs to create those decls only to be able to display a
// type that includes a template template argument. Only the name matters for
// this purpose, so we use dummy values for the other characterisitcs of the
// type.
return TemplateTemplateParmDecl::Create(
*ast, decl_ctx, SourceLocation(),
/*Depth*/ 0, /*Position*/ 0,
/*IsParameterPack*/ false, &identifier_info, template_param_list);
}
ClassTemplateSpecializationDecl *
ClangASTContext::CreateClassTemplateSpecializationDecl(
DeclContext *decl_ctx, ClassTemplateDecl *class_template_decl, int kind,
const TemplateParameterInfos &template_param_infos) {
ASTContext *ast = getASTContext();
llvm::SmallVector<clang::TemplateArgument, 2> args(
template_param_infos.args.size() +
(template_param_infos.packed_args ? 1 : 0));
std::copy(template_param_infos.args.begin(), template_param_infos.args.end(),
args.begin());
if (template_param_infos.packed_args) {
args[args.size() - 1] = TemplateArgument::CreatePackCopy(
*ast, template_param_infos.packed_args->args);
}
ClassTemplateSpecializationDecl *class_template_specialization_decl =
ClassTemplateSpecializationDecl::Create(
*ast, (TagDecl::TagKind)kind, decl_ctx, SourceLocation(),
SourceLocation(), class_template_decl, args,
nullptr);
class_template_specialization_decl->setSpecializationKind(
TSK_ExplicitSpecialization);
return class_template_specialization_decl;
}
CompilerType ClangASTContext::CreateClassTemplateSpecializationType(
ClassTemplateSpecializationDecl *class_template_specialization_decl) {
if (class_template_specialization_decl) {
ASTContext *ast = getASTContext();
if (ast)
return CompilerType(
ast, ast->getTagDeclType(class_template_specialization_decl));
}
return CompilerType();
}
static inline bool check_op_param(bool is_method,
clang::OverloadedOperatorKind op_kind,
bool unary, bool binary,
uint32_t num_params) {
// Special-case call since it can take any number of operands
if (op_kind == OO_Call)
return true;
// The parameter count doesn't include "this"
if (is_method)
++num_params;
if (num_params == 1)
return unary;
if (num_params == 2)
return binary;
else
return false;
}
bool ClangASTContext::CheckOverloadedOperatorKindParameterCount(
bool is_method, clang::OverloadedOperatorKind op_kind,
uint32_t num_params) {
switch (op_kind) {
default:
break;
// C++ standard allows any number of arguments to new/delete
case OO_New:
case OO_Array_New:
case OO_Delete:
case OO_Array_Delete:
return true;
}
#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
case OO_##Name: \
return check_op_param(is_method, op_kind, Unary, Binary, num_params);
switch (op_kind) {
#include "clang/Basic/OperatorKinds.def"
default:
break;
}
return false;
}
clang::AccessSpecifier
ClangASTContext::UnifyAccessSpecifiers(clang::AccessSpecifier lhs,
clang::AccessSpecifier rhs) {
// Make the access equal to the stricter of the field and the nested field's
// access
if (lhs == AS_none || rhs == AS_none)
return AS_none;
if (lhs == AS_private || rhs == AS_private)
return AS_private;
if (lhs == AS_protected || rhs == AS_protected)
return AS_protected;
return AS_public;
}
bool ClangASTContext::FieldIsBitfield(FieldDecl *field,
uint32_t &bitfield_bit_size) {
return FieldIsBitfield(getASTContext(), field, bitfield_bit_size);
}
bool ClangASTContext::FieldIsBitfield(ASTContext *ast, FieldDecl *field,
uint32_t &bitfield_bit_size) {
if (ast == nullptr || field == nullptr)
return false;
if (field->isBitField()) {
Expr *bit_width_expr = field->getBitWidth();
if (bit_width_expr) {
llvm::APSInt bit_width_apsint;
if (bit_width_expr->isIntegerConstantExpr(bit_width_apsint, *ast)) {
bitfield_bit_size = bit_width_apsint.getLimitedValue(UINT32_MAX);
return true;
}
}
}
return false;
}
bool ClangASTContext::RecordHasFields(const RecordDecl *record_decl) {
if (record_decl == nullptr)
return false;
if (!record_decl->field_empty())
return true;
// No fields, lets check this is a CXX record and check the base classes
const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
if (cxx_record_decl) {
CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
for (base_class = cxx_record_decl->bases_begin(),
base_class_end = cxx_record_decl->bases_end();
base_class != base_class_end; ++base_class) {
const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(
base_class->getType()->getAs<RecordType>()->getDecl());
if (RecordHasFields(base_class_decl))
return true;
}
}
return false;
}
#pragma mark Objective-C Classes
CompilerType ClangASTContext::CreateObjCClass(const char *name,
DeclContext *decl_ctx,
bool isForwardDecl,
bool isInternal,
ClangASTMetadata *metadata) {
ASTContext *ast = getASTContext();
assert(ast != nullptr);
assert(name && name[0]);
if (decl_ctx == nullptr)
decl_ctx = ast->getTranslationUnitDecl();
ObjCInterfaceDecl *decl = ObjCInterfaceDecl::Create(
*ast, decl_ctx, SourceLocation(), &ast->Idents.get(name), nullptr,
nullptr, SourceLocation(),
/*isForwardDecl,*/
isInternal);
if (decl && metadata)
SetMetadata(ast, decl, *metadata);
return CompilerType(ast, ast->getObjCInterfaceType(decl));
}
static inline bool BaseSpecifierIsEmpty(const CXXBaseSpecifier *b) {
return !ClangASTContext::RecordHasFields(b->getType()->getAsCXXRecordDecl());
}
uint32_t
ClangASTContext::GetNumBaseClasses(const CXXRecordDecl *cxx_record_decl,
bool omit_empty_base_classes) {
uint32_t num_bases = 0;
if (cxx_record_decl) {
if (omit_empty_base_classes) {
CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
for (base_class = cxx_record_decl->bases_begin(),
base_class_end = cxx_record_decl->bases_end();
base_class != base_class_end; ++base_class) {
// Skip empty base classes
if (omit_empty_base_classes) {
if (BaseSpecifierIsEmpty(base_class))
continue;
}
++num_bases;
}
} else
num_bases = cxx_record_decl->getNumBases();
}
return num_bases;
}
#pragma mark Namespace Declarations
NamespaceDecl *ClangASTContext::GetUniqueNamespaceDeclaration(
const char *name, DeclContext *decl_ctx, bool is_inline) {
NamespaceDecl *namespace_decl = nullptr;
ASTContext *ast = getASTContext();
TranslationUnitDecl *translation_unit_decl = ast->getTranslationUnitDecl();
if (decl_ctx == nullptr)
decl_ctx = translation_unit_decl;
if (name) {
IdentifierInfo &identifier_info = ast->Idents.get(name);
DeclarationName decl_name(&identifier_info);
clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
for (NamedDecl *decl : result) {
namespace_decl = dyn_cast<clang::NamespaceDecl>(decl);
if (namespace_decl)
return namespace_decl;
}
namespace_decl =
NamespaceDecl::Create(*ast, decl_ctx, is_inline, SourceLocation(),
SourceLocation(), &identifier_info, nullptr);
decl_ctx->addDecl(namespace_decl);
} else {
if (decl_ctx == translation_unit_decl) {
namespace_decl = translation_unit_decl->getAnonymousNamespace();
if (namespace_decl)
return namespace_decl;
namespace_decl =
NamespaceDecl::Create(*ast, decl_ctx, false, SourceLocation(),
SourceLocation(), nullptr, nullptr);
translation_unit_decl->setAnonymousNamespace(namespace_decl);
translation_unit_decl->addDecl(namespace_decl);
assert(namespace_decl == translation_unit_decl->getAnonymousNamespace());
} else {
NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx);
if (parent_namespace_decl) {
namespace_decl = parent_namespace_decl->getAnonymousNamespace();
if (namespace_decl)
return namespace_decl;
namespace_decl =
NamespaceDecl::Create(*ast, decl_ctx, false, SourceLocation(),
SourceLocation(), nullptr, nullptr);
parent_namespace_decl->setAnonymousNamespace(namespace_decl);
parent_namespace_decl->addDecl(namespace_decl);
assert(namespace_decl ==
parent_namespace_decl->getAnonymousNamespace());
} else {
// BAD!!!
}
}
}
#ifdef LLDB_CONFIGURATION_DEBUG
VerifyDecl(namespace_decl);
#endif
return namespace_decl;
}
NamespaceDecl *ClangASTContext::GetUniqueNamespaceDeclaration(
clang::ASTContext *ast, const char *name, clang::DeclContext *decl_ctx,
bool is_inline) {
ClangASTContext *ast_ctx = ClangASTContext::GetASTContext(ast);
if (ast_ctx == nullptr)
return nullptr;
return ast_ctx->GetUniqueNamespaceDeclaration(name, decl_ctx, is_inline);
}
clang::BlockDecl *
ClangASTContext::CreateBlockDeclaration(clang::DeclContext *ctx) {
if (ctx != nullptr) {
clang::BlockDecl *decl = clang::BlockDecl::Create(*getASTContext(), ctx,
clang::SourceLocation());
ctx->addDecl(decl);
return decl;
}
return nullptr;
}
clang::DeclContext *FindLCABetweenDecls(clang::DeclContext *left,
clang::DeclContext *right,
clang::DeclContext *root) {
if (root == nullptr)
return nullptr;
std::set<clang::DeclContext *> path_left;
for (clang::DeclContext *d = left; d != nullptr; d = d->getParent())
path_left.insert(d);
for (clang::DeclContext *d = right; d != nullptr; d = d->getParent())
if (path_left.find(d) != path_left.end())
return d;
return nullptr;
}
clang::UsingDirectiveDecl *ClangASTContext::CreateUsingDirectiveDeclaration(
clang::DeclContext *decl_ctx, clang::NamespaceDecl *ns_decl) {
if (decl_ctx != nullptr && ns_decl != nullptr) {
clang::TranslationUnitDecl *translation_unit =
(clang::TranslationUnitDecl *)GetTranslationUnitDecl(getASTContext());
clang::UsingDirectiveDecl *using_decl = clang::UsingDirectiveDecl::Create(
*getASTContext(), decl_ctx, clang::SourceLocation(),
clang::SourceLocation(), clang::NestedNameSpecifierLoc(),
clang::SourceLocation(), ns_decl,
FindLCABetweenDecls(decl_ctx, ns_decl, translation_unit));
decl_ctx->addDecl(using_decl);
return using_decl;
}
return nullptr;
}
clang::UsingDecl *
ClangASTContext::CreateUsingDeclaration(clang::DeclContext *current_decl_ctx,
clang::NamedDecl *target) {
if (current_decl_ctx != nullptr && target != nullptr) {
clang::UsingDecl *using_decl = clang::UsingDecl::Create(
*getASTContext(), current_decl_ctx, clang::SourceLocation(),
clang::NestedNameSpecifierLoc(), clang::DeclarationNameInfo(), false);
clang::UsingShadowDecl *shadow_decl = clang::UsingShadowDecl::Create(
*getASTContext(), current_decl_ctx, clang::SourceLocation(), using_decl,
target);
using_decl->addShadowDecl(shadow_decl);
current_decl_ctx->addDecl(using_decl);
return using_decl;
}
return nullptr;
}
clang::VarDecl *ClangASTContext::CreateVariableDeclaration(
clang::DeclContext *decl_context, const char *name, clang::QualType type) {
if (decl_context != nullptr) {
clang::VarDecl *var_decl = clang::VarDecl::Create(
*getASTContext(), decl_context, clang::SourceLocation(),
clang::SourceLocation(),
name && name[0] ? &getASTContext()->Idents.getOwn(name) : nullptr, type,
nullptr, clang::SC_None);
var_decl->setAccess(clang::AS_public);
decl_context->addDecl(var_decl);
return var_decl;
}
return nullptr;
}
lldb::opaque_compiler_type_t
ClangASTContext::GetOpaqueCompilerType(clang::ASTContext *ast,
lldb::BasicType basic_type) {
switch (basic_type) {
case eBasicTypeVoid:
return ast->VoidTy.getAsOpaquePtr();
case eBasicTypeChar:
return ast->CharTy.getAsOpaquePtr();
case eBasicTypeSignedChar:
return ast->SignedCharTy.getAsOpaquePtr();
case eBasicTypeUnsignedChar:
return ast->UnsignedCharTy.getAsOpaquePtr();
case eBasicTypeWChar:
return ast->getWCharType().getAsOpaquePtr();
case eBasicTypeSignedWChar:
return ast->getSignedWCharType().getAsOpaquePtr();
case eBasicTypeUnsignedWChar:
return ast->getUnsignedWCharType().getAsOpaquePtr();
case eBasicTypeChar16:
return ast->Char16Ty.getAsOpaquePtr();
case eBasicTypeChar32:
return ast->Char32Ty.getAsOpaquePtr();
case eBasicTypeShort:
return ast->ShortTy.getAsOpaquePtr();
case eBasicTypeUnsignedShort:
return ast->UnsignedShortTy.getAsOpaquePtr();
case eBasicTypeInt:
return ast->IntTy.getAsOpaquePtr();
case eBasicTypeUnsignedInt:
return ast->UnsignedIntTy.getAsOpaquePtr();
case eBasicTypeLong:
return ast->LongTy.getAsOpaquePtr();
case eBasicTypeUnsignedLong:
return ast->UnsignedLongTy.getAsOpaquePtr();
case eBasicTypeLongLong:
return ast->LongLongTy.getAsOpaquePtr();
case eBasicTypeUnsignedLongLong:
return ast->UnsignedLongLongTy.getAsOpaquePtr();
case eBasicTypeInt128:
return ast->Int128Ty.getAsOpaquePtr();
case eBasicTypeUnsignedInt128:
return ast->UnsignedInt128Ty.getAsOpaquePtr();
case eBasicTypeBool:
return ast->BoolTy.getAsOpaquePtr();
case eBasicTypeHalf:
return ast->HalfTy.getAsOpaquePtr();
case eBasicTypeFloat:
return ast->FloatTy.getAsOpaquePtr();
case eBasicTypeDouble:
return ast->DoubleTy.getAsOpaquePtr();
case eBasicTypeLongDouble:
return ast->LongDoubleTy.getAsOpaquePtr();
case eBasicTypeFloatComplex:
return ast->FloatComplexTy.getAsOpaquePtr();
case eBasicTypeDoubleComplex:
return ast->DoubleComplexTy.getAsOpaquePtr();
case eBasicTypeLongDoubleComplex:
return ast->LongDoubleComplexTy.getAsOpaquePtr();
case eBasicTypeObjCID:
return ast->getObjCIdType().getAsOpaquePtr();
case eBasicTypeObjCClass:
return ast->getObjCClassType().getAsOpaquePtr();
case eBasicTypeObjCSel:
return ast->getObjCSelType().getAsOpaquePtr();
case eBasicTypeNullPtr:
return ast->NullPtrTy.getAsOpaquePtr();
default:
return nullptr;
}
}
#pragma mark Function Types
clang::DeclarationName
ClangASTContext::GetDeclarationName(const char *name,
const CompilerType &function_clang_type) {
if (!name || !name[0])
return clang::DeclarationName();
clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS;
if (!IsOperator(name, op_kind) || op_kind == clang::NUM_OVERLOADED_OPERATORS)
return DeclarationName(&getASTContext()->Idents.get(
name)); // Not operator, but a regular function.
// Check the number of operator parameters. Sometimes we have seen bad DWARF
// that doesn't correctly describe operators and if we try to create a method
// and add it to the class, clang will assert and crash, so we need to make
// sure things are acceptable.
clang::QualType method_qual_type(ClangUtil::GetQualType(function_clang_type));
const clang::FunctionProtoType *function_type =
llvm::dyn_cast<clang::FunctionProtoType>(method_qual_type.getTypePtr());
if (function_type == nullptr)
return clang::DeclarationName();
const bool is_method = false;
const unsigned int num_params = function_type->getNumParams();
if (!ClangASTContext::CheckOverloadedOperatorKindParameterCount(
is_method, op_kind, num_params))
return clang::DeclarationName();
return getASTContext()->DeclarationNames.getCXXOperatorName(op_kind);
}
FunctionDecl *ClangASTContext::CreateFunctionDeclaration(
DeclContext *decl_ctx, const char *name,
const CompilerType &function_clang_type, int storage, bool is_inline) {
FunctionDecl *func_decl = nullptr;
ASTContext *ast = getASTContext();
if (decl_ctx == nullptr)
decl_ctx = ast->getTranslationUnitDecl();
const bool hasWrittenPrototype = true;
const bool isConstexprSpecified = false;
clang::DeclarationName declarationName =
GetDeclarationName(name, function_clang_type);
func_decl = FunctionDecl::Create(
*ast, decl_ctx, SourceLocation(), SourceLocation(), declarationName,
ClangUtil::GetQualType(function_clang_type), nullptr,
(clang::StorageClass)storage, is_inline, hasWrittenPrototype,
isConstexprSpecified);
if (func_decl)
decl_ctx->addDecl(func_decl);
#ifdef LLDB_CONFIGURATION_DEBUG
VerifyDecl(func_decl);
#endif
return func_decl;
}
CompilerType ClangASTContext::CreateFunctionType(
ASTContext *ast, const CompilerType &result_type, const CompilerType *args,
unsigned num_args, bool is_variadic, unsigned type_quals,
clang::CallingConv cc) {
if (ast == nullptr)
return CompilerType(); // invalid AST
if (!result_type || !ClangUtil::IsClangType(result_type))
return CompilerType(); // invalid return type
std::vector<QualType> qual_type_args;
if (num_args > 0 && args == nullptr)
return CompilerType(); // invalid argument array passed in
// Verify that all arguments are valid and the right type
for (unsigned i = 0; i < num_args; ++i) {
if (args[i]) {
// Make sure we have a clang type in args[i] and not a type from another
// language whose name might match
const bool is_clang_type = ClangUtil::IsClangType(args[i]);
lldbassert(is_clang_type);
if (is_clang_type)
qual_type_args.push_back(ClangUtil::GetQualType(args[i]));
else
return CompilerType(); // invalid argument type (must be a clang type)
} else
return CompilerType(); // invalid argument type (empty)
}
// TODO: Detect calling convention in DWARF?
FunctionProtoType::ExtProtoInfo proto_info;
proto_info.ExtInfo = cc;
proto_info.Variadic = is_variadic;
proto_info.ExceptionSpec = EST_None;
proto_info.TypeQuals = clang::Qualifiers::fromFastMask(type_quals);
proto_info.RefQualifier = RQ_None;
return CompilerType(ast,
ast->getFunctionType(ClangUtil::GetQualType(result_type),
qual_type_args, proto_info));
}
ParmVarDecl *ClangASTContext::CreateParameterDeclaration(
clang::DeclContext *decl_ctx, const char *name,
const CompilerType &param_type, int storage) {
ASTContext *ast = getASTContext();
assert(ast != nullptr);
auto *decl =
ParmVarDecl::Create(*ast, decl_ctx, SourceLocation(), SourceLocation(),
name && name[0] ? &ast->Idents.get(name) : nullptr,
ClangUtil::GetQualType(param_type), nullptr,
(clang::StorageClass)storage, nullptr);
decl_ctx->addDecl(decl);
return decl;
}
void ClangASTContext::SetFunctionParameters(FunctionDecl *function_decl,
ParmVarDecl **params,
unsigned num_params) {
if (function_decl)
function_decl->setParams(ArrayRef<ParmVarDecl *>(params, num_params));
}
CompilerType
ClangASTContext::CreateBlockPointerType(const CompilerType &function_type) {
QualType block_type = m_ast_up->getBlockPointerType(
clang::QualType::getFromOpaquePtr(function_type.GetOpaqueQualType()));
return CompilerType(this, block_type.getAsOpaquePtr());
}
#pragma mark Array Types
CompilerType ClangASTContext::CreateArrayType(const CompilerType &element_type,
size_t element_count,
bool is_vector) {
if (element_type.IsValid()) {
ASTContext *ast = getASTContext();
assert(ast != nullptr);
if (is_vector) {
return CompilerType(
ast, ast->getExtVectorType(ClangUtil::GetQualType(element_type),
element_count));
} else {
llvm::APInt ap_element_count(64, element_count);
if (element_count == 0) {
return CompilerType(ast, ast->getIncompleteArrayType(
ClangUtil::GetQualType(element_type),
clang::ArrayType::Normal, 0));
} else {
return CompilerType(
ast, ast->getConstantArrayType(ClangUtil::GetQualType(element_type),
ap_element_count,
clang::ArrayType::Normal, 0));
}
}
}
return CompilerType();
}
CompilerType ClangASTContext::CreateStructForIdentifier(
ConstString type_name,
const std::initializer_list<std::pair<const char *, CompilerType>>
&type_fields,
bool packed) {
CompilerType type;
if (!type_name.IsEmpty() &&
(type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name))
.IsValid()) {
lldbassert(0 && "Trying to create a type for an existing name");
return type;
}
type = CreateRecordType(nullptr, lldb::eAccessPublic, type_name.GetCString(),
clang::TTK_Struct, lldb::eLanguageTypeC);
StartTagDeclarationDefinition(type);
for (const auto &field : type_fields)
AddFieldToRecordType(type, field.first, field.second, lldb::eAccessPublic,
0);
if (packed)
SetIsPacked(type);
CompleteTagDeclarationDefinition(type);
return type;
}
CompilerType ClangASTContext::GetOrCreateStructForIdentifier(
ConstString type_name,
const std::initializer_list<std::pair<const char *, CompilerType>>
&type_fields,
bool packed) {
CompilerType type;
if ((type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name)).IsValid())
return type;
return CreateStructForIdentifier(type_name, type_fields, packed);
}
#pragma mark Enumeration Types
CompilerType
ClangASTContext::CreateEnumerationType(const char *name, DeclContext *decl_ctx,
const Declaration &decl,
const CompilerType &integer_clang_type,
bool is_scoped) {
// TODO: Do something intelligent with the Declaration object passed in
// like maybe filling in the SourceLocation with it...
ASTContext *ast = getASTContext();
// TODO: ask about these...
// const bool IsFixed = false;
EnumDecl *enum_decl = EnumDecl::Create(
*ast, decl_ctx, SourceLocation(), SourceLocation(),
name && name[0] ? &ast->Idents.get(name) : nullptr, nullptr,
is_scoped, // IsScoped
is_scoped, // IsScopedUsingClassTag
false); // IsFixed
if (enum_decl) {
if (decl_ctx)
decl_ctx->addDecl(enum_decl);
// TODO: check if we should be setting the promotion type too?
enum_decl->setIntegerType(ClangUtil::GetQualType(integer_clang_type));
enum_decl->setAccess(AS_public); // TODO respect what's in the debug info
return CompilerType(ast, ast->getTagDeclType(enum_decl));
}
return CompilerType();
}
CompilerType ClangASTContext::GetIntTypeFromBitSize(clang::ASTContext *ast,
size_t bit_size,
bool is_signed) {
if (ast) {
if (is_signed) {
if (bit_size == ast->getTypeSize(ast->SignedCharTy))
return CompilerType(ast, ast->SignedCharTy);
if (bit_size == ast->getTypeSize(ast->ShortTy))
return CompilerType(ast, ast->ShortTy);
if (bit_size == ast->getTypeSize(ast->IntTy))
return CompilerType(ast, ast->IntTy);
if (bit_size == ast->getTypeSize(ast->LongTy))
return CompilerType(ast, ast->LongTy);
if (bit_size == ast->getTypeSize(ast->LongLongTy))
return CompilerType(ast, ast->LongLongTy);
if (bit_size == ast->getTypeSize(ast->Int128Ty))
return CompilerType(ast, ast->Int128Ty);
} else {
if (bit_size == ast->getTypeSize(ast->UnsignedCharTy))
return CompilerType(ast, ast->UnsignedCharTy);
if (bit_size == ast->getTypeSize(ast->UnsignedShortTy))
return CompilerType(ast, ast->UnsignedShortTy);
if (bit_size == ast->getTypeSize(ast->UnsignedIntTy))
return CompilerType(ast, ast->UnsignedIntTy);
if (bit_size == ast->getTypeSize(ast->UnsignedLongTy))
return CompilerType(ast, ast->UnsignedLongTy);
if (bit_size == ast->getTypeSize(ast->UnsignedLongLongTy))
return CompilerType(ast, ast->UnsignedLongLongTy);
if (bit_size == ast->getTypeSize(ast->UnsignedInt128Ty))
return CompilerType(ast, ast->UnsignedInt128Ty);
}
}
return CompilerType();
}
CompilerType ClangASTContext::GetPointerSizedIntType(clang::ASTContext *ast,
bool is_signed) {
if (ast)
return GetIntTypeFromBitSize(ast, ast->getTypeSize(ast->VoidPtrTy),
is_signed);
return CompilerType();
}
void ClangASTContext::DumpDeclContextHiearchy(clang::DeclContext *decl_ctx) {
if (decl_ctx) {
DumpDeclContextHiearchy(decl_ctx->getParent());
clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl_ctx);
if (named_decl) {
printf("%20s: %s\n", decl_ctx->getDeclKindName(),
named_decl->getDeclName().getAsString().c_str());
} else {
printf("%20s\n", decl_ctx->getDeclKindName());
}
}
}
void ClangASTContext::DumpDeclHiearchy(clang::Decl *decl) {
if (decl == nullptr)
return;
DumpDeclContextHiearchy(decl->getDeclContext());
clang::RecordDecl *record_decl = llvm::dyn_cast<clang::RecordDecl>(decl);
if (record_decl) {
printf("%20s: %s%s\n", decl->getDeclKindName(),
record_decl->getDeclName().getAsString().c_str(),
record_decl->isInjectedClassName() ? " (injected class name)" : "");
} else {
clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl);
if (named_decl) {
printf("%20s: %s\n", decl->getDeclKindName(),
named_decl->getDeclName().getAsString().c_str());
} else {
printf("%20s\n", decl->getDeclKindName());
}
}
}
bool ClangASTContext::DeclsAreEquivalent(clang::Decl *lhs_decl,
clang::Decl *rhs_decl) {
if (lhs_decl && rhs_decl) {
// Make sure the decl kinds match first
const clang::Decl::Kind lhs_decl_kind = lhs_decl->getKind();
const clang::Decl::Kind rhs_decl_kind = rhs_decl->getKind();
if (lhs_decl_kind == rhs_decl_kind) {
// Now check that the decl contexts kinds are all equivalent before we
// have to check any names of the decl contexts...
clang::DeclContext *lhs_decl_ctx = lhs_decl->getDeclContext();
clang::DeclContext *rhs_decl_ctx = rhs_decl->getDeclContext();
if (lhs_decl_ctx && rhs_decl_ctx) {
while (1) {
if (lhs_decl_ctx && rhs_decl_ctx) {
const clang::Decl::Kind lhs_decl_ctx_kind =
lhs_decl_ctx->getDeclKind();
const clang::Decl::Kind rhs_decl_ctx_kind =
rhs_decl_ctx->getDeclKind();
if (lhs_decl_ctx_kind == rhs_decl_ctx_kind) {
lhs_decl_ctx = lhs_decl_ctx->getParent();
rhs_decl_ctx = rhs_decl_ctx->getParent();
if (lhs_decl_ctx == nullptr && rhs_decl_ctx == nullptr)
break;
} else
return false;
} else
return false;
}
// Now make sure the name of the decls match
clang::NamedDecl *lhs_named_decl =
llvm::dyn_cast<clang::NamedDecl>(lhs_decl);
clang::NamedDecl *rhs_named_decl =
llvm::dyn_cast<clang::NamedDecl>(rhs_decl);
if (lhs_named_decl && rhs_named_decl) {
clang::DeclarationName lhs_decl_name = lhs_named_decl->getDeclName();
clang::DeclarationName rhs_decl_name = rhs_named_decl->getDeclName();
if (lhs_decl_name.getNameKind() == rhs_decl_name.getNameKind()) {
if (lhs_decl_name.getAsString() != rhs_decl_name.getAsString())
return false;
} else
return false;
} else