ClangASTContext.cpp revision ccfba727178bb919cdff3365839bed9584df2560
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#include "clang/AST/ASTContext.h"
18#include "clang/AST/ASTImporter.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/RecordLayout.h"
21#include "clang/AST/Type.h"
22#include "clang/Basic/Builtins.h"
23#include "clang/Basic/FileManager.h"
24#include "clang/Basic/SourceManager.h"
25#include "clang/Basic/TargetInfo.h"
26#include "clang/Basic/TargetOptions.h"
27#include "clang/Frontend/FrontendOptions.h"
28#include "clang/Frontend/LangStandard.h"
29
30#include "lldb/Core/dwarf.h"
31
32#include <stdio.h>
33
34using namespace lldb_private;
35using namespace llvm;
36using namespace clang;
37
38static void
39ParseLangArgs
40(
41    LangOptions &Opts,
42    InputKind IK
43)
44{
45    // FIXME: Cleanup per-file based stuff.
46
47    // Set some properties which depend soley on the input kind; it would be nice
48    // to move these to the language standard, and have the driver resolve the
49    // input kind + language standard.
50    if (IK == IK_Asm) {
51        Opts.AsmPreprocessor = 1;
52    } else if (IK == IK_ObjC ||
53               IK == IK_ObjCXX ||
54               IK == IK_PreprocessedObjC ||
55               IK == IK_PreprocessedObjCXX) {
56        Opts.ObjC1 = Opts.ObjC2 = 1;
57    }
58
59    LangStandard::Kind LangStd = LangStandard::lang_unspecified;
60
61    if (LangStd == LangStandard::lang_unspecified) {
62        // Based on the base language, pick one.
63        switch (IK) {
64            case IK_None:
65            case IK_AST:
66                assert(0 && "Invalid input kind!");
67            case IK_OpenCL:
68                LangStd = LangStandard::lang_opencl;
69                break;
70            case IK_Asm:
71            case IK_C:
72            case IK_PreprocessedC:
73            case IK_ObjC:
74            case IK_PreprocessedObjC:
75                LangStd = LangStandard::lang_gnu99;
76                break;
77            case IK_CXX:
78            case IK_PreprocessedCXX:
79            case IK_ObjCXX:
80            case IK_PreprocessedObjCXX:
81                LangStd = LangStandard::lang_gnucxx98;
82                break;
83        }
84    }
85
86    const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
87    Opts.BCPLComment = Std.hasBCPLComments();
88    Opts.C99 = Std.isC99();
89    Opts.CPlusPlus = Std.isCPlusPlus();
90    Opts.CPlusPlus0x = Std.isCPlusPlus0x();
91    Opts.Digraphs = Std.hasDigraphs();
92    Opts.GNUMode = Std.isGNUMode();
93    Opts.GNUInline = !Std.isC99();
94    Opts.HexFloats = Std.hasHexFloats();
95    Opts.ImplicitInt = Std.hasImplicitInt();
96
97    // OpenCL has some additional defaults.
98    if (LangStd == LangStandard::lang_opencl) {
99        Opts.OpenCL = 1;
100        Opts.AltiVec = 1;
101        Opts.CXXOperatorNames = 1;
102        Opts.LaxVectorConversions = 1;
103    }
104
105    // OpenCL and C++ both have bool, true, false keywords.
106    Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
107
108//    if (Opts.CPlusPlus)
109//        Opts.CXXOperatorNames = !Args.hasArg(OPT_fno_operator_names);
110//
111//    if (Args.hasArg(OPT_fobjc_gc_only))
112//        Opts.setGCMode(LangOptions::GCOnly);
113//    else if (Args.hasArg(OPT_fobjc_gc))
114//        Opts.setGCMode(LangOptions::HybridGC);
115//
116//    if (Args.hasArg(OPT_print_ivar_layout))
117//        Opts.ObjCGCBitmapPrint = 1;
118//
119//    if (Args.hasArg(OPT_faltivec))
120//        Opts.AltiVec = 1;
121//
122//    if (Args.hasArg(OPT_pthread))
123//        Opts.POSIXThreads = 1;
124//
125//    llvm::StringRef Vis = getLastArgValue(Args, OPT_fvisibility,
126//                                          "default");
127//    if (Vis == "default")
128        Opts.setVisibilityMode(LangOptions::Default);
129//    else if (Vis == "hidden")
130//        Opts.setVisibilityMode(LangOptions::Hidden);
131//    else if (Vis == "protected")
132//        Opts.setVisibilityMode(LangOptions::Protected);
133//    else
134//        Diags.Report(diag::err_drv_invalid_value)
135//        << Args.getLastArg(OPT_fvisibility)->getAsString(Args) << Vis;
136
137//    Opts.OverflowChecking = Args.hasArg(OPT_ftrapv);
138
139    // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
140    // is specified, or -std is set to a conforming mode.
141    Opts.Trigraphs = !Opts.GNUMode;
142//    if (Args.hasArg(OPT_trigraphs))
143//        Opts.Trigraphs = 1;
144//
145//    Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
146//                                     OPT_fno_dollars_in_identifiers,
147//                                     !Opts.AsmPreprocessor);
148//    Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
149//    Opts.Microsoft = Args.hasArg(OPT_fms_extensions);
150//    Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
151//    if (Args.hasArg(OPT_fno_lax_vector_conversions))
152//        Opts.LaxVectorConversions = 0;
153//    Opts.Exceptions = Args.hasArg(OPT_fexceptions);
154//    Opts.RTTI = !Args.hasArg(OPT_fno_rtti);
155//    Opts.Blocks = Args.hasArg(OPT_fblocks);
156//    Opts.CharIsSigned = !Args.hasArg(OPT_fno_signed_char);
157//    Opts.ShortWChar = Args.hasArg(OPT_fshort_wchar);
158//    Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
159//    Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
160//    Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
161//    Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
162//    Opts.AccessControl = Args.hasArg(OPT_faccess_control);
163//    Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
164//    Opts.MathErrno = !Args.hasArg(OPT_fno_math_errno);
165//    Opts.InstantiationDepth = getLastArgIntValue(Args, OPT_ftemplate_depth, 99,
166//                                                 Diags);
167//    Opts.NeXTRuntime = !Args.hasArg(OPT_fgnu_runtime);
168//    Opts.ObjCConstantStringClass = getLastArgValue(Args,
169//                                                   OPT_fconstant_string_class);
170//    Opts.ObjCNonFragileABI = Args.hasArg(OPT_fobjc_nonfragile_abi);
171//    Opts.CatchUndefined = Args.hasArg(OPT_fcatch_undefined_behavior);
172//    Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
173//    Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
174//    Opts.Static = Args.hasArg(OPT_static_define);
175    Opts.OptimizeSize = 0;
176
177    // FIXME: Eliminate this dependency.
178//    unsigned Opt =
179//    Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags);
180//    Opts.Optimize = Opt != 0;
181    unsigned Opt = 0;
182
183    // This is the __NO_INLINE__ define, which just depends on things like the
184    // optimization level and -fno-inline, not actually whether the backend has
185    // inlining enabled.
186    //
187    // FIXME: This is affected by other options (-fno-inline).
188    Opts.NoInline = !Opt;
189
190//    unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
191//    switch (SSP) {
192//        default:
193//            Diags.Report(diag::err_drv_invalid_value)
194//            << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
195//            break;
196//        case 0: Opts.setStackProtectorMode(LangOptions::SSPOff); break;
197//        case 1: Opts.setStackProtectorMode(LangOptions::SSPOn);  break;
198//        case 2: Opts.setStackProtectorMode(LangOptions::SSPReq); break;
199//    }
200}
201
202
203ClangASTContext::ClangASTContext(const char *target_triple) :
204    m_target_triple(),
205    m_ast_context_ap(),
206    m_language_options_ap(),
207    m_source_manager_ap(),
208    m_diagnostic_ap(),
209    m_target_options_ap(),
210    m_target_info_ap(),
211    m_identifier_table_ap(),
212    m_selector_table_ap(),
213    m_builtins_ap()
214{
215    if (target_triple && target_triple[0])
216        m_target_triple.assign (target_triple);
217}
218
219//----------------------------------------------------------------------
220// Destructor
221//----------------------------------------------------------------------
222ClangASTContext::~ClangASTContext()
223{
224    m_builtins_ap.reset();
225    m_selector_table_ap.reset();
226    m_identifier_table_ap.reset();
227    m_target_info_ap.reset();
228    m_target_options_ap.reset();
229    m_diagnostic_ap.reset();
230    m_source_manager_ap.reset();
231    m_language_options_ap.reset();
232    m_ast_context_ap.reset();
233}
234
235
236void
237ClangASTContext::Clear()
238{
239    m_ast_context_ap.reset();
240    m_language_options_ap.reset();
241    m_source_manager_ap.reset();
242    m_diagnostic_ap.reset();
243    m_target_options_ap.reset();
244    m_target_info_ap.reset();
245    m_identifier_table_ap.reset();
246    m_selector_table_ap.reset();
247    m_builtins_ap.reset();
248}
249
250const char *
251ClangASTContext::GetTargetTriple ()
252{
253    return m_target_triple.c_str();
254}
255
256void
257ClangASTContext::SetTargetTriple (const char *target_triple)
258{
259    Clear();
260    m_target_triple.assign(target_triple);
261}
262
263
264ASTContext *
265ClangASTContext::getASTContext()
266{
267    if (m_ast_context_ap.get() == NULL)
268    {
269        m_ast_context_ap.reset(
270            new ASTContext(
271                *getLanguageOptions(),
272                *getSourceManager(),
273                *getTargetInfo(),
274                *getIdentifierTable(),
275                *getSelectorTable(),
276                *getBuiltinContext()));
277    }
278    return m_ast_context_ap.get();
279}
280
281Builtin::Context *
282ClangASTContext::getBuiltinContext()
283{
284    if (m_builtins_ap.get() == NULL)
285        m_builtins_ap.reset (new Builtin::Context(*getTargetInfo()));
286    return m_builtins_ap.get();
287}
288
289IdentifierTable *
290ClangASTContext::getIdentifierTable()
291{
292    if (m_identifier_table_ap.get() == NULL)
293        m_identifier_table_ap.reset(new IdentifierTable (*ClangASTContext::getLanguageOptions(), NULL));
294    return m_identifier_table_ap.get();
295}
296
297LangOptions *
298ClangASTContext::getLanguageOptions()
299{
300    if (m_language_options_ap.get() == NULL)
301    {
302        m_language_options_ap.reset(new LangOptions());
303        ParseLangArgs(*m_language_options_ap, IK_ObjCXX);
304//        InitializeLangOptions(*m_language_options_ap, IK_ObjCXX);
305    }
306    return m_language_options_ap.get();
307}
308
309SelectorTable *
310ClangASTContext::getSelectorTable()
311{
312    if (m_selector_table_ap.get() == NULL)
313        m_selector_table_ap.reset (new SelectorTable());
314    return m_selector_table_ap.get();
315}
316
317SourceManager *
318ClangASTContext::getSourceManager()
319{
320    if (m_source_manager_ap.get() == NULL)
321        m_source_manager_ap.reset(new SourceManager(*getDiagnostic()));
322    return m_source_manager_ap.get();
323}
324
325Diagnostic *
326ClangASTContext::getDiagnostic()
327{
328    if (m_diagnostic_ap.get() == NULL)
329        m_diagnostic_ap.reset(new Diagnostic());
330    return m_diagnostic_ap.get();
331}
332
333TargetOptions *
334ClangASTContext::getTargetOptions()
335{
336    if (m_target_options_ap.get() == NULL && !m_target_triple.empty())
337    {
338        m_target_options_ap.reset (new TargetOptions());
339        if (m_target_options_ap.get())
340            m_target_options_ap->Triple = m_target_triple;
341    }
342    return m_target_options_ap.get();
343}
344
345
346TargetInfo *
347ClangASTContext::getTargetInfo()
348{
349    // target_triple should be something like "x86_64-apple-darwin10"
350    if (m_target_info_ap.get() == NULL && !m_target_triple.empty())
351        m_target_info_ap.reset (TargetInfo::CreateTargetInfo(*getDiagnostic(), *getTargetOptions()));
352    return m_target_info_ap.get();
353}
354
355#pragma mark Basic Types
356
357static inline bool
358QualTypeMatchesBitSize(const uint64_t bit_size, ASTContext *ast_context, QualType qual_type)
359{
360    uint64_t qual_type_bit_size = ast_context->getTypeSize(qual_type);
361    if (qual_type_bit_size == bit_size)
362        return true;
363    return false;
364}
365
366void *
367ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (lldb::Encoding encoding, uint32_t bit_size)
368{
369    ASTContext *ast_context = getASTContext();
370
371    assert (ast_context != NULL);
372
373    return GetBuiltinTypeForEncodingAndBitSize (ast_context, encoding, bit_size);
374}
375
376void *
377ClangASTContext::GetBuiltinTypeForEncodingAndBitSize (clang::ASTContext *ast_context, lldb::Encoding encoding, uint32_t bit_size)
378{
379    if (!ast_context)
380        return NULL;
381
382    switch (encoding)
383    {
384    case lldb::eEncodingInvalid:
385        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->VoidPtrTy))
386            return ast_context->VoidPtrTy.getAsOpaquePtr();
387        break;
388
389    case lldb::eEncodingUint:
390        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedCharTy))
391            return ast_context->UnsignedCharTy.getAsOpaquePtr();
392        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedShortTy))
393            return ast_context->UnsignedShortTy.getAsOpaquePtr();
394        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedIntTy))
395            return ast_context->UnsignedIntTy.getAsOpaquePtr();
396        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedLongTy))
397            return ast_context->UnsignedLongTy.getAsOpaquePtr();
398        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedLongLongTy))
399            return ast_context->UnsignedLongLongTy.getAsOpaquePtr();
400        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedInt128Ty))
401            return ast_context->UnsignedInt128Ty.getAsOpaquePtr();
402        break;
403
404    case lldb::eEncodingSint:
405        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->CharTy))
406            return ast_context->CharTy.getAsOpaquePtr();
407        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->ShortTy))
408            return ast_context->ShortTy.getAsOpaquePtr();
409        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->IntTy))
410            return ast_context->IntTy.getAsOpaquePtr();
411        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongTy))
412            return ast_context->LongTy.getAsOpaquePtr();
413        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongLongTy))
414            return ast_context->LongLongTy.getAsOpaquePtr();
415        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->Int128Ty))
416            return ast_context->Int128Ty.getAsOpaquePtr();
417        break;
418
419    case lldb::eEncodingIEEE754:
420        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->FloatTy))
421            return ast_context->FloatTy.getAsOpaquePtr();
422        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->DoubleTy))
423            return ast_context->DoubleTy.getAsOpaquePtr();
424        if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongDoubleTy))
425            return ast_context->LongDoubleTy.getAsOpaquePtr();
426        break;
427
428    case lldb::eEncodingVector:
429    default:
430        break;
431    }
432
433    return NULL;
434}
435
436void *
437ClangASTContext::GetBuiltinTypeForDWARFEncodingAndBitSize (const char *type_name, uint32_t dw_ate, uint32_t bit_size)
438{
439    ASTContext *ast_context = getASTContext();
440
441    #define streq(a,b) strcmp(a,b) == 0
442    assert (ast_context != NULL);
443    if (ast_context)
444    {
445        switch (dw_ate)
446        {
447        default:
448            break;
449
450        case DW_ATE_address:
451            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->VoidPtrTy))
452                return ast_context->VoidPtrTy.getAsOpaquePtr();
453            break;
454
455        case DW_ATE_boolean:
456            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->BoolTy))
457                return ast_context->BoolTy.getAsOpaquePtr();
458            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedCharTy))
459                return ast_context->UnsignedCharTy.getAsOpaquePtr();
460            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedShortTy))
461                return ast_context->UnsignedShortTy.getAsOpaquePtr();
462            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedIntTy))
463                return ast_context->UnsignedIntTy.getAsOpaquePtr();
464            break;
465
466        case DW_ATE_complex_float:
467            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->FloatComplexTy))
468                return ast_context->FloatComplexTy.getAsOpaquePtr();
469            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->DoubleComplexTy))
470                return ast_context->DoubleComplexTy.getAsOpaquePtr();
471            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongDoubleComplexTy))
472                return ast_context->LongDoubleComplexTy.getAsOpaquePtr();
473            break;
474
475        case DW_ATE_float:
476            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->FloatTy))
477                return ast_context->FloatTy.getAsOpaquePtr();
478            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->DoubleTy))
479                return ast_context->DoubleTy.getAsOpaquePtr();
480            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongDoubleTy))
481                return ast_context->LongDoubleTy.getAsOpaquePtr();
482            break;
483
484        case DW_ATE_signed:
485            if (type_name)
486            {
487                if (streq(type_name, "int") ||
488                    streq(type_name, "signed int"))
489                {
490                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->IntTy))
491                        return ast_context->IntTy.getAsOpaquePtr();
492                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->Int128Ty))
493                        return ast_context->Int128Ty.getAsOpaquePtr();
494                }
495
496                if (streq(type_name, "long int") ||
497                    streq(type_name, "long long int") ||
498                    streq(type_name, "signed long long"))
499                {
500                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongTy))
501                        return ast_context->LongTy.getAsOpaquePtr();
502                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongLongTy))
503                        return ast_context->LongLongTy.getAsOpaquePtr();
504                }
505
506                if (streq(type_name, "short") ||
507                    streq(type_name, "short int") ||
508                    streq(type_name, "signed short") ||
509                    streq(type_name, "short signed int"))
510                {
511                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->ShortTy))
512                        return ast_context->ShortTy.getAsOpaquePtr();
513                }
514
515                if (streq(type_name, "char") ||
516                    streq(type_name, "signed char"))
517                {
518                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->CharTy))
519                        return ast_context->CharTy.getAsOpaquePtr();
520                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->SignedCharTy))
521                        return ast_context->SignedCharTy.getAsOpaquePtr();
522                }
523
524                if (streq(type_name, "wchar_t"))
525                {
526                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->WCharTy))
527                        return ast_context->WCharTy.getAsOpaquePtr();
528                }
529
530            }
531            // We weren't able to match up a type name, just search by size
532            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->CharTy))
533                return ast_context->CharTy.getAsOpaquePtr();
534            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->ShortTy))
535                return ast_context->ShortTy.getAsOpaquePtr();
536            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->IntTy))
537                return ast_context->IntTy.getAsOpaquePtr();
538            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongTy))
539                return ast_context->LongTy.getAsOpaquePtr();
540            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->LongLongTy))
541                return ast_context->LongLongTy.getAsOpaquePtr();
542            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->Int128Ty))
543                return ast_context->Int128Ty.getAsOpaquePtr();
544            break;
545
546        case DW_ATE_signed_char:
547            if (type_name)
548            {
549                if (streq(type_name, "signed char"))
550                {
551                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->SignedCharTy))
552                        return ast_context->SignedCharTy.getAsOpaquePtr();
553                }
554            }
555            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->CharTy))
556                return ast_context->CharTy.getAsOpaquePtr();
557            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->SignedCharTy))
558                return ast_context->SignedCharTy.getAsOpaquePtr();
559            break;
560
561        case DW_ATE_unsigned:
562            if (type_name)
563            {
564                if (streq(type_name, "unsigned int"))
565                {
566                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedIntTy))
567                        return ast_context->UnsignedIntTy.getAsOpaquePtr();
568                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedInt128Ty))
569                        return ast_context->UnsignedInt128Ty.getAsOpaquePtr();
570                }
571
572                if (streq(type_name, "unsigned int") ||
573                    streq(type_name, "long unsigned int") ||
574                    streq(type_name, "unsigned long long"))
575                {
576                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedLongTy))
577                        return ast_context->UnsignedLongTy.getAsOpaquePtr();
578                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedLongLongTy))
579                        return ast_context->UnsignedLongLongTy.getAsOpaquePtr();
580                }
581
582                if (streq(type_name, "unsigned short") ||
583                    streq(type_name, "short unsigned int"))
584                {
585                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedShortTy))
586                        return ast_context->UnsignedShortTy.getAsOpaquePtr();
587                }
588                if (streq(type_name, "unsigned char"))
589                {
590                    if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedCharTy))
591                        return ast_context->UnsignedCharTy.getAsOpaquePtr();
592                }
593
594            }
595            // We weren't able to match up a type name, just search by size
596            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedCharTy))
597                return ast_context->UnsignedCharTy.getAsOpaquePtr();
598            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedShortTy))
599                return ast_context->UnsignedShortTy.getAsOpaquePtr();
600            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedIntTy))
601                return ast_context->UnsignedIntTy.getAsOpaquePtr();
602            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedLongTy))
603                return ast_context->UnsignedLongTy.getAsOpaquePtr();
604            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedLongLongTy))
605                return ast_context->UnsignedLongLongTy.getAsOpaquePtr();
606            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedInt128Ty))
607                return ast_context->UnsignedInt128Ty.getAsOpaquePtr();
608            break;
609
610        case DW_ATE_unsigned_char:
611            if (QualTypeMatchesBitSize (bit_size, ast_context, ast_context->UnsignedCharTy))
612                return ast_context->UnsignedCharTy.getAsOpaquePtr();
613            break;
614
615        case DW_ATE_imaginary_float:
616            break;
617        }
618    }
619    // This assert should fire for anything that we don't catch above so we know
620    // to fix any issues we run into.
621    assert (!"error: ClangASTContext::GetClangTypeForDWARFEncodingAndSize() contains an unhandled encoding. Fix this ASAP!");
622    return NULL;
623}
624
625void *
626ClangASTContext::GetVoidBuiltInType()
627{
628    return getASTContext()->VoidTy.getAsOpaquePtr();
629}
630
631void *
632ClangASTContext::GetCStringType (bool is_const)
633{
634    QualType char_type(getASTContext()->CharTy);
635
636    if (is_const)
637        char_type.addConst();
638
639    return getASTContext()->getPointerType(char_type).getAsOpaquePtr();
640}
641
642void *
643ClangASTContext::GetVoidPtrType (bool is_const)
644{
645    return GetVoidPtrType(getASTContext(), is_const);
646}
647
648void *
649ClangASTContext::GetVoidPtrType (clang::ASTContext *ast_context, bool is_const)
650{
651    QualType void_ptr_type(ast_context->VoidPtrTy);
652
653    if (is_const)
654        void_ptr_type.addConst();
655
656    return void_ptr_type.getAsOpaquePtr();
657}
658
659void *
660ClangASTContext::CopyType(clang::ASTContext *dest_context,
661                          clang::ASTContext *source_context,
662                          void * clang_type)
663{
664    Diagnostic diagnostics;
665    FileManager file_manager;
666    ASTImporter importer(diagnostics,
667                         *dest_context, file_manager,
668                         *source_context, file_manager);
669    QualType ret = importer.Import(QualType::getFromOpaquePtr(clang_type));
670    return ret.getAsOpaquePtr();
671}
672
673#pragma mark CVR modifiers
674
675void *
676ClangASTContext::AddConstModifier (void *clang_type)
677{
678    if (clang_type)
679    {
680        QualType result(QualType::getFromOpaquePtr(clang_type));
681        result.addConst();
682        return result.getAsOpaquePtr();
683    }
684    return NULL;
685}
686
687void *
688ClangASTContext::AddRestrictModifier (void *clang_type)
689{
690    if (clang_type)
691    {
692        QualType result(QualType::getFromOpaquePtr(clang_type));
693        result.getQualifiers().setRestrict (true);
694        return result.getAsOpaquePtr();
695    }
696    return NULL;
697}
698
699void *
700ClangASTContext::AddVolatileModifier (void *clang_type)
701{
702    if (clang_type)
703    {
704        QualType result(QualType::getFromOpaquePtr(clang_type));
705        result.getQualifiers().setVolatile (true);
706        return result.getAsOpaquePtr();
707    }
708    return NULL;
709}
710
711#pragma mark Structure, Unions, Classes
712
713void *
714ClangASTContext::CreateRecordType (const char *name, int kind, DeclContext *decl_ctx)
715{
716    ASTContext *ast_context = getASTContext();
717    assert (ast_context != NULL);
718
719    if (decl_ctx == NULL)
720        decl_ctx = ast_context->getTranslationUnitDecl();
721
722    // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
723    // we will need to update this code. I was told to currently always use
724    // the CXXRecordDecl class since we often don't know from debug information
725    // if something is struct or a class, so we default to always use the more
726    // complete definition just in case.
727    CXXRecordDecl *decl = CXXRecordDecl::Create(*ast_context,
728                                                (TagDecl::TagKind)kind,
729                                                decl_ctx,
730                                                SourceLocation(),
731                                                name && name[0] ? &ast_context->Idents.get(name) : NULL);
732
733    return ast_context->getTagDeclType(decl).getAsOpaquePtr();
734}
735
736bool
737ClangASTContext::AddFieldToRecordType (void * record_clang_type, const char *name, void * field_type, int access, uint32_t bitfield_bit_size)
738{
739    if (record_clang_type == NULL || field_type == NULL)
740        return false;
741
742    ASTContext *ast_context = getASTContext();
743    IdentifierTable *identifier_table = getIdentifierTable();
744
745    assert (ast_context != NULL);
746    assert (identifier_table != NULL);
747
748    QualType record_qual_type(QualType::getFromOpaquePtr(record_clang_type));
749
750    Type *clang_type = record_qual_type.getTypePtr();
751    if (clang_type)
752    {
753        const RecordType *record_type = dyn_cast<RecordType>(clang_type);
754
755        if (record_type)
756        {
757            RecordDecl *record_decl = record_type->getDecl();
758
759            CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
760            if (cxx_record_decl)
761                cxx_record_decl->setEmpty (false);
762
763            clang::Expr *bit_width = NULL;
764            if (bitfield_bit_size != 0)
765            {
766                APInt bitfield_bit_size_apint(ast_context->getTypeSize(ast_context->IntTy), bitfield_bit_size);
767                bit_width = new (*ast_context)IntegerLiteral (bitfield_bit_size_apint, ast_context->IntTy, SourceLocation());
768            }
769            FieldDecl *field = FieldDecl::Create(*ast_context,
770                                                record_decl,
771                                                SourceLocation(),
772                                                name ? &identifier_table->get(name) : NULL, // Identifier
773                                                QualType::getFromOpaquePtr(field_type), // Field type
774                                                NULL,       // DeclaratorInfo *
775                                                bit_width,  // BitWidth
776                                                false);     // Mutable
777
778            field->setAccess((AccessSpecifier)access);
779
780            if (field)
781            {
782                record_decl->addDecl(field);
783                return true;
784            }
785        }
786    }
787    return false;
788}
789
790bool
791ClangASTContext::FieldIsBitfield (FieldDecl* field, uint32_t& bitfield_bit_size)
792{
793    return FieldIsBitfield(getASTContext(), field, bitfield_bit_size);
794}
795
796bool
797ClangASTContext::FieldIsBitfield
798(
799    ASTContext *ast_context,
800    FieldDecl* field,
801    uint32_t& bitfield_bit_size
802)
803{
804    if (ast_context == NULL || field == NULL)
805        return false;
806
807    if (field->isBitField())
808    {
809        Expr* bit_width_expr = field->getBitWidth();
810        if (bit_width_expr)
811        {
812            llvm::APSInt bit_width_apsint;
813            if (bit_width_expr->isIntegerConstantExpr(bit_width_apsint, *ast_context))
814            {
815                bitfield_bit_size = bit_width_apsint.getLimitedValue(UINT32_MAX);
816                return true;
817            }
818        }
819    }
820    return false;
821}
822
823bool
824ClangASTContext::RecordHasFields (const RecordDecl *record_decl)
825{
826    if (record_decl == NULL)
827        return false;
828
829    if (!record_decl->field_empty())
830        return true;
831
832    // No fields, lets check this is a CXX record and check the base classes
833    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
834    if (cxx_record_decl)
835    {
836        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
837        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
838             base_class != base_class_end;
839             ++base_class)
840        {
841            const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
842            if (RecordHasFields(base_class_decl))
843                return true;
844        }
845    }
846    return false;
847}
848
849void
850ClangASTContext::SetDefaultAccessForRecordFields (void *clang_qual_type, int default_accessibility, int *assigned_accessibilities, size_t num_assigned_accessibilities)
851{
852    if (clang_qual_type)
853    {
854        QualType qual_type(QualType::getFromOpaquePtr(clang_qual_type));
855        Type *clang_type = qual_type.getTypePtr();
856        if (clang_type)
857        {
858            RecordType *record_type = dyn_cast<RecordType>(clang_type);
859            if (record_type)
860            {
861                RecordDecl *record_decl = record_type->getDecl();
862                if (record_decl)
863                {
864                    uint32_t field_idx;
865                    RecordDecl::field_iterator field, field_end;
866                    for (field = record_decl->field_begin(), field_end = record_decl->field_end(), field_idx = 0;
867                         field != field_end;
868                         ++field, ++field_idx)
869                    {
870                        // If no accessibility was assigned, assign the correct one
871                        if (field_idx < num_assigned_accessibilities && assigned_accessibilities[field_idx] == clang::AS_none)
872                            field->setAccess ((AccessSpecifier)default_accessibility);
873                    }
874                }
875            }
876        }
877    }
878}
879
880#pragma mark C++ Base Classes
881
882CXXBaseSpecifier *
883ClangASTContext::CreateBaseClassSpecifier (void *base_class_type, int access, bool is_virtual, bool base_of_class)
884{
885    if (base_class_type)
886        return new CXXBaseSpecifier(SourceRange(), is_virtual, base_of_class, (AccessSpecifier)access, QualType::getFromOpaquePtr(base_class_type));
887    return NULL;
888}
889
890void
891ClangASTContext::DeleteBaseClassSpecifiers (CXXBaseSpecifier **base_classes, unsigned num_base_classes)
892{
893    for (unsigned i=0; i<num_base_classes; ++i)
894    {
895        delete base_classes[i];
896        base_classes[i] = NULL;
897    }
898}
899
900bool
901ClangASTContext::SetBaseClassesForClassType (void *class_clang_type, CXXBaseSpecifier const * const *base_classes, unsigned num_base_classes)
902{
903    if (class_clang_type)
904    {
905        ASTContext *ast_context = getASTContext();
906        IdentifierTable *identifier_table = getIdentifierTable();
907
908        assert (ast_context != NULL);
909        assert (identifier_table != NULL);
910
911        Type *clang_type = QualType::getFromOpaquePtr(class_clang_type).getTypePtr();
912        if (clang_type)
913        {
914            RecordType *record_type = dyn_cast<RecordType>(clang_type);
915            if (record_type)
916            {
917                CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_type->getDecl());
918                if (cxx_record_decl)
919                {
920                    //cxx_record_decl->setEmpty (false);
921                    cxx_record_decl->setBases(base_classes, num_base_classes);
922                    return true;
923                }
924            }
925        }
926    }
927    return false;
928}
929
930
931#pragma mark Aggregate Types
932
933bool
934ClangASTContext::IsAggregateType (void *clang_type)
935{
936    if (clang_type == NULL)
937        return false;
938
939    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
940
941    if (qual_type->isAggregateType ())
942        return true;
943
944    switch (qual_type->getTypeClass())
945    {
946    case Type::IncompleteArray:
947    case Type::VariableArray:
948    case Type::ConstantArray:
949    case Type::ExtVector:
950    case Type::Vector:
951    case Type::Record:
952        return true;
953
954    case Type::Typedef:
955        return ClangASTContext::IsAggregateType (cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr());
956
957    default:
958        break;
959    }
960    // The clang type does have a value
961    return false;
962}
963
964uint32_t
965ClangASTContext::GetNumChildren (void *clang_qual_type, bool omit_empty_base_classes)
966{
967    if (clang_qual_type == NULL)
968        return 0;
969
970    uint32_t num_children = 0;
971    QualType qual_type(QualType::getFromOpaquePtr(clang_qual_type));
972    switch (qual_type->getTypeClass())
973    {
974    case Type::Record:
975        {
976            const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
977            const RecordDecl *record_decl = record_type->getDecl();
978            assert(record_decl);
979            const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
980            if (cxx_record_decl)
981            {
982                if (omit_empty_base_classes)
983                {
984                    // Check each base classes to see if it or any of its
985                    // base classes contain any fields. This can help
986                    // limit the noise in variable views by not having to
987                    // show base classes that contain no members.
988                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
989                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
990                         base_class != base_class_end;
991                         ++base_class)
992                    {
993                        const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
994
995                        // Skip empty base classes
996                        if (RecordHasFields(base_class_decl) == false)
997                            continue;
998
999                        num_children++;
1000                    }
1001                }
1002                else
1003                {
1004                    // Include all base classes
1005                    num_children += cxx_record_decl->getNumBases();
1006                }
1007
1008            }
1009            RecordDecl::field_iterator field, field_end;
1010            for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field)
1011                ++num_children;
1012        }
1013        break;
1014
1015    case Type::ConstantArray:
1016        num_children = cast<ConstantArrayType>(qual_type.getTypePtr())->getSize().getLimitedValue();
1017        break;
1018
1019    case Type::Pointer:
1020        {
1021            PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
1022            QualType pointee_type = pointer_type->getPointeeType();
1023            uint32_t num_pointee_children = ClangASTContext::GetNumChildren (pointee_type.getAsOpaquePtr(), omit_empty_base_classes);
1024            // If this type points to a simple type, then it has 1 child
1025            if (num_pointee_children == 0)
1026                num_children = 1;
1027            else
1028                num_children = num_pointee_children;
1029        }
1030        break;
1031
1032    case Type::Typedef:
1033        num_children = ClangASTContext::GetNumChildren (cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr(), omit_empty_base_classes);
1034        break;
1035
1036    default:
1037        break;
1038    }
1039    return num_children;
1040}
1041
1042
1043void *
1044ClangASTContext::GetChildClangTypeAtIndex
1045(
1046    const char *parent_name,
1047    void *parent_clang_type,
1048    uint32_t idx,
1049    bool transparent_pointers,
1050    bool omit_empty_base_classes,
1051    std::string& child_name,
1052    uint32_t &child_byte_size,
1053    int32_t &child_byte_offset,
1054    uint32_t &child_bitfield_bit_size,
1055    uint32_t &child_bitfield_bit_offset
1056)
1057{
1058    if (parent_clang_type)
1059
1060        return GetChildClangTypeAtIndex (getASTContext(),
1061                                         parent_name,
1062                                         parent_clang_type,
1063                                         idx,
1064                                         transparent_pointers,
1065                                         omit_empty_base_classes,
1066                                         child_name,
1067                                         child_byte_size,
1068                                         child_byte_offset,
1069                                         child_bitfield_bit_size,
1070                                         child_bitfield_bit_offset);
1071    return NULL;
1072}
1073
1074void *
1075ClangASTContext::GetChildClangTypeAtIndex
1076(
1077    ASTContext *ast_context,
1078    const char *parent_name,
1079    void *parent_clang_type,
1080    uint32_t idx,
1081    bool transparent_pointers,
1082    bool omit_empty_base_classes,
1083    std::string& child_name,
1084    uint32_t &child_byte_size,
1085    int32_t &child_byte_offset,
1086    uint32_t &child_bitfield_bit_size,
1087    uint32_t &child_bitfield_bit_offset
1088)
1089{
1090    if (parent_clang_type == NULL)
1091        return NULL;
1092
1093    if (idx < ClangASTContext::GetNumChildren (parent_clang_type, omit_empty_base_classes))
1094    {
1095        uint32_t bit_offset;
1096        child_bitfield_bit_size = 0;
1097        child_bitfield_bit_offset = 0;
1098        QualType parent_qual_type(QualType::getFromOpaquePtr(parent_clang_type));
1099        switch (parent_qual_type->getTypeClass())
1100        {
1101        case Type::Record:
1102            {
1103                const RecordType *record_type = cast<RecordType>(parent_qual_type.getTypePtr());
1104                const RecordDecl *record_decl = record_type->getDecl();
1105                assert(record_decl);
1106                const ASTRecordLayout &record_layout = ast_context->getASTRecordLayout(record_decl);
1107                uint32_t child_idx = 0;
1108
1109                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1110                if (cxx_record_decl)
1111                {
1112                    // We might have base classes to print out first
1113                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1114                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
1115                         base_class != base_class_end;
1116                         ++base_class)
1117                    {
1118                        const CXXRecordDecl *base_class_decl = NULL;
1119
1120                        // Skip empty base classes
1121                        if (omit_empty_base_classes)
1122                        {
1123                            base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
1124                            if (RecordHasFields(base_class_decl) == false)
1125                                continue;
1126                        }
1127
1128                        if (idx == child_idx)
1129                        {
1130                            if (base_class_decl == NULL)
1131                                base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
1132
1133
1134                            if (base_class->isVirtual())
1135                                bit_offset = record_layout.getVBaseClassOffset(base_class_decl);
1136                            else
1137                                bit_offset = record_layout.getBaseClassOffset(base_class_decl);
1138
1139                            // Base classes should be a multiple of 8 bits in size
1140                            assert (bit_offset % 8 == 0);
1141                            child_byte_offset = bit_offset/8;
1142                            std::string base_class_type_name(base_class->getType().getAsString());
1143
1144                            child_name.assign(base_class_type_name.c_str());
1145
1146                            uint64_t clang_type_info_bit_size = ast_context->getTypeSize(base_class->getType());
1147
1148                            // Base classes biut sizes should be a multiple of 8 bits in size
1149                            assert (clang_type_info_bit_size % 8 == 0);
1150                            child_byte_size = clang_type_info_bit_size / 8;
1151                            return base_class->getType().getAsOpaquePtr();
1152                        }
1153                        // We don't increment the child index in the for loop since we might
1154                        // be skipping empty base classes
1155                        ++child_idx;
1156                    }
1157                }
1158                const unsigned num_fields = record_layout.getFieldCount();
1159
1160                // Make sure index is in range...
1161                uint32_t field_idx = 0;
1162                RecordDecl::field_iterator field, field_end;
1163                for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field, ++field_idx, ++child_idx)
1164                {
1165                    if (idx == child_idx)
1166                    {
1167                        // Print the member type if requested
1168                        // Print the member name and equal sign
1169                        child_name.assign(field->getNameAsString().c_str());
1170
1171                        // Figure out the type byte size (field_type_info.first) and
1172                        // alignment (field_type_info.second) from the AST context.
1173                        std::pair<uint64_t, unsigned> field_type_info = ast_context->getTypeInfo(field->getType());
1174                        assert(field_idx < num_fields);
1175
1176                        child_byte_size = field_type_info.first / 8;
1177
1178                        // Figure out the field offset within the current struct/union/class type
1179                        bit_offset = record_layout.getFieldOffset (field_idx);
1180                        child_byte_offset = bit_offset / 8;
1181                        if (ClangASTContext::FieldIsBitfield (ast_context, *field, child_bitfield_bit_size))
1182                            child_bitfield_bit_offset = bit_offset % 8;
1183
1184                        return field->getType().getAsOpaquePtr();
1185                    }
1186                }
1187            }
1188            break;
1189
1190        case Type::ConstantArray:
1191            {
1192                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
1193                const uint64_t element_count = array->getSize().getLimitedValue();
1194
1195                if (idx < element_count)
1196                {
1197                    std::pair<uint64_t, unsigned> field_type_info = ast_context->getTypeInfo(array->getElementType());
1198
1199                    char element_name[32];
1200                    ::snprintf (element_name, sizeof (element_name), "%s[%u]", parent_name ? parent_name : "", idx);
1201
1202                    child_name.assign(element_name);
1203                    assert(field_type_info.first % 8 == 0);
1204                    child_byte_size = field_type_info.first / 8;
1205                    child_byte_offset = idx * child_byte_size;
1206                    return array->getElementType().getAsOpaquePtr();
1207                }
1208            }
1209            break;
1210
1211        case Type::Pointer:
1212            {
1213                PointerType *pointer_type = cast<PointerType>(parent_qual_type.getTypePtr());
1214                QualType pointee_type = pointer_type->getPointeeType();
1215
1216                if (transparent_pointers && ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
1217                {
1218                    return GetChildClangTypeAtIndex (ast_context,
1219                                                     parent_name,
1220                                                     pointer_type->getPointeeType().getAsOpaquePtr(),
1221                                                     idx,
1222                                                     transparent_pointers,
1223                                                     omit_empty_base_classes,
1224                                                     child_name,
1225                                                     child_byte_size,
1226                                                     child_byte_offset,
1227                                                     child_bitfield_bit_size,
1228                                                     child_bitfield_bit_offset);
1229                }
1230                else
1231                {
1232                    if (parent_name)
1233                    {
1234                        child_name.assign(1, '*');
1235                        child_name += parent_name;
1236                    }
1237
1238                    // We have a pointer to an simple type
1239                    if (idx == 0)
1240                    {
1241                        std::pair<uint64_t, unsigned> clang_type_info = ast_context->getTypeInfo(pointee_type);
1242                        assert(clang_type_info.first % 8 == 0);
1243                        child_byte_size = clang_type_info.first / 8;
1244                        child_byte_offset = 0;
1245                        return pointee_type.getAsOpaquePtr();
1246                    }
1247                }
1248            }
1249            break;
1250
1251        case Type::Typedef:
1252            return GetChildClangTypeAtIndex (ast_context,
1253                                             parent_name,
1254                                             cast<TypedefType>(parent_qual_type)->LookThroughTypedefs().getAsOpaquePtr(),
1255                                             idx,
1256                                             transparent_pointers,
1257                                             omit_empty_base_classes,
1258                                             child_name,
1259                                             child_byte_size,
1260                                             child_byte_offset,
1261                                             child_bitfield_bit_size,
1262                                             child_bitfield_bit_offset);
1263            break;
1264
1265        default:
1266            break;
1267        }
1268    }
1269    return false;
1270}
1271
1272static inline bool
1273BaseSpecifierIsEmpty (const CXXBaseSpecifier *b)
1274{
1275    return ClangASTContext::RecordHasFields(cast<CXXRecordDecl>(b->getType()->getAs<RecordType>()->getDecl())) == false;
1276}
1277
1278static uint32_t
1279GetNumBaseClasses (const CXXRecordDecl *cxx_record_decl, bool omit_empty_base_classes)
1280{
1281    uint32_t num_bases = 0;
1282    if (cxx_record_decl)
1283    {
1284        if (omit_empty_base_classes)
1285        {
1286            CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1287            for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
1288                 base_class != base_class_end;
1289                 ++base_class)
1290            {
1291                // Skip empty base classes
1292                if (omit_empty_base_classes)
1293                {
1294                    if (BaseSpecifierIsEmpty (base_class))
1295                        continue;
1296                }
1297                ++num_bases;
1298            }
1299        }
1300        else
1301            num_bases = cxx_record_decl->getNumBases();
1302    }
1303    return num_bases;
1304}
1305
1306
1307static uint32_t
1308GetIndexForRecordBase
1309(
1310    const RecordDecl *record_decl,
1311    const CXXBaseSpecifier *base_spec,
1312    bool omit_empty_base_classes
1313)
1314{
1315    uint32_t child_idx = 0;
1316
1317    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1318
1319//    const char *super_name = record_decl->getNameAsCString();
1320//    const char *base_name = base_spec->getType()->getAs<RecordType>()->getDecl()->getNameAsCString();
1321//    printf ("GetIndexForRecordChild (%s, %s)\n", super_name, base_name);
1322//
1323    if (cxx_record_decl)
1324    {
1325        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1326        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
1327             base_class != base_class_end;
1328             ++base_class)
1329        {
1330            if (omit_empty_base_classes)
1331            {
1332                if (BaseSpecifierIsEmpty (base_class))
1333                    continue;
1334            }
1335
1336//            printf ("GetIndexForRecordChild (%s, %s) base[%u] = %s\n", super_name, base_name,
1337//                    child_idx,
1338//                    base_class->getType()->getAs<RecordType>()->getDecl()->getNameAsCString());
1339//
1340//
1341            if (base_class == base_spec)
1342                return child_idx;
1343            ++child_idx;
1344        }
1345    }
1346
1347    return UINT32_MAX;
1348}
1349
1350
1351static uint32_t
1352GetIndexForRecordChild
1353(
1354    const RecordDecl *record_decl,
1355    NamedDecl *canonical_decl,
1356    bool omit_empty_base_classes
1357)
1358{
1359    uint32_t child_idx = GetNumBaseClasses (dyn_cast<CXXRecordDecl>(record_decl), omit_empty_base_classes);
1360
1361//    const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1362//
1363////    printf ("GetIndexForRecordChild (%s, %s)\n", record_decl->getNameAsCString(), canonical_decl->getNameAsCString());
1364//    if (cxx_record_decl)
1365//    {
1366//        CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1367//        for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
1368//             base_class != base_class_end;
1369//             ++base_class)
1370//        {
1371//            if (omit_empty_base_classes)
1372//            {
1373//                if (BaseSpecifierIsEmpty (base_class))
1374//                    continue;
1375//            }
1376//
1377////            printf ("GetIndexForRecordChild (%s, %s) base[%u] = %s\n",
1378////                    record_decl->getNameAsCString(),
1379////                    canonical_decl->getNameAsCString(),
1380////                    child_idx,
1381////                    base_class->getType()->getAs<RecordType>()->getDecl()->getNameAsCString());
1382//
1383//
1384//            CXXRecordDecl *curr_base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
1385//            if (curr_base_class_decl == canonical_decl)
1386//            {
1387//                return child_idx;
1388//            }
1389//            ++child_idx;
1390//        }
1391//    }
1392//
1393//    const uint32_t num_bases = child_idx;
1394    RecordDecl::field_iterator field, field_end;
1395    for (field = record_decl->field_begin(), field_end = record_decl->field_end();
1396         field != field_end;
1397         ++field, ++child_idx)
1398    {
1399//            printf ("GetIndexForRecordChild (%s, %s) field[%u] = %s\n",
1400//                    record_decl->getNameAsCString(),
1401//                    canonical_decl->getNameAsCString(),
1402//                    child_idx - num_bases,
1403//                    field->getNameAsCString());
1404
1405        if (field->getCanonicalDecl() == canonical_decl)
1406            return child_idx;
1407    }
1408
1409    return UINT32_MAX;
1410}
1411
1412// Look for a child member (doesn't include base classes, but it does include
1413// their members) in the type hierarchy. Returns an index path into "clang_type"
1414// on how to reach the appropriate member.
1415//
1416//    class A
1417//    {
1418//    public:
1419//        int m_a;
1420//        int m_b;
1421//    };
1422//
1423//    class B
1424//    {
1425//    };
1426//
1427//    class C :
1428//        public B,
1429//        public A
1430//    {
1431//    };
1432//
1433// If we have a clang type that describes "class C", and we wanted to looked
1434// "m_b" in it:
1435//
1436// With omit_empty_base_classes == false we would get an integer array back with:
1437// { 1,  1 }
1438// The first index 1 is the child index for "class A" within class C
1439// The second index 1 is the child index for "m_b" within class A
1440//
1441// With omit_empty_base_classes == true we would get an integer array back with:
1442// { 0,  1 }
1443// 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)
1444// The second index 1 is the child index for "m_b" within class A
1445
1446size_t
1447ClangASTContext::GetIndexOfChildMemberWithName
1448(
1449    ASTContext *ast_context,
1450    void *clang_type,
1451    const char *name,
1452    bool omit_empty_base_classes,
1453    std::vector<uint32_t>& child_indexes
1454)
1455{
1456    if (clang_type && name && name[0])
1457    {
1458        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
1459        switch (qual_type->getTypeClass())
1460        {
1461        case Type::Record:
1462            {
1463                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
1464                const RecordDecl *record_decl = record_type->getDecl();
1465
1466                assert(record_decl);
1467                uint32_t child_idx = 0;
1468
1469                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1470
1471                // Try and find a field that matches NAME
1472                RecordDecl::field_iterator field, field_end;
1473                StringRef name_sref(name);
1474                for (field = record_decl->field_begin(), field_end = record_decl->field_end();
1475                     field != field_end;
1476                     ++field, ++child_idx)
1477                {
1478                    if (field->getName().equals (name_sref))
1479                    {
1480                        // We have to add on the number of base classes to this index!
1481                        child_indexes.push_back (child_idx + GetNumBaseClasses (cxx_record_decl, omit_empty_base_classes));
1482                        return child_indexes.size();
1483                    }
1484                }
1485
1486                if (cxx_record_decl)
1487                {
1488                    const RecordDecl *parent_record_decl = cxx_record_decl;
1489
1490                    //printf ("parent = %s\n", parent_record_decl->getNameAsCString());
1491
1492                    //const Decl *root_cdecl = cxx_record_decl->getCanonicalDecl();
1493                    // Didn't find things easily, lets let clang do its thang...
1494                    IdentifierInfo & ident_ref = ast_context->Idents.get(name, name + strlen (name));
1495                    DeclarationName decl_name(&ident_ref);
1496
1497                    CXXBasePaths paths;
1498                    if (cxx_record_decl->lookupInBases(CXXRecordDecl::FindOrdinaryMember,
1499                                                       decl_name.getAsOpaquePtr(),
1500                                                       paths))
1501                    {
1502                        uint32_t child_idx;
1503                        CXXBasePaths::const_paths_iterator path, path_end = paths.end();
1504                        for (path = paths.begin(); path != path_end; ++path)
1505                        {
1506                            const size_t num_path_elements = path->size();
1507                            for (size_t e=0; e<num_path_elements; ++e)
1508                            {
1509                                CXXBasePathElement elem = (*path)[e];
1510
1511                                child_idx = GetIndexForRecordBase (parent_record_decl, elem.Base, omit_empty_base_classes);
1512                                if (child_idx == UINT32_MAX)
1513                                {
1514                                    child_indexes.clear();
1515                                    return 0;
1516                                }
1517                                else
1518                                {
1519                                    child_indexes.push_back (child_idx);
1520                                    parent_record_decl = cast<RecordDecl>(elem.Base->getType()->getAs<RecordType>()->getDecl());
1521                                }
1522                            }
1523                            DeclContext::lookup_iterator named_decl_pos;
1524                            for (named_decl_pos = path->Decls.first;
1525                                 named_decl_pos != path->Decls.second && parent_record_decl;
1526                                 ++named_decl_pos)
1527                            {
1528                                //printf ("path[%zu] = %s\n", child_indexes.size(), (*named_decl_pos)->getNameAsCString());
1529
1530                                child_idx = GetIndexForRecordChild (parent_record_decl, *named_decl_pos, omit_empty_base_classes);
1531                                if (child_idx == UINT32_MAX)
1532                                {
1533                                    child_indexes.clear();
1534                                    return 0;
1535                                }
1536                                else
1537                                {
1538                                    child_indexes.push_back (child_idx);
1539                                }
1540                            }
1541                        }
1542                        return child_indexes.size();
1543                    }
1544                }
1545
1546            }
1547            break;
1548
1549        case Type::ConstantArray:
1550            {
1551//                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
1552//                const uint64_t element_count = array->getSize().getLimitedValue();
1553//
1554//                if (idx < element_count)
1555//                {
1556//                    std::pair<uint64_t, unsigned> field_type_info = ast_context->getTypeInfo(array->getElementType());
1557//
1558//                    char element_name[32];
1559//                    ::snprintf (element_name, sizeof (element_name), "%s[%u]", parent_name ? parent_name : "", idx);
1560//
1561//                    child_name.assign(element_name);
1562//                    assert(field_type_info.first % 8 == 0);
1563//                    child_byte_size = field_type_info.first / 8;
1564//                    child_byte_offset = idx * child_byte_size;
1565//                    return array->getElementType().getAsOpaquePtr();
1566//                }
1567            }
1568            break;
1569
1570//        case Type::MemberPointerType:
1571//            {
1572//                MemberPointerType *mem_ptr_type = cast<MemberPointerType>(qual_type.getTypePtr());
1573//                QualType pointee_type = mem_ptr_type->getPointeeType();
1574//
1575//                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
1576//                {
1577//                    return GetIndexOfChildWithName (ast_context,
1578//                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
1579//                                                    name);
1580//                }
1581//            }
1582//            break;
1583//
1584        case Type::LValueReference:
1585        case Type::RValueReference:
1586            {
1587                ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
1588                QualType pointee_type = reference_type->getPointeeType();
1589
1590                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
1591                {
1592                    return GetIndexOfChildMemberWithName (ast_context,
1593                                                          reference_type->getPointeeType().getAsOpaquePtr(),
1594                                                          name,
1595                                                          omit_empty_base_classes,
1596                                                          child_indexes);
1597                }
1598            }
1599            break;
1600
1601        case Type::Pointer:
1602            {
1603                PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
1604                QualType pointee_type = pointer_type->getPointeeType();
1605
1606                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
1607                {
1608                    return GetIndexOfChildMemberWithName (ast_context,
1609                                                          pointer_type->getPointeeType().getAsOpaquePtr(),
1610                                                          name,
1611                                                          omit_empty_base_classes,
1612                                                          child_indexes);
1613                }
1614                else
1615                {
1616//                    if (parent_name)
1617//                    {
1618//                        child_name.assign(1, '*');
1619//                        child_name += parent_name;
1620//                    }
1621//
1622//                    // We have a pointer to an simple type
1623//                    if (idx == 0)
1624//                    {
1625//                        std::pair<uint64_t, unsigned> clang_type_info = ast_context->getTypeInfo(pointee_type);
1626//                        assert(clang_type_info.first % 8 == 0);
1627//                        child_byte_size = clang_type_info.first / 8;
1628//                        child_byte_offset = 0;
1629//                        return pointee_type.getAsOpaquePtr();
1630//                    }
1631                }
1632            }
1633            break;
1634
1635        case Type::Typedef:
1636            return GetIndexOfChildMemberWithName (ast_context,
1637                                                  cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr(),
1638                                                  name,
1639                                                  omit_empty_base_classes,
1640                                                  child_indexes);
1641
1642        default:
1643            break;
1644        }
1645    }
1646    return 0;
1647}
1648
1649
1650// Get the index of the child of "clang_type" whose name matches. This function
1651// doesn't descend into the children, but only looks one level deep and name
1652// matches can include base class names.
1653
1654uint32_t
1655ClangASTContext::GetIndexOfChildWithName
1656(
1657    ASTContext *ast_context,
1658    void *clang_type,
1659    const char *name,
1660    bool omit_empty_base_classes
1661)
1662{
1663    if (clang_type && name && name[0])
1664    {
1665        QualType qual_type(QualType::getFromOpaquePtr(clang_type));
1666        switch (qual_type->getTypeClass())
1667        {
1668        case Type::Record:
1669            {
1670                const RecordType *record_type = cast<RecordType>(qual_type.getTypePtr());
1671                const RecordDecl *record_decl = record_type->getDecl();
1672
1673                assert(record_decl);
1674                uint32_t child_idx = 0;
1675
1676                const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1677
1678                if (cxx_record_decl)
1679                {
1680                    CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1681                    for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end();
1682                         base_class != base_class_end;
1683                         ++base_class)
1684                    {
1685                        // Skip empty base classes
1686                        CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(base_class->getType()->getAs<RecordType>()->getDecl());
1687                        if (omit_empty_base_classes && RecordHasFields(base_class_decl) == false)
1688                            continue;
1689
1690                        if (base_class->getType().getAsString().compare (name) == 0)
1691                            return child_idx;
1692                        ++child_idx;
1693                    }
1694                }
1695
1696                // Try and find a field that matches NAME
1697                RecordDecl::field_iterator field, field_end;
1698                StringRef name_sref(name);
1699                for (field = record_decl->field_begin(), field_end = record_decl->field_end();
1700                     field != field_end;
1701                     ++field, ++child_idx)
1702                {
1703                    if (field->getName().equals (name_sref))
1704                        return child_idx;
1705                }
1706
1707            }
1708            break;
1709
1710        case Type::ConstantArray:
1711            {
1712//                const ConstantArrayType *array = cast<ConstantArrayType>(parent_qual_type.getTypePtr());
1713//                const uint64_t element_count = array->getSize().getLimitedValue();
1714//
1715//                if (idx < element_count)
1716//                {
1717//                    std::pair<uint64_t, unsigned> field_type_info = ast_context->getTypeInfo(array->getElementType());
1718//
1719//                    char element_name[32];
1720//                    ::snprintf (element_name, sizeof (element_name), "%s[%u]", parent_name ? parent_name : "", idx);
1721//
1722//                    child_name.assign(element_name);
1723//                    assert(field_type_info.first % 8 == 0);
1724//                    child_byte_size = field_type_info.first / 8;
1725//                    child_byte_offset = idx * child_byte_size;
1726//                    return array->getElementType().getAsOpaquePtr();
1727//                }
1728            }
1729            break;
1730
1731//        case Type::MemberPointerType:
1732//            {
1733//                MemberPointerType *mem_ptr_type = cast<MemberPointerType>(qual_type.getTypePtr());
1734//                QualType pointee_type = mem_ptr_type->getPointeeType();
1735//
1736//                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
1737//                {
1738//                    return GetIndexOfChildWithName (ast_context,
1739//                                                    mem_ptr_type->getPointeeType().getAsOpaquePtr(),
1740//                                                    name);
1741//                }
1742//            }
1743//            break;
1744//
1745        case Type::LValueReference:
1746        case Type::RValueReference:
1747            {
1748                ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
1749                QualType pointee_type = reference_type->getPointeeType();
1750
1751                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
1752                {
1753                    return GetIndexOfChildWithName (ast_context,
1754                                                    reference_type->getPointeeType().getAsOpaquePtr(),
1755                                                    name,
1756                                                    omit_empty_base_classes);
1757                }
1758            }
1759            break;
1760
1761        case Type::Pointer:
1762            {
1763                PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
1764                QualType pointee_type = pointer_type->getPointeeType();
1765
1766                if (ClangASTContext::IsAggregateType (pointee_type.getAsOpaquePtr()))
1767                {
1768                    return GetIndexOfChildWithName (ast_context,
1769                                                    pointer_type->getPointeeType().getAsOpaquePtr(),
1770                                                    name,
1771                                                    omit_empty_base_classes);
1772                }
1773                else
1774                {
1775//                    if (parent_name)
1776//                    {
1777//                        child_name.assign(1, '*');
1778//                        child_name += parent_name;
1779//                    }
1780//
1781//                    // We have a pointer to an simple type
1782//                    if (idx == 0)
1783//                    {
1784//                        std::pair<uint64_t, unsigned> clang_type_info = ast_context->getTypeInfo(pointee_type);
1785//                        assert(clang_type_info.first % 8 == 0);
1786//                        child_byte_size = clang_type_info.first / 8;
1787//                        child_byte_offset = 0;
1788//                        return pointee_type.getAsOpaquePtr();
1789//                    }
1790                }
1791            }
1792            break;
1793
1794        case Type::Typedef:
1795            return GetIndexOfChildWithName (ast_context,
1796                                            cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr(),
1797                                            name,
1798                                            omit_empty_base_classes);
1799
1800        default:
1801            break;
1802        }
1803    }
1804    return UINT32_MAX;
1805}
1806
1807#pragma mark TagType
1808
1809bool
1810ClangASTContext::SetTagTypeKind (void *tag_clang_type, int kind)
1811{
1812    if (tag_clang_type)
1813    {
1814        QualType tag_qual_type(QualType::getFromOpaquePtr(tag_clang_type));
1815        Type *clang_type = tag_qual_type.getTypePtr();
1816        if (clang_type)
1817        {
1818            TagType *tag_type = dyn_cast<TagType>(clang_type);
1819            if (tag_type)
1820            {
1821                TagDecl *tag_decl = dyn_cast<TagDecl>(tag_type->getDecl());
1822                if (tag_decl)
1823                {
1824                    tag_decl->setTagKind ((TagDecl::TagKind)kind);
1825                    return true;
1826                }
1827            }
1828        }
1829    }
1830    return false;
1831}
1832
1833
1834#pragma mark DeclContext Functions
1835
1836DeclContext *
1837ClangASTContext::GetDeclContextForType (void *clang_type)
1838{
1839    if (clang_type == NULL)
1840        return NULL;
1841
1842    QualType qual_type(QualType::getFromOpaquePtr(clang_type));
1843    switch (qual_type->getTypeClass())
1844    {
1845    case Type::FunctionNoProto:         break;
1846    case Type::FunctionProto:           break;
1847    case Type::IncompleteArray:         break;
1848    case Type::VariableArray:           break;
1849    case Type::ConstantArray:           break;
1850    case Type::ExtVector:               break;
1851    case Type::Vector:                  break;
1852    case Type::Builtin:                 break;
1853    case Type::ObjCObjectPointer:       break;
1854    case Type::BlockPointer:            break;
1855    case Type::Pointer:                 break;
1856    case Type::LValueReference:         break;
1857    case Type::RValueReference:         break;
1858    case Type::MemberPointer:           break;
1859    case Type::Complex:                 break;
1860    case Type::ObjCInterface:           break;
1861    case Type::Record:
1862        return cast<RecordType>(qual_type)->getDecl();
1863    case Type::Enum:
1864        return cast<EnumType>(qual_type)->getDecl();
1865    case Type::Typedef:
1866        return ClangASTContext::GetDeclContextForType (cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr());
1867
1868    case Type::TypeOfExpr:              break;
1869    case Type::TypeOf:                  break;
1870    case Type::Decltype:                break;
1871    //case Type::QualifiedName:           break;
1872    case Type::TemplateSpecialization:  break;
1873    }
1874    // No DeclContext in this type...
1875    return NULL;
1876}
1877
1878#pragma mark Namespace Declarations
1879
1880NamespaceDecl *
1881ClangASTContext::GetUniqueNamespaceDeclaration (const char *name, const Declaration &decl, DeclContext *decl_ctx)
1882{
1883    // TODO: Do something intelligent with the Declaration object passed in
1884    // like maybe filling in the SourceLocation with it...
1885    if (name)
1886    {
1887        ASTContext *ast_context = getASTContext();
1888        if (decl_ctx == NULL)
1889            decl_ctx = ast_context->getTranslationUnitDecl();
1890        return NamespaceDecl::Create(*ast_context, decl_ctx, SourceLocation(), &ast_context->Idents.get(name));
1891    }
1892    return NULL;
1893}
1894
1895
1896#pragma mark Function Types
1897
1898FunctionDecl *
1899ClangASTContext::CreateFunctionDeclaration (const char *name, void *function_clang_type, int storage, bool is_inline)
1900{
1901    if (name)
1902    {
1903        ASTContext *ast_context = getASTContext();
1904        assert (ast_context != NULL);
1905
1906        if (name && name[0])
1907        {
1908            return FunctionDecl::Create(*ast_context,
1909                                        ast_context->getTranslationUnitDecl(),
1910                                        SourceLocation(),
1911                                        DeclarationName (&ast_context->Idents.get(name)),
1912                                        QualType::getFromOpaquePtr(function_clang_type),
1913                                        NULL,
1914                                        (FunctionDecl::StorageClass)storage,
1915                                        (FunctionDecl::StorageClass)storage,
1916                                        is_inline);
1917        }
1918        else
1919        {
1920            return FunctionDecl::Create(*ast_context,
1921                                        ast_context->getTranslationUnitDecl(),
1922                                        SourceLocation(),
1923                                        DeclarationName (),
1924                                        QualType::getFromOpaquePtr(function_clang_type),
1925                                        NULL,
1926                                        (FunctionDecl::StorageClass)storage,
1927                                        (FunctionDecl::StorageClass)storage,
1928                                        is_inline);
1929        }
1930    }
1931    return NULL;
1932}
1933
1934void *
1935ClangASTContext::CreateFunctionType (void *result_type, void **args, unsigned num_args, bool isVariadic, unsigned TypeQuals)
1936{
1937    ASTContext *ast_context = getASTContext();
1938    assert (ast_context != NULL);
1939    std::vector<QualType> qual_type_args;
1940    for (unsigned i=0; i<num_args; ++i)
1941        qual_type_args.push_back (QualType::getFromOpaquePtr(args[i]));
1942
1943    // TODO: Detect calling convention in DWARF?
1944    return ast_context->getFunctionType(QualType::getFromOpaquePtr(result_type),
1945                                        qual_type_args.data(),
1946                                        qual_type_args.size(),
1947                                        isVariadic,
1948                                        TypeQuals,
1949                                        false,  // hasExceptionSpec
1950                                        false,  // hasAnyExceptionSpec,
1951                                        0,      // NumExs
1952                                        0,      // const QualType *ExArray
1953                                        FunctionType::ExtInfo ()).getAsOpaquePtr();    // NoReturn);
1954}
1955
1956ParmVarDecl *
1957ClangASTContext::CreateParmeterDeclaration (const char *name, void * return_type, int storage)
1958{
1959    ASTContext *ast_context = getASTContext();
1960    assert (ast_context != NULL);
1961    return ParmVarDecl::Create(*ast_context,
1962                                ast_context->getTranslationUnitDecl(),
1963                                SourceLocation(),
1964                                name && name[0] ? &ast_context->Idents.get(name) : NULL,
1965                                QualType::getFromOpaquePtr(return_type),
1966                                NULL,
1967                                (VarDecl::StorageClass)storage,
1968                                (VarDecl::StorageClass)storage,
1969                                0);
1970}
1971
1972void
1973ClangASTContext::SetFunctionParameters (FunctionDecl *function_decl, ParmVarDecl **params, unsigned num_params)
1974{
1975    if (function_decl)
1976        function_decl->setParams (params, num_params);
1977}
1978
1979
1980#pragma mark Array Types
1981
1982void *
1983ClangASTContext::CreateArrayType (void *element_type, size_t element_count, uint32_t bit_stride)
1984{
1985    if (element_type)
1986    {
1987        ASTContext *ast_context = getASTContext();
1988        assert (ast_context != NULL);
1989        llvm::APInt ap_element_count (64, element_count);
1990        return ast_context->getConstantArrayType(QualType::getFromOpaquePtr(element_type),
1991                                                 ap_element_count,
1992                                                 ArrayType::Normal,
1993                                                 0).getAsOpaquePtr(); // ElemQuals
1994    }
1995    return NULL;
1996}
1997
1998
1999#pragma mark TagDecl
2000
2001bool
2002ClangASTContext::StartTagDeclarationDefinition (void *clang_type)
2003{
2004    if (clang_type)
2005    {
2006        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2007        Type *t = qual_type.getTypePtr();
2008        if (t)
2009        {
2010            TagType *tag_type = dyn_cast<TagType>(t);
2011            if (tag_type)
2012            {
2013                TagDecl *tag_decl = tag_type->getDecl();
2014                if (tag_decl)
2015                {
2016                    tag_decl->startDefinition();
2017                    return true;
2018                }
2019            }
2020        }
2021    }
2022    return false;
2023}
2024
2025bool
2026ClangASTContext::CompleteTagDeclarationDefinition (void *clang_type)
2027{
2028    if (clang_type)
2029    {
2030        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2031        Type *t = qual_type.getTypePtr();
2032        if (t)
2033        {
2034            TagType *tag_type = dyn_cast<TagType>(t);
2035            if (tag_type)
2036            {
2037                TagDecl *tag_decl = tag_type->getDecl();
2038                if (tag_decl)
2039                {
2040                    tag_decl->completeDefinition();
2041                    return true;
2042                }
2043            }
2044        }
2045    }
2046    return false;
2047}
2048
2049
2050#pragma mark Enumeration Types
2051
2052void *
2053ClangASTContext::CreateEnumerationType (const Declaration &decl, const char *name)
2054{
2055    // TODO: Do something intelligent with the Declaration object passed in
2056    // like maybe filling in the SourceLocation with it...
2057    ASTContext *ast_context = getASTContext();
2058    assert (ast_context != NULL);
2059    EnumDecl *enum_decl = EnumDecl::Create(*ast_context,
2060                                           ast_context->getTranslationUnitDecl(),
2061                                           SourceLocation(),
2062                                           name && name[0] ? &ast_context->Idents.get(name) : NULL,
2063                                           SourceLocation(),
2064                                           NULL);
2065    if (enum_decl)
2066        return ast_context->getTagDeclType(enum_decl).getAsOpaquePtr();
2067    return NULL;
2068}
2069
2070bool
2071ClangASTContext::AddEnumerationValueToEnumerationType
2072(
2073    void *enum_clang_type,
2074    void *enumerator_clang_type,
2075    const Declaration &decl,
2076    const char *name,
2077    int64_t enum_value,
2078    uint32_t enum_value_bit_size
2079)
2080{
2081    if (enum_clang_type && enumerator_clang_type && name)
2082    {
2083        // TODO: Do something intelligent with the Declaration object passed in
2084        // like maybe filling in the SourceLocation with it...
2085        ASTContext *ast_context = getASTContext();
2086        IdentifierTable *identifier_table = getIdentifierTable();
2087
2088        assert (ast_context != NULL);
2089        assert (identifier_table != NULL);
2090        QualType enum_qual_type (QualType::getFromOpaquePtr(enum_clang_type));
2091
2092        Type *clang_type = enum_qual_type.getTypePtr();
2093        if (clang_type)
2094        {
2095            const EnumType *enum_type = dyn_cast<EnumType>(clang_type);
2096
2097            if (enum_type)
2098            {
2099                llvm::APSInt enum_llvm_apsint(enum_value_bit_size, false);
2100                enum_llvm_apsint = enum_value;
2101                EnumConstantDecl *enumerator_decl =
2102                    EnumConstantDecl::Create(*ast_context,
2103                                             enum_type->getDecl(),
2104                                             SourceLocation(),
2105                                             name ? &identifier_table->get(name) : NULL,    // Identifier
2106                                             QualType::getFromOpaquePtr(enumerator_clang_type),
2107                                             NULL,
2108                                             enum_llvm_apsint);
2109
2110                if (enumerator_decl)
2111                {
2112                    enum_type->getDecl()->addDecl(enumerator_decl);
2113                    return true;
2114                }
2115            }
2116        }
2117    }
2118    return false;
2119}
2120
2121#pragma mark Pointers & References
2122
2123void *
2124ClangASTContext::CreatePointerType (void *clang_type)
2125{
2126    if (clang_type)
2127        return getASTContext()->getPointerType(QualType::getFromOpaquePtr(clang_type)).getAsOpaquePtr();
2128    return NULL;
2129}
2130
2131void *
2132ClangASTContext::CreateLValueReferenceType (void *clang_type)
2133{
2134    if (clang_type)
2135        return getASTContext()->getLValueReferenceType (QualType::getFromOpaquePtr(clang_type)).getAsOpaquePtr();
2136    return NULL;
2137}
2138
2139void *
2140ClangASTContext::CreateRValueReferenceType (void *clang_type)
2141{
2142    if (clang_type)
2143        return getASTContext()->getRValueReferenceType (QualType::getFromOpaquePtr(clang_type)).getAsOpaquePtr();
2144    return NULL;
2145}
2146
2147void *
2148ClangASTContext::CreateMemberPointerType (void * clang_pointee_type, void * clang_class_type)
2149{
2150    if (clang_pointee_type && clang_pointee_type)
2151        return getASTContext()->getMemberPointerType(QualType::getFromOpaquePtr(clang_pointee_type),
2152                                                     QualType::getFromOpaquePtr(clang_class_type).getTypePtr()).getAsOpaquePtr();
2153    return NULL;
2154}
2155
2156size_t
2157ClangASTContext::GetPointerBitSize ()
2158{
2159    ASTContext *ast_context = getASTContext();
2160    return ast_context->getTypeSize(ast_context->VoidPtrTy);
2161}
2162
2163bool
2164ClangASTContext::IsPointerOrReferenceType (void *clang_type, void **target_type)
2165{
2166    if (clang_type == NULL)
2167        return false;
2168
2169    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2170    switch (qual_type->getTypeClass())
2171    {
2172    case Type::ObjCObjectPointer:
2173        if (target_type)
2174            *target_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
2175        return true;
2176    case Type::BlockPointer:
2177        if (target_type)
2178            *target_type = cast<BlockPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
2179        return true;
2180    case Type::Pointer:
2181        if (target_type)
2182            *target_type = cast<PointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
2183        return true;
2184    case Type::MemberPointer:
2185        if (target_type)
2186            *target_type = cast<MemberPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
2187        return true;
2188    case Type::LValueReference:
2189        if (target_type)
2190            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
2191        return true;
2192    case Type::RValueReference:
2193        if (target_type)
2194            *target_type = cast<LValueReferenceType>(qual_type)->desugar().getAsOpaquePtr();
2195        return true;
2196    case Type::Typedef:
2197        return ClangASTContext::IsPointerOrReferenceType (cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr());
2198    default:
2199        break;
2200    }
2201    return false;
2202}
2203
2204size_t
2205ClangASTContext::GetTypeBitSize (clang::ASTContext *ast_context, void *clang_type)
2206{
2207    if (clang_type)
2208        return ast_context->getTypeSize(QualType::getFromOpaquePtr(clang_type));
2209    return 0;
2210}
2211
2212size_t
2213ClangASTContext::GetTypeBitAlign (clang::ASTContext *ast_context, void *clang_type)
2214{
2215    if (clang_type)
2216        return ast_context->getTypeAlign(QualType::getFromOpaquePtr(clang_type));
2217    return 0;
2218}
2219
2220bool
2221ClangASTContext::IsIntegerType (void * clang_type, bool &is_signed)
2222{
2223    if (!clang_type)
2224        return false;
2225
2226    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2227    const BuiltinType *builtin_type = dyn_cast<BuiltinType>(qual_type->getCanonicalTypeInternal());
2228
2229    if (builtin_type)
2230    {
2231        if (builtin_type->isInteger())
2232            is_signed = builtin_type->isSignedInteger();
2233
2234        return true;
2235    }
2236
2237    return false;
2238}
2239
2240bool
2241ClangASTContext::IsPointerType (void *clang_type, void **target_type)
2242{
2243    if (clang_type)
2244    {
2245        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2246        switch (qual_type->getTypeClass())
2247        {
2248        case Type::ObjCObjectPointer:
2249            if (target_type)
2250                *target_type = cast<ObjCObjectPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
2251            return true;
2252        case Type::BlockPointer:
2253            if (target_type)
2254                *target_type = cast<BlockPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
2255            return true;
2256        case Type::Pointer:
2257            if (target_type)
2258                *target_type = cast<PointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
2259            return true;
2260        case Type::MemberPointer:
2261            if (target_type)
2262                *target_type = cast<MemberPointerType>(qual_type)->getPointeeType().getAsOpaquePtr();
2263            return true;
2264        case Type::Typedef:
2265            return ClangASTContext::IsPointerOrReferenceType (cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr(), target_type);
2266        default:
2267            break;
2268        }
2269    }
2270    return false;
2271}
2272
2273bool
2274ClangASTContext::IsFloatingPointType (void *clang_type, uint32_t &count, bool &is_complex)
2275{
2276    if (clang_type)
2277    {
2278        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2279
2280        if (const BuiltinType *BT = dyn_cast<BuiltinType>(qual_type->getCanonicalTypeInternal()))
2281        {
2282            clang::BuiltinType::Kind kind = BT->getKind();
2283            if (kind >= BuiltinType::Float && kind <= BuiltinType::LongDouble)
2284            {
2285                count = 1;
2286                is_complex = false;
2287                return true;
2288            }
2289        }
2290        else if (const ComplexType *CT = dyn_cast<ComplexType>(qual_type->getCanonicalTypeInternal()))
2291        {
2292            if (IsFloatingPointType(CT->getElementType().getAsOpaquePtr(), count, is_complex))
2293            {
2294                count = 2;
2295                is_complex = true;
2296                return true;
2297            }
2298        }
2299        else if (const VectorType *VT = dyn_cast<VectorType>(qual_type->getCanonicalTypeInternal()))
2300        {
2301            if (IsFloatingPointType(VT->getElementType().getAsOpaquePtr(), count, is_complex))
2302            {
2303                count = VT->getNumElements();
2304                is_complex = false;
2305                return true;
2306            }
2307        }
2308    }
2309    return false;
2310}
2311
2312
2313bool
2314ClangASTContext::IsCStringType (void *clang_type, uint32_t &length)
2315{
2316    if (clang_type)
2317    {
2318        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2319        switch (qual_type->getTypeClass())
2320        {
2321        case Type::ConstantArray:
2322            {
2323                ConstantArrayType *array = cast<ConstantArrayType>(qual_type.getTypePtr());
2324                QualType element_qual_type = array->getElementType();
2325                Type *canonical_type = element_qual_type->getCanonicalTypeInternal().getTypePtr();
2326                if (canonical_type && canonical_type->isCharType())
2327                {
2328                    // We know the size of the array and it could be a C string
2329                    // since it is an array of characters
2330                    length = array->getSize().getLimitedValue();
2331                    return true;
2332                }
2333            }
2334            break;
2335
2336        case Type::Pointer:
2337            {
2338                PointerType *pointer_type = cast<PointerType>(qual_type.getTypePtr());
2339                Type *pointee_type_ptr = pointer_type->getPointeeType().getTypePtr();
2340                if (pointee_type_ptr)
2341                {
2342                    Type *canonical_type_ptr = pointee_type_ptr->getCanonicalTypeInternal().getTypePtr();
2343                    length = 0; // No length info, read until a NULL terminator is received
2344                    if (canonical_type_ptr)
2345                        return canonical_type_ptr->isCharType();
2346                    else
2347                        return pointee_type_ptr->isCharType();
2348                }
2349            }
2350            break;
2351
2352        case Type::Typedef:
2353            return ClangASTContext::IsCStringType (cast<TypedefType>(qual_type)->LookThroughTypedefs().getAsOpaquePtr(), length);
2354
2355        case Type::LValueReference:
2356        case Type::RValueReference:
2357            {
2358                ReferenceType *reference_type = cast<ReferenceType>(qual_type.getTypePtr());
2359                Type *pointee_type_ptr = reference_type->getPointeeType().getTypePtr();
2360                if (pointee_type_ptr)
2361                {
2362                    Type *canonical_type_ptr = pointee_type_ptr->getCanonicalTypeInternal().getTypePtr();
2363                    length = 0; // No length info, read until a NULL terminator is received
2364                    if (canonical_type_ptr)
2365                        return canonical_type_ptr->isCharType();
2366                    else
2367                        return pointee_type_ptr->isCharType();
2368                }
2369            }
2370            break;
2371        }
2372    }
2373    return false;
2374}
2375
2376bool
2377ClangASTContext::IsArrayType (void * clang_type, void **member_type, uint64_t *size)
2378{
2379    if (!clang_type)
2380        return false;
2381
2382    QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2383
2384    switch (qual_type->getTypeClass())
2385    {
2386    case Type::ConstantArray:
2387        if (member_type)
2388            *member_type = cast<ConstantArrayType>(qual_type)->getElementType().getAsOpaquePtr();
2389        if (size)
2390            *size = cast<ConstantArrayType>(qual_type)->getSize().getLimitedValue(ULONG_LONG_MAX);
2391        return true;
2392    case Type::IncompleteArray:
2393        if (member_type)
2394            *member_type = cast<IncompleteArrayType>(qual_type)->getElementType().getAsOpaquePtr();
2395        if (size)
2396            *size = 0;
2397        return true;
2398    case Type::VariableArray:
2399        if (member_type)
2400            *member_type = cast<VariableArrayType>(qual_type)->getElementType().getAsOpaquePtr();
2401        if (size)
2402            *size = 0;
2403    case Type::DependentSizedArray:
2404        if (member_type)
2405            *member_type = cast<DependentSizedArrayType>(qual_type)->getElementType().getAsOpaquePtr();
2406        if (size)
2407            *size = 0;
2408        return true;
2409    }
2410    return false;
2411}
2412
2413
2414#pragma mark Typedefs
2415
2416void *
2417ClangASTContext::CreateTypedefType (const char *name, void *clang_type, DeclContext *decl_ctx)
2418{
2419    if (clang_type)
2420    {
2421        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2422        ASTContext *ast_context = getASTContext();
2423        IdentifierTable *identifier_table = getIdentifierTable();
2424        assert (ast_context != NULL);
2425        assert (identifier_table != NULL);
2426        if (decl_ctx == NULL)
2427            decl_ctx = ast_context->getTranslationUnitDecl();
2428        TypedefDecl *decl = TypedefDecl::Create(*ast_context,
2429                                                decl_ctx,
2430                                                SourceLocation(),
2431                                                name ? &identifier_table->get(name) : NULL, // Identifier
2432                                                ast_context->CreateTypeSourceInfo(qual_type));
2433
2434        // Get a uniqued QualType for the typedef decl type
2435        return ast_context->getTypedefType (decl).getAsOpaquePtr();
2436    }
2437    return NULL;
2438}
2439
2440
2441std::string
2442ClangASTContext::GetTypeName (void *opaque_qual_type)
2443{
2444    std::string return_name;
2445
2446    clang::QualType qual_type(clang::QualType::getFromOpaquePtr(opaque_qual_type));
2447
2448    const clang::TypedefType *typedef_type = qual_type->getAs<clang::TypedefType>();
2449    if (typedef_type)
2450    {
2451        const clang::TypedefDecl *typedef_decl = typedef_type->getDecl();
2452        return_name = typedef_decl->getQualifiedNameAsString();
2453    }
2454    else
2455    {
2456        return_name = qual_type.getAsString();
2457    }
2458
2459    return return_name;
2460}
2461
2462// Disable this for now since I can't seem to get a nicely formatted float
2463// out of the APFloat class without just getting the float, double or quad
2464// and then using a formatted print on it which defeats the purpose. We ideally
2465// would like to get perfect string values for any kind of float semantics
2466// so we can support remote targets. The code below also requires a patch to
2467// llvm::APInt.
2468//bool
2469//ClangASTContext::ConvertFloatValueToString (ASTContext *ast_context, void *clang_type, const uint8_t* bytes, size_t byte_size, int apint_byte_order, std::string &float_str)
2470//{
2471//  uint32_t count = 0;
2472//  bool is_complex = false;
2473//  if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
2474//  {
2475//      unsigned num_bytes_per_float = byte_size / count;
2476//      unsigned num_bits_per_float = num_bytes_per_float * 8;
2477//
2478//      float_str.clear();
2479//      uint32_t i;
2480//      for (i=0; i<count; i++)
2481//      {
2482//          APInt ap_int(num_bits_per_float, bytes + i * num_bytes_per_float, (APInt::ByteOrder)apint_byte_order);
2483//          bool is_ieee = false;
2484//          APFloat ap_float(ap_int, is_ieee);
2485//          char s[1024];
2486//          unsigned int hex_digits = 0;
2487//          bool upper_case = false;
2488//
2489//          if (ap_float.convertToHexString(s, hex_digits, upper_case, APFloat::rmNearestTiesToEven) > 0)
2490//          {
2491//              if (i > 0)
2492//                  float_str.append(", ");
2493//              float_str.append(s);
2494//              if (i == 1 && is_complex)
2495//                  float_str.append(1, 'i');
2496//          }
2497//      }
2498//      return !float_str.empty();
2499//  }
2500//  return false;
2501//}
2502
2503size_t
2504ClangASTContext::ConvertStringToFloatValue (ASTContext *ast_context, void *clang_type, const char *s, uint8_t *dst, size_t dst_size)
2505{
2506    if (clang_type)
2507    {
2508        QualType qual_type (QualType::getFromOpaquePtr(clang_type));
2509        uint32_t count = 0;
2510        bool is_complex = false;
2511        if (ClangASTContext::IsFloatingPointType (clang_type, count, is_complex))
2512        {
2513            // TODO: handle complex and vector types
2514            if (count != 1)
2515                return false;
2516
2517            StringRef s_sref(s);
2518            APFloat ap_float(ast_context->getFloatTypeSemantics(qual_type), s_sref);
2519
2520            const uint64_t bit_size = ast_context->getTypeSize (qual_type);
2521            const uint64_t byte_size = bit_size / 8;
2522            if (dst_size >= byte_size)
2523            {
2524                if (bit_size == sizeof(float)*8)
2525                {
2526                    float float32 = ap_float.convertToFloat();
2527                    ::memcpy (dst, &float32, byte_size);
2528                    return byte_size;
2529                }
2530                else if (bit_size >= 64)
2531                {
2532                    llvm::APInt ap_int(ap_float.bitcastToAPInt());
2533                    ::memcpy (dst, ap_int.getRawData(), byte_size);
2534                    return byte_size;
2535                }
2536            }
2537        }
2538    }
2539    return 0;
2540}
2541