ClangASTContext.cpp revision fe6dc6e241c52822710380cec0931351a1d7b2d3
1//===-- ClangASTContext.cpp -------------------------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Symbol/ClangASTContext.h"
11
12// C Includes
13// C++ Includes
14#include <string>
15
16// Other libraries and framework includes
17
18// Clang headers like to use NDEBUG inside of them to enable/disable debug
19// releated features using "#ifndef NDEBUG" preprocessor blocks to do one thing
20// or another. This is bad because it means that if clang was built in release
21// mode, it assumes that you are building in release mode which is not always
22// the case. You can end up with functions that are defined as empty in header
23// files when NDEBUG is not defined, and this can cause link errors with the
24// clang .a files that you have since you might be missing functions in the .a
25// file. So we have to define NDEBUG when including clang headers to avoid any
26// mismatches. This is covered by rdar://problem/8691220
27
28#if !defined(NDEBUG) && !defined(LLVM_NDEBUG_OFF)
29#define LLDB_DEFINED_NDEBUG_FOR_CLANG
30#define NDEBUG
31// Need to include assert.h so it is as clang would expect it to be (disabled)
32#include <assert.h>
33#endif
34
35#include "clang/AST/ASTContext.h"
36#include "clang/AST/ASTImporter.h"
37#include "clang/AST/Attr.h"
38#include "clang/AST/CXXInheritance.h"
39#include "clang/AST/DeclObjC.h"
40#include "clang/AST/DeclTemplate.h"
41#include "clang/AST/RecordLayout.h"
42#include "clang/AST/Type.h"
43#include "clang/Basic/Builtins.h"
44#include "clang/Basic/Diagnostic.h"
45#include "clang/Basic/FileManager.h"
46#include "clang/Basic/FileSystemOptions.h"
47#include "clang/Basic/SourceManager.h"
48#include "clang/Basic/TargetInfo.h"
49#include "clang/Basic/TargetOptions.h"
50#include "clang/Frontend/FrontendOptions.h"
51#include "clang/Frontend/LangStandard.h"
52
53#ifdef LLDB_DEFINED_NDEBUG_FOR_CLANG
54#undef NDEBUG
55#undef LLDB_DEFINED_NDEBUG_FOR_CLANG
56// Need to re-include assert.h so it is as _we_ would expect it to be (enabled)
57#include <assert.h>
58#endif
59
60#include "lldb/Core/ArchSpec.h"
61#include "lldb/Core/dwarf.h"
62#include "lldb/Core/Flags.h"
63#include "lldb/Core/Log.h"
64#include "lldb/Core/RegularExpression.h"
65#include "lldb/Expression/ASTDumper.h"
66#include "lldb/Symbol/ClangExternalASTSourceCommon.h"
67#include "lldb/Symbol/VerifyDecl.h"
68#include "lldb/Target/ExecutionContext.h"
69#include "lldb/Target/Process.h"
70#include "lldb/Target/ObjCLanguageRuntime.h"
71
72
73#include <stdio.h>
74
75using namespace lldb;
76using namespace lldb_private;
77using namespace llvm;
78using namespace clang;
79
80
81static bool
82GetCompleteQualType (clang::ASTContext *ast, clang::QualType qual_type, bool allow_completion = true)
83{
84    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
85    switch (type_class)
86    {
87    case clang::Type::ConstantArray:
88        {
89            const clang::ArrayType *array_type = dyn_cast<clang::ArrayType>(qual_type.getTypePtr());
90
91            if (array_type)
92                return GetCompleteQualType (ast, array_type->getElementType(), allow_completion);
93        }
94        break;
95
96    case clang::Type::Record:
97    case clang::Type::Enum:
98        {
99            const clang::TagType *tag_type = dyn_cast<clang::TagType>(qual_type.getTypePtr());
100            if (tag_type)
101            {
102                clang::TagDecl *tag_decl = tag_type->getDecl();
103                if (tag_decl)
104                {
105                    if (tag_decl->isCompleteDefinition())
106                        return true;
107
108                    if (!allow_completion)
109                        return false;
110
111                    if (tag_decl->hasExternalLexicalStorage())
112                    {
113                        if (ast)
114                        {
115                            ExternalASTSource *external_ast_source = ast->getExternalSource();
116                            if (external_ast_source)
117                            {
118                                external_ast_source->CompleteType(tag_decl);
119                                return !tag_type->isIncompleteType();
120                            }
121                        }
122                    }
123                    return false;
124                }
125            }
126
127        }
128        break;
129
130    case clang::Type::ObjCObject:
131    case clang::Type::ObjCInterface:
132        {
133            const clang::ObjCObjectType *objc_class_type = dyn_cast<clang::ObjCObjectType>(qual_type);
134            if (objc_class_type)
135            {
136                clang::ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
137                // We currently can't complete objective C types through the newly added ASTContext
138                // because it only supports TagDecl objects right now...
139                if (class_interface_decl)
140                {
141                    if (class_interface_decl->getDefinition())
142                        return true;
143
144                    if (!allow_completion)
145                        return false;
146
147                    if (class_interface_decl->hasExternalLexicalStorage())
148                    {
149                        if (ast)
150                        {
151                            ExternalASTSource *external_ast_source = ast->getExternalSource();
152                            if (external_ast_source)
153                            {
154                                external_ast_source->CompleteType (class_interface_decl);
155                                return !objc_class_type->isIncompleteType();
156                            }
157                        }
158                    }
159                    return false;
160                }
161            }
162        }
163        break;
164
165    case clang::Type::Typedef:
166        return GetCompleteQualType (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType(), allow_completion);
167
168    case clang::Type::Elaborated:
169        return GetCompleteQualType (ast, cast<ElaboratedType>(qual_type)->getNamedType(), allow_completion);
170
171    default:
172        break;
173    }
174
175    return true;
176}
177
178static AccessSpecifier
179ConvertAccessTypeToAccessSpecifier (AccessType access)
180{
181    switch (access)
182    {
183    default:               break;
184    case eAccessNone:      return AS_none;
185    case eAccessPublic:    return AS_public;
186    case eAccessPrivate:   return AS_private;
187    case eAccessProtected: return AS_protected;
188    }
189    return AS_none;
190}
191
192static ObjCIvarDecl::AccessControl
193ConvertAccessTypeToObjCIvarAccessControl (AccessType access)
194{
195    switch (access)
196    {
197    case eAccessNone:      return ObjCIvarDecl::None;
198    case eAccessPublic:    return ObjCIvarDecl::Public;
199    case eAccessPrivate:   return ObjCIvarDecl::Private;
200    case eAccessProtected: return ObjCIvarDecl::Protected;
201    case eAccessPackage:   return ObjCIvarDecl::Package;
202    }
203    return ObjCIvarDecl::None;
204}
205
206
207static void
208ParseLangArgs
209(
210    LangOptions &Opts,
211    InputKind IK
212)
213{
214    // FIXME: Cleanup per-file based stuff.
215
216    // Set some properties which depend soley on the input kind; it would be nice
217    // to move these to the language standard, and have the driver resolve the
218    // input kind + language standard.
219    if (IK == IK_Asm) {
220        Opts.AsmPreprocessor = 1;
221    } else if (IK == IK_ObjC ||
222               IK == IK_ObjCXX ||
223               IK == IK_PreprocessedObjC ||
224               IK == IK_PreprocessedObjCXX) {
225        Opts.ObjC1 = Opts.ObjC2 = 1;
226    }
227
228    LangStandard::Kind LangStd = LangStandard::lang_unspecified;
229
230    if (LangStd == LangStandard::lang_unspecified) {
231        // Based on the base language, pick one.
232        switch (IK) {
233            case IK_None:
234            case IK_AST:
235            case IK_LLVM_IR:
236                assert (!"Invalid input kind!");
237            case IK_OpenCL:
238                LangStd = LangStandard::lang_opencl;
239                break;
240            case IK_CUDA:
241                LangStd = LangStandard::lang_cuda;
242                break;
243            case IK_Asm:
244            case IK_C:
245            case IK_PreprocessedC:
246            case IK_ObjC:
247            case IK_PreprocessedObjC:
248                LangStd = LangStandard::lang_gnu99;
249                break;
250            case IK_CXX:
251            case IK_PreprocessedCXX:
252            case IK_ObjCXX:
253            case IK_PreprocessedObjCXX:
254                LangStd = LangStandard::lang_gnucxx98;
255                break;
256        }
257    }
258
259    const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
260    Opts.LineComment = Std.hasLineComments();
261    Opts.C99 = Std.isC99();
262    Opts.CPlusPlus = Std.isCPlusPlus();
263    Opts.CPlusPlus11 = Std.isCPlusPlus11();
264    Opts.Digraphs = Std.hasDigraphs();
265    Opts.GNUMode = Std.isGNUMode();
266    Opts.GNUInline = !Std.isC99();
267    Opts.HexFloats = Std.hasHexFloats();
268    Opts.ImplicitInt = Std.hasImplicitInt();
269
270    Opts.WChar = true;
271
272    // OpenCL has some additional defaults.
273    if (LangStd == LangStandard::lang_opencl) {
274        Opts.OpenCL = 1;
275        Opts.AltiVec = 1;
276        Opts.CXXOperatorNames = 1;
277        Opts.LaxVectorConversions = 1;
278    }
279
280    // OpenCL and C++ both have bool, true, false keywords.
281    Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
282
283//    if (Opts.CPlusPlus)
284//        Opts.CXXOperatorNames = !Args.hasArg(OPT_fno_operator_names);
285//
286//    if (Args.hasArg(OPT_fobjc_gc_only))
287//        Opts.setGCMode(LangOptions::GCOnly);
288//    else if (Args.hasArg(OPT_fobjc_gc))
289//        Opts.setGCMode(LangOptions::HybridGC);
290//
291//    if (Args.hasArg(OPT_print_ivar_layout))
292//        Opts.ObjCGCBitmapPrint = 1;
293//
294//    if (Args.hasArg(OPT_faltivec))
295//        Opts.AltiVec = 1;
296//
297//    if (Args.hasArg(OPT_pthread))
298//        Opts.POSIXThreads = 1;
299//
300//    llvm::StringRef Vis = getLastArgValue(Args, OPT_fvisibility,
301//                                          "default");
302//    if (Vis == "default")
303        Opts.setValueVisibilityMode(DefaultVisibility);
304//    else if (Vis == "hidden")
305//        Opts.setVisibilityMode(LangOptions::Hidden);
306//    else if (Vis == "protected")
307//        Opts.setVisibilityMode(LangOptions::Protected);
308//    else
309//        Diags.Report(diag::err_drv_invalid_value)
310//        << Args.getLastArg(OPT_fvisibility)->getAsString(Args) << Vis;
311
312//    Opts.OverflowChecking = Args.hasArg(OPT_ftrapv);
313
314    // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
315    // is specified, or -std is set to a conforming mode.
316    Opts.Trigraphs = !Opts.GNUMode;
317//    if (Args.hasArg(OPT_trigraphs))
318//        Opts.Trigraphs = 1;
319//
320//    Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
321//                                     OPT_fno_dollars_in_identifiers,
322//                                     !Opts.AsmPreprocessor);
323//    Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
324//    Opts.Microsoft = Args.hasArg(OPT_fms_extensions);
325//    Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
326//    if (Args.hasArg(OPT_fno_lax_vector_conversions))
327//        Opts.LaxVectorConversions = 0;
328//    Opts.Exceptions = Args.hasArg(OPT_fexceptions);
329//    Opts.RTTI = !Args.hasArg(OPT_fno_rtti);
330//    Opts.Blocks = Args.hasArg(OPT_fblocks);
331//    Opts.CharIsSigned = !Args.hasArg(OPT_fno_signed_char);
332//    Opts.ShortWChar = Args.hasArg(OPT_fshort_wchar);
333//    Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
334//    Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
335//    Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
336//    Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
337//    Opts.AccessControl = Args.hasArg(OPT_faccess_control);
338//    Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
339//    Opts.MathErrno = !Args.hasArg(OPT_fno_math_errno);
340//    Opts.InstantiationDepth = getLastArgIntValue(Args, OPT_ftemplate_depth, 99,
341//                                                 Diags);
342//    Opts.NeXTRuntime = !Args.hasArg(OPT_fgnu_runtime);
343//    Opts.ObjCConstantStringClass = getLastArgValue(Args,
344//                                                   OPT_fconstant_string_class);
345//    Opts.ObjCNonFragileABI = Args.hasArg(OPT_fobjc_nonfragile_abi);
346//    Opts.CatchUndefined = Args.hasArg(OPT_fcatch_undefined_behavior);
347//    Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
348//    Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
349//    Opts.Static = Args.hasArg(OPT_static_define);
350    Opts.OptimizeSize = 0;
351
352    // FIXME: Eliminate this dependency.
353//    unsigned Opt =
354//    Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags);
355//    Opts.Optimize = Opt != 0;
356    unsigned Opt = 0;
357
358    // This is the __NO_INLINE__ define, which just depends on things like the
359    // optimization level and -fno-inline, not actually whether the backend has
360    // inlining enabled.
361    //
362    // FIXME: This is affected by other options (-fno-inline).
363    Opts.NoInlineDefine = !Opt;
364
365//    unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
366//    switch (SSP) {
367//        default:
368//            Diags.Report(diag::err_drv_invalid_value)
369//            << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
370//            break;
371//        case 0: Opts.setStackProtectorMode(LangOptions::SSPOff); break;
372//        case 1: Opts.setStackProtectorMode(LangOptions::SSPOn);  break;
373//        case 2: Opts.setStackProtectorMode(LangOptions::SSPReq); break;
374//    }
375}
376
377
378ClangASTContext::ClangASTContext (const char *target_triple) :
379    m_target_triple(),
380    m_ast_ap(),
381    m_language_options_ap(),
382    m_source_manager_ap(),
383    m_diagnostics_engine_ap(),
384    m_target_options_rp(),
385    m_target_info_ap(),
386    m_identifier_table_ap(),
387    m_selector_table_ap(),
388    m_builtins_ap(),
389    m_callback_tag_decl (NULL),
390    m_callback_objc_decl (NULL),
391    m_callback_baton (NULL)
392
393{
394    if (target_triple && target_triple[0])
395        SetTargetTriple (target_triple);
396}
397
398//----------------------------------------------------------------------
399// Destructor
400//----------------------------------------------------------------------
401ClangASTContext::~ClangASTContext()
402{
403    m_builtins_ap.reset();
404    m_selector_table_ap.reset();
405    m_identifier_table_ap.reset();
406    m_target_info_ap.reset();
407    m_target_options_rp.reset();
408    m_diagnostics_engine_ap.reset();
409    m_source_manager_ap.reset();
410    m_language_options_ap.reset();
411    m_ast_ap.reset();
412}
413
414
415void
416ClangASTContext::Clear()
417{
418    m_ast_ap.reset();
419    m_language_options_ap.reset();
420    m_source_manager_ap.reset();
421    m_diagnostics_engine_ap.reset();
422    m_target_options_rp.reset();
423    m_target_info_ap.reset();
424    m_identifier_table_ap.reset();
425    m_selector_table_ap.reset();
426    m_builtins_ap.reset();
427}
428
429const char *
430ClangASTContext::GetTargetTriple ()
431{
432    return m_target_triple.c_str();
433}
434
435void
436ClangASTContext::SetTargetTriple (const char *target_triple)
437{
438    Clear();
439    m_target_triple.assign(target_triple);
440}
441
442void
443ClangASTContext::SetArchitecture (const ArchSpec &arch)
444{
445    SetTargetTriple(arch.GetTriple().str().c_str());
446}
447
448bool
449ClangASTContext::HasExternalSource ()
450{
451    ASTContext *ast = getASTContext();
452    if (ast)
453        return ast->getExternalSource () != NULL;
454    return false;
455}
456
457void
458ClangASTContext::SetExternalSource (llvm::OwningPtr<ExternalASTSource> &ast_source_ap)
459{
460    ASTContext *ast = getASTContext();
461    if (ast)
462    {
463        ast->setExternalSource (ast_source_ap);
464        ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(true);
465        //ast->getTranslationUnitDecl()->setHasExternalVisibleStorage(true);
466    }
467}
468
469void
470ClangASTContext::RemoveExternalSource ()
471{
472    ASTContext *ast = getASTContext();
473
474    if (ast)
475    {
476        llvm::OwningPtr<ExternalASTSource> empty_ast_source_ap;
477        ast->setExternalSource (empty_ast_source_ap);
478        ast->getTranslationUnitDecl()->setHasExternalLexicalStorage(false);
479        //ast->getTranslationUnitDecl()->setHasExternalVisibleStorage(false);
480    }
481}
482
483
484
485ASTContext *
486ClangASTContext::getASTContext()
487{
488    if (m_ast_ap.get() == NULL)
489    {
490        m_ast_ap.reset(new ASTContext (*getLanguageOptions(),
491                                       *getSourceManager(),
492                                       getTargetInfo(),
493                                       *getIdentifierTable(),
494                                       *getSelectorTable(),
495                                       *getBuiltinContext(),
496                                       0));
497
498        if ((m_callback_tag_decl || m_callback_objc_decl) && m_callback_baton)
499        {
500            m_ast_ap->getTranslationUnitDecl()->setHasExternalLexicalStorage();
501            //m_ast_ap->getTranslationUnitDecl()->setHasExternalVisibleStorage();
502        }
503
504        m_ast_ap->getDiagnostics().setClient(getDiagnosticConsumer(), false);
505    }
506    return m_ast_ap.get();
507}
508
509Builtin::Context *
510ClangASTContext::getBuiltinContext()
511{
512    if (m_builtins_ap.get() == NULL)
513        m_builtins_ap.reset (new Builtin::Context());
514    return m_builtins_ap.get();
515}
516
517IdentifierTable *
518ClangASTContext::getIdentifierTable()
519{
520    if (m_identifier_table_ap.get() == NULL)
521        m_identifier_table_ap.reset(new IdentifierTable (*ClangASTContext::getLanguageOptions(), NULL));
522    return m_identifier_table_ap.get();
523}
524
525LangOptions *
526ClangASTContext::getLanguageOptions()
527{
528    if (m_language_options_ap.get() == NULL)
529    {
530        m_language_options_ap.reset(new LangOptions());
531        ParseLangArgs(*m_language_options_ap, IK_ObjCXX);
532//        InitializeLangOptions(*m_language_options_ap, IK_ObjCXX);
533    }
534    return m_language_options_ap.get();
535}
536
537SelectorTable *
538ClangASTContext::getSelectorTable()
539{
540    if (m_selector_table_ap.get() == NULL)
541        m_selector_table_ap.reset (new SelectorTable());
542    return m_selector_table_ap.get();
543}
544
545clang::FileManager *
546ClangASTContext::getFileManager()
547{
548    if (m_file_manager_ap.get() == NULL)
549    {
550        clang::FileSystemOptions file_system_options;
551        m_file_manager_ap.reset(new clang::FileManager(file_system_options));
552    }
553    return m_file_manager_ap.get();
554}
555
556clang::SourceManager *
557ClangASTContext::getSourceManager()
558{
559    if (m_source_manager_ap.get() == NULL)
560        m_source_manager_ap.reset(new clang::SourceManager(*getDiagnosticsEngine(), *getFileManager()));
561    return m_source_manager_ap.get();
562}
563
564clang::DiagnosticsEngine *
565ClangASTContext::getDiagnosticsEngine()
566{
567    if (m_diagnostics_engine_ap.get() == NULL)
568    {
569        llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_id_sp(new DiagnosticIDs());
570        m_diagnostics_engine_ap.reset(new DiagnosticsEngine(diag_id_sp, new DiagnosticOptions()));
571    }
572    return m_diagnostics_engine_ap.get();
573}
574
575class NullDiagnosticConsumer : public DiagnosticConsumer
576{
577public:
578    NullDiagnosticConsumer ()
579    {
580        m_log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
581    }
582
583    void HandleDiagnostic (DiagnosticsEngine::Level DiagLevel, const Diagnostic &info)
584    {
585        if (m_log)
586        {
587            llvm::SmallVector<char, 32> diag_str(10);
588            info.FormatDiagnostic(diag_str);
589            diag_str.push_back('\0');
590            m_log->Printf("Compiler diagnostic: %s\n", diag_str.data());
591        }
592    }
593
594    DiagnosticConsumer *clone (DiagnosticsEngine &Diags) const
595    {
596        return new NullDiagnosticConsumer ();
597    }
598private:
599    LogSP m_log;
600};
601
602DiagnosticConsumer *
603ClangASTContext::getDiagnosticConsumer()
604{
605    if (m_diagnostic_consumer_ap.get() == NULL)
606        m_diagnostic_consumer_ap.reset(new NullDiagnosticConsumer);
607
608    return m_diagnostic_consumer_ap.get();
609}
610
611TargetOptions *
612ClangASTContext::getTargetOptions()
613{
614    if (m_target_options_rp.getPtr() == NULL && !m_target_triple.empty())
615    {
616        m_target_options_rp.reset ();
617        m_target_options_rp = new TargetOptions();
618        if (m_target_options_rp.getPtr() != NULL)
619            m_target_options_rp->Triple = m_target_triple;
620    }
621    return m_target_options_rp.getPtr();
622}
623
624
625TargetInfo *
626ClangASTContext::getTargetInfo()
627{
628    // target_triple should be something like "x86_64-apple-macosx"
629    if (m_target_info_ap.get() == NULL && !m_target_triple.empty())
630        m_target_info_ap.reset (TargetInfo::CreateTargetInfo(*getDiagnosticsEngine(), getTargetOptions()));
631    return m_target_info_ap.get();
632}
633
634#pragma mark Basic Types
635
636static inline bool
637QualTypeMatchesBitSize(const uint64_t bit_size, ASTContext *ast, QualType qual_type)
638{
639    uint64_t qual_type_bit_size = ast->getTypeSize(qual_type);
640    if (qual_type_bit_size == bit_size)
641        return true;
642    return false;
643}
644
645clang_type_t
646ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (Encoding encoding, uint32_t bit_size)
647{
648    ASTContext *ast = getASTContext();
649
650    assert (ast != NULL);
651
652    return GetBuiltinTypeForEncodingAndBitSize (ast, encoding, bit_size);
653}
654
655clang_type_t
656ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (ASTContext *ast, Encoding encoding, uint32_t bit_size)
657{
658    if (!ast)
659        return NULL;
660
661    switch (encoding)
662    {
663    case eEncodingInvalid:
664        if (QualTypeMatchesBitSize (bit_size, ast, ast->VoidPtrTy))
665            return ast->VoidPtrTy.getAsOpaquePtr();
666        break;
667
668    case eEncodingUint:
669        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
670            return ast->UnsignedCharTy.getAsOpaquePtr();
671        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
672            return ast->UnsignedShortTy.getAsOpaquePtr();
673        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
674            return ast->UnsignedIntTy.getAsOpaquePtr();
675        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongTy))
676            return ast->UnsignedLongTy.getAsOpaquePtr();
677        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongLongTy))
678            return ast->UnsignedLongLongTy.getAsOpaquePtr();
679        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedInt128Ty))
680            return ast->UnsignedInt128Ty.getAsOpaquePtr();
681        break;
682
683    case eEncodingSint:
684        if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
685            return ast->CharTy.getAsOpaquePtr();
686        if (QualTypeMatchesBitSize (bit_size, ast, ast->ShortTy))
687            return ast->ShortTy.getAsOpaquePtr();
688        if (QualTypeMatchesBitSize (bit_size, ast, ast->IntTy))
689            return ast->IntTy.getAsOpaquePtr();
690        if (QualTypeMatchesBitSize (bit_size, ast, ast->LongTy))
691            return ast->LongTy.getAsOpaquePtr();
692        if (QualTypeMatchesBitSize (bit_size, ast, ast->LongLongTy))
693            return ast->LongLongTy.getAsOpaquePtr();
694        if (QualTypeMatchesBitSize (bit_size, ast, ast->Int128Ty))
695            return ast->Int128Ty.getAsOpaquePtr();
696        break;
697
698    case eEncodingIEEE754:
699        if (QualTypeMatchesBitSize (bit_size, ast, ast->FloatTy))
700            return ast->FloatTy.getAsOpaquePtr();
701        if (QualTypeMatchesBitSize (bit_size, ast, ast->DoubleTy))
702            return ast->DoubleTy.getAsOpaquePtr();
703        if (QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleTy))
704            return ast->LongDoubleTy.getAsOpaquePtr();
705        break;
706
707    case eEncodingVector:
708        // Sanity check that bit_size is a multiple of 8's.
709        if (bit_size && !(bit_size & 0x7u))
710            return ast->getExtVectorType (ast->UnsignedCharTy, bit_size/8).getAsOpaquePtr();
711        break;
712    }
713
714    return NULL;
715}
716
717clang_type_t
718ClangASTContext::GetBuiltinTypeForDWARFEncodingAndBitSize (const char *type_name, uint32_t dw_ate, uint32_t bit_size)
719{
720    ASTContext *ast = getASTContext();
721
722#define streq(a,b) strcmp(a,b) == 0
723    assert (ast != NULL);
724    if (ast)
725    {
726        switch (dw_ate)
727        {
728            default:
729                break;
730
731            case DW_ATE_address:
732                if (QualTypeMatchesBitSize (bit_size, ast, ast->VoidPtrTy))
733                    return ast->VoidPtrTy.getAsOpaquePtr();
734                break;
735
736            case DW_ATE_boolean:
737                if (QualTypeMatchesBitSize (bit_size, ast, ast->BoolTy))
738                    return ast->BoolTy.getAsOpaquePtr();
739                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
740                    return ast->UnsignedCharTy.getAsOpaquePtr();
741                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
742                    return ast->UnsignedShortTy.getAsOpaquePtr();
743                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
744                    return ast->UnsignedIntTy.getAsOpaquePtr();
745                break;
746
747            case DW_ATE_lo_user:
748                // This has been seen to mean DW_AT_complex_integer
749                if (type_name)
750                {
751                    if (::strstr(type_name, "complex"))
752                    {
753                        clang_type_t complex_int_clang_type = GetBuiltinTypeForDWARFEncodingAndBitSize ("int", DW_ATE_signed, bit_size/2);
754                        return ast->getComplexType (QualType::getFromOpaquePtr(complex_int_clang_type)).getAsOpaquePtr();
755                    }
756                }
757                break;
758
759            case DW_ATE_complex_float:
760                if (QualTypeMatchesBitSize (bit_size, ast, ast->FloatComplexTy))
761                    return ast->FloatComplexTy.getAsOpaquePtr();
762                else if (QualTypeMatchesBitSize (bit_size, ast, ast->DoubleComplexTy))
763                    return ast->DoubleComplexTy.getAsOpaquePtr();
764                else if (QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleComplexTy))
765                    return ast->LongDoubleComplexTy.getAsOpaquePtr();
766                else
767                {
768                    clang_type_t complex_float_clang_type = GetBuiltinTypeForDWARFEncodingAndBitSize ("float", DW_ATE_float, bit_size/2);
769                    return ast->getComplexType (QualType::getFromOpaquePtr(complex_float_clang_type)).getAsOpaquePtr();
770                }
771                break;
772
773            case DW_ATE_float:
774                if (QualTypeMatchesBitSize (bit_size, ast, ast->FloatTy))
775                    return ast->FloatTy.getAsOpaquePtr();
776                if (QualTypeMatchesBitSize (bit_size, ast, ast->DoubleTy))
777                    return ast->DoubleTy.getAsOpaquePtr();
778                if (QualTypeMatchesBitSize (bit_size, ast, ast->LongDoubleTy))
779                    return ast->LongDoubleTy.getAsOpaquePtr();
780                break;
781
782            case DW_ATE_signed:
783                if (type_name)
784                {
785                    if (streq(type_name, "wchar_t") &&
786                        QualTypeMatchesBitSize (bit_size, ast, ast->WCharTy))
787                        return ast->WCharTy.getAsOpaquePtr();
788                    if (streq(type_name, "void") &&
789                        QualTypeMatchesBitSize (bit_size, ast, ast->VoidTy))
790                        return ast->VoidTy.getAsOpaquePtr();
791                    if (strstr(type_name, "long long") &&
792                        QualTypeMatchesBitSize (bit_size, ast, ast->LongLongTy))
793                        return ast->LongLongTy.getAsOpaquePtr();
794                    if (strstr(type_name, "long") &&
795                        QualTypeMatchesBitSize (bit_size, ast, ast->LongTy))
796                        return ast->LongTy.getAsOpaquePtr();
797                    if (strstr(type_name, "short") &&
798                        QualTypeMatchesBitSize (bit_size, ast, ast->ShortTy))
799                        return ast->ShortTy.getAsOpaquePtr();
800                    if (strstr(type_name, "char"))
801                    {
802                        if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
803                            return ast->CharTy.getAsOpaquePtr();
804                        if (QualTypeMatchesBitSize (bit_size, ast, ast->SignedCharTy))
805                            return ast->SignedCharTy.getAsOpaquePtr();
806                    }
807                    if (strstr(type_name, "int"))
808                    {
809                        if (QualTypeMatchesBitSize (bit_size, ast, ast->IntTy))
810                            return ast->IntTy.getAsOpaquePtr();
811                        if (QualTypeMatchesBitSize (bit_size, ast, ast->Int128Ty))
812                            return ast->Int128Ty.getAsOpaquePtr();
813                    }
814                }
815                // We weren't able to match up a type name, just search by size
816                if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
817                    return ast->CharTy.getAsOpaquePtr();
818                if (QualTypeMatchesBitSize (bit_size, ast, ast->ShortTy))
819                    return ast->ShortTy.getAsOpaquePtr();
820                if (QualTypeMatchesBitSize (bit_size, ast, ast->IntTy))
821                    return ast->IntTy.getAsOpaquePtr();
822                if (QualTypeMatchesBitSize (bit_size, ast, ast->LongTy))
823                    return ast->LongTy.getAsOpaquePtr();
824                if (QualTypeMatchesBitSize (bit_size, ast, ast->LongLongTy))
825                    return ast->LongLongTy.getAsOpaquePtr();
826                if (QualTypeMatchesBitSize (bit_size, ast, ast->Int128Ty))
827                    return ast->Int128Ty.getAsOpaquePtr();
828                break;
829
830            case DW_ATE_signed_char:
831                if (type_name)
832                {
833                    if (streq(type_name, "signed char"))
834                    {
835                        if (QualTypeMatchesBitSize (bit_size, ast, ast->SignedCharTy))
836                            return ast->SignedCharTy.getAsOpaquePtr();
837                    }
838                }
839                if (QualTypeMatchesBitSize (bit_size, ast, ast->CharTy))
840                    return ast->CharTy.getAsOpaquePtr();
841                if (QualTypeMatchesBitSize (bit_size, ast, ast->SignedCharTy))
842                    return ast->SignedCharTy.getAsOpaquePtr();
843                break;
844
845            case DW_ATE_unsigned:
846                if (type_name)
847                {
848                    if (strstr(type_name, "long long"))
849                    {
850                        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongLongTy))
851                            return ast->UnsignedLongLongTy.getAsOpaquePtr();
852                    }
853                    else if (strstr(type_name, "long"))
854                    {
855                        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongTy))
856                            return ast->UnsignedLongTy.getAsOpaquePtr();
857                    }
858                    else if (strstr(type_name, "short"))
859                    {
860                        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
861                            return ast->UnsignedShortTy.getAsOpaquePtr();
862                    }
863                    else if (strstr(type_name, "char"))
864                    {
865                        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
866                            return ast->UnsignedCharTy.getAsOpaquePtr();
867                    }
868                    else if (strstr(type_name, "int"))
869                    {
870                        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
871                            return ast->UnsignedIntTy.getAsOpaquePtr();
872                        if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedInt128Ty))
873                            return ast->UnsignedInt128Ty.getAsOpaquePtr();
874                    }
875                }
876                // We weren't able to match up a type name, just search by size
877                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
878                    return ast->UnsignedCharTy.getAsOpaquePtr();
879                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
880                    return ast->UnsignedShortTy.getAsOpaquePtr();
881                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedIntTy))
882                    return ast->UnsignedIntTy.getAsOpaquePtr();
883                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongTy))
884                    return ast->UnsignedLongTy.getAsOpaquePtr();
885                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedLongLongTy))
886                    return ast->UnsignedLongLongTy.getAsOpaquePtr();
887                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedInt128Ty))
888                    return ast->UnsignedInt128Ty.getAsOpaquePtr();
889                break;
890
891            case DW_ATE_unsigned_char:
892                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedCharTy))
893                    return ast->UnsignedCharTy.getAsOpaquePtr();
894                if (QualTypeMatchesBitSize (bit_size, ast, ast->UnsignedShortTy))
895                    return ast->UnsignedShortTy.getAsOpaquePtr();
896                break;
897
898            case DW_ATE_imaginary_float:
899                break;
900
901            case DW_ATE_UTF:
902                if (type_name)
903                {
904                    if (streq(type_name, "char16_t"))
905                    {
906                        return ast->Char16Ty.getAsOpaquePtr();
907                    }
908                    else if (streq(type_name, "char32_t"))
909                    {
910                        return ast->Char32Ty.getAsOpaquePtr();
911                    }
912                }
913                break;
914        }
915    }
916    // This assert should fire for anything that we don't catch above so we know
917    // to fix any issues we run into.
918    if (type_name)
919    {
920        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);
921    }
922    else
923    {
924        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);
925    }
926    return NULL;
927}
928
929clang_type_t
930ClangASTContext::GetBuiltInType_void(ASTContext *ast)
931{
932    return ast->VoidTy.getAsOpaquePtr();
933}
934
935clang_type_t
936ClangASTContext::GetBuiltInType_bool()
937{
938    return getASTContext()->BoolTy.getAsOpaquePtr();
939}
940
941clang_type_t
942ClangASTContext::GetBuiltInType_objc_id()
943{
944    return getASTContext()->getObjCIdType().getAsOpaquePtr();
945}
946
947clang_type_t
948ClangASTContext::GetBuiltInType_objc_Class()
949{
950    return getASTContext()->getObjCClassType().getAsOpaquePtr();
951}
952
953clang_type_t
954ClangASTContext::GetBuiltInType_objc_selector()
955{
956    return getASTContext()->getObjCSelType().getAsOpaquePtr();
957}
958
959clang_type_t
960ClangASTContext::GetUnknownAnyType(clang::ASTContext *ast)
961{
962    return ast->UnknownAnyTy.getAsOpaquePtr();
963}
964
965clang_type_t
966ClangASTContext::GetCStringType (bool is_const)
967{
968    QualType char_type(getASTContext()->CharTy);
969
970    if (is_const)
971        char_type.addConst();
972
973    return getASTContext()->getPointerType(char_type).getAsOpaquePtr();
974}
975
976clang_type_t
977ClangASTContext::GetVoidType()
978{
979    return GetVoidType(getASTContext());
980}
981
982clang_type_t
983ClangASTContext::GetVoidType(ASTContext *ast)
984{
985    return ast->VoidTy.getAsOpaquePtr();
986}
987
988clang_type_t
989ClangASTContext::GetVoidPtrType (bool is_const)
990{
991    return GetVoidPtrType(getASTContext(), is_const);
992}
993
994clang_type_t
995ClangASTContext::GetVoidPtrType (ASTContext *ast, bool is_const)
996{
997    QualType void_ptr_type(ast->VoidPtrTy);
998
999    if (is_const)
1000        void_ptr_type.addConst();
1001
1002    return void_ptr_type.getAsOpaquePtr();
1003}
1004
1005clang::DeclContext *
1006ClangASTContext::GetTranslationUnitDecl (clang::ASTContext *ast)
1007{
1008    return ast->getTranslationUnitDecl();
1009}
1010
1011clang_type_t
1012ClangASTContext::CopyType (ASTContext *dst_ast,
1013                           ASTContext *src_ast,
1014                           clang_type_t clang_type)
1015{
1016    FileSystemOptions file_system_options;
1017    FileManager file_manager (file_system_options);
1018    ASTImporter importer(*dst_ast, file_manager,
1019                         *src_ast, file_manager,
1020                         false);
1021
1022    QualType src (QualType::getFromOpaquePtr(clang_type));
1023    QualType dst (importer.Import(src));
1024
1025    return dst.getAsOpaquePtr();
1026}
1027
1028
1029clang::Decl *
1030ClangASTContext::CopyDecl (ASTContext *dst_ast,
1031                           ASTContext *src_ast,
1032                           clang::Decl *source_decl)
1033{
1034    FileSystemOptions file_system_options;
1035    FileManager file_manager (file_system_options);
1036    ASTImporter importer(*dst_ast, file_manager,
1037                         *src_ast, file_manager,
1038                         false);
1039
1040    return importer.Import(source_decl);
1041}
1042
1043bool
1044ClangASTContext::AreTypesSame (ASTContext *ast,
1045                               clang_type_t type1,
1046                               clang_type_t type2,
1047                               bool ignore_qualifiers)
1048{
1049    if (type1 == type2)
1050        return true;
1051
1052    QualType type1_qual = QualType::getFromOpaquePtr(type1);
1053    QualType type2_qual = QualType::getFromOpaquePtr(type2);
1054
1055    if (ignore_qualifiers)
1056    {
1057        type1_qual = type1_qual.getUnqualifiedType();
1058        type2_qual = type2_qual.getUnqualifiedType();
1059    }
1060
1061    return ast->hasSameType (type1_qual,
1062                             type2_qual);
1063}
1064
1065#pragma mark CVR modifiers
1066
1067clang_type_t
1068ClangASTContext::AddConstModifier (clang_type_t clang_type)
1069{
1070    if (clang_type)
1071    {
1072        QualType result(QualType::getFromOpaquePtr(clang_type));
1073        result.addConst();
1074        return result.getAsOpaquePtr();
1075    }
1076    return NULL;
1077}
1078
1079clang_type_t
1080ClangASTContext::AddRestrictModifier (clang_type_t clang_type)
1081{
1082    if (clang_type)
1083    {
1084        QualType result(QualType::getFromOpaquePtr(clang_type));
1085        result.getQualifiers().setRestrict (true);
1086        return result.getAsOpaquePtr();
1087    }
1088    return NULL;
1089}
1090
1091clang_type_t
1092ClangASTContext::AddVolatileModifier (clang_type_t clang_type)
1093{
1094    if (clang_type)
1095    {
1096        QualType result(QualType::getFromOpaquePtr(clang_type));
1097        result.getQualifiers().setVolatile (true);
1098        return result.getAsOpaquePtr();
1099    }
1100    return NULL;
1101}
1102
1103
1104clang_type_t
1105ClangASTContext::GetTypeForDecl (TagDecl *decl)
1106{
1107    // No need to call the getASTContext() accessor (which can create the AST
1108    // if it isn't created yet, because we can't have created a decl in this
1109    // AST if our AST didn't already exist...
1110    if (m_ast_ap.get())
1111        return m_ast_ap->getTagDeclType(decl).getAsOpaquePtr();
1112    return NULL;
1113}
1114
1115clang_type_t
1116ClangASTContext::GetTypeForDecl (ObjCInterfaceDecl *decl)
1117{
1118    // No need to call the getASTContext() accessor (which can create the AST
1119    // if it isn't created yet, because we can't have created a decl in this
1120    // AST if our AST didn't already exist...
1121    if (m_ast_ap.get())
1122        return m_ast_ap->getObjCInterfaceType(decl).getAsOpaquePtr();
1123    return NULL;
1124}
1125
1126#pragma mark Structure, Unions, Classes
1127
1128clang_type_t
1129ClangASTContext::CreateRecordType (DeclContext *decl_ctx,
1130                                   AccessType access_type,
1131                                   const char *name,
1132                                   int kind,
1133                                   LanguageType language,
1134                                   ClangASTMetadata *metadata)
1135{
1136    ASTContext *ast = getASTContext();
1137    assert (ast != NULL);
1138
1139    if (decl_ctx == NULL)
1140        decl_ctx = ast->getTranslationUnitDecl();
1141
1142
1143    if (language == eLanguageTypeObjC || language == eLanguageTypeObjC_plus_plus)
1144    {
1145        bool isForwardDecl = true;
1146        bool isInternal = false;
1147        return CreateObjCClass (name, decl_ctx, isForwardDecl, isInternal, metadata);
1148    }
1149
1150    // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
1151    // we will need to update this code. I was told to currently always use
1152    // the CXXRecordDecl class since we often don't know from debug information
1153    // if something is struct or a class, so we default to always use the more
1154    // complete definition just in case.
1155    CXXRecordDecl *decl = CXXRecordDecl::Create (*ast,
1156                                                 (TagDecl::TagKind)kind,
1157                                                 decl_ctx,
1158                                                 SourceLocation(),
1159                                                 SourceLocation(),
1160                                                 name && name[0] ? &ast->Idents.get(name) : NULL);
1161
1162    if (decl)
1163    {
1164        if (metadata)
1165            SetMetadata(ast, (uintptr_t)decl, *metadata);
1166
1167        if (access_type != eAccessNone)
1168            decl->setAccess (ConvertAccessTypeToAccessSpecifier (access_type));
1169
1170        if (decl_ctx)
1171            decl_ctx->addDecl (decl);
1172
1173        return ast->getTagDeclType(decl).getAsOpaquePtr();
1174    }
1175    return NULL;
1176}
1177
1178static TemplateParameterList *
1179CreateTemplateParameterList (ASTContext *ast,
1180                             const ClangASTContext::TemplateParameterInfos &template_param_infos,
1181                             llvm::SmallVector<NamedDecl *, 8> &template_param_decls)
1182{
1183    const bool parameter_pack = false;
1184    const bool is_typename = false;
1185    const unsigned depth = 0;
1186    const size_t num_template_params = template_param_infos.GetSize();
1187    for (size_t i=0; i<num_template_params; ++i)
1188    {
1189        const char *name = template_param_infos.names[i];
1190        if (template_param_infos.args[i].getKind() == TemplateArgument::Integral)
1191        {
1192            template_param_decls.push_back (NonTypeTemplateParmDecl::Create (*ast,
1193                                                                             ast->getTranslationUnitDecl(), // Is this the right decl context?, SourceLocation StartLoc,
1194                                                                             SourceLocation(),
1195                                                                             SourceLocation(),
1196                                                                             depth,
1197                                                                             i,
1198                                                                             &ast->Idents.get(name),
1199                                                                             template_param_infos.args[i].getIntegralType(),
1200                                                                             parameter_pack,
1201                                                                             NULL));
1202
1203        }
1204        else
1205        {
1206            template_param_decls.push_back (TemplateTypeParmDecl::Create (*ast,
1207                                                                          ast->getTranslationUnitDecl(), // Is this the right decl context?
1208                                                                          SourceLocation(),
1209                                                                          SourceLocation(),
1210                                                                          depth,
1211                                                                          i,
1212                                                                          &ast->Idents.get(name),
1213                                                                          is_typename,
1214                                                                          parameter_pack));
1215        }
1216    }
1217
1218    TemplateParameterList *template_param_list = TemplateParameterList::Create (*ast,
1219                                                                                SourceLocation(),
1220                                                                                SourceLocation(),
1221                                                                                &template_param_decls.front(),
1222                                                                                template_param_decls.size(),
1223                                                                                SourceLocation());
1224    return template_param_list;
1225}
1226
1227clang::FunctionTemplateDecl *
1228ClangASTContext::CreateFunctionTemplateDecl (clang::DeclContext *decl_ctx,
1229                                             clang::FunctionDecl *func_decl,
1230                                             const char *name,
1231                                             const TemplateParameterInfos &template_param_infos)
1232{
1233//    /// \brief Create a function template node.
1234    ASTContext *ast = getASTContext();
1235
1236    llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1237
1238    TemplateParameterList *template_param_list = CreateTemplateParameterList (ast,
1239                                                                              template_param_infos,
1240                                                                              template_param_decls);
1241    FunctionTemplateDecl *func_tmpl_decl = FunctionTemplateDecl::Create (*ast,
1242                                                                         decl_ctx,
1243                                                                         func_decl->getLocation(),
1244                                                                         func_decl->getDeclName(),
1245                                                                         template_param_list,
1246                                                                         func_decl);
1247
1248    for (size_t i=0, template_param_decl_count = template_param_decls.size();
1249         i < template_param_decl_count;
1250         ++i)
1251    {
1252        // TODO: verify which decl context we should put template_param_decls into..
1253        template_param_decls[i]->setDeclContext (func_decl);
1254    }
1255
1256    return func_tmpl_decl;
1257}
1258
1259void
1260ClangASTContext::CreateFunctionTemplateSpecializationInfo (FunctionDecl *func_decl,
1261                                                           clang::FunctionTemplateDecl *func_tmpl_decl,
1262                                                           const TemplateParameterInfos &infos)
1263{
1264    TemplateArgumentList template_args (TemplateArgumentList::OnStack,
1265                                        infos.args.data(),
1266                                        infos.args.size());
1267
1268    func_decl->setFunctionTemplateSpecialization (func_tmpl_decl,
1269                                                  &template_args,
1270                                                  NULL);
1271}
1272
1273
1274ClassTemplateDecl *
1275ClangASTContext::CreateClassTemplateDecl (DeclContext *decl_ctx,
1276                                          lldb::AccessType access_type,
1277                                          const char *class_name,
1278                                          int kind,
1279                                          const TemplateParameterInfos &template_param_infos)
1280{
1281    ASTContext *ast = getASTContext();
1282
1283    ClassTemplateDecl *class_template_decl = NULL;
1284    if (decl_ctx == NULL)
1285        decl_ctx = ast->getTranslationUnitDecl();
1286
1287    IdentifierInfo &identifier_info = ast->Idents.get(class_name);
1288    DeclarationName decl_name (&identifier_info);
1289
1290    clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1291
1292    for (NamedDecl *decl : result)
1293    {
1294        class_template_decl = dyn_cast<clang::ClassTemplateDecl>(decl);
1295        if (class_template_decl)
1296            return class_template_decl;
1297    }
1298
1299    llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1300
1301    TemplateParameterList *template_param_list = CreateTemplateParameterList (ast,
1302                                                                              template_param_infos,
1303                                                                              template_param_decls);
1304
1305    CXXRecordDecl *template_cxx_decl = CXXRecordDecl::Create (*ast,
1306                                                              (TagDecl::TagKind)kind,
1307                                                              decl_ctx,  // What decl context do we use here? TU? The actual decl context?
1308                                                              SourceLocation(),
1309                                                              SourceLocation(),
1310                                                              &identifier_info);
1311
1312    for (size_t i=0, template_param_decl_count = template_param_decls.size();
1313         i < template_param_decl_count;
1314         ++i)
1315    {
1316        template_param_decls[i]->setDeclContext (template_cxx_decl);
1317    }
1318
1319    // With templated classes, we say that a class is templated with
1320    // specializations, but that the bare class has no functions.
1321    //template_cxx_decl->startDefinition();
1322    //template_cxx_decl->completeDefinition();
1323
1324    class_template_decl = ClassTemplateDecl::Create (*ast,
1325                                                     decl_ctx,  // What decl context do we use here? TU? The actual decl context?
1326                                                     SourceLocation(),
1327                                                     decl_name,
1328                                                     template_param_list,
1329                                                     template_cxx_decl,
1330                                                     NULL);
1331
1332    if (class_template_decl)
1333    {
1334        if (access_type != eAccessNone)
1335            class_template_decl->setAccess (ConvertAccessTypeToAccessSpecifier (access_type));
1336
1337        //if (TagDecl *ctx_tag_decl = dyn_cast<TagDecl>(decl_ctx))
1338        //    CompleteTagDeclarationDefinition(GetTypeForDecl(ctx_tag_decl));
1339
1340        decl_ctx->addDecl (class_template_decl);
1341
1342#ifdef LLDB_CONFIGURATION_DEBUG
1343        VerifyDecl(class_template_decl);
1344#endif
1345    }
1346
1347    return class_template_decl;
1348}
1349
1350
1351ClassTemplateSpecializationDecl *
1352ClangASTContext::CreateClassTemplateSpecializationDecl (DeclContext *decl_ctx,
1353                                                        ClassTemplateDecl *class_template_decl,
1354                                                        int kind,
1355                                                        const TemplateParameterInfos &template_param_infos)
1356{
1357    ASTContext *ast = getASTContext();
1358    ClassTemplateSpecializationDecl *class_template_specialization_decl = ClassTemplateSpecializationDecl::Create (*ast,
1359                                                                                                                   (TagDecl::TagKind)kind,
1360                                                                                                                   decl_ctx,
1361                                                                                                                   SourceLocation(),
1362                                                                                                                   SourceLocation(),
1363                                                                                                                   class_template_decl,
1364                                                                                                                   &template_param_infos.args.front(),
1365                                                                                                                   template_param_infos.args.size(),
1366                                                                                                                   NULL);
1367
1368    class_template_specialization_decl->setSpecializationKind(TSK_ExplicitSpecialization);
1369
1370    return class_template_specialization_decl;
1371}
1372
1373lldb::clang_type_t
1374ClangASTContext::CreateClassTemplateSpecializationType (ClassTemplateSpecializationDecl *class_template_specialization_decl)
1375{
1376    if (class_template_specialization_decl)
1377    {
1378        ASTContext *ast = getASTContext();
1379        if (ast)
1380            return ast->getTagDeclType(class_template_specialization_decl).getAsOpaquePtr();
1381    }
1382    return NULL;
1383}
1384
1385bool
1386ClangASTContext::SetHasExternalStorage (clang_type_t clang_type, bool has_extern)
1387{
1388    if (clang_type == NULL)
1389        return false;
1390
1391    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
1392
1393    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
1394    switch (type_class)
1395    {
1396    case clang::Type::Record:
1397        {
1398            CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
1399            if (cxx_record_decl)
1400            {
1401                cxx_record_decl->setHasExternalLexicalStorage (has_extern);
1402                cxx_record_decl->setHasExternalVisibleStorage (has_extern);
1403                return true;
1404            }
1405        }
1406        break;
1407
1408    case clang::Type::Enum:
1409        {
1410            EnumDecl *enum_decl = cast<EnumType>(qual_type)->getDecl();
1411            if (enum_decl)
1412            {
1413                enum_decl->setHasExternalLexicalStorage (has_extern);
1414                enum_decl->setHasExternalVisibleStorage (has_extern);
1415                return true;
1416            }
1417        }
1418        break;
1419
1420    case clang::Type::ObjCObject:
1421    case clang::Type::ObjCInterface:
1422        {
1423            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
1424            assert (objc_class_type);
1425            if (objc_class_type)
1426            {
1427                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
1428
1429                if (class_interface_decl)
1430                {
1431                    class_interface_decl->setHasExternalLexicalStorage (has_extern);
1432                    class_interface_decl->setHasExternalVisibleStorage (has_extern);
1433                    return true;
1434                }
1435            }
1436        }
1437        break;
1438
1439    case clang::Type::Typedef:
1440        return ClangASTContext::SetHasExternalStorage (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(), has_extern);
1441
1442    case clang::Type::Elaborated:
1443        return ClangASTContext::SetHasExternalStorage (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(), has_extern);
1444
1445    default:
1446        break;
1447    }
1448    return false;
1449}
1450
1451static bool
1452IsOperator (const char *name, OverloadedOperatorKind &op_kind)
1453{
1454    if (name == NULL || name[0] == '\0')
1455        return false;
1456
1457#define OPERATOR_PREFIX "operator"
1458#define OPERATOR_PREFIX_LENGTH (sizeof (OPERATOR_PREFIX) - 1)
1459
1460    const char *post_op_name = NULL;
1461
1462    bool no_space = true;
1463
1464    if (::strncmp(name, OPERATOR_PREFIX, OPERATOR_PREFIX_LENGTH))
1465        return false;
1466
1467    post_op_name = name + OPERATOR_PREFIX_LENGTH;
1468
1469    if (post_op_name[0] == ' ')
1470    {
1471        post_op_name++;
1472        no_space = false;
1473    }
1474
1475#undef OPERATOR_PREFIX
1476#undef OPERATOR_PREFIX_LENGTH
1477
1478    // This is an operator, set the overloaded operator kind to invalid
1479    // in case this is a conversion operator...
1480    op_kind = NUM_OVERLOADED_OPERATORS;
1481
1482    switch (post_op_name[0])
1483    {
1484    default:
1485        if (no_space)
1486            return false;
1487        break;
1488    case 'n':
1489        if (no_space)
1490            return false;
1491        if  (strcmp (post_op_name, "new") == 0)
1492            op_kind = OO_New;
1493        else if (strcmp (post_op_name, "new[]") == 0)
1494            op_kind = OO_Array_New;
1495        break;
1496
1497    case 'd':
1498        if (no_space)
1499            return false;
1500        if (strcmp (post_op_name, "delete") == 0)
1501            op_kind = OO_Delete;
1502        else if (strcmp (post_op_name, "delete[]") == 0)
1503            op_kind = OO_Array_Delete;
1504        break;
1505
1506    case '+':
1507        if (post_op_name[1] == '\0')
1508            op_kind = OO_Plus;
1509        else if (post_op_name[2] == '\0')
1510        {
1511            if (post_op_name[1] == '=')
1512                op_kind = OO_PlusEqual;
1513            else if (post_op_name[1] == '+')
1514                op_kind = OO_PlusPlus;
1515        }
1516        break;
1517
1518    case '-':
1519        if (post_op_name[1] == '\0')
1520            op_kind = OO_Minus;
1521        else if (post_op_name[2] == '\0')
1522        {
1523            switch (post_op_name[1])
1524            {
1525            case '=': op_kind = OO_MinusEqual; break;
1526            case '-': op_kind = OO_MinusMinus; break;
1527            case '>': op_kind = OO_Arrow; break;
1528            }
1529        }
1530        else if (post_op_name[3] == '\0')
1531        {
1532            if (post_op_name[2] == '*')
1533                op_kind = OO_ArrowStar; break;
1534        }
1535        break;
1536
1537    case '*':
1538        if (post_op_name[1] == '\0')
1539            op_kind = OO_Star;
1540        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1541            op_kind = OO_StarEqual;
1542        break;
1543
1544    case '/':
1545        if (post_op_name[1] == '\0')
1546            op_kind = OO_Slash;
1547        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1548            op_kind = OO_SlashEqual;
1549        break;
1550
1551    case '%':
1552        if (post_op_name[1] == '\0')
1553            op_kind = OO_Percent;
1554        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1555            op_kind = OO_PercentEqual;
1556        break;
1557
1558
1559    case '^':
1560        if (post_op_name[1] == '\0')
1561            op_kind = OO_Caret;
1562        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1563            op_kind = OO_CaretEqual;
1564        break;
1565
1566    case '&':
1567        if (post_op_name[1] == '\0')
1568            op_kind = OO_Amp;
1569        else if (post_op_name[2] == '\0')
1570        {
1571            switch (post_op_name[1])
1572            {
1573            case '=': op_kind = OO_AmpEqual; break;
1574            case '&': op_kind = OO_AmpAmp; break;
1575            }
1576        }
1577        break;
1578
1579    case '|':
1580        if (post_op_name[1] == '\0')
1581            op_kind = OO_Pipe;
1582        else if (post_op_name[2] == '\0')
1583        {
1584            switch (post_op_name[1])
1585            {
1586            case '=': op_kind = OO_PipeEqual; break;
1587            case '|': op_kind = OO_PipePipe; break;
1588            }
1589        }
1590        break;
1591
1592    case '~':
1593        if (post_op_name[1] == '\0')
1594            op_kind = OO_Tilde;
1595        break;
1596
1597    case '!':
1598        if (post_op_name[1] == '\0')
1599            op_kind = OO_Exclaim;
1600        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1601            op_kind = OO_ExclaimEqual;
1602        break;
1603
1604    case '=':
1605        if (post_op_name[1] == '\0')
1606            op_kind = OO_Equal;
1607        else if (post_op_name[1] == '=' && post_op_name[2] == '\0')
1608            op_kind = OO_EqualEqual;
1609        break;
1610
1611    case '<':
1612        if (post_op_name[1] == '\0')
1613            op_kind = OO_Less;
1614        else if (post_op_name[2] == '\0')
1615        {
1616            switch (post_op_name[1])
1617            {
1618            case '<': op_kind = OO_LessLess; break;
1619            case '=': op_kind = OO_LessEqual; break;
1620            }
1621        }
1622        else if (post_op_name[3] == '\0')
1623        {
1624            if (post_op_name[2] == '=')
1625                op_kind = OO_LessLessEqual;
1626        }
1627        break;
1628
1629    case '>':
1630        if (post_op_name[1] == '\0')
1631            op_kind = OO_Greater;
1632        else if (post_op_name[2] == '\0')
1633        {
1634            switch (post_op_name[1])
1635            {
1636            case '>': op_kind = OO_GreaterGreater; break;
1637            case '=': op_kind = OO_GreaterEqual; break;
1638            }
1639        }
1640        else if (post_op_name[1] == '>' &&
1641                 post_op_name[2] == '=' &&
1642                 post_op_name[3] == '\0')
1643        {
1644                op_kind = OO_GreaterGreaterEqual;
1645        }
1646        break;
1647
1648    case ',':
1649        if (post_op_name[1] == '\0')
1650            op_kind = OO_Comma;
1651        break;
1652
1653    case '(':
1654        if (post_op_name[1] == ')' && post_op_name[2] == '\0')
1655            op_kind = OO_Call;
1656        break;
1657
1658    case '[':
1659        if (post_op_name[1] == ']' && post_op_name[2] == '\0')
1660            op_kind = OO_Subscript;
1661        break;
1662    }
1663
1664    return true;
1665}
1666
1667static inline bool
1668check_op_param (uint32_t op_kind, bool unary, bool binary, uint32_t num_params)
1669{
1670    // Special-case call since it can take any number of operands
1671    if(op_kind == OO_Call)
1672        return true;
1673
1674    // The parameter count doens't include "this"
1675    if (num_params == 0)
1676        return unary;
1677    if (num_params == 1)
1678        return binary;
1679    else
1680    return false;
1681}
1682
1683bool
1684ClangASTContext::CheckOverloadedOperatorKindParameterCount (uint32_t op_kind, uint32_t num_params)
1685{
1686    switch (op_kind)
1687    {
1688    default:
1689        break;
1690    // C++ standard allows any number of arguments to new/delete
1691    case OO_New:
1692    case OO_Array_New:
1693    case OO_Delete:
1694    case OO_Array_Delete:
1695        return true;
1696    }
1697
1698#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) case OO_##Name: return check_op_param (op_kind, Unary, Binary, num_params);
1699    switch (op_kind)
1700    {
1701#include "clang/Basic/OperatorKinds.def"
1702        default: break;
1703    }
1704    return false;
1705}
1706
1707CXXMethodDecl *
1708ClangASTContext::AddMethodToCXXRecordType
1709(
1710    ASTContext *ast,
1711    clang_type_t record_opaque_type,
1712    const char *name,
1713    clang_type_t method_opaque_type,
1714    lldb::AccessType access,
1715    bool is_virtual,
1716    bool is_static,
1717    bool is_inline,
1718    bool is_explicit,
1719    bool is_attr_used,
1720    bool is_artificial
1721)
1722{
1723    if (!record_opaque_type || !method_opaque_type || !name)
1724        return NULL;
1725
1726    assert(ast);
1727
1728    IdentifierTable *identifier_table = &ast->Idents;
1729
1730    assert(identifier_table);
1731
1732    QualType record_qual_type(QualType::getFromOpaquePtr(record_opaque_type));
1733
1734    CXXRecordDecl *cxx_record_decl = record_qual_type->getAsCXXRecordDecl();
1735
1736    if (cxx_record_decl == NULL)
1737        return NULL;
1738
1739    QualType method_qual_type (QualType::getFromOpaquePtr (method_opaque_type));
1740
1741    CXXMethodDecl *cxx_method_decl = NULL;
1742
1743    DeclarationName decl_name (&identifier_table->get(name));
1744
1745    const clang::FunctionType *function_Type = dyn_cast<FunctionType>(method_qual_type.getTypePtr());
1746
1747    if (function_Type == NULL)
1748        return NULL;
1749
1750    const FunctionProtoType *method_function_prototype (dyn_cast<FunctionProtoType>(function_Type));
1751
1752    if (!method_function_prototype)
1753        return NULL;
1754
1755    unsigned int num_params = method_function_prototype->getNumArgs();
1756
1757    CXXDestructorDecl *cxx_dtor_decl(NULL);
1758    CXXConstructorDecl *cxx_ctor_decl(NULL);
1759
1760    if (name[0] == '~')
1761    {
1762        cxx_dtor_decl = CXXDestructorDecl::Create (*ast,
1763                                                   cxx_record_decl,
1764                                                   SourceLocation(),
1765                                                   DeclarationNameInfo (ast->DeclarationNames.getCXXDestructorName (ast->getCanonicalType (record_qual_type)), SourceLocation()),
1766                                                   method_qual_type,
1767                                                   NULL,
1768                                                   is_inline,
1769                                                   is_artificial);
1770        cxx_method_decl = cxx_dtor_decl;
1771    }
1772    else if (decl_name == cxx_record_decl->getDeclName())
1773    {
1774       cxx_ctor_decl = CXXConstructorDecl::Create (*ast,
1775                                                   cxx_record_decl,
1776                                                   SourceLocation(),
1777                                                   DeclarationNameInfo (ast->DeclarationNames.getCXXConstructorName (ast->getCanonicalType (record_qual_type)), SourceLocation()),
1778                                                   method_qual_type,
1779                                                   NULL, // TypeSourceInfo *
1780                                                   is_explicit,
1781                                                   is_inline,
1782                                                   is_artificial,
1783                                                   false /*is_constexpr*/);
1784        cxx_method_decl = cxx_ctor_decl;
1785    }
1786    else
1787    {
1788
1789        OverloadedOperatorKind op_kind = NUM_OVERLOADED_OPERATORS;
1790        if (IsOperator (name, op_kind))
1791        {
1792            if (op_kind != NUM_OVERLOADED_OPERATORS)
1793            {
1794                // Check the number of operator parameters. Sometimes we have
1795                // seen bad DWARF that doesn't correctly describe operators and
1796                // if we try to create a methed and add it to the class, clang
1797                // will assert and crash, so we need to make sure things are
1798                // acceptable.
1799                if (!ClangASTContext::CheckOverloadedOperatorKindParameterCount (op_kind, num_params))
1800                    return NULL;
1801                cxx_method_decl = CXXMethodDecl::Create (*ast,
1802                                                         cxx_record_decl,
1803                                                         SourceLocation(),
1804                                                         DeclarationNameInfo (ast->DeclarationNames.getCXXOperatorName (op_kind), SourceLocation()),
1805                                                         method_qual_type,
1806                                                         NULL, // TypeSourceInfo *
1807                                                         is_static,
1808                                                         SC_None,
1809                                                         is_inline,
1810                                                         false /*is_constexpr*/,
1811                                                         SourceLocation());
1812            }
1813            else if (num_params == 0)
1814            {
1815                // Conversion operators don't take params...
1816                cxx_method_decl = CXXConversionDecl::Create (*ast,
1817                                                             cxx_record_decl,
1818                                                             SourceLocation(),
1819                                                             DeclarationNameInfo (ast->DeclarationNames.getCXXConversionFunctionName (ast->getCanonicalType (function_Type->getResultType())), SourceLocation()),
1820                                                             method_qual_type,
1821                                                             NULL, // TypeSourceInfo *
1822                                                             is_inline,
1823                                                             is_explicit,
1824                                                             false /*is_constexpr*/,
1825                                                             SourceLocation());
1826            }
1827        }
1828
1829        if (cxx_method_decl == NULL)
1830        {
1831            cxx_method_decl = CXXMethodDecl::Create (*ast,
1832                                                     cxx_record_decl,
1833                                                     SourceLocation(),
1834                                                     DeclarationNameInfo (decl_name, SourceLocation()),
1835                                                     method_qual_type,
1836                                                     NULL, // TypeSourceInfo *
1837                                                     is_static,
1838                                                     SC_None,
1839                                                     is_inline,
1840                                                     false /*is_constexpr*/,
1841                                                     SourceLocation());
1842        }
1843    }
1844
1845    AccessSpecifier access_specifier = ConvertAccessTypeToAccessSpecifier (access);
1846
1847    cxx_method_decl->setAccess (access_specifier);
1848    cxx_method_decl->setVirtualAsWritten (is_virtual);
1849
1850    if (is_attr_used)
1851        cxx_method_decl->addAttr(::new (*ast) UsedAttr(SourceRange(), *ast));
1852
1853    // Populate the method decl with parameter decls
1854
1855    llvm::SmallVector<ParmVarDecl *, 12> params;
1856
1857    for (int param_index = 0;
1858         param_index < num_params;
1859         ++param_index)
1860    {
1861        params.push_back (ParmVarDecl::Create (*ast,
1862                                               cxx_method_decl,
1863                                               SourceLocation(),
1864                                               SourceLocation(),
1865                                               NULL, // anonymous
1866                                               method_function_prototype->getArgType(param_index),
1867                                               NULL,
1868                                               SC_None,
1869                                               SC_None,
1870                                               NULL));
1871    }
1872
1873    cxx_method_decl->setParams (ArrayRef<ParmVarDecl*>(params));
1874
1875    cxx_record_decl->addDecl (cxx_method_decl);
1876
1877    // Sometimes the debug info will mention a constructor (default/copy/move),
1878    // destructor, or assignment operator (copy/move) but there won't be any
1879    // version of this in the code. So we check if the function was artificially
1880    // generated and if it is trivial and this lets the compiler/backend know
1881    // that it can inline the IR for these when it needs to and we can avoid a
1882    // "missing function" error when running expressions.
1883
1884    if (is_artificial)
1885    {
1886        if (cxx_ctor_decl &&
1887            ((cxx_ctor_decl->isDefaultConstructor() && cxx_record_decl->hasTrivialDefaultConstructor ()) ||
1888             (cxx_ctor_decl->isCopyConstructor()    && cxx_record_decl->hasTrivialCopyConstructor    ()) ||
1889             (cxx_ctor_decl->isMoveConstructor()    && cxx_record_decl->hasTrivialMoveConstructor    ()) ))
1890        {
1891            cxx_ctor_decl->setDefaulted();
1892            cxx_ctor_decl->setTrivial(true);
1893        }
1894        else if (cxx_dtor_decl)
1895        {
1896            if (cxx_record_decl->hasTrivialDestructor())
1897            {
1898                cxx_dtor_decl->setDefaulted();
1899                cxx_dtor_decl->setTrivial(true);
1900            }
1901        }
1902        else if ((cxx_method_decl->isCopyAssignmentOperator() && cxx_record_decl->hasTrivialCopyAssignment()) ||
1903                 (cxx_method_decl->isMoveAssignmentOperator() && cxx_record_decl->hasTrivialMoveAssignment()))
1904        {
1905            cxx_method_decl->setDefaulted();
1906            cxx_method_decl->setTrivial(true);
1907        }
1908    }
1909
1910#ifdef LLDB_CONFIGURATION_DEBUG
1911    VerifyDecl(cxx_method_decl);
1912#endif
1913
1914//    printf ("decl->isPolymorphic()             = %i\n", cxx_record_decl->isPolymorphic());
1915//    printf ("decl->isAggregate()               = %i\n", cxx_record_decl->isAggregate());
1916//    printf ("decl->isPOD()                     = %i\n", cxx_record_decl->isPOD());
1917//    printf ("decl->isEmpty()                   = %i\n", cxx_record_decl->isEmpty());
1918//    printf ("decl->isAbstract()                = %i\n", cxx_record_decl->isAbstract());
1919//    printf ("decl->hasTrivialConstructor()     = %i\n", cxx_record_decl->hasTrivialConstructor());
1920//    printf ("decl->hasTrivialCopyConstructor() = %i\n", cxx_record_decl->hasTrivialCopyConstructor());
1921//    printf ("decl->hasTrivialCopyAssignment()  = %i\n", cxx_record_decl->hasTrivialCopyAssignment());
1922//    printf ("decl->hasTrivialDestructor()      = %i\n", cxx_record_decl->hasTrivialDestructor());
1923    return cxx_method_decl;
1924}
1925
1926clang::FieldDecl *
1927ClangASTContext::AddFieldToRecordType
1928(
1929    ASTContext *ast,
1930    clang_type_t record_clang_type,
1931    const char *name,
1932    clang_type_t field_type,
1933    AccessType access,
1934    uint32_t bitfield_bit_size
1935)
1936{
1937    if (record_clang_type == NULL || field_type == NULL)
1938        return NULL;
1939
1940    FieldDecl *field = NULL;
1941    IdentifierTable *identifier_table = &ast->Idents;
1942
1943    assert (ast != NULL);
1944    assert (identifier_table != NULL);
1945
1946    QualType record_qual_type(QualType::getFromOpaquePtr(record_clang_type));
1947
1948    const clang::Type *clang_type = record_qual_type.getTypePtr();
1949    if (clang_type)
1950    {
1951        const RecordType *record_type = dyn_cast<RecordType>(clang_type);
1952
1953        if (record_type)
1954        {
1955            RecordDecl *record_decl = record_type->getDecl();
1956
1957            clang::Expr *bit_width = NULL;
1958            if (bitfield_bit_size != 0)
1959            {
1960                APInt bitfield_bit_size_apint(ast->getTypeSize(ast->IntTy), bitfield_bit_size);
1961                bit_width = new (*ast)IntegerLiteral (*ast, bitfield_bit_size_apint, ast->IntTy, SourceLocation());
1962            }
1963            field = FieldDecl::Create (*ast,
1964                                       record_decl,
1965                                       SourceLocation(),
1966                                       SourceLocation(),
1967                                       name ? &identifier_table->get(name) : NULL, // Identifier
1968                                       QualType::getFromOpaquePtr(field_type), // Field type
1969                                       NULL,            // TInfo *
1970                                       bit_width,       // BitWidth
1971                                       false,           // Mutable
1972                                       ICIS_NoInit);    // HasInit
1973
1974            if (!name) {
1975                // Determine whether this field corresponds to an anonymous
1976                // struct or union.
1977                if (const TagType *TagT = field->getType()->getAs<TagType>()) {
1978                  if (RecordDecl *Rec = dyn_cast<RecordDecl>(TagT->getDecl()))
1979                    if (!Rec->getDeclName()) {
1980                      Rec->setAnonymousStructOrUnion(true);
1981                      field->setImplicit();
1982
1983                    }
1984                }
1985            }
1986
1987            field->setAccess (ConvertAccessTypeToAccessSpecifier (access));
1988
1989            if (field)
1990            {
1991                record_decl->addDecl(field);
1992
1993#ifdef LLDB_CONFIGURATION_DEBUG
1994                VerifyDecl(field);
1995#endif
1996            }
1997        }
1998        else
1999        {
2000            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(clang_type);
2001            if (objc_class_type)
2002            {
2003                bool is_synthesized = false;
2004                field = ClangASTContext::AddObjCClassIVar (ast,
2005                                                   record_clang_type,
2006                                                   name,
2007                                                   field_type,
2008                                                   access,
2009                                                   bitfield_bit_size,
2010                                                   is_synthesized);
2011            }
2012        }
2013    }
2014    return field;
2015}
2016
2017static clang::AccessSpecifier UnifyAccessSpecifiers (clang::AccessSpecifier lhs,
2018                                                     clang::AccessSpecifier rhs)
2019{
2020    clang::AccessSpecifier ret = lhs;
2021
2022    // Make the access equal to the stricter of the field and the nested field's access
2023    switch (ret)
2024    {
2025        case clang::AS_none:
2026            break;
2027        case clang::AS_private:
2028            break;
2029        case clang::AS_protected:
2030            if (rhs == AS_private)
2031                ret = AS_private;
2032            break;
2033        case clang::AS_public:
2034            ret = rhs;
2035            break;
2036    }
2037
2038    return ret;
2039}
2040
2041void
2042ClangASTContext::BuildIndirectFields (clang::ASTContext *ast,
2043                                      lldb::clang_type_t record_clang_type)
2044{
2045    QualType record_qual_type(QualType::getFromOpaquePtr(record_clang_type));
2046
2047    const RecordType *record_type = record_qual_type->getAs<RecordType>();
2048
2049    if (!record_type)
2050        return;
2051
2052    RecordDecl *record_decl = record_type->getDecl();
2053
2054    if (!record_decl)
2055        return;
2056
2057    typedef llvm::SmallVector <IndirectFieldDecl *, 1> IndirectFieldVector;
2058
2059    IndirectFieldVector indirect_fields;
2060    RecordDecl::field_iterator field_pos;
2061    RecordDecl::field_iterator field_end_pos = record_decl->field_end();
2062    RecordDecl::field_iterator last_field_pos = field_end_pos;
2063    for (field_pos = record_decl->field_begin(); field_pos != field_end_pos; last_field_pos = field_pos++)
2064    {
2065        if (field_pos->isAnonymousStructOrUnion())
2066        {
2067            QualType field_qual_type = field_pos->getType();
2068
2069            const RecordType *field_record_type = field_qual_type->getAs<RecordType>();
2070
2071            if (!field_record_type)
2072                continue;
2073
2074            RecordDecl *field_record_decl = field_record_type->getDecl();
2075
2076            if (!field_record_decl)
2077                continue;
2078
2079            for (RecordDecl::decl_iterator di = field_record_decl->decls_begin(), de = field_record_decl->decls_end();
2080                 di != de;
2081                 ++di)
2082            {
2083                if (FieldDecl *nested_field_decl = dyn_cast<FieldDecl>(*di))
2084                {
2085                    NamedDecl **chain = new (*ast) NamedDecl*[2];
2086                    chain[0] = *field_pos;
2087                    chain[1] = nested_field_decl;
2088                    IndirectFieldDecl *indirect_field = IndirectFieldDecl::Create(*ast,
2089                                                                                  record_decl,
2090                                                                                  SourceLocation(),
2091                                                                                  nested_field_decl->getIdentifier(),
2092                                                                                  nested_field_decl->getType(),
2093                                                                                  chain,
2094                                                                                  2);
2095
2096                    indirect_field->setAccess(UnifyAccessSpecifiers(field_pos->getAccess(),
2097                                                                    nested_field_decl->getAccess()));
2098
2099                    indirect_fields.push_back(indirect_field);
2100                }
2101                else if (IndirectFieldDecl *nested_indirect_field_decl = dyn_cast<IndirectFieldDecl>(*di))
2102                {
2103                    int nested_chain_size = nested_indirect_field_decl->getChainingSize();
2104                    NamedDecl **chain = new (*ast) NamedDecl*[nested_chain_size + 1];
2105                    chain[0] = *field_pos;
2106
2107                    int chain_index = 1;
2108                    for (IndirectFieldDecl::chain_iterator nci = nested_indirect_field_decl->chain_begin(),
2109                         nce = nested_indirect_field_decl->chain_end();
2110                         nci < nce;
2111                         ++nci)
2112                    {
2113                        chain[chain_index] = *nci;
2114                        chain_index++;
2115                    }
2116
2117                    IndirectFieldDecl *indirect_field = IndirectFieldDecl::Create(*ast,
2118                                                                                  record_decl,
2119                                                                                  SourceLocation(),
2120                                                                                  nested_indirect_field_decl->getIdentifier(),
2121                                                                                  nested_indirect_field_decl->getType(),
2122                                                                                  chain,
2123                                                                                  nested_chain_size + 1);
2124
2125                    indirect_field->setAccess(UnifyAccessSpecifiers(field_pos->getAccess(),
2126                                                                    nested_indirect_field_decl->getAccess()));
2127
2128                    indirect_fields.push_back(indirect_field);
2129                }
2130            }
2131        }
2132    }
2133
2134    // Check the last field to see if it has an incomplete array type as its
2135    // last member and if it does, the tell the record decl about it
2136    if (last_field_pos != field_end_pos)
2137    {
2138        if (last_field_pos->getType()->isIncompleteArrayType())
2139            record_decl->hasFlexibleArrayMember();
2140    }
2141
2142    for (IndirectFieldVector::iterator ifi = indirect_fields.begin(), ife = indirect_fields.end();
2143         ifi < ife;
2144         ++ifi)
2145    {
2146        record_decl->addDecl(*ifi);
2147    }
2148}
2149
2150bool
2151ClangASTContext::FieldIsBitfield (FieldDecl* field, uint32_t& bitfield_bit_size)
2152{
2153    return FieldIsBitfield(getASTContext(), field, bitfield_bit_size);
2154}
2155
2156bool
2157ClangASTContext::FieldIsBitfield
2158(
2159    ASTContext *ast,
2160    FieldDecl* field,
2161    uint32_t& bitfield_bit_size
2162)
2163{
2164    if (ast == NULL || field == NULL)
2165        return false;
2166
2167    if (field->isBitField())
2168    {
2169        Expr* bit_width_expr = field->getBitWidth();
2170        if (bit_width_expr)
2171        {
2172            llvm::APSInt bit_width_apsint;
2173            if (bit_width_expr->isIntegerConstantExpr(bit_width_apsint, *ast))
2174            {
2175                bitfield_bit_size = bit_width_apsint.getLimitedValue(UINT32_MAX);
2176                return true;
2177            }
2178        }
2179    }
2180    return false;
2181}
2182
2183bool
2184ClangASTContext::RecordHasFields (const RecordDecl *record_decl)
2185{
2186    if (record_decl == NULL)
2187        return false;
2188
2189    if (!record_decl->field_empty())
2190        return true;
2191
2192    // No fields, lets check this is a CXX record and check the base classes
2193    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
2194    if (cxx_record_decl)
2195    {
2196        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
2197        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
2198             base_class != base_class_end;
2199             ++base_class)
2200        {
2201            const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
2202            if (RecordHasFields(base_class_decl))
2203                return true;
2204        }
2205    }
2206    return false;
2207}
2208
2209void
2210ClangASTContext::SetDefaultAccessForRecordFields (clang_type_t clang_type, int default_accessibility, int *assigned_accessibilities, size_t num_assigned_accessibilities)
2211{
2212    if (clang_type)
2213    {
2214        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
2215
2216        const RecordType *record_type = dyn_cast<RecordType>(qual_type.getTypePtr());
2217        if (record_type)
2218        {
2219            RecordDecl *record_decl = record_type->getDecl();
2220            if (record_decl)
2221            {
2222                uint32_t field_idx;
2223                RecordDecl::field_iterator field, field_end;
2224                for (field = record_decl->field_begin(), field_end = record_decl->field_end(), field_idx = 0;
2225                     field != field_end;
2226                     ++field, ++field_idx)
2227                {
2228                    // If no accessibility was assigned, assign the correct one
2229                    if (field_idx < num_assigned_accessibilities && assigned_accessibilities[field_idx] == clang::AS_none)
2230                        field->setAccess ((AccessSpecifier)default_accessibility);
2231                }
2232            }
2233        }
2234    }
2235}
2236
2237#pragma mark C++ Base Classes
2238
2239CXXBaseSpecifier *
2240ClangASTContext::CreateBaseClassSpecifier (clang_type_t base_class_type, AccessType access, bool is_virtual, bool base_of_class)
2241{
2242    if (base_class_type)
2243        return new CXXBaseSpecifier (SourceRange(),
2244                                     is_virtual,
2245                                     base_of_class,
2246                                     ConvertAccessTypeToAccessSpecifier (access),
2247                                     getASTContext()->getTrivialTypeSourceInfo (QualType::getFromOpaquePtr(base_class_type)),
2248                                     SourceLocation());
2249    return NULL;
2250}
2251
2252void
2253ClangASTContext::DeleteBaseClassSpecifiers (CXXBaseSpecifier **base_classes, unsigned num_base_classes)
2254{
2255    for (unsigned i=0; i<num_base_classes; ++i)
2256    {
2257        delete base_classes[i];
2258        base_classes[i] = NULL;
2259    }
2260}
2261
2262bool
2263ClangASTContext::SetBaseClassesForClassType (clang_type_t class_clang_type, CXXBaseSpecifier const * const *base_classes, unsigned num_base_classes)
2264{
2265    if (class_clang_type)
2266    {
2267        CXXRecordDecl *cxx_record_decl = QualType::getFromOpaquePtr(class_clang_type)->getAsCXXRecordDecl();
2268        if (cxx_record_decl)
2269        {
2270            cxx_record_decl->setBases(base_classes, num_base_classes);
2271            return true;
2272        }
2273    }
2274    return false;
2275}
2276#pragma mark Objective C Classes
2277
2278clang_type_t
2279ClangASTContext::CreateObjCClass
2280(
2281    const char *name,
2282    DeclContext *decl_ctx,
2283    bool isForwardDecl,
2284    bool isInternal,
2285    ClangASTMetadata *metadata
2286)
2287{
2288    ASTContext *ast = getASTContext();
2289    assert (ast != NULL);
2290    assert (name && name[0]);
2291    if (decl_ctx == NULL)
2292        decl_ctx = ast->getTranslationUnitDecl();
2293
2294    // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
2295    // we will need to update this code. I was told to currently always use
2296    // the CXXRecordDecl class since we often don't know from debug information
2297    // if something is struct or a class, so we default to always use the more
2298    // complete definition just in case.
2299    ObjCInterfaceDecl *decl = ObjCInterfaceDecl::Create (*ast,
2300                                                         decl_ctx,
2301                                                         SourceLocation(),
2302                                                         &ast->Idents.get(name),
2303                                                         NULL,
2304                                                         SourceLocation(),
2305                                                         /*isForwardDecl,*/
2306                                                         isInternal);
2307
2308    if (decl && metadata)
2309        SetMetadata(ast, (uintptr_t)decl, *metadata);
2310
2311    return ast->getObjCInterfaceType(decl).getAsOpaquePtr();
2312}
2313
2314bool
2315ClangASTContext::SetObjCSuperClass (clang_type_t class_opaque_type, clang_type_t super_opaque_type)
2316{
2317    if (class_opaque_type && super_opaque_type)
2318    {
2319        QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2320        QualType super_qual_type(QualType::getFromOpaquePtr(super_opaque_type));
2321        const clang::Type *class_type = class_qual_type.getTypePtr();
2322        const clang::Type *super_type = super_qual_type.getTypePtr();
2323        if (class_type && super_type)
2324        {
2325            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2326            const ObjCObjectType *objc_super_type = dyn_cast<ObjCObjectType>(super_type);
2327            if (objc_class_type && objc_super_type)
2328            {
2329                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2330                ObjCInterfaceDecl *super_interface_decl = objc_super_type->getInterface();
2331                if (class_interface_decl && super_interface_decl)
2332                {
2333                    class_interface_decl->setSuperClass(super_interface_decl);
2334                    return true;
2335                }
2336            }
2337        }
2338    }
2339    return false;
2340}
2341
2342
2343FieldDecl *
2344ClangASTContext::AddObjCClassIVar
2345(
2346    ASTContext *ast,
2347    clang_type_t class_opaque_type,
2348    const char *name,
2349    clang_type_t ivar_opaque_type,
2350    AccessType access,
2351    uint32_t bitfield_bit_size,
2352    bool is_synthesized
2353)
2354{
2355    if (class_opaque_type == NULL || ivar_opaque_type == NULL)
2356        return NULL;
2357
2358    ObjCIvarDecl *field = NULL;
2359
2360    IdentifierTable *identifier_table = &ast->Idents;
2361
2362    assert (ast != NULL);
2363    assert (identifier_table != NULL);
2364
2365    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2366
2367    const clang::Type *class_type = class_qual_type.getTypePtr();
2368    if (class_type)
2369    {
2370        const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2371
2372        if (objc_class_type)
2373        {
2374            ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2375
2376            if (class_interface_decl)
2377            {
2378                clang::Expr *bit_width = NULL;
2379                if (bitfield_bit_size != 0)
2380                {
2381                    APInt bitfield_bit_size_apint(ast->getTypeSize(ast->IntTy), bitfield_bit_size);
2382                    bit_width = new (*ast)IntegerLiteral (*ast, bitfield_bit_size_apint, ast->IntTy, SourceLocation());
2383                }
2384
2385                field = ObjCIvarDecl::Create (*ast,
2386                                              class_interface_decl,
2387                                              SourceLocation(),
2388                                              SourceLocation(),
2389                                              name ? &identifier_table->get(name) : NULL, // Identifier
2390                                              QualType::getFromOpaquePtr(ivar_opaque_type), // Field type
2391                                              NULL, // TypeSourceInfo *
2392                                              ConvertAccessTypeToObjCIvarAccessControl (access),
2393                                              bit_width,
2394                                              is_synthesized);
2395
2396                if (field)
2397                {
2398                    class_interface_decl->addDecl(field);
2399
2400#ifdef LLDB_CONFIGURATION_DEBUG
2401                    VerifyDecl(field);
2402#endif
2403
2404                    return field;
2405                }
2406            }
2407        }
2408    }
2409    return NULL;
2410}
2411
2412bool
2413ClangASTContext::AddObjCClassProperty
2414(
2415    ASTContext *ast,
2416    clang_type_t class_opaque_type,
2417    const char *property_name,
2418    clang_type_t property_opaque_type,
2419    ObjCIvarDecl *ivar_decl,
2420    const char *property_setter_name,
2421    const char *property_getter_name,
2422    uint32_t property_attributes,
2423    ClangASTMetadata *metadata
2424)
2425{
2426    if (class_opaque_type == NULL || property_name == NULL || property_name[0] == '\0')
2427        return false;
2428
2429    IdentifierTable *identifier_table = &ast->Idents;
2430
2431    assert (ast != NULL);
2432    assert (identifier_table != NULL);
2433
2434    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2435    const clang::Type *class_type = class_qual_type.getTypePtr();
2436    if (class_type)
2437    {
2438        const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2439
2440        if (objc_class_type)
2441        {
2442            ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2443
2444            clang_type_t property_opaque_type_to_access = NULL;
2445
2446            if (property_opaque_type)
2447                property_opaque_type_to_access = property_opaque_type;
2448            else if (ivar_decl)
2449                property_opaque_type_to_access = ivar_decl->getType().getAsOpaquePtr();
2450
2451            if (class_interface_decl && property_opaque_type_to_access)
2452            {
2453                clang::TypeSourceInfo *prop_type_source;
2454                if (ivar_decl)
2455                    prop_type_source = ast->getTrivialTypeSourceInfo (ivar_decl->getType());
2456                else
2457                    prop_type_source = ast->getTrivialTypeSourceInfo (QualType::getFromOpaquePtr(property_opaque_type));
2458
2459                ObjCPropertyDecl *property_decl = ObjCPropertyDecl::Create(*ast,
2460                                                                           class_interface_decl,
2461                                                                           SourceLocation(), // Source Location
2462                                                                           &identifier_table->get(property_name),
2463                                                                           SourceLocation(), //Source Location for AT
2464                                                                           SourceLocation(), //Source location for (
2465                                                                           prop_type_source
2466                                                                           );
2467
2468                if (property_decl)
2469                {
2470                    if (metadata)
2471                        SetMetadata(ast, (uintptr_t)property_decl, *metadata);
2472
2473                    class_interface_decl->addDecl (property_decl);
2474
2475                    Selector setter_sel, getter_sel;
2476
2477                    if (property_setter_name != NULL)
2478                    {
2479                        std::string property_setter_no_colon(property_setter_name, strlen(property_setter_name) - 1);
2480                        clang::IdentifierInfo *setter_ident = &identifier_table->get(property_setter_no_colon.c_str());
2481                        setter_sel = ast->Selectors.getSelector(1, &setter_ident);
2482                    }
2483                    else if (!(property_attributes & DW_APPLE_PROPERTY_readonly))
2484                    {
2485                        std::string setter_sel_string("set");
2486                        setter_sel_string.push_back(::toupper(property_name[0]));
2487                        setter_sel_string.append(&property_name[1]);
2488                        clang::IdentifierInfo *setter_ident = &identifier_table->get(setter_sel_string.c_str());
2489                        setter_sel = ast->Selectors.getSelector(1, &setter_ident);
2490                    }
2491                    property_decl->setSetterName(setter_sel);
2492                    property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_setter);
2493
2494                    if (property_getter_name != NULL)
2495                    {
2496                        clang::IdentifierInfo *getter_ident = &identifier_table->get(property_getter_name);
2497                        getter_sel = ast->Selectors.getSelector(0, &getter_ident);
2498                    }
2499                    else
2500                    {
2501                        clang::IdentifierInfo *getter_ident = &identifier_table->get(property_name);
2502                        getter_sel = ast->Selectors.getSelector(0, &getter_ident);
2503                    }
2504                    property_decl->setGetterName(getter_sel);
2505                    property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_getter);
2506
2507                    if (ivar_decl)
2508                        property_decl->setPropertyIvarDecl (ivar_decl);
2509
2510                    if (property_attributes & DW_APPLE_PROPERTY_readonly)
2511                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_readonly);
2512                    if (property_attributes & DW_APPLE_PROPERTY_readwrite)
2513                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_readwrite);
2514                    if (property_attributes & DW_APPLE_PROPERTY_assign)
2515                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_assign);
2516                    if (property_attributes & DW_APPLE_PROPERTY_retain)
2517                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_retain);
2518                    if (property_attributes & DW_APPLE_PROPERTY_copy)
2519                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_copy);
2520                    if (property_attributes & DW_APPLE_PROPERTY_nonatomic)
2521                        property_decl->setPropertyAttributes (clang::ObjCPropertyDecl::OBJC_PR_nonatomic);
2522
2523                    if (!getter_sel.isNull() && !class_interface_decl->lookupInstanceMethod(getter_sel))
2524                    {
2525                        QualType result_type = QualType::getFromOpaquePtr(property_opaque_type_to_access);
2526
2527                        const bool isInstance = true;
2528                        const bool isVariadic = false;
2529                        const bool isSynthesized = false;
2530                        const bool isImplicitlyDeclared = true;
2531                        const bool isDefined = false;
2532                        const ObjCMethodDecl::ImplementationControl impControl = ObjCMethodDecl::None;
2533                        const bool HasRelatedResultType = false;
2534
2535                        ObjCMethodDecl *getter = ObjCMethodDecl::Create(*ast,
2536                                                                        SourceLocation(),
2537                                                                        SourceLocation(),
2538                                                                        getter_sel,
2539                                                                        result_type,
2540                                                                        NULL,
2541                                                                        class_interface_decl,
2542                                                                        isInstance,
2543                                                                        isVariadic,
2544                                                                        isSynthesized,
2545                                                                        isImplicitlyDeclared,
2546                                                                        isDefined,
2547                                                                        impControl,
2548                                                                        HasRelatedResultType);
2549
2550                        if (getter && metadata)
2551                            SetMetadata(ast, (uintptr_t)getter, *metadata);
2552
2553                        getter->setMethodParams(*ast, ArrayRef<ParmVarDecl*>(), ArrayRef<SourceLocation>());
2554
2555                        class_interface_decl->addDecl(getter);
2556                    }
2557
2558                    if (!setter_sel.isNull() && !class_interface_decl->lookupInstanceMethod(setter_sel))
2559                    {
2560                        QualType result_type = ast->VoidTy;
2561
2562                        const bool isInstance = true;
2563                        const bool isVariadic = false;
2564                        const bool isSynthesized = false;
2565                        const bool isImplicitlyDeclared = true;
2566                        const bool isDefined = false;
2567                        const ObjCMethodDecl::ImplementationControl impControl = ObjCMethodDecl::None;
2568                        const bool HasRelatedResultType = false;
2569
2570                        ObjCMethodDecl *setter = ObjCMethodDecl::Create(*ast,
2571                                                                        SourceLocation(),
2572                                                                        SourceLocation(),
2573                                                                        setter_sel,
2574                                                                        result_type,
2575                                                                        NULL,
2576                                                                        class_interface_decl,
2577                                                                        isInstance,
2578                                                                        isVariadic,
2579                                                                        isSynthesized,
2580                                                                        isImplicitlyDeclared,
2581                                                                        isDefined,
2582                                                                        impControl,
2583                                                                        HasRelatedResultType);
2584
2585                        if (setter && metadata)
2586                            SetMetadata(ast, (uintptr_t)setter, *metadata);
2587
2588                        llvm::SmallVector<ParmVarDecl *, 1> params;
2589
2590                        params.push_back (ParmVarDecl::Create (*ast,
2591                                                               setter,
2592                                                               SourceLocation(),
2593                                                               SourceLocation(),
2594                                                               NULL, // anonymous
2595                                                               QualType::getFromOpaquePtr(property_opaque_type_to_access),
2596                                                               NULL,
2597                                                               SC_Auto,
2598                                                               SC_Auto,
2599                                                               NULL));
2600
2601                        setter->setMethodParams(*ast, ArrayRef<ParmVarDecl*>(params), ArrayRef<SourceLocation>());
2602
2603                        class_interface_decl->addDecl(setter);
2604                    }
2605
2606                    return true;
2607                }
2608            }
2609        }
2610    }
2611    return false;
2612}
2613
2614bool
2615ClangASTContext::ObjCTypeHasIVars (clang_type_t class_opaque_type, bool check_superclass)
2616{
2617    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2618
2619    const clang::Type *class_type = class_qual_type.getTypePtr();
2620    if (class_type)
2621    {
2622        const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2623
2624        if (objc_class_type)
2625            return ObjCDeclHasIVars (objc_class_type->getInterface(), check_superclass);
2626    }
2627    return false;
2628}
2629
2630bool
2631ClangASTContext::ObjCDeclHasIVars (ObjCInterfaceDecl *class_interface_decl, bool check_superclass)
2632{
2633    while (class_interface_decl)
2634    {
2635        if (class_interface_decl->ivar_size() > 0)
2636            return true;
2637
2638        if (check_superclass)
2639            class_interface_decl = class_interface_decl->getSuperClass();
2640        else
2641            break;
2642    }
2643    return false;
2644}
2645
2646ObjCMethodDecl *
2647ClangASTContext::AddMethodToObjCObjectType (ASTContext *ast,
2648                                            clang_type_t class_opaque_type,
2649                                            const char *name,  // the full symbol name as seen in the symbol table ("-[NString stringWithCString:]")
2650                                            clang_type_t method_opaque_type,
2651                                            lldb::AccessType access,
2652                                            bool is_artificial)
2653{
2654    if (class_opaque_type == NULL || method_opaque_type == NULL)
2655        return NULL;
2656
2657    IdentifierTable *identifier_table = &ast->Idents;
2658
2659    assert (ast != NULL);
2660    assert (identifier_table != NULL);
2661
2662    QualType class_qual_type(QualType::getFromOpaquePtr(class_opaque_type));
2663
2664    const clang::Type *class_type = class_qual_type.getTypePtr();
2665    if (class_type == NULL)
2666        return NULL;
2667
2668    const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(class_type);
2669
2670    if (objc_class_type == NULL)
2671        return NULL;
2672
2673    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
2674
2675    if (class_interface_decl == NULL)
2676        return NULL;
2677
2678    const char *selector_start = ::strchr (name, ' ');
2679    if (selector_start == NULL)
2680        return NULL;
2681
2682    selector_start++;
2683    llvm::SmallVector<IdentifierInfo *, 12> selector_idents;
2684
2685    size_t len = 0;
2686    const char *start;
2687    //printf ("name = '%s'\n", name);
2688
2689    unsigned num_selectors_with_args = 0;
2690    for (start = selector_start;
2691         start && *start != '\0' && *start != ']';
2692         start += len)
2693    {
2694        len = ::strcspn(start, ":]");
2695        bool has_arg = (start[len] == ':');
2696        if (has_arg)
2697            ++num_selectors_with_args;
2698        selector_idents.push_back (&identifier_table->get (StringRef (start, len)));
2699        if (has_arg)
2700            len += 1;
2701    }
2702
2703
2704    if (selector_idents.size() == 0)
2705        return 0;
2706
2707    clang::Selector method_selector = ast->Selectors.getSelector (num_selectors_with_args ? selector_idents.size() : 0,
2708                                                                          selector_idents.data());
2709
2710    QualType method_qual_type (QualType::getFromOpaquePtr (method_opaque_type));
2711
2712    // Populate the method decl with parameter decls
2713    const clang::Type *method_type(method_qual_type.getTypePtr());
2714
2715    if (method_type == NULL)
2716        return NULL;
2717
2718    const FunctionProtoType *method_function_prototype (dyn_cast<FunctionProtoType>(method_type));
2719
2720    if (!method_function_prototype)
2721        return NULL;
2722
2723
2724    bool is_variadic = false;
2725    bool is_synthesized = false;
2726    bool is_defined = false;
2727    ObjCMethodDecl::ImplementationControl imp_control = ObjCMethodDecl::None;
2728
2729    const unsigned num_args = method_function_prototype->getNumArgs();
2730
2731    if (num_args != num_selectors_with_args)
2732        return NULL; // some debug information is corrupt.  We are not going to deal with it.
2733
2734    ObjCMethodDecl *objc_method_decl = ObjCMethodDecl::Create (*ast,
2735                                                               SourceLocation(), // beginLoc,
2736                                                               SourceLocation(), // endLoc,
2737                                                               method_selector,
2738                                                               method_function_prototype->getResultType(),
2739                                                               NULL, // TypeSourceInfo *ResultTInfo,
2740                                                               GetDeclContextForType (class_opaque_type),
2741                                                               name[0] == '-',
2742                                                               is_variadic,
2743                                                               is_synthesized,
2744                                                               true, // is_implicitly_declared; we force this to true because we don't have source locations
2745                                                               is_defined,
2746                                                               imp_control,
2747                                                               false /*has_related_result_type*/);
2748
2749
2750    if (objc_method_decl == NULL)
2751        return NULL;
2752
2753    if (num_args > 0)
2754    {
2755        llvm::SmallVector<ParmVarDecl *, 12> params;
2756
2757        for (int param_index = 0; param_index < num_args; ++param_index)
2758        {
2759            params.push_back (ParmVarDecl::Create (*ast,
2760                                                   objc_method_decl,
2761                                                   SourceLocation(),
2762                                                   SourceLocation(),
2763                                                   NULL, // anonymous
2764                                                   method_function_prototype->getArgType(param_index),
2765                                                   NULL,
2766                                                   SC_Auto,
2767                                                   SC_Auto,
2768                                                   NULL));
2769        }
2770
2771        objc_method_decl->setMethodParams(*ast, ArrayRef<ParmVarDecl*>(params), ArrayRef<SourceLocation>());
2772    }
2773
2774    class_interface_decl->addDecl (objc_method_decl);
2775
2776#ifdef LLDB_CONFIGURATION_DEBUG
2777    VerifyDecl(objc_method_decl);
2778#endif
2779
2780    return objc_method_decl;
2781}
2782
2783size_t
2784ClangASTContext::GetNumTemplateArguments (clang::ASTContext *ast, clang_type_t clang_type)
2785{
2786    if (clang_type)
2787    {
2788        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2789
2790        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2791        switch (type_class)
2792        {
2793            case clang::Type::Record:
2794                if (GetCompleteQualType (ast, qual_type))
2795                {
2796                    const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
2797                    if (cxx_record_decl)
2798                    {
2799                        const ClassTemplateSpecializationDecl *template_decl = dyn_cast<ClassTemplateSpecializationDecl>(cxx_record_decl);
2800                        if (template_decl)
2801                            return template_decl->getTemplateArgs().size();
2802                    }
2803                }
2804                break;
2805
2806            case clang::Type::Typedef:
2807                return ClangASTContext::GetNumTemplateArguments (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
2808
2809            case clang::Type::Elaborated:
2810                return ClangASTContext::GetNumTemplateArguments (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
2811
2812            default:
2813                break;
2814        }
2815    }
2816    return 0;
2817}
2818
2819clang_type_t
2820ClangASTContext::GetTemplateArgument (clang::ASTContext *ast, clang_type_t clang_type, size_t arg_idx, lldb::TemplateArgumentKind &kind)
2821{
2822    if (clang_type)
2823    {
2824        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2825
2826        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2827        switch (type_class)
2828        {
2829            case clang::Type::Record:
2830                if (GetCompleteQualType (ast, qual_type))
2831                {
2832                    const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
2833                    if (cxx_record_decl)
2834                    {
2835                        const ClassTemplateSpecializationDecl *template_decl = dyn_cast<ClassTemplateSpecializationDecl>(cxx_record_decl);
2836                        if (template_decl && arg_idx < template_decl->getTemplateArgs().size())
2837                        {
2838                            const TemplateArgument &template_arg = template_decl->getTemplateArgs()[arg_idx];
2839                            switch (template_arg.getKind())
2840                            {
2841                                case clang::TemplateArgument::Null:
2842                                    kind = eTemplateArgumentKindNull;
2843                                    return NULL;
2844
2845                                case clang::TemplateArgument::Type:
2846                                    kind = eTemplateArgumentKindType;
2847                                    return template_arg.getAsType().getAsOpaquePtr();
2848
2849                                case clang::TemplateArgument::Declaration:
2850                                    kind = eTemplateArgumentKindDeclaration;
2851                                    return NULL;
2852
2853                                case clang::TemplateArgument::Integral:
2854                                    kind = eTemplateArgumentKindIntegral;
2855                                    return template_arg.getIntegralType().getAsOpaquePtr();
2856
2857                                case clang::TemplateArgument::Template:
2858                                    kind = eTemplateArgumentKindTemplate;
2859                                    return NULL;
2860
2861                                case clang::TemplateArgument::TemplateExpansion:
2862                                    kind = eTemplateArgumentKindTemplateExpansion;
2863                                    return NULL;
2864
2865                                case clang::TemplateArgument::Expression:
2866                                    kind = eTemplateArgumentKindExpression;
2867                                    return NULL;
2868
2869                                case clang::TemplateArgument::Pack:
2870                                    kind = eTemplateArgumentKindPack;
2871                                    return NULL;
2872
2873                                default:
2874                                    assert (!"Unhandled TemplateArgument::ArgKind");
2875                                    kind = eTemplateArgumentKindNull;
2876                                    return NULL;
2877                            }
2878                        }
2879                    }
2880                }
2881                break;
2882
2883            case clang::Type::Typedef:
2884                return ClangASTContext::GetTemplateArgument (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(), arg_idx, kind);
2885
2886            case clang::Type::Elaborated:
2887                return ClangASTContext::GetTemplateArgument (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(), arg_idx, kind);
2888
2889            default:
2890                break;
2891        }
2892    }
2893    kind = eTemplateArgumentKindNull;
2894    return NULL;
2895}
2896
2897uint32_t
2898ClangASTContext::GetTypeInfo
2899(
2900    clang_type_t clang_type,
2901    clang::ASTContext *ast,
2902    clang_type_t *pointee_or_element_clang_type
2903)
2904{
2905    if (clang_type == NULL)
2906        return 0;
2907
2908    if (pointee_or_element_clang_type)
2909        *pointee_or_element_clang_type = NULL;
2910
2911    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2912
2913    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2914    switch (type_class)
2915    {
2916    case clang::Type::Builtin:
2917        switch (cast<clang::BuiltinType>(qual_type)->getKind())
2918        {
2919        case clang::BuiltinType::ObjCId:
2920        case clang::BuiltinType::ObjCClass:
2921            if (ast && pointee_or_element_clang_type)
2922                *pointee_or_element_clang_type = ast->ObjCBuiltinClassTy.getAsOpaquePtr();
2923            return eTypeIsBuiltIn | eTypeIsPointer | eTypeHasValue;
2924                break;
2925        case clang::BuiltinType::Bool:
2926        case clang::BuiltinType::Char_U:
2927        case clang::BuiltinType::UChar:
2928        case clang::BuiltinType::WChar_U:
2929        case clang::BuiltinType::Char16:
2930        case clang::BuiltinType::Char32:
2931        case clang::BuiltinType::UShort:
2932        case clang::BuiltinType::UInt:
2933        case clang::BuiltinType::ULong:
2934        case clang::BuiltinType::ULongLong:
2935        case clang::BuiltinType::UInt128:
2936        case clang::BuiltinType::Char_S:
2937        case clang::BuiltinType::SChar:
2938        case clang::BuiltinType::WChar_S:
2939        case clang::BuiltinType::Short:
2940        case clang::BuiltinType::Int:
2941        case clang::BuiltinType::Long:
2942        case clang::BuiltinType::LongLong:
2943        case clang::BuiltinType::Int128:
2944        case clang::BuiltinType::Float:
2945        case clang::BuiltinType::Double:
2946        case clang::BuiltinType::LongDouble:
2947                return eTypeIsBuiltIn | eTypeHasValue | eTypeIsScalar;
2948        default:
2949            break;
2950        }
2951        return eTypeIsBuiltIn | eTypeHasValue;
2952
2953    case clang::Type::BlockPointer:
2954        if (pointee_or_element_clang_type)
2955            *pointee_or_element_clang_type = qual_type->getPointeeType().getAsOpaquePtr();
2956        return eTypeIsPointer | eTypeHasChildren | eTypeIsBlock;
2957
2958    case clang::Type::Complex:                          return eTypeIsBuiltIn | eTypeHasValue;
2959
2960    case clang::Type::ConstantArray:
2961    case clang::Type::DependentSizedArray:
2962    case clang::Type::IncompleteArray:
2963    case clang::Type::VariableArray:
2964        if (pointee_or_element_clang_type)
2965            *pointee_or_element_clang_type = cast<ArrayType>(qual_type.getTypePtr())->getElementType().getAsOpaquePtr();
2966        return eTypeHasChildren | eTypeIsArray;
2967
2968    case clang::Type::DependentName:                    return 0;
2969    case clang::Type::DependentSizedExtVector:          return eTypeHasChildren | eTypeIsVector;
2970    case clang::Type::DependentTemplateSpecialization:  return eTypeIsTemplate;
2971    case clang::Type::Decltype:                         return 0;
2972
2973    case clang::Type::Enum:
2974        if (pointee_or_element_clang_type)
2975            *pointee_or_element_clang_type = cast<EnumType>(qual_type)->getDecl()->getIntegerType().getAsOpaquePtr();
2976        return eTypeIsEnumeration | eTypeHasValue;
2977
2978    case clang::Type::Elaborated:
2979        return ClangASTContext::GetTypeInfo (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
2980                                             ast,
2981                                             pointee_or_element_clang_type);
2982    case clang::Type::ExtVector:                        return eTypeHasChildren | eTypeIsVector;
2983    case clang::Type::FunctionProto:                    return eTypeIsFuncPrototype | eTypeHasValue;
2984    case clang::Type::FunctionNoProto:                  return eTypeIsFuncPrototype | eTypeHasValue;
2985    case clang::Type::InjectedClassName:                return 0;
2986
2987    case clang::Type::LValueReference:
2988    case clang::Type::RValueReference:
2989        if (pointee_or_element_clang_type)
2990            *pointee_or_element_clang_type = cast<ReferenceType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr();
2991        return eTypeHasChildren | eTypeIsReference | eTypeHasValue;
2992
2993    case clang::Type::MemberPointer:                    return eTypeIsPointer   | eTypeIsMember | eTypeHasValue;
2994
2995    case clang::Type::ObjCObjectPointer:
2996        if (pointee_or_element_clang_type)
2997            *pointee_or_element_clang_type = qual_type->getPointeeType().getAsOpaquePtr();
2998        return eTypeHasChildren | eTypeIsObjC | eTypeIsClass | eTypeIsPointer | eTypeHasValue;
2999
3000    case clang::Type::ObjCObject:                       return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
3001    case clang::Type::ObjCInterface:                    return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
3002
3003    case clang::Type::Pointer:
3004        if (pointee_or_element_clang_type)
3005            *pointee_or_element_clang_type = qual_type->getPointeeType().getAsOpaquePtr();
3006        return eTypeHasChildren | eTypeIsPointer | eTypeHasValue;
3007
3008    case clang::Type::Record:
3009        if (qual_type->getAsCXXRecordDecl())
3010            return eTypeHasChildren | eTypeIsClass | eTypeIsCPlusPlus;
3011        else
3012            return eTypeHasChildren | eTypeIsStructUnion;
3013        break;
3014    case clang::Type::SubstTemplateTypeParm:            return eTypeIsTemplate;
3015    case clang::Type::TemplateTypeParm:                 return eTypeIsTemplate;
3016    case clang::Type::TemplateSpecialization:           return eTypeIsTemplate;
3017
3018    case clang::Type::Typedef:
3019        return eTypeIsTypedef | ClangASTContext::GetTypeInfo (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3020                                                                  ast,
3021                                                                  pointee_or_element_clang_type);
3022
3023    case clang::Type::TypeOfExpr:                       return 0;
3024    case clang::Type::TypeOf:                           return 0;
3025    case clang::Type::UnresolvedUsing:                  return 0;
3026    case clang::Type::Vector:                           return eTypeHasChildren | eTypeIsVector;
3027    default:                                            return 0;
3028    }
3029    return 0;
3030}
3031
3032
3033#pragma mark Aggregate Types
3034
3035bool
3036ClangASTContext::IsAggregateType (clang_type_t clang_type)
3037{
3038    if (clang_type == NULL)
3039        return false;
3040
3041    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
3042
3043    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3044    switch (type_class)
3045    {
3046    case clang::Type::IncompleteArray:
3047    case clang::Type::VariableArray:
3048    case clang::Type::ConstantArray:
3049    case clang::Type::ExtVector:
3050    case clang::Type::Vector:
3051    case clang::Type::Record:
3052    case clang::Type::ObjCObject:
3053    case clang::Type::ObjCInterface:
3054        return true;
3055    case clang::Type::Elaborated:
3056        return ClangASTContext::IsAggregateType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3057    case clang::Type::Typedef:
3058        return ClangASTContext::IsAggregateType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3059
3060    default:
3061        break;
3062    }
3063    // The clang type does have a value
3064    return false;
3065}
3066
3067uint32_t
3068ClangASTContext::GetNumChildren (clang::ASTContext *ast, clang_type_t clang_type, bool omit_empty_base_classes)
3069{
3070    if (clang_type == NULL)
3071        return 0;
3072
3073    uint32_t num_children = 0;
3074    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3075    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3076    switch (type_class)
3077    {
3078    case clang::Type::Builtin:
3079        switch (cast<clang::BuiltinType>(qual_type)->getKind())
3080        {
3081        case clang::BuiltinType::ObjCId:    // child is Class
3082        case clang::BuiltinType::ObjCClass: // child is Class
3083            num_children = 1;
3084            break;
3085
3086        default:
3087            break;
3088        }
3089        break;
3090
3091    case clang::Type::Complex: return 0;
3092
3093    case clang::Type::Record:
3094        if (GetCompleteQualType (ast, qual_type))
3095        {
3096            const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
3097            const RecordDecl *record_decl = record_type->getDecl();
3098            assert(record_decl);
3099            const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
3100            if (cxx_record_decl)
3101            {
3102                if (omit_empty_base_classes)
3103                {
3104                    // Check each base classes to see if it or any of its
3105                    // base classes contain any fields. This can help
3106                    // limit the noise in variable views by not having to
3107                    // show base classes that contain no members.
3108                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3109                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
3110                         base_class != base_class_end;
3111                         ++base_class)
3112                    {
3113                        const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3114
3115                        // Skip empty base classes
3116                        if (RecordHasFields(base_class_decl) == false)
3117                            continue;
3118
3119                        num_children++;
3120                    }
3121                }
3122                else
3123                {
3124                    // Include all base classes
3125                    num_children += cxx_record_decl->getNumBases();
3126                }
3127
3128            }
3129            RecordDecl::field_iterator field, field_end;
3130            for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field)
3131                ++num_children;
3132        }
3133        break;
3134
3135    case clang::Type::ObjCObject:
3136    case clang::Type::ObjCInterface:
3137        if (GetCompleteQualType (ast, qual_type))
3138        {
3139            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
3140            assert (objc_class_type);
3141            if (objc_class_type)
3142            {
3143                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3144
3145                if (class_interface_decl)
3146                {
3147
3148                    ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
3149                    if (superclass_interface_decl)
3150                    {
3151                        if (omit_empty_base_classes)
3152                        {
3153                            if (ClangASTContext::ObjCDeclHasIVars (superclass_interface_decl, true))
3154                                ++num_children;
3155                        }
3156                        else
3157                            ++num_children;
3158                    }
3159
3160                    num_children += class_interface_decl->ivar_size();
3161                }
3162            }
3163        }
3164        break;
3165
3166    case clang::Type::ObjCObjectPointer:
3167        {
3168            const ObjCObjectPointerType *pointer_type = cast<ObjCObjectPointerType>(qual_type.getTypePtr());
3169            QualType pointee_type = pointer_type->getPointeeType();
3170            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (ast,
3171                                                                             pointee_type.getAsOpaquePtr(),
3172                                                                             omit_empty_base_classes);
3173            // If this type points to a simple type, then it has 1 child
3174            if (num_pointee_children == 0)
3175                num_children = 1;
3176            else
3177                num_children = num_pointee_children;
3178        }
3179        break;
3180
3181    case clang::Type::ConstantArray:
3182        num_children = cast<ConstantArrayType>(qual_type.getTypePtr())->getSize().getLimitedValue();
3183        break;
3184
3185    case clang::Type::Pointer:
3186        {
3187            const PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
3188            QualType pointee_type (pointer_type->getPointeeType());
3189            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (ast,
3190                                                                             pointee_type.getAsOpaquePtr(),
3191                                                                             omit_empty_base_classes);
3192            if (num_pointee_children == 0)
3193            {
3194                // We have a pointer to a pointee type that claims it has no children.
3195                // We will want to look at
3196                num_children = ClangASTContext::GetNumPointeeChildren (pointee_type.getAsOpaquePtr());
3197            }
3198            else
3199                num_children = num_pointee_children;
3200        }
3201        break;
3202
3203    case clang::Type::LValueReference:
3204    case clang::Type::RValueReference:
3205        {
3206            const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
3207            QualType pointee_type = reference_type->getPointeeType();
3208            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (ast,
3209                                                                             pointee_type.getAsOpaquePtr(),
3210                                                                             omit_empty_base_classes);
3211            // If this type points to a simple type, then it has 1 child
3212            if (num_pointee_children == 0)
3213                num_children = 1;
3214            else
3215                num_children = num_pointee_children;
3216        }
3217        break;
3218
3219
3220    case clang::Type::Typedef:
3221        num_children = ClangASTContext::GetNumChildren (ast,
3222                                                        cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3223                                                        omit_empty_base_classes);
3224        break;
3225
3226    case clang::Type::Elaborated:
3227        num_children = ClangASTContext::GetNumChildren (ast,
3228                                                        cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3229                                                        omit_empty_base_classes);
3230        break;
3231
3232    default:
3233        break;
3234    }
3235    return num_children;
3236}
3237
3238uint32_t
3239ClangASTContext::GetNumDirectBaseClasses (clang::ASTContext *ast, clang_type_t clang_type)
3240{
3241    if (clang_type == NULL)
3242        return 0;
3243
3244    uint32_t count = 0;
3245    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3246    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3247    switch (type_class)
3248    {
3249        case clang::Type::Record:
3250            if (GetCompleteQualType (ast, qual_type))
3251            {
3252                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3253                if (cxx_record_decl)
3254                    count = cxx_record_decl->getNumBases();
3255            }
3256            break;
3257
3258        case clang::Type::ObjCObject:
3259        case clang::Type::ObjCInterface:
3260            if (GetCompleteQualType (ast, qual_type))
3261            {
3262                const ObjCObjectType *objc_class_type = qual_type->getAsObjCQualifiedInterfaceType();
3263                if (objc_class_type)
3264                {
3265                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3266
3267                    if (class_interface_decl && class_interface_decl->getSuperClass())
3268                        count = 1;
3269                }
3270            }
3271            break;
3272
3273
3274        case clang::Type::Typedef:
3275            count = ClangASTContext::GetNumDirectBaseClasses (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3276            break;
3277
3278        case clang::Type::Elaborated:
3279            count = ClangASTContext::GetNumDirectBaseClasses (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3280            break;
3281
3282        default:
3283            break;
3284    }
3285    return count;
3286}
3287
3288uint32_t
3289ClangASTContext::GetNumVirtualBaseClasses (clang::ASTContext *ast,
3290                                           clang_type_t clang_type)
3291{
3292    if (clang_type == NULL)
3293        return 0;
3294
3295    uint32_t count = 0;
3296    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3297    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3298    switch (type_class)
3299    {
3300        case clang::Type::Record:
3301            if (GetCompleteQualType (ast, qual_type))
3302            {
3303                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3304                if (cxx_record_decl)
3305                    count = cxx_record_decl->getNumVBases();
3306            }
3307            break;
3308
3309        case clang::Type::Typedef:
3310            count = ClangASTContext::GetNumVirtualBaseClasses (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3311            break;
3312
3313        case clang::Type::Elaborated:
3314            count = ClangASTContext::GetNumVirtualBaseClasses (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3315            break;
3316
3317        default:
3318            break;
3319    }
3320    return count;
3321}
3322
3323uint32_t
3324ClangASTContext::GetNumFields (clang::ASTContext *ast, clang_type_t clang_type)
3325{
3326    if (clang_type == NULL)
3327        return 0;
3328
3329    uint32_t count = 0;
3330    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3331    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3332    switch (type_class)
3333    {
3334        case clang::Type::Record:
3335            if (GetCompleteQualType (ast, qual_type))
3336            {
3337                const RecordType *record_type = dyn_cast<RecordType>(qual_type.getTypePtr());
3338                if (record_type)
3339                {
3340                    RecordDecl *record_decl = record_type->getDecl();
3341                    if (record_decl)
3342                    {
3343                        uint32_t field_idx = 0;
3344                        RecordDecl::field_iterator field, field_end;
3345                        for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field)
3346                            ++field_idx;
3347                        count = field_idx;
3348                    }
3349                }
3350            }
3351            break;
3352
3353        case clang::Type::Typedef:
3354            count = ClangASTContext::GetNumFields (ast, cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3355            break;
3356
3357        case clang::Type::Elaborated:
3358            count = ClangASTContext::GetNumFields (ast, cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3359            break;
3360
3361        case clang::Type::ObjCObject:
3362        case clang::Type::ObjCInterface:
3363            if (GetCompleteQualType (ast, qual_type))
3364            {
3365                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
3366                if (objc_class_type)
3367                {
3368                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3369
3370                    if (class_interface_decl)
3371                        count = class_interface_decl->ivar_size();
3372                }
3373            }
3374            break;
3375
3376        default:
3377            break;
3378    }
3379    return count;
3380}
3381
3382clang_type_t
3383ClangASTContext::GetDirectBaseClassAtIndex (clang::ASTContext *ast,
3384                                            clang_type_t clang_type,
3385                                            size_t idx,
3386                                            uint32_t *bit_offset_ptr)
3387{
3388    if (clang_type == NULL)
3389        return 0;
3390
3391    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3392    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3393    switch (type_class)
3394    {
3395        case clang::Type::Record:
3396            if (GetCompleteQualType (ast, qual_type))
3397            {
3398                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3399                if (cxx_record_decl)
3400                {
3401                    uint32_t curr_idx = 0;
3402                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3403                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
3404                         base_class != base_class_end;
3405                         ++base_class, ++curr_idx)
3406                    {
3407                        if (curr_idx == idx)
3408                        {
3409                            if (bit_offset_ptr)
3410                            {
3411                                const ASTRecordLayout &record_layout = ast->getASTRecordLayout(cxx_record_decl);
3412                                const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3413//                                if (base_class->isVirtual())
3414//                                    *bit_offset_ptr = record_layout.getVBaseClassOffset(base_class_decl).getQuantity() * 8;
3415//                                else
3416                                    *bit_offset_ptr = record_layout.getBaseClassOffset(base_class_decl).getQuantity() * 8;
3417                            }
3418                            return base_class->getType().getAsOpaquePtr();
3419                        }
3420                    }
3421                }
3422            }
3423            break;
3424
3425        case clang::Type::ObjCObject:
3426        case clang::Type::ObjCInterface:
3427            if (idx == 0 && GetCompleteQualType (ast, qual_type))
3428            {
3429                const ObjCObjectType *objc_class_type = qual_type->getAsObjCQualifiedInterfaceType();
3430                if (objc_class_type)
3431                {
3432                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3433
3434                    if (class_interface_decl)
3435                    {
3436                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
3437                        if (superclass_interface_decl)
3438                        {
3439                            if (bit_offset_ptr)
3440                                *bit_offset_ptr = 0;
3441                            return ast->getObjCInterfaceType(superclass_interface_decl).getAsOpaquePtr();
3442                        }
3443                    }
3444                }
3445            }
3446            break;
3447
3448
3449        case clang::Type::Typedef:
3450            return ClangASTContext::GetDirectBaseClassAtIndex (ast,
3451                                                               cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3452                                                               idx,
3453                                                               bit_offset_ptr);
3454
3455        case clang::Type::Elaborated:
3456            return  ClangASTContext::GetDirectBaseClassAtIndex (ast,
3457                                                                cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3458                                                                idx,
3459                                                                bit_offset_ptr);
3460
3461        default:
3462            break;
3463    }
3464    return NULL;
3465}
3466
3467clang_type_t
3468ClangASTContext::GetVirtualBaseClassAtIndex (clang::ASTContext *ast,
3469                                             clang_type_t clang_type,
3470                                             size_t idx,
3471                                             uint32_t *bit_offset_ptr)
3472{
3473    if (clang_type == NULL)
3474        return 0;
3475
3476    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3477    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3478    switch (type_class)
3479    {
3480        case clang::Type::Record:
3481            if (GetCompleteQualType (ast, qual_type))
3482            {
3483                const CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3484                if (cxx_record_decl)
3485                {
3486                    uint32_t curr_idx = 0;
3487                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3488                    for (base_class = cxx_record_decl->vbases_begin(), base_class_end = cxx_record_decl->vbases_end();
3489                         base_class != base_class_end;
3490                         ++base_class, ++curr_idx)
3491                    {
3492                        if (curr_idx == idx)
3493                        {
3494                            if (bit_offset_ptr)
3495                            {
3496                                const ASTRecordLayout &record_layout = ast->getASTRecordLayout(cxx_record_decl);
3497                                const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3498                                *bit_offset_ptr = record_layout.getVBaseClassOffset(base_class_decl).getQuantity() * 8;
3499
3500                            }
3501                            return base_class->getType().getAsOpaquePtr();
3502                        }
3503                    }
3504                }
3505            }
3506            break;
3507
3508        case clang::Type::Typedef:
3509            return ClangASTContext::GetVirtualBaseClassAtIndex (ast,
3510                                                                cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3511                                                                idx,
3512                                                                bit_offset_ptr);
3513
3514        case clang::Type::Elaborated:
3515            return  ClangASTContext::GetVirtualBaseClassAtIndex (ast,
3516                                                                 cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3517                                                                 idx,
3518                                                                 bit_offset_ptr);
3519
3520        default:
3521            break;
3522    }
3523    return NULL;
3524}
3525
3526clang_type_t
3527ClangASTContext::GetFieldAtIndex (clang::ASTContext *ast,
3528                                  clang_type_t clang_type,
3529                                  size_t idx,
3530                                  std::string& name,
3531                                  uint64_t *bit_offset_ptr,
3532                                  uint32_t *bitfield_bit_size_ptr,
3533                                  bool *is_bitfield_ptr)
3534{
3535    if (clang_type == NULL)
3536        return 0;
3537
3538    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3539    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3540    switch (type_class)
3541    {
3542        case clang::Type::Record:
3543            if (GetCompleteQualType (ast, qual_type))
3544            {
3545                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
3546                const RecordDecl *record_decl = record_type->getDecl();
3547                uint32_t field_idx = 0;
3548                RecordDecl::field_iterator field, field_end;
3549                for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field, ++field_idx)
3550                {
3551                    if (idx == field_idx)
3552                    {
3553                        // Print the member type if requested
3554                        // Print the member name and equal sign
3555                        name.assign(field->getNameAsString());
3556
3557                        // Figure out the type byte size (field_type_info.first) and
3558                        // alignment (field_type_info.second) from the AST context.
3559                        if (bit_offset_ptr)
3560                        {
3561                            const ASTRecordLayout &record_layout = ast->getASTRecordLayout(record_decl);
3562                            *bit_offset_ptr = record_layout.getFieldOffset (field_idx);
3563                        }
3564
3565                        const bool is_bitfield = field->isBitField();
3566
3567                        if (bitfield_bit_size_ptr)
3568                        {
3569                            *bitfield_bit_size_ptr = 0;
3570
3571                            if (is_bitfield && ast)
3572                            {
3573                                Expr *bitfield_bit_size_expr = field->getBitWidth();
3574                                llvm::APSInt bitfield_apsint;
3575                                if (bitfield_bit_size_expr && bitfield_bit_size_expr->EvaluateAsInt(bitfield_apsint, *ast))
3576                                {
3577                                    *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
3578                                }
3579                            }
3580                        }
3581                        if (is_bitfield_ptr)
3582                            *is_bitfield_ptr = is_bitfield;
3583
3584                        return field->getType().getAsOpaquePtr();
3585                    }
3586                }
3587            }
3588            break;
3589
3590        case clang::Type::ObjCObject:
3591        case clang::Type::ObjCInterface:
3592            if (GetCompleteQualType (ast, qual_type))
3593            {
3594                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
3595                assert (objc_class_type);
3596                if (objc_class_type)
3597                {
3598                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
3599
3600                    if (class_interface_decl)
3601                    {
3602                        if (idx < (class_interface_decl->ivar_size()))
3603                        {
3604                            ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
3605                            uint32_t ivar_idx = 0;
3606
3607                            for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos, ++ivar_idx)
3608                            {
3609                                if (ivar_idx == idx)
3610                                {
3611                                    const ObjCIvarDecl* ivar_decl = *ivar_pos;
3612
3613                                    QualType ivar_qual_type(ivar_decl->getType());
3614
3615                                    name.assign(ivar_decl->getNameAsString());
3616
3617                                    if (bit_offset_ptr)
3618                                    {
3619                                        const ASTRecordLayout &interface_layout = ast->getASTObjCInterfaceLayout(class_interface_decl);
3620                                        *bit_offset_ptr = interface_layout.getFieldOffset (ivar_idx);
3621                                    }
3622
3623                                    const bool is_bitfield = ivar_pos->isBitField();
3624
3625                                    if (bitfield_bit_size_ptr)
3626                                    {
3627                                        *bitfield_bit_size_ptr = 0;
3628
3629                                        if (is_bitfield && ast)
3630                                        {
3631                                            Expr *bitfield_bit_size_expr = ivar_pos->getBitWidth();
3632                                            llvm::APSInt bitfield_apsint;
3633                                            if (bitfield_bit_size_expr && bitfield_bit_size_expr->EvaluateAsInt(bitfield_apsint, *ast))
3634                                            {
3635                                                *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
3636                                            }
3637                                        }
3638                                    }
3639                                    if (is_bitfield_ptr)
3640                                        *is_bitfield_ptr = is_bitfield;
3641
3642                                    return ivar_qual_type.getAsOpaquePtr();
3643                                }
3644                            }
3645                        }
3646                    }
3647                }
3648            }
3649            break;
3650
3651
3652        case clang::Type::Typedef:
3653            return ClangASTContext::GetFieldAtIndex (ast,
3654                                                     cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
3655                                                     idx,
3656                                                     name,
3657                                                     bit_offset_ptr,
3658                                                     bitfield_bit_size_ptr,
3659                                                     is_bitfield_ptr);
3660
3661        case clang::Type::Elaborated:
3662            return  ClangASTContext::GetFieldAtIndex (ast,
3663                                                      cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
3664                                                      idx,
3665                                                      name,
3666                                                      bit_offset_ptr,
3667                                                      bitfield_bit_size_ptr,
3668                                                      is_bitfield_ptr);
3669
3670        default:
3671            break;
3672    }
3673    return NULL;
3674}
3675
3676lldb::BasicType
3677ClangASTContext::GetLLDBBasicTypeEnumeration (clang_type_t clang_type)
3678{
3679    if (clang_type)
3680    {
3681        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3682        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3683        if (type_class == clang::Type::Builtin)
3684        {
3685            switch (cast<clang::BuiltinType>(qual_type)->getKind())
3686            {
3687            case clang::BuiltinType::Void:      return eBasicTypeVoid;
3688            case clang::BuiltinType::Bool:      return eBasicTypeBool;
3689            case clang::BuiltinType::Char_S:    return eBasicTypeSignedChar;
3690            case clang::BuiltinType::Char_U:    return eBasicTypeUnsignedChar;
3691            case clang::BuiltinType::Char16:    return eBasicTypeChar16;
3692            case clang::BuiltinType::Char32:    return eBasicTypeChar32;
3693            case clang::BuiltinType::UChar:     return eBasicTypeUnsignedChar;
3694            case clang::BuiltinType::SChar:     return eBasicTypeSignedChar;
3695            case clang::BuiltinType::WChar_S:   return eBasicTypeSignedWChar;
3696            case clang::BuiltinType::WChar_U:   return eBasicTypeUnsignedWChar;
3697            case clang::BuiltinType::Short:     return eBasicTypeShort;
3698            case clang::BuiltinType::UShort:    return eBasicTypeUnsignedShort;
3699            case clang::BuiltinType::Int:       return eBasicTypeInt;
3700            case clang::BuiltinType::UInt:      return eBasicTypeUnsignedInt;
3701            case clang::BuiltinType::Long:      return eBasicTypeLong;
3702            case clang::BuiltinType::ULong:     return eBasicTypeUnsignedLong;
3703            case clang::BuiltinType::LongLong:  return eBasicTypeLongLong;
3704            case clang::BuiltinType::ULongLong: return eBasicTypeUnsignedLongLong;
3705            case clang::BuiltinType::Int128:    return eBasicTypeInt128;
3706            case clang::BuiltinType::UInt128:   return eBasicTypeUnsignedInt128;
3707
3708            case clang::BuiltinType::Half:      return eBasicTypeHalf;
3709            case clang::BuiltinType::Float:     return eBasicTypeFloat;
3710            case clang::BuiltinType::Double:    return eBasicTypeDouble;
3711            case clang::BuiltinType::LongDouble:return eBasicTypeLongDouble;
3712
3713            case clang::BuiltinType::NullPtr:   return eBasicTypeNullPtr;
3714            case clang::BuiltinType::ObjCId:    return eBasicTypeObjCID;
3715            case clang::BuiltinType::ObjCClass: return eBasicTypeObjCClass;
3716            case clang::BuiltinType::ObjCSel:   return eBasicTypeObjCSel;
3717            case clang::BuiltinType::Dependent:
3718            case clang::BuiltinType::Overload:
3719            case clang::BuiltinType::BoundMember:
3720            case clang::BuiltinType::PseudoObject:
3721            case clang::BuiltinType::UnknownAny:
3722            case clang::BuiltinType::BuiltinFn:
3723            case clang::BuiltinType::ARCUnbridgedCast:
3724            case clang::BuiltinType::OCLEvent:
3725            case clang::BuiltinType::OCLImage1d:
3726            case clang::BuiltinType::OCLImage1dArray:
3727            case clang::BuiltinType::OCLImage1dBuffer:
3728            case clang::BuiltinType::OCLImage2d:
3729            case clang::BuiltinType::OCLImage2dArray:
3730            case clang::BuiltinType::OCLImage3d:
3731            case clang::BuiltinType::OCLSampler:
3732                return eBasicTypeOther;
3733            }
3734        }
3735    }
3736
3737    return eBasicTypeInvalid;
3738}
3739
3740
3741
3742// If a pointer to a pointee type (the clang_type arg) says that it has no
3743// children, then we either need to trust it, or override it and return a
3744// different result. For example, an "int *" has one child that is an integer,
3745// but a function pointer doesn't have any children. Likewise if a Record type
3746// claims it has no children, then there really is nothing to show.
3747uint32_t
3748ClangASTContext::GetNumPointeeChildren (clang_type_t clang_type)
3749{
3750    if (clang_type == NULL)
3751        return 0;
3752
3753    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
3754    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3755    switch (type_class)
3756    {
3757    case clang::Type::Builtin:
3758        switch (cast<clang::BuiltinType>(qual_type)->getKind())
3759        {
3760        case clang::BuiltinType::UnknownAny:
3761        case clang::BuiltinType::Void:
3762        case clang::BuiltinType::NullPtr:
3763        case clang::BuiltinType::OCLEvent:
3764        case clang::BuiltinType::OCLImage1d:
3765        case clang::BuiltinType::OCLImage1dArray:
3766        case clang::BuiltinType::OCLImage1dBuffer:
3767        case clang::BuiltinType::OCLImage2d:
3768        case clang::BuiltinType::OCLImage2dArray:
3769        case clang::BuiltinType::OCLImage3d:
3770        case clang::BuiltinType::OCLSampler:
3771            return 0;
3772        case clang::BuiltinType::Bool:
3773        case clang::BuiltinType::Char_U:
3774        case clang::BuiltinType::UChar:
3775        case clang::BuiltinType::WChar_U:
3776        case clang::BuiltinType::Char16:
3777        case clang::BuiltinType::Char32:
3778        case clang::BuiltinType::UShort:
3779        case clang::BuiltinType::UInt:
3780        case clang::BuiltinType::ULong:
3781        case clang::BuiltinType::ULongLong:
3782        case clang::BuiltinType::UInt128:
3783        case clang::BuiltinType::Char_S:
3784        case clang::BuiltinType::SChar:
3785        case clang::BuiltinType::WChar_S:
3786        case clang::BuiltinType::Short:
3787        case clang::BuiltinType::Int:
3788        case clang::BuiltinType::Long:
3789        case clang::BuiltinType::LongLong:
3790        case clang::BuiltinType::Int128:
3791        case clang::BuiltinType::Float:
3792        case clang::BuiltinType::Double:
3793        case clang::BuiltinType::LongDouble:
3794        case clang::BuiltinType::Dependent:
3795        case clang::BuiltinType::Overload:
3796        case clang::BuiltinType::ObjCId:
3797        case clang::BuiltinType::ObjCClass:
3798        case clang::BuiltinType::ObjCSel:
3799        case clang::BuiltinType::BoundMember:
3800        case clang::BuiltinType::Half:
3801        case clang::BuiltinType::ARCUnbridgedCast:
3802        case clang::BuiltinType::PseudoObject:
3803        case clang::BuiltinType::BuiltinFn:
3804            return 1;
3805        }
3806        break;
3807
3808    case clang::Type::Complex:                  return 1;
3809    case clang::Type::Pointer:                  return 1;
3810    case clang::Type::BlockPointer:             return 0;   // If block pointers don't have debug info, then no children for them
3811    case clang::Type::LValueReference:          return 1;
3812    case clang::Type::RValueReference:          return 1;
3813    case clang::Type::MemberPointer:            return 0;
3814    case clang::Type::ConstantArray:            return 0;
3815    case clang::Type::IncompleteArray:          return 0;
3816    case clang::Type::VariableArray:            return 0;
3817    case clang::Type::DependentSizedArray:      return 0;
3818    case clang::Type::DependentSizedExtVector:  return 0;
3819    case clang::Type::Vector:                   return 0;
3820    case clang::Type::ExtVector:                return 0;
3821    case clang::Type::FunctionProto:            return 0;   // When we function pointers, they have no children...
3822    case clang::Type::FunctionNoProto:          return 0;   // When we function pointers, they have no children...
3823    case clang::Type::UnresolvedUsing:          return 0;
3824    case clang::Type::Paren:                    return 0;
3825    case clang::Type::Typedef:                  return ClangASTContext::GetNumPointeeChildren (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
3826    case clang::Type::Elaborated:               return ClangASTContext::GetNumPointeeChildren (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
3827    case clang::Type::TypeOfExpr:               return 0;
3828    case clang::Type::TypeOf:                   return 0;
3829    case clang::Type::Decltype:                 return 0;
3830    case clang::Type::Record:                   return 0;
3831    case clang::Type::Enum:                     return 1;
3832    case clang::Type::TemplateTypeParm:         return 1;
3833    case clang::Type::SubstTemplateTypeParm:    return 1;
3834    case clang::Type::TemplateSpecialization:   return 1;
3835    case clang::Type::InjectedClassName:        return 0;
3836    case clang::Type::DependentName:            return 1;
3837    case clang::Type::DependentTemplateSpecialization:  return 1;
3838    case clang::Type::ObjCObject:               return 0;
3839    case clang::Type::ObjCInterface:            return 0;
3840    case clang::Type::ObjCObjectPointer:        return 1;
3841    default:
3842        break;
3843    }
3844    return 0;
3845}
3846
3847clang_type_t
3848ClangASTContext::GetChildClangTypeAtIndex
3849(
3850    ExecutionContext *exe_ctx,
3851    const char *parent_name,
3852    clang_type_t parent_clang_type,
3853    size_t idx,
3854    bool transparent_pointers,
3855    bool omit_empty_base_classes,
3856    bool ignore_array_bounds,
3857    std::string& child_name,
3858    uint32_t &child_byte_size,
3859    int32_t &child_byte_offset,
3860    uint32_t &child_bitfield_bit_size,
3861    uint32_t &child_bitfield_bit_offset,
3862    bool &child_is_base_class,
3863    bool &child_is_deref_of_parent
3864)
3865{
3866    if (parent_clang_type)
3867
3868        return GetChildClangTypeAtIndex (exe_ctx,
3869                                         getASTContext(),
3870                                         parent_name,
3871                                         parent_clang_type,
3872                                         idx,
3873                                         transparent_pointers,
3874                                         omit_empty_base_classes,
3875                                         ignore_array_bounds,
3876                                         child_name,
3877                                         child_byte_size,
3878                                         child_byte_offset,
3879                                         child_bitfield_bit_size,
3880                                         child_bitfield_bit_offset,
3881                                         child_is_base_class,
3882                                         child_is_deref_of_parent);
3883    return NULL;
3884}
3885
3886clang_type_t
3887ClangASTContext::GetChildClangTypeAtIndex
3888(
3889    ExecutionContext *exe_ctx,
3890    ASTContext *ast,
3891    const char *parent_name,
3892    clang_type_t parent_clang_type,
3893    size_t idx,
3894    bool transparent_pointers,
3895    bool omit_empty_base_classes,
3896    bool ignore_array_bounds,
3897    std::string& child_name,
3898    uint32_t &child_byte_size,
3899    int32_t &child_byte_offset,
3900    uint32_t &child_bitfield_bit_size,
3901    uint32_t &child_bitfield_bit_offset,
3902    bool &child_is_base_class,
3903    bool &child_is_deref_of_parent
3904)
3905{
3906    if (parent_clang_type == NULL)
3907        return NULL;
3908
3909    QualType parent_qual_type(QualType::getFromOpaquePtr(parent_clang_type));
3910    const clang::Type::TypeClass parent_type_class = parent_qual_type->getTypeClass();
3911    child_bitfield_bit_size = 0;
3912    child_bitfield_bit_offset = 0;
3913    child_is_base_class = false;
3914
3915    const bool idx_is_valid = idx < ClangASTContext::GetNumChildren (ast, parent_clang_type, omit_empty_base_classes);
3916    uint32_t bit_offset;
3917    switch (parent_type_class)
3918    {
3919    case clang::Type::Builtin:
3920        if (idx_is_valid)
3921        {
3922            switch (cast<clang::BuiltinType>(parent_qual_type)->getKind())
3923            {
3924            case clang::BuiltinType::ObjCId:
3925            case clang::BuiltinType::ObjCClass:
3926                child_name = "isa";
3927                child_byte_size = ast->getTypeSize(ast->ObjCBuiltinClassTy) / CHAR_BIT;
3928                return ast->ObjCBuiltinClassTy.getAsOpaquePtr();
3929
3930            default:
3931                break;
3932            }
3933        }
3934        break;
3935
3936    case clang::Type::Record:
3937        if (idx_is_valid && GetCompleteQualType (ast, parent_qual_type))
3938        {
3939            const RecordType *record_type = cast<RecordType>(parent_qual_type.getTypePtr());
3940            const RecordDecl *record_decl = record_type->getDecl();
3941            assert(record_decl);
3942            const ASTRecordLayout &record_layout = ast->getASTRecordLayout(record_decl);
3943            uint32_t child_idx = 0;
3944
3945            const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
3946            if (cxx_record_decl)
3947            {
3948                // We might have base classes to print out first
3949                CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
3950                for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
3951                     base_class != base_class_end;
3952                     ++base_class)
3953                {
3954                    const CXXRecordDecl *base_class_decl = NULL;
3955
3956                    // Skip empty base classes
3957                    if (omit_empty_base_classes)
3958                    {
3959                        base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3960                        if (RecordHasFields(base_class_decl) == false)
3961                            continue;
3962                    }
3963
3964                    if (idx == child_idx)
3965                    {
3966                        if (base_class_decl == NULL)
3967                            base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
3968
3969
3970                        if (base_class->isVirtual())
3971                            bit_offset = record_layout.getVBaseClassOffset(base_class_decl).getQuantity() * 8;
3972                        else
3973                            bit_offset = record_layout.getBaseClassOffset(base_class_decl).getQuantity() * 8;
3974
3975                        // Base classes should be a multiple of 8 bits in size
3976                        child_byte_offset = bit_offset/8;
3977
3978                        child_name = ClangASTType::GetTypeNameForQualType(ast, base_class->getType());
3979
3980                        uint64_t clang_type_info_bit_size = ast->getTypeSize(base_class->getType());
3981
3982                        // Base classes bit sizes should be a multiple of 8 bits in size
3983                        assert (clang_type_info_bit_size % 8 == 0);
3984                        child_byte_size = clang_type_info_bit_size / 8;
3985                        child_is_base_class = true;
3986                        return base_class->getType().getAsOpaquePtr();
3987                    }
3988                    // We don't increment the child index in the for loop since we might
3989                    // be skipping empty base classes
3990                    ++child_idx;
3991                }
3992            }
3993            // Make sure index is in range...
3994            uint32_t field_idx = 0;
3995            RecordDecl::field_iterator field, field_end;
3996            for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field, ++field_idx, ++child_idx)
3997            {
3998                if (idx == child_idx)
3999                {
4000                    // Print the member type if requested
4001                    // Print the member name and equal sign
4002                    child_name.assign(field->getNameAsString().c_str());
4003
4004                    // Figure out the type byte size (field_type_info.first) and
4005                    // alignment (field_type_info.second) from the AST context.
4006                    std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(field->getType());
4007                    assert(field_idx < record_layout.getFieldCount());
4008
4009                    child_byte_size = field_type_info.first / 8;
4010
4011                    // Figure out the field offset within the current struct/union/class type
4012                    bit_offset = record_layout.getFieldOffset (field_idx);
4013                    child_byte_offset = bit_offset / 8;
4014                    if (ClangASTContext::FieldIsBitfield (ast, *field, child_bitfield_bit_size))
4015                        child_bitfield_bit_offset = bit_offset % 8;
4016
4017                    return field->getType().getAsOpaquePtr();
4018                }
4019            }
4020        }
4021        break;
4022
4023    case clang::Type::ObjCObject:
4024    case clang::Type::ObjCInterface:
4025        if (idx_is_valid && GetCompleteQualType (ast, parent_qual_type))
4026        {
4027            const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(parent_qual_type.getTypePtr());
4028            assert (objc_class_type);
4029            if (objc_class_type)
4030            {
4031                uint32_t child_idx = 0;
4032                ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
4033
4034                if (class_interface_decl)
4035                {
4036
4037                    const ASTRecordLayout &interface_layout = ast->getASTObjCInterfaceLayout(class_interface_decl);
4038                    ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
4039                    if (superclass_interface_decl)
4040                    {
4041                        if (omit_empty_base_classes)
4042                        {
4043                            if (ClangASTContext::GetNumChildren(ast, ast->getObjCInterfaceType(superclass_interface_decl).getAsOpaquePtr(), omit_empty_base_classes) > 0)
4044                            {
4045                                if (idx == 0)
4046                                {
4047                                    QualType ivar_qual_type(ast->getObjCInterfaceType(superclass_interface_decl));
4048
4049
4050                                    child_name.assign(superclass_interface_decl->getNameAsString().c_str());
4051
4052                                    std::pair<uint64_t, unsigned> ivar_type_info = ast->getTypeInfo(ivar_qual_type.getTypePtr());
4053
4054                                    child_byte_size = ivar_type_info.first / 8;
4055                                    child_byte_offset = 0;
4056                                    child_is_base_class = true;
4057
4058                                    return ivar_qual_type.getAsOpaquePtr();
4059                                }
4060
4061                                ++child_idx;
4062                            }
4063                        }
4064                        else
4065                            ++child_idx;
4066                    }
4067
4068                    const uint32_t superclass_idx = child_idx;
4069
4070                    if (idx < (child_idx + class_interface_decl->ivar_size()))
4071                    {
4072                        ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
4073
4074                        for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos)
4075                        {
4076                            if (child_idx == idx)
4077                            {
4078                                ObjCIvarDecl* ivar_decl = *ivar_pos;
4079
4080                                QualType ivar_qual_type(ivar_decl->getType());
4081
4082                                child_name.assign(ivar_decl->getNameAsString().c_str());
4083
4084                                std::pair<uint64_t, unsigned> ivar_type_info = ast->getTypeInfo(ivar_qual_type.getTypePtr());
4085
4086                                child_byte_size = ivar_type_info.first / 8;
4087
4088                                // Figure out the field offset within the current struct/union/class type
4089                                // For ObjC objects, we can't trust the bit offset we get from the Clang AST, since
4090                                // that doesn't account for the space taken up by unbacked properties, or from
4091                                // the changing size of base classes that are newer than this class.
4092                                // So if we have a process around that we can ask about this object, do so.
4093                                child_byte_offset = LLDB_INVALID_IVAR_OFFSET;
4094                                Process *process = NULL;
4095                                if (exe_ctx)
4096                                    process = exe_ctx->GetProcessPtr();
4097                                if (process)
4098                                {
4099                                    ObjCLanguageRuntime *objc_runtime = process->GetObjCLanguageRuntime();
4100                                    if (objc_runtime != NULL)
4101                                    {
4102                                        ClangASTType parent_ast_type (ast, parent_qual_type.getAsOpaquePtr());
4103                                        child_byte_offset = objc_runtime->GetByteOffsetForIvar (parent_ast_type, ivar_decl->getNameAsString().c_str());
4104                                    }
4105                                }
4106
4107                                // Setting this to UINT32_MAX to make sure we don't compute it twice...
4108                                bit_offset = UINT32_MAX;
4109
4110                                if (child_byte_offset == LLDB_INVALID_IVAR_OFFSET)
4111                                {
4112                                    bit_offset = interface_layout.getFieldOffset (child_idx - superclass_idx);
4113                                    child_byte_offset = bit_offset / 8;
4114                                }
4115
4116                                // Note, the ObjC Ivar Byte offset is just that, it doesn't account for the bit offset
4117                                // of a bitfield within its containing object.  So regardless of where we get the byte
4118                                // offset from, we still need to get the bit offset for bitfields from the layout.
4119
4120                                if (ClangASTContext::FieldIsBitfield (ast, ivar_decl, child_bitfield_bit_size))
4121                                {
4122                                    if (bit_offset == UINT32_MAX)
4123                                        bit_offset = interface_layout.getFieldOffset (child_idx - superclass_idx);
4124
4125                                    child_bitfield_bit_offset = bit_offset % 8;
4126                                }
4127                                return ivar_qual_type.getAsOpaquePtr();
4128                            }
4129                            ++child_idx;
4130                        }
4131                    }
4132                }
4133            }
4134        }
4135        break;
4136
4137    case clang::Type::ObjCObjectPointer:
4138        if (idx_is_valid)
4139        {
4140            const ObjCObjectPointerType *pointer_type = cast<ObjCObjectPointerType>(parent_qual_type.getTypePtr());
4141            QualType pointee_type = pointer_type->getPointeeType();
4142
4143            if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4144            {
4145                child_is_deref_of_parent = false;
4146                bool tmp_child_is_deref_of_parent = false;
4147                return GetChildClangTypeAtIndex (exe_ctx,
4148                                                 ast,
4149                                                 parent_name,
4150                                                 pointer_type->getPointeeType().getAsOpaquePtr(),
4151                                                 idx,
4152                                                 transparent_pointers,
4153                                                 omit_empty_base_classes,
4154                                                 ignore_array_bounds,
4155                                                 child_name,
4156                                                 child_byte_size,
4157                                                 child_byte_offset,
4158                                                 child_bitfield_bit_size,
4159                                                 child_bitfield_bit_offset,
4160                                                 child_is_base_class,
4161                                                 tmp_child_is_deref_of_parent);
4162            }
4163            else
4164            {
4165                child_is_deref_of_parent = true;
4166                if (parent_name)
4167                {
4168                    child_name.assign(1, '*');
4169                    child_name += parent_name;
4170                }
4171
4172                // We have a pointer to an simple type
4173                if (idx == 0 && GetCompleteQualType(ast, pointee_type))
4174                {
4175                    std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4176                    assert(clang_type_info.first % 8 == 0);
4177                    child_byte_size = clang_type_info.first / 8;
4178                    child_byte_offset = 0;
4179                    return pointee_type.getAsOpaquePtr();
4180                }
4181            }
4182        }
4183        break;
4184
4185        case clang::Type::ConstantArray:
4186        case clang::Type::IncompleteArray:
4187            if (ignore_array_bounds || idx_is_valid)
4188            {
4189                const ArrayType *array = cast<ArrayType>(parent_qual_type.getTypePtr());
4190                if (array)
4191                {
4192                    if (GetCompleteQualType (ast, array->getElementType()))
4193                    {
4194                        std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(array->getElementType());
4195
4196                        char element_name[64];
4197                        ::snprintf (element_name, sizeof (element_name), "[%zu]", idx);
4198
4199                        child_name.assign(element_name);
4200                        assert(field_type_info.first % 8 == 0);
4201                        child_byte_size = field_type_info.first / 8;
4202                        child_byte_offset = (int32_t)idx * (int32_t)child_byte_size;
4203                        return array->getElementType().getAsOpaquePtr();
4204                    }
4205                }
4206            }
4207            break;
4208
4209
4210    case clang::Type::Pointer:
4211        if (idx_is_valid)
4212        {
4213            const PointerType *pointer_type = cast<PointerType>(parent_qual_type.getTypePtr());
4214            QualType pointee_type = pointer_type->getPointeeType();
4215
4216            // Don't dereference "void *" pointers
4217            if (pointee_type->isVoidType())
4218                return NULL;
4219
4220            if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4221            {
4222                child_is_deref_of_parent = false;
4223                bool tmp_child_is_deref_of_parent = false;
4224                return GetChildClangTypeAtIndex (exe_ctx,
4225                                                 ast,
4226                                                 parent_name,
4227                                                 pointer_type->getPointeeType().getAsOpaquePtr(),
4228                                                 idx,
4229                                                 transparent_pointers,
4230                                                 omit_empty_base_classes,
4231                                                 ignore_array_bounds,
4232                                                 child_name,
4233                                                 child_byte_size,
4234                                                 child_byte_offset,
4235                                                 child_bitfield_bit_size,
4236                                                 child_bitfield_bit_offset,
4237                                                 child_is_base_class,
4238                                                 tmp_child_is_deref_of_parent);
4239            }
4240            else
4241            {
4242                child_is_deref_of_parent = true;
4243
4244                if (parent_name)
4245                {
4246                    child_name.assign(1, '*');
4247                    child_name += parent_name;
4248                }
4249
4250                // We have a pointer to an simple type
4251                if (idx == 0)
4252                {
4253                    std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4254                    assert(clang_type_info.first % 8 == 0);
4255                    child_byte_size = clang_type_info.first / 8;
4256                    child_byte_offset = 0;
4257                    return pointee_type.getAsOpaquePtr();
4258                }
4259            }
4260        }
4261        break;
4262
4263    case clang::Type::LValueReference:
4264    case clang::Type::RValueReference:
4265        if (idx_is_valid)
4266        {
4267            const ReferenceType *reference_type = cast<ReferenceType>(parent_qual_type.getTypePtr());
4268            QualType pointee_type(reference_type->getPointeeType());
4269            clang_type_t pointee_clang_type = pointee_type.getAsOpaquePtr();
4270            if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_clang_type))
4271            {
4272                child_is_deref_of_parent = false;
4273                bool tmp_child_is_deref_of_parent = false;
4274                return GetChildClangTypeAtIndex (exe_ctx,
4275                                                 ast,
4276                                                 parent_name,
4277                                                 pointee_clang_type,
4278                                                 idx,
4279                                                 transparent_pointers,
4280                                                 omit_empty_base_classes,
4281                                                 ignore_array_bounds,
4282                                                 child_name,
4283                                                 child_byte_size,
4284                                                 child_byte_offset,
4285                                                 child_bitfield_bit_size,
4286                                                 child_bitfield_bit_offset,
4287                                                 child_is_base_class,
4288                                                 tmp_child_is_deref_of_parent);
4289            }
4290            else
4291            {
4292                if (parent_name)
4293                {
4294                    child_name.assign(1, '&');
4295                    child_name += parent_name;
4296                }
4297
4298                // We have a pointer to an simple type
4299                if (idx == 0)
4300                {
4301                    std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4302                    assert(clang_type_info.first % 8 == 0);
4303                    child_byte_size = clang_type_info.first / 8;
4304                    child_byte_offset = 0;
4305                    return pointee_type.getAsOpaquePtr();
4306                }
4307            }
4308        }
4309        break;
4310
4311    case clang::Type::Typedef:
4312        return GetChildClangTypeAtIndex (exe_ctx,
4313                                         ast,
4314                                         parent_name,
4315                                         cast<TypedefType>(parent_qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
4316                                         idx,
4317                                         transparent_pointers,
4318                                         omit_empty_base_classes,
4319                                         ignore_array_bounds,
4320                                         child_name,
4321                                         child_byte_size,
4322                                         child_byte_offset,
4323                                         child_bitfield_bit_size,
4324                                         child_bitfield_bit_offset,
4325                                         child_is_base_class,
4326                                         child_is_deref_of_parent);
4327        break;
4328
4329    case clang::Type::Elaborated:
4330        return GetChildClangTypeAtIndex (exe_ctx,
4331                                         ast,
4332                                         parent_name,
4333                                         cast<ElaboratedType>(parent_qual_type)->getNamedType().getAsOpaquePtr(),
4334                                         idx,
4335                                         transparent_pointers,
4336                                         omit_empty_base_classes,
4337                                         ignore_array_bounds,
4338                                         child_name,
4339                                         child_byte_size,
4340                                         child_byte_offset,
4341                                         child_bitfield_bit_size,
4342                                         child_bitfield_bit_offset,
4343                                         child_is_base_class,
4344                                         child_is_deref_of_parent);
4345
4346    default:
4347        break;
4348    }
4349    return NULL;
4350}
4351
4352static inline bool
4353BaseSpecifierIsEmpty (const CXXBaseSpecifier *b)
4354{
4355    return ClangASTContext::RecordHasFields(b->getType()->getAsCXXRecordDecl()) == false;
4356}
4357
4358static uint32_t
4359GetNumBaseClasses (const CXXRecordDecl *cxx_record_decl, bool omit_empty_base_classes)
4360{
4361    uint32_t num_bases = 0;
4362    if (cxx_record_decl)
4363    {
4364        if (omit_empty_base_classes)
4365        {
4366            CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4367            for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4368                 base_class != base_class_end;
4369                 ++base_class)
4370            {
4371                // Skip empty base classes
4372                if (omit_empty_base_classes)
4373                {
4374                    if (BaseSpecifierIsEmpty (base_class))
4375                        continue;
4376                }
4377                ++num_bases;
4378            }
4379        }
4380        else
4381            num_bases = cxx_record_decl->getNumBases();
4382    }
4383    return num_bases;
4384}
4385
4386
4387static uint32_t
4388GetIndexForRecordBase
4389(
4390    const RecordDecl *record_decl,
4391    const CXXBaseSpecifier *base_spec,
4392    bool omit_empty_base_classes
4393)
4394{
4395    uint32_t child_idx = 0;
4396
4397    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4398
4399//    const char *super_name = record_decl->getNameAsCString();
4400//    const char *base_name = base_spec->getType()->getAs<RecordType>()->getDecl()->getNameAsCString();
4401//    printf ("GetIndexForRecordChild (%s, %s)\n", super_name, base_name);
4402//
4403    if (cxx_record_decl)
4404    {
4405        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4406        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4407             base_class != base_class_end;
4408             ++base_class)
4409        {
4410            if (omit_empty_base_classes)
4411            {
4412                if (BaseSpecifierIsEmpty (base_class))
4413                    continue;
4414            }
4415
4416//            printf ("GetIndexForRecordChild (%s, %s) base[%u] = %s\n", super_name, base_name,
4417//                    child_idx,
4418//                    base_class->getType()->getAs<RecordType>()->getDecl()->getNameAsCString());
4419//
4420//
4421            if (base_class == base_spec)
4422                return child_idx;
4423            ++child_idx;
4424        }
4425    }
4426
4427    return UINT32_MAX;
4428}
4429
4430
4431static uint32_t
4432GetIndexForRecordChild
4433(
4434    const RecordDecl *record_decl,
4435    NamedDecl *canonical_decl,
4436    bool omit_empty_base_classes
4437)
4438{
4439    uint32_t child_idx = GetNumBaseClasses (dyn_cast<CXXRecordDecl>(record_decl), omit_empty_base_classes);
4440
4441//    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4442//
4443////    printf ("GetIndexForRecordChild (%s, %s)\n", record_decl->getNameAsCString(), canonical_decl->getNameAsCString());
4444//    if (cxx_record_decl)
4445//    {
4446//        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4447//        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4448//             base_class != base_class_end;
4449//             ++base_class)
4450//        {
4451//            if (omit_empty_base_classes)
4452//            {
4453//                if (BaseSpecifierIsEmpty (base_class))
4454//                    continue;
4455//            }
4456//
4457////            printf ("GetIndexForRecordChild (%s, %s) base[%u] = %s\n",
4458////                    record_decl->getNameAsCString(),
4459////                    canonical_decl->getNameAsCString(),
4460////                    child_idx,
4461////                    base_class->getType()->getAs<RecordType>()->getDecl()->getNameAsCString());
4462//
4463//
4464//            CXXRecordDecl *curr_base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
4465//            if (curr_base_class_decl == canonical_decl)
4466//            {
4467//                return child_idx;
4468//            }
4469//            ++child_idx;
4470//        }
4471//    }
4472//
4473//    const uint32_t num_bases = child_idx;
4474    RecordDecl::field_iterator field, field_end;
4475    for (field = record_decl->field_begin(), field_end = record_decl->field_end();
4476         field != field_end;
4477         ++field, ++child_idx)
4478    {
4479//            printf ("GetIndexForRecordChild (%s, %s) field[%u] = %s\n",
4480//                    record_decl->getNameAsCString(),
4481//                    canonical_decl->getNameAsCString(),
4482//                    child_idx - num_bases,
4483//                    field->getNameAsCString());
4484
4485        if (field->getCanonicalDecl() == canonical_decl)
4486            return child_idx;
4487    }
4488
4489    return UINT32_MAX;
4490}
4491
4492// Look for a child member (doesn't include base classes, but it does include
4493// their members) in the type hierarchy. Returns an index path into "clang_type"
4494// on how to reach the appropriate member.
4495//
4496//    class A
4497//    {
4498//    public:
4499//        int m_a;
4500//        int m_b;
4501//    };
4502//
4503//    class B
4504//    {
4505//    };
4506//
4507//    class C :
4508//        public B,
4509//        public A
4510//    {
4511//    };
4512//
4513// If we have a clang type that describes "class C", and we wanted to looked
4514// "m_b" in it:
4515//
4516// With omit_empty_base_classes == false we would get an integer array back with:
4517// { 1,  1 }
4518// The first index 1 is the child index for "class A" within class C
4519// The second index 1 is the child index for "m_b" within class A
4520//
4521// With omit_empty_base_classes == true we would get an integer array back with:
4522// { 0,  1 }
4523// The first index 0 is the child index for "class A" within class C (since class B doesn't have any members it doesn't count)
4524// The second index 1 is the child index for "m_b" within class A
4525
4526size_t
4527ClangASTContext::GetIndexOfChildMemberWithName
4528(
4529    ASTContext *ast,
4530    clang_type_t clang_type,
4531    const char *name,
4532    bool omit_empty_base_classes,
4533    std::vector<uint32_t>& child_indexes
4534)
4535{
4536    if (clang_type && name && name[0])
4537    {
4538        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
4539        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4540        switch (type_class)
4541        {
4542        case clang::Type::Record:
4543            if (GetCompleteQualType (ast, qual_type))
4544            {
4545                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
4546                const RecordDecl *record_decl = record_type->getDecl();
4547
4548                assert(record_decl);
4549                uint32_t child_idx = 0;
4550
4551                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4552
4553                // Try and find a field that matches NAME
4554                RecordDecl::field_iterator field, field_end;
4555                StringRef name_sref(name);
4556                for (field = record_decl->field_begin(), field_end = record_decl->field_end();
4557                     field != field_end;
4558                     ++field, ++child_idx)
4559                {
4560                    if (field->getName().equals (name_sref))
4561                    {
4562                        // We have to add on the number of base classes to this index!
4563                        child_indexes.push_back (child_idx + GetNumBaseClasses (cxx_record_decl, omit_empty_base_classes));
4564                        return child_indexes.size();
4565                    }
4566                }
4567
4568                if (cxx_record_decl)
4569                {
4570                    const RecordDecl *parent_record_decl = cxx_record_decl;
4571
4572                    //printf ("parent = %s\n", parent_record_decl->getNameAsCString());
4573
4574                    //const Decl *root_cdecl = cxx_record_decl->getCanonicalDecl();
4575                    // Didn't find things easily, lets let clang do its thang...
4576                    IdentifierInfo & ident_ref = ast->Idents.get(name_sref);
4577                    DeclarationName decl_name(&ident_ref);
4578
4579                    CXXBasePaths paths;
4580                    if (cxx_record_decl->lookupInBases(CXXRecordDecl::FindOrdinaryMember,
4581                                                       decl_name.getAsOpaquePtr(),
4582                                                       paths))
4583                    {
4584                        CXXBasePaths::const_paths_iterator path, path_end = paths.end();
4585                        for (path = paths.begin(); path != path_end; ++path)
4586                        {
4587                            const size_t num_path_elements = path->size();
4588                            for (size_t e=0; e<num_path_elements; ++e)
4589                            {
4590                                CXXBasePathElement elem = (*path)[e];
4591
4592                                child_idx = GetIndexForRecordBase (parent_record_decl, elem.Base, omit_empty_base_classes);
4593                                if (child_idx == UINT32_MAX)
4594                                {
4595                                    child_indexes.clear();
4596                                    return 0;
4597                                }
4598                                else
4599                                {
4600                                    child_indexes.push_back (child_idx);
4601                                    parent_record_decl = cast<RecordDecl>(elem.Base->getType()->getAs<RecordType>()->getDecl());
4602                                }
4603                            }
4604                            for (NamedDecl *path_decl : path->Decls)
4605                            {
4606                                child_idx = GetIndexForRecordChild (parent_record_decl, path_decl, omit_empty_base_classes);
4607                                if (child_idx == UINT32_MAX)
4608                                {
4609                                    child_indexes.clear();
4610                                    return 0;
4611                                }
4612                                else
4613                                {
4614                                    child_indexes.push_back (child_idx);
4615                                }
4616                            }
4617                        }
4618                        return child_indexes.size();
4619                    }
4620                }
4621
4622            }
4623            break;
4624
4625        case clang::Type::ObjCObject:
4626        case clang::Type::ObjCInterface:
4627            if (GetCompleteQualType (ast, qual_type))
4628            {
4629                StringRef name_sref(name);
4630                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
4631                assert (objc_class_type);
4632                if (objc_class_type)
4633                {
4634                    uint32_t child_idx = 0;
4635                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
4636
4637                    if (class_interface_decl)
4638                    {
4639                        ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
4640                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
4641
4642                        for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos, ++child_idx)
4643                        {
4644                            const ObjCIvarDecl* ivar_decl = *ivar_pos;
4645
4646                            if (ivar_decl->getName().equals (name_sref))
4647                            {
4648                                if ((!omit_empty_base_classes && superclass_interface_decl) ||
4649                                    ( omit_empty_base_classes && ObjCDeclHasIVars (superclass_interface_decl, true)))
4650                                    ++child_idx;
4651
4652                                child_indexes.push_back (child_idx);
4653                                return child_indexes.size();
4654                            }
4655                        }
4656
4657                        if (superclass_interface_decl)
4658                        {
4659                            // The super class index is always zero for ObjC classes,
4660                            // so we push it onto the child indexes in case we find
4661                            // an ivar in our superclass...
4662                            child_indexes.push_back (0);
4663
4664                            if (GetIndexOfChildMemberWithName (ast,
4665                                                               ast->getObjCInterfaceType(superclass_interface_decl).getAsOpaquePtr(),
4666                                                               name,
4667                                                               omit_empty_base_classes,
4668                                                               child_indexes))
4669                            {
4670                                // We did find an ivar in a superclass so just
4671                                // return the results!
4672                                return child_indexes.size();
4673                            }
4674
4675                            // We didn't find an ivar matching "name" in our
4676                            // superclass, pop the superclass zero index that
4677                            // we pushed on above.
4678                            child_indexes.pop_back();
4679                        }
4680                    }
4681                }
4682            }
4683            break;
4684
4685        case clang::Type::ObjCObjectPointer:
4686            {
4687                return GetIndexOfChildMemberWithName (ast,
4688                                                      cast<ObjCObjectPointerType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr(),
4689                                                      name,
4690                                                      omit_empty_base_classes,
4691                                                      child_indexes);
4692            }
4693            break;
4694
4695
4696        case clang::Type::ConstantArray:
4697            {
4698//                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
4699//                const uint64_t element_count = array->getSize().getLimitedValue();
4700//
4701//                if (idx < element_count)
4702//                {
4703//                    std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(array->getElementType());
4704//
4705//                    char element_name[32];
4706//                    ::snprintf (element_name, sizeof (element_name), "%s[%u]", parent_name ? parent_name : "", idx);
4707//
4708//                    child_name.assign(element_name);
4709//                    assert(field_type_info.first % 8 == 0);
4710//                    child_byte_size = field_type_info.first / 8;
4711//                    child_byte_offset = idx * child_byte_size;
4712//                    return array->getElementType().getAsOpaquePtr();
4713//                }
4714            }
4715            break;
4716
4717//        case clang::Type::MemberPointerType:
4718//            {
4719//                MemberPointerType *mem_ptr_type = cast<MemberPointerType>(qual_type.getTypePtr());
4720//                QualType pointee_type = mem_ptr_type->getPointeeType();
4721//
4722//                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4723//                {
4724//                    return GetIndexOfChildWithName (ast,
4725//                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
4726//                                                    name);
4727//                }
4728//            }
4729//            break;
4730//
4731        case clang::Type::LValueReference:
4732        case clang::Type::RValueReference:
4733            {
4734                const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
4735                QualType pointee_type = reference_type->getPointeeType();
4736
4737                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4738                {
4739                    return GetIndexOfChildMemberWithName (ast,
4740                                                          reference_type->getPointeeType().getAsOpaquePtr(),
4741                                                          name,
4742                                                          omit_empty_base_classes,
4743                                                          child_indexes);
4744                }
4745            }
4746            break;
4747
4748        case clang::Type::Pointer:
4749            {
4750                const PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
4751                QualType pointee_type = pointer_type->getPointeeType();
4752
4753                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4754                {
4755                    return GetIndexOfChildMemberWithName (ast,
4756                                                          pointer_type->getPointeeType().getAsOpaquePtr(),
4757                                                          name,
4758                                                          omit_empty_base_classes,
4759                                                          child_indexes);
4760                }
4761                else
4762                {
4763//                    if (parent_name)
4764//                    {
4765//                        child_name.assign(1, '*');
4766//                        child_name += parent_name;
4767//                    }
4768//
4769//                    // We have a pointer to an simple type
4770//                    if (idx == 0)
4771//                    {
4772//                        std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4773//                        assert(clang_type_info.first % 8 == 0);
4774//                        child_byte_size = clang_type_info.first / 8;
4775//                        child_byte_offset = 0;
4776//                        return pointee_type.getAsOpaquePtr();
4777//                    }
4778                }
4779            }
4780            break;
4781
4782        case clang::Type::Typedef:
4783            return GetIndexOfChildMemberWithName (ast,
4784                                                  cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
4785                                                  name,
4786                                                  omit_empty_base_classes,
4787                                                  child_indexes);
4788
4789        case clang::Type::Elaborated:
4790            return GetIndexOfChildMemberWithName (ast,
4791                                                  cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
4792                                                  name,
4793                                                  omit_empty_base_classes,
4794                                                  child_indexes);
4795
4796        default:
4797            break;
4798        }
4799    }
4800    return 0;
4801}
4802
4803
4804// Get the index of the child of "clang_type" whose name matches. This function
4805// doesn't descend into the children, but only looks one level deep and name
4806// matches can include base class names.
4807
4808uint32_t
4809ClangASTContext::GetIndexOfChildWithName
4810(
4811    ASTContext *ast,
4812    clang_type_t clang_type,
4813    const char *name,
4814    bool omit_empty_base_classes
4815)
4816{
4817    if (clang_type && name && name[0])
4818    {
4819        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
4820
4821        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4822
4823        switch (type_class)
4824        {
4825        case clang::Type::Record:
4826            if (GetCompleteQualType (ast, qual_type))
4827            {
4828                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
4829                const RecordDecl *record_decl = record_type->getDecl();
4830
4831                assert(record_decl);
4832                uint32_t child_idx = 0;
4833
4834                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
4835
4836                if (cxx_record_decl)
4837                {
4838                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
4839                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
4840                         base_class != base_class_end;
4841                         ++base_class)
4842                    {
4843                        // Skip empty base classes
4844                        CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
4845                        if (omit_empty_base_classes && RecordHasFields(base_class_decl) == false)
4846                            continue;
4847
4848                        std::string base_class_type_name (ClangASTType::GetTypeNameForQualType(ast, base_class->getType()));
4849                        if (base_class_type_name.compare (name) == 0)
4850                            return child_idx;
4851                        ++child_idx;
4852                    }
4853                }
4854
4855                // Try and find a field that matches NAME
4856                RecordDecl::field_iterator field, field_end;
4857                StringRef name_sref(name);
4858                for (field = record_decl->field_begin(), field_end = record_decl->field_end();
4859                     field != field_end;
4860                     ++field, ++child_idx)
4861                {
4862                    if (field->getName().equals (name_sref))
4863                        return child_idx;
4864                }
4865
4866            }
4867            break;
4868
4869        case clang::Type::ObjCObject:
4870        case clang::Type::ObjCInterface:
4871            if (GetCompleteQualType (ast, qual_type))
4872            {
4873                StringRef name_sref(name);
4874                const ObjCObjectType *objc_class_type = dyn_cast<ObjCObjectType>(qual_type.getTypePtr());
4875                assert (objc_class_type);
4876                if (objc_class_type)
4877                {
4878                    uint32_t child_idx = 0;
4879                    ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface();
4880
4881                    if (class_interface_decl)
4882                    {
4883                        ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end();
4884                        ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass();
4885
4886                        for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos, ++child_idx)
4887                        {
4888                            const ObjCIvarDecl* ivar_decl = *ivar_pos;
4889
4890                            if (ivar_decl->getName().equals (name_sref))
4891                            {
4892                                if ((!omit_empty_base_classes && superclass_interface_decl) ||
4893                                    ( omit_empty_base_classes && ObjCDeclHasIVars (superclass_interface_decl, true)))
4894                                    ++child_idx;
4895
4896                                return child_idx;
4897                            }
4898                        }
4899
4900                        if (superclass_interface_decl)
4901                        {
4902                            if (superclass_interface_decl->getName().equals (name_sref))
4903                                return 0;
4904                        }
4905                    }
4906                }
4907            }
4908            break;
4909
4910        case clang::Type::ObjCObjectPointer:
4911            {
4912                return GetIndexOfChildWithName (ast,
4913                                                cast<ObjCObjectPointerType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr(),
4914                                                name,
4915                                                omit_empty_base_classes);
4916            }
4917            break;
4918
4919        case clang::Type::ConstantArray:
4920            {
4921//                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
4922//                const uint64_t element_count = array->getSize().getLimitedValue();
4923//
4924//                if (idx < element_count)
4925//                {
4926//                    std::pair<uint64_t, unsigned> field_type_info = ast->getTypeInfo(array->getElementType());
4927//
4928//                    char element_name[32];
4929//                    ::snprintf (element_name, sizeof (element_name), "%s[%u]", parent_name ? parent_name : "", idx);
4930//
4931//                    child_name.assign(element_name);
4932//                    assert(field_type_info.first % 8 == 0);
4933//                    child_byte_size = field_type_info.first / 8;
4934//                    child_byte_offset = idx * child_byte_size;
4935//                    return array->getElementType().getAsOpaquePtr();
4936//                }
4937            }
4938            break;
4939
4940//        case clang::Type::MemberPointerType:
4941//            {
4942//                MemberPointerType *mem_ptr_type = cast<MemberPointerType>(qual_type.getTypePtr());
4943//                QualType pointee_type = mem_ptr_type->getPointeeType();
4944//
4945//                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4946//                {
4947//                    return GetIndexOfChildWithName (ast,
4948//                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
4949//                                                    name);
4950//                }
4951//            }
4952//            break;
4953//
4954        case clang::Type::LValueReference:
4955        case clang::Type::RValueReference:
4956            {
4957                const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
4958                QualType pointee_type = reference_type->getPointeeType();
4959
4960                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4961                {
4962                    return GetIndexOfChildWithName (ast,
4963                                                    reference_type->getPointeeType().getAsOpaquePtr(),
4964                                                    name,
4965                                                    omit_empty_base_classes);
4966                }
4967            }
4968            break;
4969
4970        case clang::Type::Pointer:
4971            {
4972                const PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
4973                QualType pointee_type = pointer_type->getPointeeType();
4974
4975                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
4976                {
4977                    return GetIndexOfChildWithName (ast,
4978                                                    pointer_type->getPointeeType().getAsOpaquePtr(),
4979                                                    name,
4980                                                    omit_empty_base_classes);
4981                }
4982                else
4983                {
4984//                    if (parent_name)
4985//                    {
4986//                        child_name.assign(1, '*');
4987//                        child_name += parent_name;
4988//                    }
4989//
4990//                    // We have a pointer to an simple type
4991//                    if (idx == 0)
4992//                    {
4993//                        std::pair<uint64_t, unsigned> clang_type_info = ast->getTypeInfo(pointee_type);
4994//                        assert(clang_type_info.first % 8 == 0);
4995//                        child_byte_size = clang_type_info.first / 8;
4996//                        child_byte_offset = 0;
4997//                        return pointee_type.getAsOpaquePtr();
4998//                    }
4999                }
5000            }
5001            break;
5002
5003        case clang::Type::Elaborated:
5004            return GetIndexOfChildWithName (ast,
5005                                            cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
5006                                            name,
5007                                            omit_empty_base_classes);
5008
5009        case clang::Type::Typedef:
5010            return GetIndexOfChildWithName (ast,
5011                                            cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
5012                                            name,
5013                                            omit_empty_base_classes);
5014
5015        default:
5016            break;
5017        }
5018    }
5019    return UINT32_MAX;
5020}
5021
5022#pragma mark TagType
5023
5024bool
5025ClangASTContext::SetTagTypeKind (clang_type_t tag_clang_type, int kind)
5026{
5027    if (tag_clang_type)
5028    {
5029        QualType tag_qual_type(QualType::getFromOpaquePtr(tag_clang_type));
5030        const clang::Type *clang_type = tag_qual_type.getTypePtr();
5031        if (clang_type)
5032        {
5033            const TagType *tag_type = dyn_cast<TagType>(clang_type);
5034            if (tag_type)
5035            {
5036                TagDecl *tag_decl = dyn_cast<TagDecl>(tag_type->getDecl());
5037                if (tag_decl)
5038                {
5039                    tag_decl->setTagKind ((TagDecl::TagKind)kind);
5040                    return true;
5041                }
5042            }
5043        }
5044    }
5045    return false;
5046}
5047
5048
5049#pragma mark DeclContext Functions
5050
5051DeclContext *
5052ClangASTContext::GetDeclContextForType (clang_type_t clang_type)
5053{
5054    if (clang_type == NULL)
5055        return NULL;
5056
5057    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
5058    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5059    switch (type_class)
5060    {
5061    case clang::Type::UnaryTransform:           break;
5062    case clang::Type::FunctionNoProto:          break;
5063    case clang::Type::FunctionProto:            break;
5064    case clang::Type::IncompleteArray:          break;
5065    case clang::Type::VariableArray:            break;
5066    case clang::Type::ConstantArray:            break;
5067    case clang::Type::DependentSizedArray:      break;
5068    case clang::Type::ExtVector:                break;
5069    case clang::Type::DependentSizedExtVector:  break;
5070    case clang::Type::Vector:                   break;
5071    case clang::Type::Builtin:                  break;
5072    case clang::Type::BlockPointer:             break;
5073    case clang::Type::Pointer:                  break;
5074    case clang::Type::LValueReference:          break;
5075    case clang::Type::RValueReference:          break;
5076    case clang::Type::MemberPointer:            break;
5077    case clang::Type::Complex:                  break;
5078    case clang::Type::ObjCObject:               break;
5079    case clang::Type::ObjCInterface:            return cast<ObjCObjectType>(qual_type.getTypePtr())->getInterface();
5080    case clang::Type::ObjCObjectPointer:        return ClangASTContext::GetDeclContextForType (cast<ObjCObjectPointerType>(qual_type.getTypePtr())->getPointeeType().getAsOpaquePtr());
5081    case clang::Type::Record:                   return cast<RecordType>(qual_type)->getDecl();
5082    case clang::Type::Enum:                     return cast<EnumType>(qual_type)->getDecl();
5083    case clang::Type::Typedef:                  return ClangASTContext::GetDeclContextForType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
5084    case clang::Type::Elaborated:               return ClangASTContext::GetDeclContextForType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
5085    case clang::Type::TypeOfExpr:               break;
5086    case clang::Type::TypeOf:                   break;
5087    case clang::Type::Decltype:                 break;
5088    //case clang::Type::QualifiedName:          break;
5089    case clang::Type::TemplateSpecialization:   break;
5090    case clang::Type::DependentTemplateSpecialization:  break;
5091    case clang::Type::TemplateTypeParm:         break;
5092    case clang::Type::SubstTemplateTypeParm:    break;
5093    case clang::Type::SubstTemplateTypeParmPack:break;
5094    case clang::Type::PackExpansion:            break;
5095    case clang::Type::UnresolvedUsing:          break;
5096    case clang::Type::Paren:                    break;
5097    case clang::Type::Attributed:               break;
5098    case clang::Type::Auto:                     break;
5099    case clang::Type::InjectedClassName:        break;
5100    case clang::Type::DependentName:            break;
5101    case clang::Type::Atomic:                   break;
5102    }
5103    // No DeclContext in this type...
5104    return NULL;
5105}
5106
5107#pragma mark Namespace Declarations
5108
5109NamespaceDecl *
5110ClangASTContext::GetUniqueNamespaceDeclaration (const char *name, DeclContext *decl_ctx)
5111{
5112    NamespaceDecl *namespace_decl = NULL;
5113    ASTContext *ast = getASTContext();
5114    TranslationUnitDecl *translation_unit_decl = ast->getTranslationUnitDecl ();
5115    if (decl_ctx == NULL)
5116        decl_ctx = translation_unit_decl;
5117
5118    if (name)
5119    {
5120        IdentifierInfo &identifier_info = ast->Idents.get(name);
5121        DeclarationName decl_name (&identifier_info);
5122        clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
5123        for (NamedDecl *decl : result)
5124        {
5125            namespace_decl = dyn_cast<clang::NamespaceDecl>(decl);
5126            if (namespace_decl)
5127                return namespace_decl;
5128        }
5129
5130        namespace_decl = NamespaceDecl::Create(*ast,
5131                                               decl_ctx,
5132                                               false,
5133                                               SourceLocation(),
5134                                               SourceLocation(),
5135                                               &identifier_info,
5136                                               NULL);
5137
5138        decl_ctx->addDecl (namespace_decl);
5139    }
5140    else
5141    {
5142        if (decl_ctx == translation_unit_decl)
5143        {
5144            namespace_decl = translation_unit_decl->getAnonymousNamespace();
5145            if (namespace_decl)
5146                return namespace_decl;
5147
5148            namespace_decl = NamespaceDecl::Create(*ast,
5149                                                   decl_ctx,
5150                                                   false,
5151                                                   SourceLocation(),
5152                                                   SourceLocation(),
5153                                                   NULL,
5154                                                   NULL);
5155            translation_unit_decl->setAnonymousNamespace (namespace_decl);
5156            translation_unit_decl->addDecl (namespace_decl);
5157            assert (namespace_decl == translation_unit_decl->getAnonymousNamespace());
5158        }
5159        else
5160        {
5161            NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx);
5162            if (parent_namespace_decl)
5163            {
5164                namespace_decl = parent_namespace_decl->getAnonymousNamespace();
5165                if (namespace_decl)
5166                    return namespace_decl;
5167                namespace_decl = NamespaceDecl::Create(*ast,
5168                                                       decl_ctx,
5169                                                       false,
5170                                                       SourceLocation(),
5171                                                       SourceLocation(),
5172                                                       NULL,
5173                                                       NULL);
5174                parent_namespace_decl->setAnonymousNamespace (namespace_decl);
5175                parent_namespace_decl->addDecl (namespace_decl);
5176                assert (namespace_decl == parent_namespace_decl->getAnonymousNamespace());
5177            }
5178            else
5179            {
5180                // BAD!!!
5181            }
5182        }
5183
5184
5185        if (namespace_decl)
5186        {
5187            // If we make it here, we are creating the anonymous namespace decl
5188            // for the first time, so we need to do the using directive magic
5189            // like SEMA does
5190            UsingDirectiveDecl* using_directive_decl = UsingDirectiveDecl::Create (*ast,
5191                                                                                   decl_ctx,
5192                                                                                   SourceLocation(),
5193                                                                                   SourceLocation(),
5194                                                                                   NestedNameSpecifierLoc(),
5195                                                                                   SourceLocation(),
5196                                                                                   namespace_decl,
5197                                                                                   decl_ctx);
5198            using_directive_decl->setImplicit();
5199            decl_ctx->addDecl(using_directive_decl);
5200        }
5201    }
5202#ifdef LLDB_CONFIGURATION_DEBUG
5203    VerifyDecl(namespace_decl);
5204#endif
5205    return namespace_decl;
5206}
5207
5208
5209#pragma mark Function Types
5210
5211FunctionDecl *
5212ClangASTContext::CreateFunctionDeclaration (DeclContext *decl_ctx, const char *name, clang_type_t function_clang_type, int storage, bool is_inline)
5213{
5214    FunctionDecl *func_decl = NULL;
5215    ASTContext *ast = getASTContext();
5216    if (decl_ctx == NULL)
5217        decl_ctx = ast->getTranslationUnitDecl();
5218
5219    if (name && name[0])
5220    {
5221        func_decl = FunctionDecl::Create (*ast,
5222                                          decl_ctx,
5223                                          SourceLocation(),
5224                                          SourceLocation(),
5225                                          DeclarationName (&ast->Idents.get(name)),
5226                                          QualType::getFromOpaquePtr(function_clang_type),
5227                                          NULL,
5228                                          (FunctionDecl::StorageClass)storage,
5229                                          (FunctionDecl::StorageClass)storage,
5230                                          is_inline);
5231    }
5232    else
5233    {
5234        func_decl = FunctionDecl::Create (*ast,
5235                                          decl_ctx,
5236                                          SourceLocation(),
5237                                          SourceLocation(),
5238                                          DeclarationName (),
5239                                          QualType::getFromOpaquePtr(function_clang_type),
5240                                          NULL,
5241                                          (FunctionDecl::StorageClass)storage,
5242                                          (FunctionDecl::StorageClass)storage,
5243                                          is_inline);
5244    }
5245    if (func_decl)
5246        decl_ctx->addDecl (func_decl);
5247
5248#ifdef LLDB_CONFIGURATION_DEBUG
5249    VerifyDecl(func_decl);
5250#endif
5251
5252    return func_decl;
5253}
5254
5255clang_type_t
5256ClangASTContext::CreateFunctionType (ASTContext *ast,
5257                                     clang_type_t result_type,
5258                                     clang_type_t *args,
5259                                     unsigned num_args,
5260                                     bool is_variadic,
5261                                     unsigned type_quals)
5262{
5263    assert (ast != NULL);
5264    std::vector<QualType> qual_type_args;
5265    for (unsigned i=0; i<num_args; ++i)
5266        qual_type_args.push_back (QualType::getFromOpaquePtr(args[i]));
5267
5268    // TODO: Detect calling convention in DWARF?
5269    FunctionProtoType::ExtProtoInfo proto_info;
5270    proto_info.Variadic = is_variadic;
5271    proto_info.ExceptionSpecType = EST_None;
5272    proto_info.TypeQuals = type_quals;
5273    proto_info.RefQualifier = RQ_None;
5274    proto_info.NumExceptions = 0;
5275    proto_info.Exceptions = NULL;
5276
5277    return ast->getFunctionType (QualType::getFromOpaquePtr(result_type),
5278                                 qual_type_args,
5279                                 proto_info).getAsOpaquePtr();
5280}
5281
5282ParmVarDecl *
5283ClangASTContext::CreateParameterDeclaration (const char *name, clang_type_t param_type, int storage)
5284{
5285    ASTContext *ast = getASTContext();
5286    assert (ast != NULL);
5287    return ParmVarDecl::Create(*ast,
5288                                ast->getTranslationUnitDecl(),
5289                                SourceLocation(),
5290                                SourceLocation(),
5291                                name && name[0] ? &ast->Idents.get(name) : NULL,
5292                                QualType::getFromOpaquePtr(param_type),
5293                                NULL,
5294                                (VarDecl::StorageClass)storage,
5295                                (VarDecl::StorageClass)storage,
5296                                0);
5297}
5298
5299void
5300ClangASTContext::SetFunctionParameters (FunctionDecl *function_decl, ParmVarDecl **params, unsigned num_params)
5301{
5302    if (function_decl)
5303        function_decl->setParams (ArrayRef<ParmVarDecl*>(params, num_params));
5304}
5305
5306
5307#pragma mark Array Types
5308
5309clang_type_t
5310ClangASTContext::CreateArrayType (clang_type_t element_type, size_t element_count)
5311{
5312    if (element_type)
5313    {
5314        ASTContext *ast = getASTContext();
5315        assert (ast != NULL);
5316        llvm::APInt ap_element_count (64, element_count);
5317        if (element_count == 0)
5318        {
5319            return ast->getIncompleteArrayType(QualType::getFromOpaquePtr(element_type),
5320                                               ArrayType::Normal,
5321                                               0).getAsOpaquePtr();
5322
5323        }
5324        else
5325        {
5326            return ast->getConstantArrayType(QualType::getFromOpaquePtr(element_type),
5327                                                     ap_element_count,
5328                                                     ArrayType::Normal,
5329                                                     0).getAsOpaquePtr(); // ElemQuals
5330        }
5331    }
5332    return NULL;
5333}
5334
5335
5336#pragma mark TagDecl
5337
5338bool
5339ClangASTContext::StartTagDeclarationDefinition (clang_type_t clang_type)
5340{
5341    if (clang_type)
5342    {
5343        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5344        const clang::Type *t = qual_type.getTypePtr();
5345        if (t)
5346        {
5347            const TagType *tag_type = dyn_cast<TagType>(t);
5348            if (tag_type)
5349            {
5350                TagDecl *tag_decl = tag_type->getDecl();
5351                if (tag_decl)
5352                {
5353                    tag_decl->startDefinition();
5354                    return true;
5355                }
5356            }
5357
5358            const ObjCObjectType *object_type = dyn_cast<ObjCObjectType>(t);
5359            if (object_type)
5360            {
5361                ObjCInterfaceDecl *interface_decl = object_type->getInterface();
5362                if (interface_decl)
5363                {
5364                    interface_decl->startDefinition();
5365                    return true;
5366                }
5367            }
5368        }
5369    }
5370    return false;
5371}
5372
5373bool
5374ClangASTContext::CompleteTagDeclarationDefinition (clang_type_t clang_type)
5375{
5376    if (clang_type)
5377    {
5378        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5379
5380        CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
5381
5382        if (cxx_record_decl)
5383        {
5384            cxx_record_decl->completeDefinition();
5385
5386            return true;
5387        }
5388
5389        const EnumType *enum_type = dyn_cast<EnumType>(qual_type.getTypePtr());
5390
5391        if (enum_type)
5392        {
5393            EnumDecl *enum_decl = enum_type->getDecl();
5394
5395            if (enum_decl)
5396            {
5397                /// TODO This really needs to be fixed.
5398
5399                unsigned NumPositiveBits = 1;
5400                unsigned NumNegativeBits = 0;
5401
5402                ASTContext *ast = getASTContext();
5403
5404                QualType promotion_qual_type;
5405                // If the enum integer type is less than an integer in bit width,
5406                // then we must promote it to an integer size.
5407                if (ast->getTypeSize(enum_decl->getIntegerType()) < ast->getTypeSize(ast->IntTy))
5408                {
5409                    if (enum_decl->getIntegerType()->isSignedIntegerType())
5410                        promotion_qual_type = ast->IntTy;
5411                    else
5412                        promotion_qual_type = ast->UnsignedIntTy;
5413                }
5414                else
5415                    promotion_qual_type = enum_decl->getIntegerType();
5416
5417                enum_decl->completeDefinition(enum_decl->getIntegerType(), promotion_qual_type, NumPositiveBits, NumNegativeBits);
5418                return true;
5419            }
5420        }
5421    }
5422    return false;
5423}
5424
5425
5426#pragma mark Enumeration Types
5427
5428clang_type_t
5429ClangASTContext::CreateEnumerationType
5430(
5431    const char *name,
5432    DeclContext *decl_ctx,
5433    const Declaration &decl,
5434    clang_type_t integer_qual_type
5435)
5436{
5437    // TODO: Do something intelligent with the Declaration object passed in
5438    // like maybe filling in the SourceLocation with it...
5439    ASTContext *ast = getASTContext();
5440    assert (ast != NULL);
5441
5442    // TODO: ask about these...
5443//    const bool IsScoped = false;
5444//    const bool IsFixed = false;
5445
5446    EnumDecl *enum_decl = EnumDecl::Create (*ast,
5447                                            decl_ctx,
5448                                            SourceLocation(),
5449                                            SourceLocation(),
5450                                            name && name[0] ? &ast->Idents.get(name) : NULL,
5451                                            NULL,
5452                                            false,  // IsScoped
5453                                            false,  // IsScopedUsingClassTag
5454                                            false); // IsFixed
5455
5456
5457    if (enum_decl)
5458    {
5459        // TODO: check if we should be setting the promotion type too?
5460        enum_decl->setIntegerType(QualType::getFromOpaquePtr (integer_qual_type));
5461
5462        enum_decl->setAccess(AS_public); // TODO respect what's in the debug info
5463
5464        return ast->getTagDeclType(enum_decl).getAsOpaquePtr();
5465    }
5466    return NULL;
5467}
5468
5469clang_type_t
5470ClangASTContext::GetEnumerationIntegerType (clang_type_t enum_clang_type)
5471{
5472    QualType enum_qual_type (QualType::getFromOpaquePtr(enum_clang_type));
5473
5474    const clang::Type *clang_type = enum_qual_type.getTypePtr();
5475    if (clang_type)
5476    {
5477        const EnumType *enum_type = dyn_cast<EnumType>(clang_type);
5478        if (enum_type)
5479        {
5480            EnumDecl *enum_decl = enum_type->getDecl();
5481            if (enum_decl)
5482                return enum_decl->getIntegerType().getAsOpaquePtr();
5483        }
5484    }
5485    return NULL;
5486}
5487bool
5488ClangASTContext::AddEnumerationValueToEnumerationType
5489(
5490    clang_type_t enum_clang_type,
5491    clang_type_t enumerator_clang_type,
5492    const Declaration &decl,
5493    const char *name,
5494    int64_t enum_value,
5495    uint32_t enum_value_bit_size
5496)
5497{
5498    if (enum_clang_type && enumerator_clang_type && name)
5499    {
5500        // TODO: Do something intelligent with the Declaration object passed in
5501        // like maybe filling in the SourceLocation with it...
5502        ASTContext *ast = getASTContext();
5503        IdentifierTable *identifier_table = getIdentifierTable();
5504
5505        assert (ast != NULL);
5506        assert (identifier_table != NULL);
5507        QualType enum_qual_type (QualType::getFromOpaquePtr(enum_clang_type));
5508
5509        bool is_signed = false;
5510        IsIntegerType (enumerator_clang_type, is_signed);
5511        const clang::Type *clang_type = enum_qual_type.getTypePtr();
5512        if (clang_type)
5513        {
5514            const EnumType *enum_type = dyn_cast<EnumType>(clang_type);
5515
5516            if (enum_type)
5517            {
5518                llvm::APSInt enum_llvm_apsint(enum_value_bit_size, is_signed);
5519                enum_llvm_apsint = enum_value;
5520                EnumConstantDecl *enumerator_decl =
5521                    EnumConstantDecl::Create (*ast,
5522                                              enum_type->getDecl(),
5523                                              SourceLocation(),
5524                                              name ? &identifier_table->get(name) : NULL,    // Identifier
5525                                              QualType::getFromOpaquePtr(enumerator_clang_type),
5526                                              NULL,
5527                                              enum_llvm_apsint);
5528
5529                if (enumerator_decl)
5530                {
5531                    enum_type->getDecl()->addDecl(enumerator_decl);
5532
5533#ifdef LLDB_CONFIGURATION_DEBUG
5534                    VerifyDecl(enumerator_decl);
5535#endif
5536
5537                    return true;
5538                }
5539            }
5540        }
5541    }
5542    return false;
5543}
5544
5545#pragma mark Pointers & References
5546
5547clang_type_t
5548ClangASTContext::CreatePointerType (clang_type_t clang_type)
5549{
5550    return CreatePointerType (getASTContext(), clang_type);
5551}
5552
5553clang_type_t
5554ClangASTContext::CreatePointerType (clang::ASTContext *ast, clang_type_t clang_type)
5555{
5556    if (ast && clang_type)
5557    {
5558        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5559
5560        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5561        switch (type_class)
5562        {
5563        case clang::Type::ObjCObject:
5564        case clang::Type::ObjCInterface:
5565            return ast->getObjCObjectPointerType(qual_type).getAsOpaquePtr();
5566
5567        default:
5568            return ast->getPointerType(qual_type).getAsOpaquePtr();
5569        }
5570    }
5571    return NULL;
5572}
5573
5574clang_type_t
5575ClangASTContext::CreateLValueReferenceType (clang::ASTContext *ast,
5576                                            clang_type_t clang_type)
5577{
5578    if (clang_type)
5579        return ast->getLValueReferenceType (QualType::getFromOpaquePtr(clang_type)).getAsOpaquePtr();
5580    return NULL;
5581}
5582
5583clang_type_t
5584ClangASTContext::CreateRValueReferenceType (clang::ASTContext *ast,
5585                                            clang_type_t clang_type)
5586{
5587    if (clang_type)
5588        return ast->getRValueReferenceType (QualType::getFromOpaquePtr(clang_type)).getAsOpaquePtr();
5589    return NULL;
5590}
5591
5592clang_type_t
5593ClangASTContext::CreateMemberPointerType (clang_type_t clang_pointee_type, clang_type_t clang_class_type)
5594{
5595    if (clang_pointee_type && clang_pointee_type)
5596        return getASTContext()->getMemberPointerType(QualType::getFromOpaquePtr(clang_pointee_type),
5597                                                     QualType::getFromOpaquePtr(clang_class_type).getTypePtr()).getAsOpaquePtr();
5598    return NULL;
5599}
5600
5601uint64_t
5602ClangASTContext::GetPointerBitSize ()
5603{
5604    ASTContext *ast = getASTContext();
5605    return ast->getTypeSize(ast->VoidPtrTy);
5606}
5607
5608bool
5609ClangASTContext::IsPossibleDynamicType (clang::ASTContext *ast,
5610                                        clang_type_t clang_type,
5611                                        clang_type_t *dynamic_pointee_type,
5612                                        bool check_cplusplus,
5613                                        bool check_objc)
5614{
5615    QualType pointee_qual_type;
5616    if (clang_type)
5617    {
5618        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5619        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5620        bool success = false;
5621        switch (type_class)
5622        {
5623            case clang::Type::Builtin:
5624                if (check_objc && cast<clang::BuiltinType>(qual_type)->getKind() == clang::BuiltinType::ObjCId)
5625                {
5626                    if (dynamic_pointee_type)
5627                        *dynamic_pointee_type = clang_type;
5628                    return true;
5629                }
5630                break;
5631
5632            case clang::Type::ObjCObjectPointer:
5633                if (check_objc)
5634                {
5635                    if (dynamic_pointee_type)
5636                        *dynamic_pointee_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5637                    return true;
5638                }
5639                break;
5640
5641            case clang::Type::Pointer:
5642                pointee_qual_type = cast<PointerType>(qual_type)->getPointeeType();
5643                success = true;
5644                break;
5645
5646            case clang::Type::LValueReference:
5647            case clang::Type::RValueReference:
5648                pointee_qual_type = cast<ReferenceType>(qual_type)->getPointeeType();
5649                success = true;
5650                break;
5651
5652            case clang::Type::Typedef:
5653                return ClangASTContext::IsPossibleDynamicType (ast,
5654                                                               cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
5655                                                               dynamic_pointee_type,
5656                                                               check_cplusplus,
5657                                                               check_objc);
5658
5659            case clang::Type::Elaborated:
5660                return ClangASTContext::IsPossibleDynamicType (ast,
5661                                                               cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
5662                                                               dynamic_pointee_type,
5663                                                               check_cplusplus,
5664                                                               check_objc);
5665
5666            default:
5667                break;
5668        }
5669
5670        if (success)
5671        {
5672            // Check to make sure what we are pointing too is a possible dynamic C++ type
5673            // We currently accept any "void *" (in case we have a class that has been
5674            // watered down to an opaque pointer) and virtual C++ classes.
5675            const clang::Type::TypeClass pointee_type_class = pointee_qual_type->getTypeClass();
5676            switch (pointee_type_class)
5677            {
5678                case clang::Type::Builtin:
5679                    switch (cast<clang::BuiltinType>(pointee_qual_type)->getKind())
5680                    {
5681                        case clang::BuiltinType::UnknownAny:
5682                        case clang::BuiltinType::Void:
5683                            if (dynamic_pointee_type)
5684                                *dynamic_pointee_type = pointee_qual_type.getAsOpaquePtr();
5685                            return true;
5686
5687                        case clang::BuiltinType::NullPtr:
5688                        case clang::BuiltinType::Bool:
5689                        case clang::BuiltinType::Char_U:
5690                        case clang::BuiltinType::UChar:
5691                        case clang::BuiltinType::WChar_U:
5692                        case clang::BuiltinType::Char16:
5693                        case clang::BuiltinType::Char32:
5694                        case clang::BuiltinType::UShort:
5695                        case clang::BuiltinType::UInt:
5696                        case clang::BuiltinType::ULong:
5697                        case clang::BuiltinType::ULongLong:
5698                        case clang::BuiltinType::UInt128:
5699                        case clang::BuiltinType::Char_S:
5700                        case clang::BuiltinType::SChar:
5701                        case clang::BuiltinType::WChar_S:
5702                        case clang::BuiltinType::Short:
5703                        case clang::BuiltinType::Int:
5704                        case clang::BuiltinType::Long:
5705                        case clang::BuiltinType::LongLong:
5706                        case clang::BuiltinType::Int128:
5707                        case clang::BuiltinType::Float:
5708                        case clang::BuiltinType::Double:
5709                        case clang::BuiltinType::LongDouble:
5710                        case clang::BuiltinType::Dependent:
5711                        case clang::BuiltinType::Overload:
5712                        case clang::BuiltinType::ObjCId:
5713                        case clang::BuiltinType::ObjCClass:
5714                        case clang::BuiltinType::ObjCSel:
5715                        case clang::BuiltinType::BoundMember:
5716                        case clang::BuiltinType::Half:
5717                        case clang::BuiltinType::ARCUnbridgedCast:
5718                        case clang::BuiltinType::PseudoObject:
5719                        case clang::BuiltinType::BuiltinFn:
5720                        case clang::BuiltinType::OCLEvent:
5721                        case clang::BuiltinType::OCLImage1d:
5722                        case clang::BuiltinType::OCLImage1dArray:
5723                        case clang::BuiltinType::OCLImage1dBuffer:
5724                        case clang::BuiltinType::OCLImage2d:
5725                        case clang::BuiltinType::OCLImage2dArray:
5726                        case clang::BuiltinType::OCLImage3d:
5727                        case clang::BuiltinType::OCLSampler:
5728                            break;
5729                    }
5730                    break;
5731
5732                case clang::Type::Record:
5733                    if (check_cplusplus)
5734                    {
5735                        CXXRecordDecl *cxx_record_decl = pointee_qual_type->getAsCXXRecordDecl();
5736                        if (cxx_record_decl)
5737                        {
5738                            bool is_complete = cxx_record_decl->isCompleteDefinition();
5739
5740                            if (is_complete)
5741                                success = cxx_record_decl->isDynamicClass();
5742                            else
5743                            {
5744                                ClangASTMetadata *metadata = GetMetadata (ast, (uintptr_t)cxx_record_decl);
5745                                if (metadata)
5746                                    success = metadata->GetIsDynamicCXXType();
5747                                else
5748                                {
5749                                    is_complete = ClangASTContext::GetCompleteType (ast, pointee_qual_type.getAsOpaquePtr());
5750                                    if (is_complete)
5751                                        success = cxx_record_decl->isDynamicClass();
5752                                    else
5753                                        success = false;
5754                                }
5755                            }
5756
5757                            if (success)
5758                            {
5759                                if (dynamic_pointee_type)
5760                                    *dynamic_pointee_type = pointee_qual_type.getAsOpaquePtr();
5761                                return true;
5762                            }
5763                        }
5764                    }
5765                    break;
5766
5767                case clang::Type::ObjCObject:
5768                case clang::Type::ObjCInterface:
5769                    if (check_objc)
5770                    {
5771                        if (dynamic_pointee_type)
5772                            *dynamic_pointee_type = pointee_qual_type.getAsOpaquePtr();
5773                        return true;
5774                    }
5775                    break;
5776
5777                default:
5778                    break;
5779            }
5780        }
5781    }
5782    if (dynamic_pointee_type)
5783        *dynamic_pointee_type = NULL;
5784    return false;
5785}
5786
5787
5788bool
5789ClangASTContext::IsPossibleCPlusPlusDynamicType (clang::ASTContext *ast, clang_type_t clang_type, clang_type_t *dynamic_pointee_type)
5790{
5791    return IsPossibleDynamicType (ast,
5792                                  clang_type,
5793                                  dynamic_pointee_type,
5794                                  true,     // Check for dynamic C++ types
5795                                  false);   // Check for dynamic ObjC types
5796}
5797
5798bool
5799ClangASTContext::IsReferenceType (clang_type_t clang_type, clang_type_t *target_type)
5800{
5801    if (clang_type == NULL)
5802        return false;
5803
5804    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5805    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5806
5807    switch (type_class)
5808    {
5809    case clang::Type::LValueReference:
5810        if (target_type)
5811            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5812        return true;
5813    case clang::Type::RValueReference:
5814        if (target_type)
5815            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5816        return true;
5817    case clang::Type::Typedef:
5818        return ClangASTContext::IsReferenceType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
5819    case clang::Type::Elaborated:
5820        return ClangASTContext::IsReferenceType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
5821    default:
5822        break;
5823    }
5824
5825    return false;
5826}
5827
5828bool
5829ClangASTContext::IsPointerOrReferenceType (clang_type_t clang_type, clang_type_t*target_type)
5830{
5831    if (clang_type == NULL)
5832        return false;
5833
5834    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5835    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5836    switch (type_class)
5837    {
5838    case clang::Type::Builtin:
5839        switch (cast<clang::BuiltinType>(qual_type)->getKind())
5840        {
5841        default:
5842            break;
5843        case clang::BuiltinType::ObjCId:
5844        case clang::BuiltinType::ObjCClass:
5845            return true;
5846        }
5847        return false;
5848    case clang::Type::ObjCObjectPointer:
5849        if (target_type)
5850            *target_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5851        return true;
5852    case clang::Type::BlockPointer:
5853        if (target_type)
5854            *target_type = cast<BlockPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5855        return true;
5856    case clang::Type::Pointer:
5857        if (target_type)
5858            *target_type = cast<PointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5859        return true;
5860    case clang::Type::MemberPointer:
5861        if (target_type)
5862            *target_type = cast<MemberPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5863        return true;
5864    case clang::Type::LValueReference:
5865        if (target_type)
5866            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5867        return true;
5868    case clang::Type::RValueReference:
5869        if (target_type)
5870            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
5871        return true;
5872    case clang::Type::Typedef:
5873        return ClangASTContext::IsPointerOrReferenceType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
5874    case clang::Type::Elaborated:
5875        return ClangASTContext::IsPointerOrReferenceType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
5876    default:
5877        break;
5878    }
5879    return false;
5880}
5881
5882bool
5883ClangASTContext::IsIntegerType (clang_type_t clang_type, bool &is_signed)
5884{
5885    if (!clang_type)
5886        return false;
5887
5888    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5889    const BuiltinType *builtin_type = dyn_cast<BuiltinType>(qual_type->getCanonicalTypeInternal());
5890
5891    if (builtin_type)
5892    {
5893        if (builtin_type->isInteger())
5894        {
5895            is_signed = builtin_type->isSignedInteger();
5896            return true;
5897        }
5898    }
5899
5900    return false;
5901}
5902
5903bool
5904ClangASTContext::IsPointerType (clang_type_t clang_type, clang_type_t *target_type)
5905{
5906    if (target_type)
5907        *target_type = NULL;
5908
5909    if (clang_type)
5910    {
5911        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5912        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5913        switch (type_class)
5914        {
5915        case clang::Type::Builtin:
5916            switch (cast<clang::BuiltinType>(qual_type)->getKind())
5917            {
5918            default:
5919                break;
5920            case clang::BuiltinType::ObjCId:
5921            case clang::BuiltinType::ObjCClass:
5922                return true;
5923            }
5924            return false;
5925        case clang::Type::ObjCObjectPointer:
5926            if (target_type)
5927                *target_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5928            return true;
5929        case clang::Type::BlockPointer:
5930            if (target_type)
5931                *target_type = cast<BlockPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5932            return true;
5933        case clang::Type::Pointer:
5934            if (target_type)
5935                *target_type = cast<PointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5936            return true;
5937        case clang::Type::MemberPointer:
5938            if (target_type)
5939                *target_type = cast<MemberPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
5940            return true;
5941        case clang::Type::Typedef:
5942            return ClangASTContext::IsPointerType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(), target_type);
5943        case clang::Type::Elaborated:
5944            return ClangASTContext::IsPointerType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(), target_type);
5945        default:
5946            break;
5947        }
5948    }
5949    return false;
5950}
5951
5952bool
5953ClangASTContext::IsFloatingPointType (clang_type_t clang_type, uint32_t &count, bool &is_complex)
5954{
5955    if (clang_type)
5956    {
5957        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
5958
5959        if (const BuiltinType *BT = dyn_cast<BuiltinType>(qual_type->getCanonicalTypeInternal()))
5960        {
5961            clang::BuiltinType::Kind kind = BT->getKind();
5962            if (kind >= BuiltinType::Float && kind <= BuiltinType::LongDouble)
5963            {
5964                count = 1;
5965                is_complex = false;
5966                return true;
5967            }
5968        }
5969        else if (const ComplexType *CT = dyn_cast<ComplexType>(qual_type->getCanonicalTypeInternal()))
5970        {
5971            if (IsFloatingPointType(CT->getElementType().getAsOpaquePtr(), count, is_complex))
5972            {
5973                count = 2;
5974                is_complex = true;
5975                return true;
5976            }
5977        }
5978        else if (const VectorType *VT = dyn_cast<VectorType>(qual_type->getCanonicalTypeInternal()))
5979        {
5980            if (IsFloatingPointType(VT->getElementType().getAsOpaquePtr(), count, is_complex))
5981            {
5982                count = VT->getNumElements();
5983                is_complex = false;
5984                return true;
5985            }
5986        }
5987    }
5988    return false;
5989}
5990
5991bool
5992ClangASTContext::IsScalarType (lldb::clang_type_t clang_type)
5993{
5994    bool is_signed;
5995    if (ClangASTContext::IsIntegerType(clang_type, is_signed))
5996        return true;
5997
5998    uint32_t count;
5999    bool is_complex;
6000    return ClangASTContext::IsFloatingPointType(clang_type, count, is_complex) && !is_complex;
6001}
6002
6003bool
6004ClangASTContext::IsPointerToScalarType (lldb::clang_type_t clang_type)
6005{
6006    if (!IsPointerType(clang_type))
6007        return false;
6008
6009    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6010    lldb::clang_type_t pointee_type = qual_type.getTypePtr()->getPointeeType().getAsOpaquePtr();
6011    return IsScalarType(pointee_type);
6012}
6013
6014bool
6015ClangASTContext::IsArrayOfScalarType (lldb::clang_type_t clang_type)
6016{
6017    clang_type = GetAsArrayType(clang_type, NULL, NULL, NULL);
6018
6019    if (clang_type == 0)
6020        return false;
6021
6022    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6023    lldb::clang_type_t item_type = cast<ArrayType>(qual_type.getTypePtr())->getElementType().getAsOpaquePtr();
6024    return IsScalarType(item_type);
6025}
6026
6027
6028bool
6029ClangASTContext::GetCXXClassName (clang_type_t clang_type, std::string &class_name)
6030{
6031    if (clang_type)
6032    {
6033        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6034
6035        CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
6036        if (cxx_record_decl)
6037        {
6038            class_name.assign (cxx_record_decl->getIdentifier()->getNameStart());
6039            return true;
6040        }
6041    }
6042    class_name.clear();
6043    return false;
6044}
6045
6046
6047bool
6048ClangASTContext::IsCXXClassType (clang_type_t clang_type)
6049{
6050    if (clang_type)
6051    {
6052        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6053        if (qual_type->getAsCXXRecordDecl() != NULL)
6054            return true;
6055    }
6056    return false;
6057}
6058
6059bool
6060ClangASTContext::IsBeingDefined (lldb::clang_type_t clang_type)
6061{
6062    if (clang_type)
6063    {
6064        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6065        const clang::TagType *tag_type = dyn_cast<clang::TagType>(qual_type);
6066        if (tag_type)
6067            return tag_type->isBeingDefined();
6068    }
6069    return false;
6070}
6071
6072bool
6073ClangASTContext::IsObjCClassType (clang_type_t clang_type)
6074{
6075    if (clang_type)
6076    {
6077        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6078        if (qual_type->isObjCObjectOrInterfaceType())
6079            return true;
6080    }
6081    return false;
6082}
6083
6084bool
6085ClangASTContext::IsObjCObjectPointerType (lldb::clang_type_t clang_type, clang_type_t *class_type)
6086{
6087    if (clang_type)
6088    {
6089        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6090        if (qual_type->isObjCObjectPointerType())
6091        {
6092            if (class_type)
6093            {
6094                *class_type = NULL;
6095
6096                if (!qual_type->isObjCClassType() &&
6097                    !qual_type->isObjCIdType())
6098                {
6099                    const ObjCObjectPointerType *obj_pointer_type = dyn_cast<ObjCObjectPointerType>(qual_type);
6100                    if (!obj_pointer_type)
6101                        *class_type = NULL;
6102                    else
6103                        *class_type = QualType(obj_pointer_type->getInterfaceType(), 0).getAsOpaquePtr();
6104                }
6105            }
6106            return true;
6107        }
6108    }
6109    return false;
6110}
6111
6112bool
6113ClangASTContext::GetObjCClassName (lldb::clang_type_t clang_type,
6114                                   std::string &class_name)
6115{
6116    if (!clang_type)
6117        return false;
6118
6119    const ObjCObjectType *object_type = dyn_cast<ObjCObjectType>(QualType::getFromOpaquePtr(clang_type));
6120    if (!object_type)
6121        return false;
6122
6123    const ObjCInterfaceDecl *interface = object_type->getInterface();
6124    if (!interface)
6125        return false;
6126
6127    class_name = interface->getNameAsString();
6128    return true;
6129}
6130
6131bool
6132ClangASTContext::IsCharType (clang_type_t clang_type)
6133{
6134    if (clang_type)
6135        return QualType::getFromOpaquePtr(clang_type)->isCharType();
6136    return false;
6137}
6138
6139bool
6140ClangASTContext::IsCStringType (clang_type_t clang_type, uint32_t &length)
6141{
6142    clang_type_t pointee_or_element_clang_type = NULL;
6143    Flags type_flags (ClangASTContext::GetTypeInfo (clang_type, NULL, &pointee_or_element_clang_type));
6144
6145    if (pointee_or_element_clang_type == NULL)
6146        return false;
6147
6148    if (type_flags.AnySet (eTypeIsArray | eTypeIsPointer))
6149    {
6150        QualType pointee_or_element_qual_type (QualType::getFromOpaquePtr (pointee_or_element_clang_type));
6151
6152        if (pointee_or_element_qual_type.getUnqualifiedType()->isCharType())
6153        {
6154            QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6155            if (type_flags.Test (eTypeIsArray))
6156            {
6157                // We know the size of the array and it could be a C string
6158                // since it is an array of characters
6159                length = cast<ConstantArrayType>(qual_type.getTypePtr())->getSize().getLimitedValue();
6160                return true;
6161            }
6162            else
6163            {
6164                length = 0;
6165                return true;
6166            }
6167
6168        }
6169    }
6170    return false;
6171}
6172
6173bool
6174ClangASTContext::IsFunctionPointerType (clang_type_t clang_type)
6175{
6176    if (clang_type)
6177    {
6178        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6179
6180        if (qual_type->isFunctionPointerType())
6181            return true;
6182
6183        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6184        switch (type_class)
6185        {
6186        default:
6187            break;
6188        case clang::Type::Typedef:
6189            return ClangASTContext::IsFunctionPointerType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
6190        case clang::Type::Elaborated:
6191            return ClangASTContext::IsFunctionPointerType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
6192
6193        case clang::Type::LValueReference:
6194        case clang::Type::RValueReference:
6195            {
6196                const ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
6197                if (reference_type)
6198                    return ClangASTContext::IsFunctionPointerType (reference_type->getPointeeType().getAsOpaquePtr());
6199            }
6200            break;
6201        }
6202    }
6203    return false;
6204}
6205
6206size_t
6207ClangASTContext::GetArraySize (clang_type_t clang_type)
6208{
6209    if (clang_type)
6210    {
6211        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
6212        const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6213        switch (type_class)
6214        {
6215        case clang::Type::ConstantArray:
6216            {
6217                const ConstantArrayType *array = cast<ConstantArrayType>(QualType::getFromOpaquePtr(clang_type).getTypePtr());
6218                if (array)
6219                    return array->getSize().getLimitedValue();
6220            }
6221            break;
6222
6223        case clang::Type::Typedef:
6224            return ClangASTContext::GetArraySize(cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr());
6225
6226        case clang::Type::Elaborated:
6227            return ClangASTContext::GetArraySize(cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr());
6228
6229        default:
6230            break;
6231        }
6232    }
6233    return 0;
6234}
6235
6236clang_type_t
6237ClangASTContext::GetAsArrayType (clang_type_t clang_type, clang_type_t*member_type, uint64_t *size, bool *is_incomplete)
6238{
6239    if (is_incomplete)
6240        *is_incomplete = false;
6241    if (!clang_type)
6242        return 0;
6243
6244    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6245
6246    const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6247    switch (type_class)
6248    {
6249    default:
6250        break;
6251
6252    case clang::Type::ConstantArray:
6253        if (member_type)
6254            *member_type = cast<ConstantArrayType>(qual_type)->getElementType().getAsOpaquePtr();
6255        if (size)
6256            *size = cast<ConstantArrayType>(qual_type)->getSize().getLimitedValue(ULLONG_MAX);
6257        return clang_type;
6258
6259    case clang::Type::IncompleteArray:
6260        if (member_type)
6261            *member_type = cast<IncompleteArrayType>(qual_type)->getElementType().getAsOpaquePtr();
6262        if (size)
6263            *size = 0;
6264        if (is_incomplete)
6265            *is_incomplete = true;
6266        return clang_type;
6267
6268    case clang::Type::VariableArray:
6269        if (member_type)
6270            *member_type = cast<VariableArrayType>(qual_type)->getElementType().getAsOpaquePtr();
6271        if (size)
6272            *size = 0;
6273        return clang_type;
6274
6275    case clang::Type::DependentSizedArray:
6276        if (member_type)
6277            *member_type = cast<DependentSizedArrayType>(qual_type)->getElementType().getAsOpaquePtr();
6278        if (size)
6279            *size = 0;
6280        return clang_type;
6281
6282    case clang::Type::Typedef:
6283        return ClangASTContext::GetAsArrayType (cast<TypedefType>(qual_type)->getDecl()->getUnderlyingType().getAsOpaquePtr(),
6284                                                member_type,
6285                                                size,
6286                                                is_incomplete);
6287
6288    case clang::Type::Elaborated:
6289        return ClangASTContext::GetAsArrayType (cast<ElaboratedType>(qual_type)->getNamedType().getAsOpaquePtr(),
6290                                                member_type,
6291                                                size,
6292                                                is_incomplete);
6293    }
6294    return 0;
6295}
6296
6297
6298#pragma mark Typedefs
6299
6300clang_type_t
6301ClangASTContext::CreateTypedefType (const char *name, clang_type_t clang_type, DeclContext *decl_ctx)
6302{
6303    if (clang_type)
6304    {
6305        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6306        ASTContext *ast = getASTContext();
6307        IdentifierTable *identifier_table = getIdentifierTable();
6308        assert (ast != NULL);
6309        assert (identifier_table != NULL);
6310        if (decl_ctx == NULL)
6311            decl_ctx = ast->getTranslationUnitDecl();
6312        TypedefDecl *decl = TypedefDecl::Create (*ast,
6313                                                 decl_ctx,
6314                                                 SourceLocation(),
6315                                                 SourceLocation(),
6316                                                 name ? &identifier_table->get(name) : NULL, // Identifier
6317                                                 ast->getTrivialTypeSourceInfo(qual_type));
6318
6319        //decl_ctx->addDecl (decl);
6320
6321        decl->setAccess(AS_public); // TODO respect proper access specifier
6322
6323        // Get a uniqued QualType for the typedef decl type
6324        return ast->getTypedefType (decl).getAsOpaquePtr();
6325    }
6326    return NULL;
6327}
6328
6329// Disable this for now since I can't seem to get a nicely formatted float
6330// out of the APFloat class without just getting the float, double or quad
6331// and then using a formatted print on it which defeats the purpose. We ideally
6332// would like to get perfect string values for any kind of float semantics
6333// so we can support remote targets. The code below also requires a patch to
6334// llvm::APInt.
6335//bool
6336//ClangASTContext::ConvertFloatValueToString (ASTContext *ast, clang_type_t clang_type, const uint8_t* bytes, size_t byte_size, int apint_byte_order, std::string &float_str)
6337//{
6338//  uint32_t count = 0;
6339//  bool is_complex = false;
6340//  if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
6341//  {
6342//      unsigned num_bytes_per_float = byte_size / count;
6343//      unsigned num_bits_per_float = num_bytes_per_float * 8;
6344//
6345//      float_str.clear();
6346//      uint32_t i;
6347//      for (i=0; i<count; i++)
6348//      {
6349//          APInt ap_int(num_bits_per_float, bytes + i * num_bytes_per_float, (APInt::ByteOrder)apint_byte_order);
6350//          bool is_ieee = false;
6351//          APFloat ap_float(ap_int, is_ieee);
6352//          char s[1024];
6353//          unsigned int hex_digits = 0;
6354//          bool upper_case = false;
6355//
6356//          if (ap_float.convertToHexString(s, hex_digits, upper_case, APFloat::rmNearestTiesToEven) > 0)
6357//          {
6358//              if (i > 0)
6359//                  float_str.append(", ");
6360//              float_str.append(s);
6361//              if (i == 1 && is_complex)
6362//                  float_str.append(1, 'i');
6363//          }
6364//      }
6365//      return !float_str.empty();
6366//  }
6367//  return false;
6368//}
6369
6370size_t
6371ClangASTContext::ConvertStringToFloatValue (ASTContext *ast, clang_type_t clang_type, const char *s, uint8_t *dst, size_t dst_size)
6372{
6373    if (clang_type)
6374    {
6375        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6376        uint32_t count = 0;
6377        bool is_complex = false;
6378        if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
6379        {
6380            // TODO: handle complex and vector types
6381            if (count != 1)
6382                return false;
6383
6384            StringRef s_sref(s);
6385            APFloat ap_float(ast->getFloatTypeSemantics(qual_type), s_sref);
6386
6387            const uint64_t bit_size = ast->getTypeSize (qual_type);
6388            const uint64_t byte_size = bit_size / 8;
6389            if (dst_size >= byte_size)
6390            {
6391                if (bit_size == sizeof(float)*8)
6392                {
6393                    float float32 = ap_float.convertToFloat();
6394                    ::memcpy (dst, &float32, byte_size);
6395                    return byte_size;
6396                }
6397                else if (bit_size >= 64)
6398                {
6399                    llvm::APInt ap_int(ap_float.bitcastToAPInt());
6400                    ::memcpy (dst, ap_int.getRawData(), byte_size);
6401                    return byte_size;
6402                }
6403            }
6404        }
6405    }
6406    return 0;
6407}
6408
6409unsigned
6410ClangASTContext::GetTypeQualifiers(clang_type_t clang_type)
6411{
6412    assert (clang_type);
6413
6414    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
6415
6416    return qual_type.getQualifiers().getCVRQualifiers();
6417}
6418
6419bool
6420ClangASTContext::GetCompleteType (clang::ASTContext *ast, lldb::clang_type_t clang_type)
6421{
6422    if (clang_type == NULL)
6423        return false;
6424
6425    return GetCompleteQualType (ast, clang::QualType::getFromOpaquePtr(clang_type));
6426}
6427
6428
6429bool
6430ClangASTContext::GetCompleteType (clang_type_t clang_type)
6431{
6432    return ClangASTContext::GetCompleteType (getASTContext(), clang_type);
6433}
6434
6435bool
6436ClangASTContext::IsCompleteType (clang::ASTContext *ast, lldb::clang_type_t clang_type)
6437{
6438    if (clang_type == NULL)
6439        return false;
6440
6441    return GetCompleteQualType (ast, clang::QualType::getFromOpaquePtr(clang_type), false); // just check but don't let it actually complete
6442}
6443
6444
6445bool
6446ClangASTContext::IsCompleteType (clang_type_t clang_type)
6447{
6448    return ClangASTContext::IsCompleteType (getASTContext(), clang_type);
6449}
6450
6451bool
6452ClangASTContext::GetCompleteDecl (clang::ASTContext *ast,
6453                                  clang::Decl *decl)
6454{
6455    if (!decl)
6456        return false;
6457
6458    ExternalASTSource *ast_source = ast->getExternalSource();
6459
6460    if (!ast_source)
6461        return false;
6462
6463    if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl))
6464    {
6465        if (tag_decl->isCompleteDefinition())
6466            return true;
6467
6468        if (!tag_decl->hasExternalLexicalStorage())
6469            return false;
6470
6471        ast_source->CompleteType(tag_decl);
6472
6473        return !tag_decl->getTypeForDecl()->isIncompleteType();
6474    }
6475    else if (clang::ObjCInterfaceDecl *objc_interface_decl = llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl))
6476    {
6477        if (objc_interface_decl->getDefinition())
6478            return true;
6479
6480        if (!objc_interface_decl->hasExternalLexicalStorage())
6481            return false;
6482
6483        ast_source->CompleteType(objc_interface_decl);
6484
6485        return !objc_interface_decl->getTypeForDecl()->isIncompleteType();
6486    }
6487    else
6488    {
6489        return false;
6490    }
6491}
6492
6493void
6494ClangASTContext::SetMetadataAsUserID (uintptr_t object,
6495                                      user_id_t user_id)
6496{
6497    ClangASTMetadata meta_data;
6498    meta_data.SetUserID (user_id);
6499    SetMetadata (object, meta_data);
6500}
6501
6502void
6503ClangASTContext::SetMetadata (clang::ASTContext *ast,
6504                              uintptr_t object,
6505                              ClangASTMetadata &metadata)
6506{
6507    ClangExternalASTSourceCommon *external_source =
6508        static_cast<ClangExternalASTSourceCommon*>(ast->getExternalSource());
6509
6510    if (external_source)
6511        external_source->SetMetadata(object, metadata);
6512}
6513
6514ClangASTMetadata *
6515ClangASTContext::GetMetadata (clang::ASTContext *ast,
6516                              uintptr_t object)
6517{
6518    ClangExternalASTSourceCommon *external_source =
6519        static_cast<ClangExternalASTSourceCommon*>(ast->getExternalSource());
6520
6521    if (external_source && external_source->HasMetadata(object))
6522        return external_source->GetMetadata(object);
6523    else
6524        return NULL;
6525}
6526
6527clang::DeclContext *
6528ClangASTContext::GetAsDeclContext (clang::CXXMethodDecl *cxx_method_decl)
6529{
6530    return llvm::dyn_cast<clang::DeclContext>(cxx_method_decl);
6531}
6532
6533clang::DeclContext *
6534ClangASTContext::GetAsDeclContext (clang::ObjCMethodDecl *objc_method_decl)
6535{
6536    return llvm::dyn_cast<clang::DeclContext>(objc_method_decl);
6537}
6538
6539
6540bool
6541ClangASTContext::GetClassMethodInfoForDeclContext (clang::DeclContext *decl_ctx,
6542                                                   lldb::LanguageType &language,
6543                                                   bool &is_instance_method,
6544                                                   ConstString &language_object_name)
6545{
6546    language_object_name.Clear();
6547    language = eLanguageTypeUnknown;
6548    is_instance_method = false;
6549
6550    if (decl_ctx)
6551    {
6552        if (clang::CXXMethodDecl *method_decl = llvm::dyn_cast<clang::CXXMethodDecl>(decl_ctx))
6553        {
6554            if (method_decl->isStatic())
6555            {
6556                is_instance_method = false;
6557            }
6558            else
6559            {
6560                language_object_name.SetCString("this");
6561                is_instance_method = true;
6562            }
6563            language = eLanguageTypeC_plus_plus;
6564            return true;
6565        }
6566        else if (clang::ObjCMethodDecl *method_decl = llvm::dyn_cast<clang::ObjCMethodDecl>(decl_ctx))
6567        {
6568            // Both static and instance methods have a "self" object in objective C
6569            language_object_name.SetCString("self");
6570            if (method_decl->isInstanceMethod())
6571            {
6572                is_instance_method = true;
6573            }
6574            else
6575            {
6576                is_instance_method = false;
6577            }
6578            language = eLanguageTypeObjC;
6579            return true;
6580        }
6581        else if (clang::FunctionDecl *function_decl = llvm::dyn_cast<clang::FunctionDecl>(decl_ctx))
6582        {
6583            ClangASTMetadata *metadata = GetMetadata (&decl_ctx->getParentASTContext(), (uintptr_t) function_decl);
6584            if (metadata && metadata->HasObjectPtr())
6585            {
6586                language_object_name.SetCString (metadata->GetObjectPtrName());
6587                language = eLanguageTypeObjC;
6588                is_instance_method = true;
6589            }
6590            return true;
6591        }
6592    }
6593    return false;
6594}
6595
6596