DWARFASTParserClang.cpp revision 321369
12088Ssos//===-- DWARFASTParserClang.cpp ---------------------------------*- C++ -*-===//
25536Ssos//
32088Ssos//                     The LLVM Compiler Infrastructure
42088Ssos//
52088Ssos// This file is distributed under the University of Illinois Open Source
62088Ssos// License. See LICENSE.TXT for details.
72088Ssos//
82088Ssos//===----------------------------------------------------------------------===//
95994Ssos
105994Ssos#include <stdlib.h>
112088Ssos
122088Ssos#include "DWARFASTParserClang.h"
132088Ssos#include "DWARFCompileUnit.h"
142088Ssos#include "DWARFDIE.h"
1597748Sschweikh#include "DWARFDIECollection.h"
162088Ssos#include "DWARFDebugInfo.h"
172088Ssos#include "DWARFDeclContext.h"
182088Ssos#include "DWARFDefines.h"
192088Ssos#include "SymbolFileDWARF.h"
202088Ssos#include "SymbolFileDWARFDebugMap.h"
212088Ssos#include "UniqueDWARFASTType.h"
222088Ssos
232088Ssos#include "Plugins/Language/ObjC/ObjCLanguage.h"
242088Ssos#include "lldb/Core/Module.h"
252088Ssos#include "lldb/Core/Value.h"
262088Ssos#include "lldb/Host/Host.h"
272088Ssos#include "lldb/Interpreter/Args.h"
282088Ssos#include "lldb/Symbol/ClangASTImporter.h"
29114601Sobrien#include "lldb/Symbol/ClangExternalASTSourceCommon.h"
30114601Sobrien#include "lldb/Symbol/ClangUtil.h"
3129603Scharnier#include "lldb/Symbol/CompileUnit.h"
322088Ssos#include "lldb/Symbol/Function.h"
3329603Scharnier#include "lldb/Symbol/ObjectFile.h"
342088Ssos#include "lldb/Symbol/SymbolVendor.h"
3529603Scharnier#include "lldb/Symbol/TypeList.h"
363864Sswallace#include "lldb/Symbol/TypeMap.h"
3729603Scharnier#include "lldb/Target/Language.h"
3842505Syokota#include "lldb/Utility/LLDBAssert.h"
3966834Sphk#include "lldb/Utility/Log.h"
4066834Sphk#include "lldb/Utility/StreamString.h"
412088Ssos
422088Ssos#include "clang/AST/DeclCXX.h"
432088Ssos#include "clang/AST/DeclObjC.h"
4476643Simp
4590394Sru#include <map>
4690394Sru#include <vector>
4776643Simp
4890394Sru//#define ENABLE_DEBUG_PRINTF // COMMENT OUT THIS LINE PRIOR TO CHECKIN
4990394Sru
5090394Sru#ifdef ENABLE_DEBUG_PRINTF
5190394Sru#include <stdio.h>
5290394Sru#define DEBUG_PRINTF(fmt, ...) printf(fmt, __VA_ARGS__)
5390394Sru#else
5476643Simp#define DEBUG_PRINTF(fmt, ...)
5576643Simp#endif
5676643Simp
5776643Simpusing namespace lldb;
58196500Sedusing namespace lldb_private;
59196500SedDWARFASTParserClang::DWARFASTParserClang(ClangASTContext &ast)
602088Ssos    : m_ast(ast), m_die_to_decl_ctx(), m_decl_ctx_to_die() {}
618857Srgrimes
622088SsosDWARFASTParserClang::~DWARFASTParserClang() {}
632088Ssos
6438139Syokotastatic AccessType DW_ACCESS_to_AccessType(uint32_t dwarf_accessibility) {
652088Ssos  switch (dwarf_accessibility) {
662088Ssos  case DW_ACCESS_public:
6732316Syokota    return eAccessPublic;
6832316Syokota  case DW_ACCESS_private:
6932316Syokota    return eAccessPrivate;
7032316Syokota  case DW_ACCESS_protected:
7132316Syokota    return eAccessProtected;
7232316Syokota  default:
7332316Syokota    break;
7432316Syokota  }
7532316Syokota  return eAccessNone;
7632316Syokota}
7732316Syokota
7832316Syokotastatic bool DeclKindIsCXXClass(clang::Decl::Kind decl_kind) {
795994Ssos  switch (decl_kind) {
805994Ssos  case clang::Decl::CXXRecord:
815994Ssos  case clang::Decl::ClassTemplateSpecialization:
825994Ssos    return true;
835994Ssos  default:
845994Ssos    break;
855994Ssos  }
865994Ssos  return false;
875994Ssos}
885994Ssos
895994Ssosstruct BitfieldInfo {
905994Ssos  uint64_t bit_size;
919202Srgrimes  uint64_t bit_offset;
925994Ssos
935994Ssos  BitfieldInfo()
945994Ssos      : bit_size(LLDB_INVALID_ADDRESS), bit_offset(LLDB_INVALID_ADDRESS) {}
959202Srgrimes
965994Ssos  void Clear() {
975994Ssos    bit_size = LLDB_INVALID_ADDRESS;
985994Ssos    bit_offset = LLDB_INVALID_ADDRESS;
995994Ssos  }
1005994Ssos
1015994Ssos  bool IsValid() const {
1025994Ssos    return (bit_size != LLDB_INVALID_ADDRESS) &&
1035994Ssos           (bit_offset != LLDB_INVALID_ADDRESS);
1042088Ssos  }
1052088Ssos
10646761Syokota  bool NextBitfieldOffsetIsValid(const uint64_t next_bit_offset) const {
10746761Syokota    if (IsValid()) {
10846761Syokota      // This bitfield info is valid, so any subsequent bitfields
10946761Syokota      // must not overlap and must be at a higher bit offset than
11046761Syokota      // any previous bitfield + size.
11146761Syokota      return (bit_size + bit_offset) <= next_bit_offset;
11246761Syokota    } else {
1132088Ssos      // If the this BitfieldInfo is not valid, then any offset isOK
1146046Ssos      return true;
1152088Ssos    }
11632316Syokota  }
1172088Ssos};
11899816Salfred
11999816SalfredClangASTImporter &DWARFASTParserClang::GetClangASTImporter() {
12099816Salfred  if (!m_clang_ast_importer_ap) {
12199814Salfred    m_clang_ast_importer_ap.reset(new ClangASTImporter);
12299816Salfred  }
12399814Salfred  return *m_clang_ast_importer_ap;
12499816Salfred}
12599816Salfred
12699816SalfredTypeSP DWARFASTParserClang::ParseTypeFromDWO(const DWARFDIE &die, Log *log) {
12799816Salfred  ModuleSP dwo_module_sp = die.GetContainingDWOModule();
12899816Salfred  if (dwo_module_sp) {
12999816Salfred    // This type comes from an external DWO module
13099816Salfred    std::vector<CompilerContext> dwo_context;
13199816Salfred    die.GetDWOContext(dwo_context);
13299816Salfred    TypeMap dwo_types;
13399816Salfred    if (dwo_module_sp->GetSymbolVendor()->FindTypes(dwo_context, true,
13499816Salfred                                                    dwo_types)) {
135162327Semax      const size_t num_dwo_types = dwo_types.GetSize();
13699816Salfred      if (num_dwo_types == 1) {
13799816Salfred        // We found a real definition for this type elsewhere
13899816Salfred        // so lets use it and cache the fact that we found
13999816Salfred        // a complete type for this die
14099816Salfred        TypeSP dwo_type_sp = dwo_types.GetTypeAtIndex(0);
14199816Salfred        if (dwo_type_sp) {
1422088Ssos          lldb_private::CompilerType dwo_type =
1432088Ssos              dwo_type_sp->GetForwardCompilerType();
1442088Ssos
1452088Ssos          lldb_private::CompilerType type =
1462088Ssos              GetClangASTImporter().CopyType(m_ast, dwo_type);
1472088Ssos
14829603Scharnier          // printf ("copied_qual_type: ast = %p, clang_type = %p, name =
1492088Ssos          // '%s'\n", m_ast, copied_qual_type.getAsOpaquePtr(),
1502088Ssos          // external_type->GetName().GetCString());
1512088Ssos          if (type) {
1522088Ssos            SymbolFileDWARF *dwarf = die.GetDWARF();
1532088Ssos            TypeSP type_sp(new Type(die.GetID(), dwarf, dwo_type_sp->GetName(),
1542088Ssos                                    dwo_type_sp->GetByteSize(), NULL,
1552088Ssos                                    LLDB_INVALID_UID, Type::eEncodingInvalid,
1565536Ssos                                    &dwo_type_sp->GetDeclaration(), type,
1575536Ssos                                    Type::eResolveStateForward));
1585536Ssos
1592088Ssos            dwarf->GetTypeList()->Insert(type_sp);
1602088Ssos            dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
16177394Ssobomax            clang::TagDecl *tag_decl = ClangASTContext::GetAsTagDecl(type);
1622088Ssos            if (tag_decl)
1632088Ssos              LinkDeclContextToDIE(tag_decl, die);
1642088Ssos            else {
1652088Ssos              clang::DeclContext *defn_decl_ctx =
16677394Ssobomax                  GetCachedClangDeclContextForDIE(die);
1672088Ssos              if (defn_decl_ctx)
1682088Ssos                LinkDeclContextToDIE(defn_decl_ctx, die);
1692088Ssos            }
1702088Ssos            return type_sp;
1712088Ssos          }
1722088Ssos        }
1732088Ssos      }
1742088Ssos    }
1752088Ssos  }
1762088Ssos  return TypeSP();
1772088Ssos}
1782088Ssos
1792088SsosTypeSP DWARFASTParserClang::ParseTypeFromDWARF(const SymbolContext &sc,
1802088Ssos                                               const DWARFDIE &die, Log *log,
18199816Salfred                                               bool *type_is_new_ptr) {
1822088Ssos  TypeSP type_sp;
18332316Syokota
1842088Ssos  if (type_is_new_ptr)
185196500Sed    *type_is_new_ptr = false;
1862088Ssos
187196500Sed  AccessType accessibility = eAccessNone;
1882088Ssos  if (die) {
189196500Sed    SymbolFileDWARF *dwarf = die.GetDWARF();
1902088Ssos    if (log) {
191196500Sed      DWARFDIE context_die;
1922088Ssos      clang::DeclContext *context =
193196500Sed          GetClangDeclContextContainingDIE(die, &context_die);
1942088Ssos
195196500Sed      dwarf->GetObjectFile()->GetModule()->LogMessage(
1962088Ssos          log, "SymbolFileDWARF::ParseType (die = 0x%8.8x, decl_ctx = %p (die "
197196500Sed               "0x%8.8x)) %s name = '%s')",
1982088Ssos          die.GetOffset(), static_cast<void *>(context),
199196500Sed          context_die.GetOffset(), die.GetTagAsCString(), die.GetName());
2002088Ssos    }
201196500Sed    //
2022088Ssos    //        Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
203196500Sed    //        if (log && dwarf_cu)
20448105Syokota    //        {
205196500Sed    //            StreamString s;
2062088Ssos    //            die->DumpLocation (this, dwarf_cu, s);
207196500Sed    //            dwarf->GetObjectFile()->GetModule()->LogMessage (log,
2082088Ssos    //            "SymbolFileDwarf::%s %s", __FUNCTION__, s.GetData());
209196500Sed    //
2102088Ssos    //        }
211196500Sed
2122088Ssos    Type *type_ptr = dwarf->GetDIEToType().lookup(die.GetDIE());
213196500Sed    TypeList *type_list = dwarf->GetTypeList();
2142088Ssos    if (type_ptr == NULL) {
215196500Sed      if (type_is_new_ptr)
2162088Ssos        *type_is_new_ptr = true;
217196500Sed
2182088Ssos      const dw_tag_t tag = die.Tag();
219196500Sed
2205994Ssos      bool is_forward_declaration = false;
221196500Sed      DWARFAttributes attributes;
22238053Syokota      const char *type_name_cstr = NULL;
223196500Sed      ConstString type_name_const_str;
22454380Syokota      Type::ResolveState resolve_state = Type::eResolveStateUnresolved;
225196500Sed      uint64_t byte_size = 0;
22654380Syokota      Declaration decl;
227196500Sed
22854380Syokota      Type::EncodingDataType encoding_data_type = Type::eEncodingIsUID;
229196500Sed      CompilerType clang_type;
23054380Syokota      DWARFFormValue form_value;
231196500Sed
23254380Syokota      dw_attr_t attr;
233196500Sed
23454380Syokota      switch (tag) {
235196500Sed      case DW_TAG_typedef:
23654380Syokota      case DW_TAG_base_type:
237196500Sed      case DW_TAG_pointer_type:
23865759Sdwmalone      case DW_TAG_reference_type:
239196500Sed      case DW_TAG_rvalue_reference_type:
24065759Sdwmalone      case DW_TAG_const_type:
241196500Sed      case DW_TAG_restrict_type:
24274118Sache      case DW_TAG_volatile_type:
243196500Sed      case DW_TAG_unspecified_type: {
24432316Syokota        // Set a bit that lets us know that we are currently parsing this
24532316Syokota        dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED;
24632316Syokota
247196500Sed        const size_t num_attributes = die.GetAttributes(attributes);
2482088Ssos        uint32_t encoding = 0;
2492088Ssos        DWARFFormValue encoding_uid;
2502088Ssos
251196500Sed        if (num_attributes > 0) {
2522088Ssos          uint32_t i;
2532088Ssos          for (i = 0; i < num_attributes; ++i) {
2542088Ssos            attr = attributes.AttributeAtIndex(i);
255196500Sed            if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2562088Ssos              switch (attr) {
2572088Ssos              case DW_AT_decl_file:
2582088Ssos                decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
259197330Sed                    form_value.Unsigned()));
2602088Ssos                break;
2612088Ssos              case DW_AT_decl_line:
2622088Ssos                decl.SetLine(form_value.Unsigned());
2632088Ssos                break;
2642088Ssos              case DW_AT_decl_column:
2652088Ssos                decl.SetColumn(form_value.Unsigned());
2662088Ssos                break;
26777394Ssobomax              case DW_AT_name:
26832316Syokota
2692088Ssos                type_name_cstr = form_value.AsCString();
27032316Syokota                // Work around a bug in llvm-gcc where they give a name to a
2712088Ssos                // reference type which doesn't
2722088Ssos                // include the "&"...
2732088Ssos                if (tag == DW_TAG_reference_type) {
27432316Syokota                  if (strchr(type_name_cstr, '&') == NULL)
27532316Syokota                    type_name_cstr = NULL;
27632316Syokota                }
27732316Syokota                if (type_name_cstr)
27832316Syokota                  type_name_const_str.SetCString(type_name_cstr);
27932316Syokota                break;
28032316Syokota              case DW_AT_byte_size:
28132316Syokota                byte_size = form_value.Unsigned();
28232316Syokota                break;
28332316Syokota              case DW_AT_encoding:
28432316Syokota                encoding = form_value.Unsigned();
28532316Syokota                break;
28632316Syokota              case DW_AT_type:
28732316Syokota                encoding_uid = form_value;
28832316Syokota                break;
28932316Syokota              default:
29032316Syokota              case DW_AT_sibling:
29132316Syokota                break;
29232316Syokota              }
2932088Ssos            }
29432316Syokota          }
29532316Syokota        }
29632316Syokota
29732316Syokota        if (tag == DW_TAG_typedef && encoding_uid.IsValid()) {
29832316Syokota          // Try to parse a typedef from the DWO file first as modules
29932316Syokota          // can contain typedef'ed structures that have no names like:
30032316Syokota          //
30132316Syokota          //  typedef struct { int a; } Foo;
30232316Syokota          //
30332316Syokota          // In this case we will have a structure with no name and a
30432316Syokota          // typedef named "Foo" that points to this unnamed structure.
30532316Syokota          // The name in the typedef is the only identifier for the struct,
3062088Ssos          // so always try to get typedefs from DWO files if possible.
3072088Ssos          //
3082088Ssos          // The type_sp returned will be empty if the typedef doesn't exist
3092088Ssos          // in a DWO file, so it is cheap to call this function just to check.
3102088Ssos          //
3112088Ssos          // If we don't do this we end up creating a TypeSP that says this
3122088Ssos          // is a typedef to type 0x123 (the DW_AT_type value would be 0x123
3132088Ssos          // in the DW_TAG_typedef), and this is the unnamed structure type.
3142088Ssos          // We will have a hard time tracking down an unnammed structure
315196500Sed          // type in the module DWO file, so we make sure we don't get into
3162088Ssos          // this situation by always resolving typedefs from the DWO file.
317196500Sed          const DWARFDIE encoding_die = dwarf->GetDIE(DIERef(encoding_uid));
3182088Ssos
3192088Ssos          // First make sure that the die that this is typedef'ed to _is_
32032316Syokota          // just a declaration (DW_AT_declaration == 1), not a full definition
3212088Ssos          // since template types can't be represented in modules since only
3222088Ssos          // concrete instances of templates are ever emitted and modules
32332316Syokota          // won't contain those
32432316Syokota          if (encoding_die &&
3252088Ssos              encoding_die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0) ==
3262088Ssos                  1) {
32732316Syokota            type_sp = ParseTypeFromDWO(die, log);
32832316Syokota            if (type_sp)
32932316Syokota              return type_sp;
33032316Syokota          }
33132316Syokota        }
33232316Syokota
3332088Ssos        DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\") type => 0x%8.8lx\n",
33432316Syokota                     die.GetID(), DW_TAG_value_to_name(tag), type_name_cstr,
33532316Syokota                     encoding_uid.Reference());
33632316Syokota
33732316Syokota        switch (tag) {
33832316Syokota        default:
33932316Syokota          break;
34032316Syokota
34132316Syokota        case DW_TAG_unspecified_type:
34232316Syokota          if (strcmp(type_name_cstr, "nullptr_t") == 0 ||
34332316Syokota              strcmp(type_name_cstr, "decltype(nullptr)") == 0) {
34432316Syokota            resolve_state = Type::eResolveStateFull;
34532316Syokota            clang_type = m_ast.GetBasicType(eBasicTypeNullPtr);
34632316Syokota            break;
34732316Syokota          }
34832316Syokota          // Fall through to base type below in case we can handle the type
34932316Syokota          // there...
35032316Syokota          LLVM_FALLTHROUGH;
35132316Syokota
35232316Syokota        case DW_TAG_base_type:
35332316Syokota          resolve_state = Type::eResolveStateFull;
35432316Syokota          clang_type = m_ast.GetBuiltinTypeForDWARFEncodingAndBitSize(
35532316Syokota              type_name_cstr, encoding, byte_size * 8);
35632316Syokota          break;
35732316Syokota
35832316Syokota        case DW_TAG_pointer_type:
35932316Syokota          encoding_data_type = Type::eEncodingIsPointerUID;
36032316Syokota          break;
36132316Syokota        case DW_TAG_reference_type:
36232316Syokota          encoding_data_type = Type::eEncodingIsLValueReferenceUID;
36332316Syokota          break;
36432316Syokota        case DW_TAG_rvalue_reference_type:
36532316Syokota          encoding_data_type = Type::eEncodingIsRValueReferenceUID;
36632316Syokota          break;
36732316Syokota        case DW_TAG_typedef:
36832316Syokota          encoding_data_type = Type::eEncodingIsTypedefUID;
36932316Syokota          break;
37032316Syokota        case DW_TAG_const_type:
37132316Syokota          encoding_data_type = Type::eEncodingIsConstUID;
37232316Syokota          break;
37332316Syokota        case DW_TAG_restrict_type:
37432316Syokota          encoding_data_type = Type::eEncodingIsRestrictUID;
37532316Syokota          break;
37632316Syokota        case DW_TAG_volatile_type:
37732316Syokota          encoding_data_type = Type::eEncodingIsVolatileUID;
37832316Syokota          break;
37932316Syokota        }
38032316Syokota
38132316Syokota        if (!clang_type &&
38232316Syokota            (encoding_data_type == Type::eEncodingIsPointerUID ||
38332316Syokota             encoding_data_type == Type::eEncodingIsTypedefUID) &&
38432316Syokota            sc.comp_unit != NULL) {
38532316Syokota          if (tag == DW_TAG_pointer_type) {
38632316Syokota            DWARFDIE target_die = die.GetReferencedDIE(DW_AT_type);
38732316Syokota
38829603Scharnier            if (target_die.GetAttributeValueAsUnsigned(DW_AT_APPLE_block, 0)) {
3892088Ssos              // Blocks have a __FuncPtr inside them which is a pointer to a
3902088Ssos              // function of the proper type.
391196500Sed
3922088Ssos              for (DWARFDIE child_die = target_die.GetFirstChild();
3932088Ssos                   child_die.IsValid(); child_die = child_die.GetSibling()) {
394196500Sed                if (!strcmp(child_die.GetAttributeValueAsString(DW_AT_name, ""),
3958857Srgrimes                            "__FuncPtr")) {
3962088Ssos                  DWARFDIE function_pointer_type =
397196500Sed                      child_die.GetReferencedDIE(DW_AT_type);
3982088Ssos
3992088Ssos                  if (function_pointer_type) {
400196500Sed                    DWARFDIE function_type =
4012088Ssos                        function_pointer_type.GetReferencedDIE(DW_AT_type);
4022088Ssos
403196500Sed                    bool function_type_is_new_pointer;
4042088Ssos                    TypeSP lldb_function_type_sp = ParseTypeFromDWARF(
4052088Ssos                        sc, function_type, log, &function_type_is_new_pointer);
406196500Sed
4072088Ssos                    if (lldb_function_type_sp) {
4082088Ssos                      clang_type = m_ast.CreateBlockPointerType(
409196500Sed                          lldb_function_type_sp->GetForwardCompilerType());
4102088Ssos                      encoding_data_type = Type::eEncodingIsUID;
4112088Ssos                      encoding_uid.Clear();
412196500Sed                      resolve_state = Type::eResolveStateFull;
4132088Ssos                    }
4142088Ssos                  }
415196500Sed
4162088Ssos                  break;
4172088Ssos                }
418196500Sed              }
4192088Ssos            }
4202088Ssos          }
421196500Sed
4222088Ssos          bool translation_unit_is_objc =
4232088Ssos              (sc.comp_unit->GetLanguage() == eLanguageTypeObjC ||
424196500Sed               sc.comp_unit->GetLanguage() == eLanguageTypeObjC_plus_plus);
42548105Syokota
42648105Syokota          if (translation_unit_is_objc) {
427196500Sed            if (type_name_cstr != NULL) {
4282088Ssos              static ConstString g_objc_type_name_id("id");
4292088Ssos              static ConstString g_objc_type_name_Class("Class");
430196500Sed              static ConstString g_objc_type_name_selector("SEL");
4312088Ssos
4322088Ssos              if (type_name_const_str == g_objc_type_name_id) {
433196500Sed                if (log)
4342088Ssos                  dwarf->GetObjectFile()->GetModule()->LogMessage(
4352088Ssos                      log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' "
436196500Sed                           "is Objective C 'id' built-in type.",
4372088Ssos                      die.GetOffset(), die.GetTagAsCString(), die.GetName());
4382088Ssos                clang_type = m_ast.GetBasicType(eBasicTypeObjCID);
439196500Sed                encoding_data_type = Type::eEncodingIsUID;
4402088Ssos                encoding_uid.Clear();
4412088Ssos                resolve_state = Type::eResolveStateFull;
442196500Sed
4432088Ssos              } else if (type_name_const_str == g_objc_type_name_Class) {
4442088Ssos                if (log)
445196500Sed                  dwarf->GetObjectFile()->GetModule()->LogMessage(
4462088Ssos                      log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' "
4472088Ssos                           "is Objective C 'Class' built-in type.",
448196500Sed                      die.GetOffset(), die.GetTagAsCString(), die.GetName());
44932316Syokota                clang_type = m_ast.GetBasicType(eBasicTypeObjCClass);
45032316Syokota                encoding_data_type = Type::eEncodingIsUID;
451196500Sed                encoding_uid.Clear();
45238053Syokota                resolve_state = Type::eResolveStateFull;
45338053Syokota              } else if (type_name_const_str == g_objc_type_name_selector) {
454196500Sed                if (log)
45554380Syokota                  dwarf->GetObjectFile()->GetModule()->LogMessage(
45654380Syokota                      log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' "
457196500Sed                           "is Objective C 'selector' built-in type.",
45854380Syokota                      die.GetOffset(), die.GetTagAsCString(), die.GetName());
45954380Syokota                clang_type = m_ast.GetBasicType(eBasicTypeObjCSel);
460196500Sed                encoding_data_type = Type::eEncodingIsUID;
46154380Syokota                encoding_uid.Clear();
46254380Syokota                resolve_state = Type::eResolveStateFull;
463196500Sed              }
46454380Syokota            } else if (encoding_data_type == Type::eEncodingIsPointerUID &&
46554380Syokota                       encoding_uid.IsValid()) {
466196500Sed              // Clang sometimes erroneously emits id as objc_object*.  In that
46754380Syokota              // case we fix up the type to "id".
46854380Syokota
469196500Sed              const DWARFDIE encoding_die = dwarf->GetDIE(DIERef(encoding_uid));
47054380Syokota
47154380Syokota              if (encoding_die && encoding_die.Tag() == DW_TAG_structure_type) {
472196500Sed                if (const char *struct_name = encoding_die.GetName()) {
47354380Syokota                  if (!strcmp(struct_name, "objc_object")) {
47454380Syokota                    if (log)
475196500Sed                      dwarf->GetObjectFile()->GetModule()->LogMessage(
47665759Sdwmalone                          log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s "
47765759Sdwmalone                               "'%s' is 'objc_object*', which we overrode to "
478196500Sed                               "'id'.",
47965759Sdwmalone                          die.GetOffset(), die.GetTagAsCString(),
48065759Sdwmalone                          die.GetName());
481196500Sed                    clang_type = m_ast.GetBasicType(eBasicTypeObjCID);
48274118Sache                    encoding_data_type = Type::eEncodingIsUID;
48374118Sache                    encoding_uid.Clear();
4842088Ssos                    resolve_state = Type::eResolveStateFull;
485196500Sed                  }
4868857Srgrimes                }
4872088Ssos              }
4888857Srgrimes            }
4892088Ssos          }
49032316Syokota        }
49132316Syokota
4922088Ssos        type_sp.reset(
4938857Srgrimes            new Type(die.GetID(), dwarf, type_name_const_str, byte_size, NULL,
4942088Ssos                     DIERef(encoding_uid).GetUID(dwarf), encoding_data_type,
49532316Syokota                     &decl, clang_type, resolve_state));
4962088Ssos
4972088Ssos        dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
4982088Ssos
4998857Srgrimes        //                  Type* encoding_type =
5002088Ssos        //                  GetUniquedTypeForDIEOffset(encoding_uid, type_sp,
5018857Srgrimes        //                  NULL, 0, 0, false);
5029202Srgrimes        //                  if (encoding_type != NULL)
5038857Srgrimes        //                  {
5042088Ssos        //                      if (encoding_type != DIE_IS_BEING_PARSED)
5058857Srgrimes        //                          type_sp->SetEncodingType(encoding_type);
5062088Ssos        //                      else
5078857Srgrimes        //                          m_indirect_fixups.push_back(type_sp.get());
5082088Ssos        //                  }
5092088Ssos      } break;
5102088Ssos
5112088Ssos      case DW_TAG_structure_type:
5122088Ssos      case DW_TAG_union_type:
51342505Syokota      case DW_TAG_class_type: {
5142088Ssos        // Set a bit that lets us know that we are currently parsing this
51529603Scharnier        dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED;
5162088Ssos        bool byte_size_valid = false;
5172088Ssos
5182088Ssos        LanguageType class_language = eLanguageTypeUnknown;
5192088Ssos        bool is_complete_objc_class = false;
5202088Ssos        // bool struct_is_class = false;
5212088Ssos        const size_t num_attributes = die.GetAttributes(attributes);
5222088Ssos        if (num_attributes > 0) {
5232088Ssos          uint32_t i;
5242088Ssos          for (i = 0; i < num_attributes; ++i) {
5252088Ssos            attr = attributes.AttributeAtIndex(i);
526196500Sed            if (attributes.ExtractFormValueAtIndex(i, form_value)) {
5272088Ssos              switch (attr) {
5288857Srgrimes              case DW_AT_decl_file:
5292088Ssos                if (die.GetCU()->DW_AT_decl_file_attributes_are_invalid()) {
5302088Ssos                  // llvm-gcc outputs invalid DW_AT_decl_file attributes that
5312088Ssos                  // always
5322088Ssos                  // point to the compile unit file, so we clear this invalid
5332088Ssos                  // value
5342088Ssos                  // so that we can still unique types efficiently.
5352088Ssos                  decl.SetFile(FileSpec("<invalid>", false));
5362088Ssos                } else
5372088Ssos                  decl.SetFile(
5382088Ssos                      sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
5392088Ssos                          form_value.Unsigned()));
5402088Ssos                break;
5412088Ssos
5426046Ssos              case DW_AT_decl_line:
5436046Ssos                decl.SetLine(form_value.Unsigned());
5446046Ssos                break;
5458857Srgrimes
5462088Ssos              case DW_AT_decl_column:
5472088Ssos                decl.SetColumn(form_value.Unsigned());
54832316Syokota                break;
54932316Syokota
55032316Syokota              case DW_AT_name:
55132316Syokota                type_name_cstr = form_value.AsCString();
55232316Syokota                type_name_const_str.SetCString(type_name_cstr);
5532088Ssos                break;
55432316Syokota
55532316Syokota              case DW_AT_byte_size:
55632316Syokota                byte_size = form_value.Unsigned();
55732316Syokota                byte_size_valid = true;
55832316Syokota                break;
55932316Syokota
56032316Syokota              case DW_AT_accessibility:
56132316Syokota                accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
56232316Syokota                break;
56332316Syokota
56432316Syokota              case DW_AT_declaration:
56532316Syokota                is_forward_declaration = form_value.Boolean();
56632316Syokota                break;
56732316Syokota
56832316Syokota              case DW_AT_APPLE_runtime_class:
56932316Syokota                class_language = (LanguageType)form_value.Signed();
57032316Syokota                break;
57132316Syokota
57232316Syokota              case DW_AT_APPLE_objc_complete_type:
57332316Syokota                is_complete_objc_class = form_value.Signed();
57432316Syokota                break;
57532316Syokota
57632316Syokota              case DW_AT_allocated:
57732316Syokota              case DW_AT_associated:
57832316Syokota              case DW_AT_data_location:
57932316Syokota              case DW_AT_description:
58032316Syokota              case DW_AT_start_scope:
58132316Syokota              case DW_AT_visibility:
58232316Syokota              default:
58332316Syokota              case DW_AT_sibling:
58432316Syokota                break;
58532316Syokota              }
58632316Syokota            }
58732316Syokota          }
58832316Syokota        }
5892088Ssos
59032316Syokota        // UniqueDWARFASTType is large, so don't create a local variables on the
59132316Syokota        // stack, put it on the heap. This function is often called recursively
592196500Sed        // and clang isn't good and sharing the stack space for variables in
593196500Sed        // different blocks.
59432316Syokota        std::unique_ptr<UniqueDWARFASTType> unique_ast_entry_ap(
59532316Syokota            new UniqueDWARFASTType());
59632316Syokota
59732316Syokota        ConstString unique_typename(type_name_const_str);
59832316Syokota        Declaration unique_decl(decl);
59932316Syokota
60032316Syokota        if (type_name_const_str) {
60132316Syokota          LanguageType die_language = die.GetLanguage();
60232316Syokota          if (Language::LanguageIsCPlusPlus(die_language)) {
60332316Syokota            // For C++, we rely solely upon the one definition rule that says
60432316Syokota            // only
60532316Syokota            // one thing can exist at a given decl context. We ignore the file
60632316Syokota            // and
60732316Syokota            // line that things are declared on.
60832316Syokota            std::string qualified_name;
60932316Syokota            if (die.GetQualifiedName(qualified_name))
61032316Syokota              unique_typename = ConstString(qualified_name);
61132316Syokota            unique_decl.Clear();
61232316Syokota          }
61332316Syokota
61432316Syokota          if (dwarf->GetUniqueDWARFASTTypeMap().Find(
61532316Syokota                  unique_typename, die, unique_decl,
61632316Syokota                  byte_size_valid ? byte_size : -1, *unique_ast_entry_ap)) {
61732316Syokota            type_sp = unique_ast_entry_ap->m_type_sp;
61832316Syokota            if (type_sp) {
61932316Syokota              dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
62032316Syokota              return type_sp;
62132316Syokota            }
62232316Syokota          }
62332316Syokota        }
62432316Syokota
62548105Syokota        DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(),
62648105Syokota                     DW_TAG_value_to_name(tag), type_name_cstr);
62748105Syokota
62832316Syokota        int tag_decl_kind = -1;
62932316Syokota        AccessType default_accessibility = eAccessNone;
63032316Syokota        if (tag == DW_TAG_structure_type) {
63132316Syokota          tag_decl_kind = clang::TTK_Struct;
63232316Syokota          default_accessibility = eAccessPublic;
63332316Syokota        } else if (tag == DW_TAG_union_type) {
63432316Syokota          tag_decl_kind = clang::TTK_Union;
63532316Syokota          default_accessibility = eAccessPublic;
63632316Syokota        } else if (tag == DW_TAG_class_type) {
63732316Syokota          tag_decl_kind = clang::TTK_Class;
63832316Syokota          default_accessibility = eAccessPrivate;
63932316Syokota        }
64032316Syokota
64132316Syokota        if (byte_size_valid && byte_size == 0 && type_name_cstr &&
64232316Syokota            die.HasChildren() == false &&
64332316Syokota            sc.comp_unit->GetLanguage() == eLanguageTypeObjC) {
64432316Syokota          // Work around an issue with clang at the moment where
64532316Syokota          // forward declarations for objective C classes are emitted
64632316Syokota          // as:
64732316Syokota          //  DW_TAG_structure_type [2]
64832316Syokota          //  DW_AT_name( "ForwardObjcClass" )
64932316Syokota          //  DW_AT_byte_size( 0x00 )
65032316Syokota          //  DW_AT_decl_file( "..." )
65132316Syokota          //  DW_AT_decl_line( 1 )
65238053Syokota          //
65338053Syokota          // Note that there is no DW_AT_declaration and there are
65438053Syokota          // no children, and the byte size is zero.
65554380Syokota          is_forward_declaration = true;
65654380Syokota        }
65754380Syokota
65854380Syokota        if (class_language == eLanguageTypeObjC ||
65954380Syokota            class_language == eLanguageTypeObjC_plus_plus) {
66054380Syokota          if (!is_complete_objc_class &&
66154380Syokota              die.Supports_DW_AT_APPLE_objc_complete_type()) {
66254380Syokota            // We have a valid eSymbolTypeObjCClass class symbol whose
66354380Syokota            // name matches the current objective C class that we
66454380Syokota            // are trying to find and this DIE isn't the complete
66554380Syokota            // definition (we checked is_complete_objc_class above and
66654380Syokota            // know it is false), so the real definition is in here somewhere
66754380Syokota            type_sp = dwarf->FindCompleteObjCDefinitionTypeForDIE(
66854380Syokota                die, type_name_const_str, true);
66954380Syokota
67054380Syokota            if (!type_sp) {
67154380Syokota              SymbolFileDWARFDebugMap *debug_map_symfile =
67254380Syokota                  dwarf->GetDebugMapSymfile();
67354380Syokota              if (debug_map_symfile) {
67454380Syokota                // We weren't able to find a full declaration in
67554380Syokota                // this DWARF, see if we have a declaration anywhere
67665759Sdwmalone                // else...
67765759Sdwmalone                type_sp =
67865759Sdwmalone                    debug_map_symfile->FindCompleteObjCDefinitionTypeForDIE(
67965759Sdwmalone                        die, type_name_const_str, true);
68065759Sdwmalone              }
68165759Sdwmalone            }
68274118Sache
68374118Sache            if (type_sp) {
68474118Sache              if (log) {
68532316Syokota                dwarf->GetObjectFile()->GetModule()->LogMessage(
68632316Syokota                    log, "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is an "
68732316Syokota                         "incomplete objc type, complete type is 0x%8.8" PRIx64,
68832316Syokota                    static_cast<void *>(this), die.GetOffset(),
68932486Syokota                    DW_TAG_value_to_name(tag), type_name_cstr,
69032316Syokota                    type_sp->GetID());
69132316Syokota              }
69232316Syokota
69332316Syokota              // We found a real definition for this type elsewhere
69432316Syokota              // so lets use it and cache the fact that we found
69532316Syokota              // a complete type for this die
69632316Syokota              dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
69732316Syokota              return type_sp;
69832316Syokota            }
69932316Syokota          }
70032316Syokota        }
70132316Syokota
70232316Syokota        if (is_forward_declaration) {
70332316Syokota          // We have a forward declaration to a type and we need
70432316Syokota          // to try and find a full declaration. We look in the
70532316Syokota          // current type index just in case we have a forward
70632316Syokota          // declaration followed by an actual declarations in the
70732316Syokota          // DWARF. If this fails, we need to look elsewhere...
70832316Syokota          if (log) {
70932316Syokota            dwarf->GetObjectFile()->GetModule()->LogMessage(
71032316Syokota                log, "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a "
71132316Syokota                     "forward declaration, trying to find complete type",
71232486Syokota                static_cast<void *>(this), die.GetOffset(),
71332316Syokota                DW_TAG_value_to_name(tag), type_name_cstr);
71432316Syokota          }
71532486Syokota
71632486Syokota          // See if the type comes from a DWO module and if so, track down that
71732486Syokota          // type.
71832316Syokota          type_sp = ParseTypeFromDWO(die, log);
71932316Syokota          if (type_sp)
72032316Syokota            return type_sp;
72132486Syokota
72232316Syokota          DWARFDeclContext die_decl_ctx;
72332316Syokota          die.GetDWARFDeclContext(die_decl_ctx);
724196500Sed
72532316Syokota          // type_sp = FindDefinitionTypeForDIE (dwarf_cu, die,
72632316Syokota          // type_name_const_str);
72732316Syokota          type_sp = dwarf->FindDefinitionTypeForDWARFDeclContext(die_decl_ctx);
72832486Syokota
72932316Syokota          if (!type_sp) {
73032316Syokota            SymbolFileDWARFDebugMap *debug_map_symfile =
73132316Syokota                dwarf->GetDebugMapSymfile();
73232486Syokota            if (debug_map_symfile) {
73332316Syokota              // We weren't able to find a full declaration in
73432316Syokota              // this DWARF, see if we have a declaration anywhere
73532316Syokota              // else...
73632316Syokota              type_sp =
73732316Syokota                  debug_map_symfile->FindDefinitionTypeForDWARFDeclContext(
73832316Syokota                      die_decl_ctx);
73932316Syokota            }
74032316Syokota          }
74132486Syokota
74232316Syokota          if (type_sp) {
74332486Syokota            if (log) {
74432486Syokota              dwarf->GetObjectFile()->GetModule()->LogMessage(
74532486Syokota                  log, "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a "
74632486Syokota                       "forward declaration, complete type is 0x%8.8" PRIx64,
74732486Syokota                  static_cast<void *>(this), die.GetOffset(),
74832316Syokota                  DW_TAG_value_to_name(tag), type_name_cstr, type_sp->GetID());
74932316Syokota            }
75032316Syokota
75132316Syokota            // We found a real definition for this type elsewhere
75232316Syokota            // so lets use it and cache the fact that we found
75332316Syokota            // a complete type for this die
75432316Syokota            dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
75532316Syokota            clang::DeclContext *defn_decl_ctx = GetCachedClangDeclContextForDIE(
75632316Syokota                dwarf->DebugInfo()->GetDIE(DIERef(type_sp->GetID(), dwarf)));
75732316Syokota            if (defn_decl_ctx)
75832316Syokota              LinkDeclContextToDIE(defn_decl_ctx, die);
75932316Syokota            return type_sp;
76032316Syokota          }
76132316Syokota        }
76232316Syokota        assert(tag_decl_kind != -1);
76332316Syokota        bool clang_type_was_created = false;
76432316Syokota        clang_type.SetCompilerType(
76532316Syokota            &m_ast, dwarf->GetForwardDeclDieToClangType().lookup(die.GetDIE()));
76632316Syokota        if (!clang_type) {
76732316Syokota          clang::DeclContext *decl_ctx =
76832316Syokota              GetClangDeclContextContainingDIE(die, nullptr);
76932316Syokota          if (accessibility == eAccessNone && decl_ctx) {
77032316Syokota            // Check the decl context that contains this class/struct/union.
77132316Syokota            // If it is a class we must give it an accessibility.
77232316Syokota            const clang::Decl::Kind containing_decl_kind =
77332316Syokota                decl_ctx->getDeclKind();
77432316Syokota            if (DeclKindIsCXXClass(containing_decl_kind))
77532316Syokota              accessibility = default_accessibility;
77632486Syokota          }
77732316Syokota
77832316Syokota          ClangASTMetadata metadata;
77932316Syokota          metadata.SetUserID(die.GetID());
78019569Sjoerg          metadata.SetIsDynamicCXXType(dwarf->ClassOrStructIsVirtual(die));
7812088Ssos
78232316Syokota          if (type_name_cstr && strchr(type_name_cstr, '<')) {
78332316Syokota            ClangASTContext::TemplateParameterInfos template_param_infos;
7842088Ssos            if (ParseTemplateParameterInfos(die, template_param_infos)) {
78576502Ssobomax              clang::ClassTemplateDecl *class_template_decl =
78619569Sjoerg                  m_ast.ParseClassTemplateDecl(decl_ctx, accessibility,
78799816Salfred                                               type_name_cstr, tag_decl_kind,
78899816Salfred                                               template_param_infos);
78999816Salfred
7902088Ssos              clang::ClassTemplateSpecializationDecl
79176569Ssobomax                  *class_specialization_decl =
79276569Ssobomax                      m_ast.CreateClassTemplateSpecializationDecl(
79376569Ssobomax                          decl_ctx, class_template_decl, tag_decl_kind,
79476502Ssobomax                          template_param_infos);
79576643Simp              clang_type = m_ast.CreateClassTemplateSpecializationType(
79676643Simp                  class_specialization_decl);
79776643Simp              clang_type_was_created = true;
79876502Ssobomax
79976643Simp              m_ast.SetMetadata(class_template_decl, metadata);
80076502Ssobomax              m_ast.SetMetadata(class_specialization_decl, metadata);
80176643Simp            }
8022088Ssos          }
80379677Sobrien
8042088Ssos          if (!clang_type_was_created) {
8052088Ssos            clang_type_was_created = true;
80632316Syokota            clang_type = m_ast.CreateRecordType(decl_ctx, accessibility,
80732316Syokota                                                type_name_cstr, tag_decl_kind,
80832316Syokota                                                class_language, &metadata);
8092088Ssos          }
81032316Syokota        }
8112088Ssos
8122088Ssos        // Store a forward declaration to this class type in case any
81319569Sjoerg        // parameters in any class methods need it for the clang
81419569Sjoerg        // types for function prototypes.
81519569Sjoerg        LinkDeclContextToDIE(m_ast.GetDeclContextForType(clang_type), die);
81619569Sjoerg        type_sp.reset(new Type(die.GetID(), dwarf, type_name_const_str,
81732316Syokota                               byte_size, NULL, LLDB_INVALID_UID,
81832316Syokota                               Type::eEncodingIsUID, &decl, clang_type,
81932316Syokota                               Type::eResolveStateForward));
82032316Syokota
82132316Syokota        type_sp->SetIsCompleteObjCClass(is_complete_objc_class);
82232316Syokota
82319569Sjoerg        // Add our type to the unique type map so we don't
82419569Sjoerg        // end up creating many copies of the same type over
82532316Syokota        // and over in the ASTContext for our module
82629603Scharnier        unique_ast_entry_ap->m_type_sp = type_sp;
8272088Ssos        unique_ast_entry_ap->m_die = die;
8282088Ssos        unique_ast_entry_ap->m_declaration = unique_decl;
8292088Ssos        unique_ast_entry_ap->m_byte_size = byte_size;
83032316Syokota        dwarf->GetUniqueDWARFASTTypeMap().Insert(unique_typename,
83132316Syokota                                                 *unique_ast_entry_ap);
83232316Syokota
83332316Syokota        if (is_forward_declaration && die.HasChildren()) {
83432316Syokota          // Check to see if the DIE actually has a definition, some version of
83532316Syokota          // GCC will
8362088Ssos          // emit DIEs with DW_AT_declaration set to true, but yet still have
8372088Ssos          // subprogram,
8382088Ssos          // members, or inheritance, so we can't trust it
83999816Salfred          DWARFDIE child_die = die.GetFirstChild();
8402088Ssos          while (child_die) {
84132316Syokota            switch (child_die.Tag()) {
84232316Syokota            case DW_TAG_inheritance:
8432088Ssos            case DW_TAG_subprogram:
8442088Ssos            case DW_TAG_member:
84532316Syokota            case DW_TAG_APPLE_property:
84629603Scharnier            case DW_TAG_class_type:
84732316Syokota            case DW_TAG_structure_type:
84832316Syokota            case DW_TAG_enumeration_type:
8492088Ssos            case DW_TAG_typedef:
8502088Ssos            case DW_TAG_union_type:
8512088Ssos              child_die.Clear();
8522088Ssos              is_forward_declaration = false;
8532088Ssos              break;
8542088Ssos            default:
85532316Syokota              child_die = child_die.GetSibling();
85632316Syokota              break;
85732316Syokota            }
85832316Syokota          }
85932316Syokota        }
86032316Syokota
86132316Syokota        if (!is_forward_declaration) {
8622088Ssos          // Always start the definition for a class type so that
8632088Ssos          // if the class has child classes or types that require
8642088Ssos          // the class to be created for use as their decl contexts
86599816Salfred          // the class will be ready to accept these child definitions.
8662088Ssos          if (die.HasChildren() == false) {
8672088Ssos            // No children for this struct/union/class, lets finish it
8682088Ssos            if (ClangASTContext::StartTagDeclarationDefinition(clang_type)) {
8692088Ssos              ClangASTContext::CompleteTagDeclarationDefinition(clang_type);
8702088Ssos            } else {
8712088Ssos              dwarf->GetObjectFile()->GetModule()->ReportError(
8722088Ssos                  "DWARF DIE at 0x%8.8x named \"%s\" was not able to start its "
8732088Ssos                  "definition.\nPlease file a bug and attach the file at the "
8742088Ssos                  "start of this error message",
87529603Scharnier                  die.GetOffset(), type_name_cstr);
8762088Ssos            }
8772088Ssos
8782088Ssos            if (tag == DW_TAG_structure_type) // this only applies in C
8792088Ssos            {
8802088Ssos              clang::RecordDecl *record_decl =
8812088Ssos                  ClangASTContext::GetAsRecordDecl(clang_type);
8822088Ssos
8832088Ssos              if (record_decl) {
8842088Ssos                GetClangASTImporter().InsertRecordDecl(
8852088Ssos                    record_decl, ClangASTImporter::LayoutInfo());
8862088Ssos              }
8872088Ssos            }
8882088Ssos          } else if (clang_type_was_created) {
8892088Ssos            // Start the definition if the class is not objective C since
89029603Scharnier            // the underlying decls respond to isCompleteDefinition(). Objective
8912088Ssos            // C decls don't respond to isCompleteDefinition() so we can't
8922088Ssos            // start the declaration definition right away. For C++
8932088Ssos            // class/union/structs
8942088Ssos            // we want to start the definition in case the class is needed as
89529603Scharnier            // the
8962088Ssos            // declaration context for a contained class or type without the
8972088Ssos            // need
8982088Ssos            // to complete that type..
899133353Sjmg
9002088Ssos            if (class_language != eLanguageTypeObjC &&
9012088Ssos                class_language != eLanguageTypeObjC_plus_plus)
90229603Scharnier              ClangASTContext::StartTagDeclarationDefinition(clang_type);
9032088Ssos
9042088Ssos            // Leave this as a forward declaration until we need
9052088Ssos            // to know the details of the type. lldb_private::Type
9062088Ssos            // will automatically call the SymbolFile virtual function
9072088Ssos            // "SymbolFileDWARF::CompleteType(Type *)"
9085536Ssos            // When the definition needs to be defined.
9092088Ssos            assert(!dwarf->GetForwardDeclClangTypeToDie().count(
91038044Syokota                       ClangUtil::RemoveFastQualifiers(clang_type)
91138044Syokota                           .GetOpaqueQualType()) &&
912164333Sru                   "Type already in the forward declaration map!");
91338044Syokota            // Can't assume m_ast.GetSymbolFile() is actually a SymbolFileDWARF,
91438044Syokota            // it can be a
9158857Srgrimes            // SymbolFileDWARFDebugMap for Apple binaries.
916164333Sru            dwarf->GetForwardDeclDieToClangType()[die.GetDIE()] =
9175536Ssos                clang_type.GetOpaqueQualType();
91838044Syokota            dwarf->GetForwardDeclClangTypeToDie()
91948982Syokota                [ClangUtil::RemoveFastQualifiers(clang_type)
92048982Syokota                     .GetOpaqueQualType()] = die.GetDIERef();
9212088Ssos            m_ast.SetHasExternalStorage(clang_type.GetOpaqueQualType(), true);
9222088Ssos          }
9238857Srgrimes        }
9245536Ssos      } break;
9252088Ssos
9262088Ssos      case DW_TAG_enumeration_type: {
9272088Ssos        // Set a bit that lets us know that we are currently parsing this
9282088Ssos        dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED;
9292088Ssos
9302088Ssos        DWARFFormValue encoding_form;
9312088Ssos
93277394Ssobomax        const size_t num_attributes = die.GetAttributes(attributes);
9332088Ssos        if (num_attributes > 0) {
9342088Ssos          uint32_t i;
93538044Syokota
93638044Syokota          for (i = 0; i < num_attributes; ++i) {
93738044Syokota            attr = attributes.AttributeAtIndex(i);
9382088Ssos            if (attributes.ExtractFormValueAtIndex(i, form_value)) {
9392088Ssos              switch (attr) {
9405536Ssos              case DW_AT_decl_file:
941164333Sru                decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
9425536Ssos                    form_value.Unsigned()));
9432088Ssos                break;
9442088Ssos              case DW_AT_decl_line:
9452088Ssos                decl.SetLine(form_value.Unsigned());
9462088Ssos                break;
9472088Ssos              case DW_AT_decl_column:
94844628Syokota                decl.SetColumn(form_value.Unsigned());
94939047Syokota                break;
95039047Syokota              case DW_AT_name:
95146761Syokota                type_name_cstr = form_value.AsCString();
9522088Ssos                type_name_const_str.SetCString(type_name_cstr);
95346761Syokota                break;
95444628Syokota              case DW_AT_type:
95546761Syokota                encoding_form = form_value;
95646761Syokota                break;
95744628Syokota              case DW_AT_byte_size:
95846761Syokota                byte_size = form_value.Unsigned();
95946761Syokota                break;
96039047Syokota              case DW_AT_accessibility:
96146761Syokota                break; // accessibility =
96246761Syokota                       // DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
9632088Ssos              case DW_AT_declaration:
9642088Ssos                is_forward_declaration = form_value.Boolean();
9652088Ssos                break;
9662088Ssos              case DW_AT_allocated:
9672088Ssos              case DW_AT_associated:
9682088Ssos              case DW_AT_bit_stride:
9692088Ssos              case DW_AT_byte_stride:
9702088Ssos              case DW_AT_data_location:
9712088Ssos              case DW_AT_description:
9722088Ssos              case DW_AT_start_scope:
97377394Ssobomax              case DW_AT_visibility:
9742088Ssos              case DW_AT_specification:
9752088Ssos              case DW_AT_abstract_origin:
97646761Syokota              case DW_AT_sibling:
97746761Syokota                break;
97846761Syokota              }
97946761Syokota            }
98046761Syokota          }
98146761Syokota
98246761Syokota          if (is_forward_declaration) {
98346761Syokota            type_sp = ParseTypeFromDWO(die, log);
9842088Ssos            if (type_sp)
9852088Ssos              return type_sp;
98644628Syokota
98744628Syokota            DWARFDeclContext die_decl_ctx;
98846761Syokota            die.GetDWARFDeclContext(die_decl_ctx);
98946761Syokota
99046761Syokota            type_sp =
99146761Syokota                dwarf->FindDefinitionTypeForDWARFDeclContext(die_decl_ctx);
9922088Ssos
9932088Ssos            if (!type_sp) {
99499816Salfred              SymbolFileDWARFDebugMap *debug_map_symfile =
99599816Salfred                  dwarf->GetDebugMapSymfile();
99642505Syokota              if (debug_map_symfile) {
99742505Syokota                // We weren't able to find a full declaration in
99842505Syokota                // this DWARF, see if we have a declaration anywhere
99999816Salfred                // else...
100042505Syokota                type_sp =
100142505Syokota                    debug_map_symfile->FindDefinitionTypeForDWARFDeclContext(
100242505Syokota                        die_decl_ctx);
100342505Syokota              }
100442505Syokota            }
100599816Salfred
10066046Ssos            if (type_sp) {
100742505Syokota              if (log) {
100842505Syokota                dwarf->GetObjectFile()->GetModule()->LogMessage(
100942505Syokota                    log, "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a "
101042505Syokota                         "forward declaration, complete type is 0x%8.8" PRIx64,
101142505Syokota                    static_cast<void *>(this), die.GetOffset(),
101242505Syokota                    DW_TAG_value_to_name(tag), type_name_cstr,
101342505Syokota                    type_sp->GetID());
101442505Syokota              }
101542505Syokota
101642505Syokota              // We found a real definition for this type elsewhere
101742505Syokota              // so lets use it and cache the fact that we found
101842505Syokota              // a complete type for this die
101942505Syokota              dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
102042505Syokota              clang::DeclContext *defn_decl_ctx =
102142505Syokota                  GetCachedClangDeclContextForDIE(dwarf->DebugInfo()->GetDIE(
102242505Syokota                      DIERef(type_sp->GetID(), dwarf)));
102342505Syokota              if (defn_decl_ctx)
102442505Syokota                LinkDeclContextToDIE(defn_decl_ctx, die);
102577394Ssobomax              return type_sp;
102642505Syokota            }
102742505Syokota          }
102842505Syokota          DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(),
102942505Syokota                       DW_TAG_value_to_name(tag), type_name_cstr);
103042505Syokota
103142505Syokota          CompilerType enumerator_clang_type;
103242505Syokota          clang_type.SetCompilerType(
103342505Syokota              &m_ast,
103442505Syokota              dwarf->GetForwardDeclDieToClangType().lookup(die.GetDIE()));
103542505Syokota          if (!clang_type) {
103642505Syokota            if (encoding_form.IsValid()) {
103742505Syokota              Type *enumerator_type =
103842505Syokota                  dwarf->ResolveTypeUID(DIERef(encoding_form));
103942505Syokota              if (enumerator_type)
104042505Syokota                enumerator_clang_type = enumerator_type->GetFullCompilerType();
104142505Syokota            }
104242505Syokota
104342505Syokota            if (!enumerator_clang_type) {
104442505Syokota              if (byte_size > 0) {
104542505Syokota                enumerator_clang_type =
104642505Syokota                    m_ast.GetBuiltinTypeForDWARFEncodingAndBitSize(
104742505Syokota                        NULL, DW_ATE_signed, byte_size * 8);
104842505Syokota              } else {
104942505Syokota                enumerator_clang_type = m_ast.GetBasicType(eBasicTypeInt);
105042505Syokota              }
105142505Syokota            }
105242505Syokota
105342505Syokota            clang_type = m_ast.CreateEnumerationType(
105442505Syokota                type_name_cstr, GetClangDeclContextContainingDIE(die, nullptr),
105577394Ssobomax                decl, enumerator_clang_type);
105642505Syokota          } else {
105742505Syokota            enumerator_clang_type =
105842505Syokota                m_ast.GetEnumerationIntegerType(clang_type.GetOpaqueQualType());
105942505Syokota          }
106042505Syokota
106142505Syokota          LinkDeclContextToDIE(
106242505Syokota              ClangASTContext::GetDeclContextForType(clang_type), die);
106342505Syokota
106442505Syokota          type_sp.reset(new Type(
106542505Syokota              die.GetID(), dwarf, type_name_const_str, byte_size, NULL,
106642505Syokota              DIERef(encoding_form).GetUID(dwarf), Type::eEncodingIsUID, &decl,
106742505Syokota              clang_type, Type::eResolveStateForward));
106842505Syokota
106942505Syokota          if (ClangASTContext::StartTagDeclarationDefinition(clang_type)) {
107042505Syokota            if (die.HasChildren()) {
107142505Syokota              SymbolContext cu_sc(die.GetLLDBCompileUnit());
107242505Syokota              bool is_signed = false;
107342505Syokota              enumerator_clang_type.IsIntegerType(is_signed);
107442505Syokota              ParseChildEnumerators(cu_sc, clang_type, is_signed,
107542505Syokota                                    type_sp->GetByteSize(), die);
107642505Syokota            }
107742505Syokota            ClangASTContext::CompleteTagDeclarationDefinition(clang_type);
107842505Syokota          } else {
107977394Ssobomax            dwarf->GetObjectFile()->GetModule()->ReportError(
108042505Syokota                "DWARF DIE at 0x%8.8x named \"%s\" was not able to start its "
108142505Syokota                "definition.\nPlease file a bug and attach the file at the "
108242505Syokota                "start of this error message",
108342505Syokota                die.GetOffset(), type_name_cstr);
108442505Syokota          }
108542505Syokota        }
1086148017Semax      } break;
1087162327Semax
1088148017Semax      case DW_TAG_inlined_subroutine:
1089148017Semax      case DW_TAG_subprogram:
1090148017Semax      case DW_TAG_subroutine_type: {
109142505Syokota        // Set a bit that lets us know that we are currently parsing this
1092148017Semax        dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED;
1093148017Semax
1094148017Semax        DWARFFormValue type_die_form;
1095148017Semax        bool is_variadic = false;
1096148017Semax        bool is_inline = false;
1097148017Semax        bool is_static = false;
1098148017Semax        bool is_virtual = false;
1099148017Semax        bool is_explicit = false;
1100148017Semax        bool is_artificial = false;
1101148017Semax        bool has_template_params = false;
1102148017Semax        DWARFFormValue specification_die_form;
1103148017Semax        DWARFFormValue abstract_origin_die_form;
1104148017Semax        dw_offset_t object_pointer_die_offset = DW_INVALID_OFFSET;
1105148017Semax
1106148017Semax        unsigned type_quals = 0;
1107148017Semax        clang::StorageClass storage =
1108148017Semax            clang::SC_None; //, Extern, Static, PrivateExtern
1109148017Semax
1110148017Semax        const size_t num_attributes = die.GetAttributes(attributes);
1111148017Semax        if (num_attributes > 0) {
1112148017Semax          uint32_t i;
1113148017Semax          for (i = 0; i < num_attributes; ++i) {
1114148017Semax            attr = attributes.AttributeAtIndex(i);
1115148017Semax            if (attributes.ExtractFormValueAtIndex(i, form_value)) {
1116148017Semax              switch (attr) {
1117148017Semax              case DW_AT_decl_file:
1118148017Semax                decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
1119148017Semax                    form_value.Unsigned()));
1120148017Semax                break;
1121148017Semax              case DW_AT_decl_line:
1122148017Semax                decl.SetLine(form_value.Unsigned());
1123148017Semax                break;
1124148017Semax              case DW_AT_decl_column:
1125148017Semax                decl.SetColumn(form_value.Unsigned());
1126148017Semax                break;
1127148017Semax              case DW_AT_name:
1128148017Semax                type_name_cstr = form_value.AsCString();
1129148017Semax                type_name_const_str.SetCString(type_name_cstr);
1130148017Semax                break;
1131148017Semax
1132148017Semax              case DW_AT_linkage_name:
1133148017Semax              case DW_AT_MIPS_linkage_name:
1134148017Semax                break; // mangled =
1135148017Semax                       // form_value.AsCString(&dwarf->get_debug_str_data());
1136148017Semax                       // break;
1137148017Semax              case DW_AT_type:
1138148017Semax                type_die_form = form_value;
1139148017Semax                break;
1140148017Semax              case DW_AT_accessibility:
1141148017Semax                accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
1142148017Semax                break;
1143148017Semax              case DW_AT_declaration:
1144148017Semax                break; // is_forward_declaration = form_value.Boolean(); break;
1145148017Semax              case DW_AT_inline:
1146148017Semax                is_inline = form_value.Boolean();
1147148017Semax                break;
1148148017Semax              case DW_AT_virtuality:
1149148017Semax                is_virtual = form_value.Boolean();
115077394Ssobomax                break;
1151201387Sed              case DW_AT_explicit:
11522088Ssos                is_explicit = form_value.Boolean();
115329603Scharnier                break;
1154148017Semax              case DW_AT_artificial:
115529603Scharnier                is_artificial = form_value.Boolean();
115677329Sdes                break;
115729603Scharnier
11582088Ssos              case DW_AT_external:
11592088Ssos                if (form_value.Unsigned()) {
11602088Ssos                  if (storage == clang::SC_None)
116151287Speter                    storage = clang::SC_Extern;
11622088Ssos                  else
11632088Ssos                    storage = clang::SC_PrivateExtern;
11642088Ssos                }
11652088Ssos                break;
1166148017Semax
11672088Ssos              case DW_AT_specification:
1168148017Semax                specification_die_form = form_value;
1169148017Semax                break;
1170148017Semax
1171148017Semax              case DW_AT_abstract_origin:
117277329Sdes                abstract_origin_die_form = form_value;
117377329Sdes                break;
117477329Sdes
117577329Sdes              case DW_AT_object_pointer:
117677329Sdes                object_pointer_die_offset = form_value.Reference();
117777329Sdes                break;
117877329Sdes
117977329Sdes              case DW_AT_allocated:
118077329Sdes              case DW_AT_associated:
118177329Sdes              case DW_AT_address_class:
118277329Sdes              case DW_AT_calling_convention:
118377329Sdes              case DW_AT_data_location:
118477329Sdes              case DW_AT_elemental:
118577329Sdes              case DW_AT_entry_pc:
118677329Sdes              case DW_AT_frame_base:
118777329Sdes              case DW_AT_high_pc:
118877329Sdes              case DW_AT_low_pc:
118977329Sdes              case DW_AT_prototyped:
119077329Sdes              case DW_AT_pure:
119177329Sdes              case DW_AT_ranges:
119277329Sdes              case DW_AT_recursive:
119377329Sdes              case DW_AT_return_addr:
119477329Sdes              case DW_AT_segment:
119577329Sdes              case DW_AT_start_scope:
119677329Sdes              case DW_AT_static_link:
119777329Sdes              case DW_AT_trampoline:
119877329Sdes              case DW_AT_visibility:
119977329Sdes              case DW_AT_vtable_elem_location:
120077329Sdes              case DW_AT_description:
120177329Sdes              case DW_AT_sibling:
120277329Sdes                break;
120377329Sdes              }
120477329Sdes            }
120577329Sdes          }
120677329Sdes        }
120777329Sdes
12082088Ssos        std::string object_pointer_name;
120929603Scharnier        if (object_pointer_die_offset != DW_INVALID_OFFSET) {
12102088Ssos          DWARFDIE object_pointer_die = die.GetDIE(object_pointer_die_offset);
12112088Ssos          if (object_pointer_die) {
12122088Ssos            const char *object_pointer_name_cstr = object_pointer_die.GetName();
1213            if (object_pointer_name_cstr)
1214              object_pointer_name = object_pointer_name_cstr;
1215          }
1216        }
1217
1218        DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(),
1219                     DW_TAG_value_to_name(tag), type_name_cstr);
1220
1221        CompilerType return_clang_type;
1222        Type *func_type = NULL;
1223
1224        if (type_die_form.IsValid())
1225          func_type = dwarf->ResolveTypeUID(DIERef(type_die_form));
1226
1227        if (func_type)
1228          return_clang_type = func_type->GetForwardCompilerType();
1229        else
1230          return_clang_type = m_ast.GetBasicType(eBasicTypeVoid);
1231
1232        std::vector<CompilerType> function_param_types;
1233        std::vector<clang::ParmVarDecl *> function_param_decls;
1234
1235        // Parse the function children for the parameters
1236
1237        DWARFDIE decl_ctx_die;
1238        clang::DeclContext *containing_decl_ctx =
1239            GetClangDeclContextContainingDIE(die, &decl_ctx_die);
1240        const clang::Decl::Kind containing_decl_kind =
1241            containing_decl_ctx->getDeclKind();
1242
1243        bool is_cxx_method = DeclKindIsCXXClass(containing_decl_kind);
1244        // Start off static. This will be set to false in
1245        // ParseChildParameters(...)
1246        // if we find a "this" parameters as the first parameter
1247        if (is_cxx_method) {
1248          is_static = true;
1249        }
1250
1251        if (die.HasChildren()) {
1252          bool skip_artificial = true;
1253          ParseChildParameters(sc, containing_decl_ctx, die, skip_artificial,
1254                               is_static, is_variadic, has_template_params,
1255                               function_param_types, function_param_decls,
1256                               type_quals);
1257        }
1258
1259        bool ignore_containing_context = false;
1260        // Check for templatized class member functions. If we had any
1261        // DW_TAG_template_type_parameter
1262        // or DW_TAG_template_value_parameter the DW_TAG_subprogram DIE, then we
1263        // can't let this become
1264        // a method in a class. Why? Because templatized functions are only
1265        // emitted if one of the
1266        // templatized methods is used in the current compile unit and we will
1267        // end up with classes
1268        // that may or may not include these member functions and this means one
1269        // class won't match another
1270        // class definition and it affects our ability to use a class in the
1271        // clang expression parser. So
1272        // for the greater good, we currently must not allow any template member
1273        // functions in a class definition.
1274        if (is_cxx_method && has_template_params) {
1275          ignore_containing_context = true;
1276          is_cxx_method = false;
1277        }
1278
1279        // clang_type will get the function prototype clang type after this call
1280        clang_type = m_ast.CreateFunctionType(
1281            return_clang_type, function_param_types.data(),
1282            function_param_types.size(), is_variadic, type_quals);
1283
1284        if (type_name_cstr) {
1285          bool type_handled = false;
1286          if (tag == DW_TAG_subprogram || tag == DW_TAG_inlined_subroutine) {
1287            ObjCLanguage::MethodName objc_method(type_name_cstr, true);
1288            if (objc_method.IsValid(true)) {
1289              CompilerType class_opaque_type;
1290              ConstString class_name(objc_method.GetClassName());
1291              if (class_name) {
1292                TypeSP complete_objc_class_type_sp(
1293                    dwarf->FindCompleteObjCDefinitionTypeForDIE(
1294                        DWARFDIE(), class_name, false));
1295
1296                if (complete_objc_class_type_sp) {
1297                  CompilerType type_clang_forward_type =
1298                      complete_objc_class_type_sp->GetForwardCompilerType();
1299                  if (ClangASTContext::IsObjCObjectOrInterfaceType(
1300                          type_clang_forward_type))
1301                    class_opaque_type = type_clang_forward_type;
1302                }
1303              }
1304
1305              if (class_opaque_type) {
1306                // If accessibility isn't set to anything valid, assume public
1307                // for
1308                // now...
1309                if (accessibility == eAccessNone)
1310                  accessibility = eAccessPublic;
1311
1312                clang::ObjCMethodDecl *objc_method_decl =
1313                    m_ast.AddMethodToObjCObjectType(
1314                        class_opaque_type, type_name_cstr, clang_type,
1315                        accessibility, is_artificial, is_variadic);
1316                type_handled = objc_method_decl != NULL;
1317                if (type_handled) {
1318                  LinkDeclContextToDIE(
1319                      ClangASTContext::GetAsDeclContext(objc_method_decl), die);
1320                  m_ast.SetMetadataAsUserID(objc_method_decl, die.GetID());
1321                } else {
1322                  dwarf->GetObjectFile()->GetModule()->ReportError(
1323                      "{0x%8.8x}: invalid Objective-C method 0x%4.4x (%s), "
1324                      "please file a bug and attach the file at the start of "
1325                      "this error message",
1326                      die.GetOffset(), tag, DW_TAG_value_to_name(tag));
1327                }
1328              }
1329            } else if (is_cxx_method) {
1330              // Look at the parent of this DIE and see if is is
1331              // a class or struct and see if this is actually a
1332              // C++ method
1333              Type *class_type = dwarf->ResolveType(decl_ctx_die);
1334              if (class_type) {
1335                bool alternate_defn = false;
1336                if (class_type->GetID() != decl_ctx_die.GetID() ||
1337                    decl_ctx_die.GetContainingDWOModuleDIE()) {
1338                  alternate_defn = true;
1339
1340                  // We uniqued the parent class of this function to another
1341                  // class
1342                  // so we now need to associate all dies under "decl_ctx_die"
1343                  // to
1344                  // DIEs in the DIE for "class_type"...
1345                  SymbolFileDWARF *class_symfile = NULL;
1346                  DWARFDIE class_type_die;
1347
1348                  SymbolFileDWARFDebugMap *debug_map_symfile =
1349                      dwarf->GetDebugMapSymfile();
1350                  if (debug_map_symfile) {
1351                    class_symfile = debug_map_symfile->GetSymbolFileByOSOIndex(
1352                        SymbolFileDWARFDebugMap::GetOSOIndexFromUserID(
1353                            class_type->GetID()));
1354                    class_type_die = class_symfile->DebugInfo()->GetDIE(
1355                        DIERef(class_type->GetID(), dwarf));
1356                  } else {
1357                    class_symfile = dwarf;
1358                    class_type_die = dwarf->DebugInfo()->GetDIE(
1359                        DIERef(class_type->GetID(), dwarf));
1360                  }
1361                  if (class_type_die) {
1362                    DWARFDIECollection failures;
1363
1364                    CopyUniqueClassMethodTypes(decl_ctx_die, class_type_die,
1365                                               class_type, failures);
1366
1367                    // FIXME do something with these failures that's smarter
1368                    // than
1369                    // just dropping them on the ground.  Unfortunately classes
1370                    // don't
1371                    // like having stuff added to them after their definitions
1372                    // are
1373                    // complete...
1374
1375                    type_ptr = dwarf->GetDIEToType()[die.GetDIE()];
1376                    if (type_ptr && type_ptr != DIE_IS_BEING_PARSED) {
1377                      type_sp = type_ptr->shared_from_this();
1378                      break;
1379                    }
1380                  }
1381                }
1382
1383                if (specification_die_form.IsValid()) {
1384                  // We have a specification which we are going to base our
1385                  // function
1386                  // prototype off of, so we need this type to be completed so
1387                  // that the
1388                  // m_die_to_decl_ctx for the method in the specification has a
1389                  // valid
1390                  // clang decl context.
1391                  class_type->GetForwardCompilerType();
1392                  // If we have a specification, then the function type should
1393                  // have been
1394                  // made with the specification and not with this die.
1395                  DWARFDIE spec_die = dwarf->DebugInfo()->GetDIE(
1396                      DIERef(specification_die_form));
1397                  clang::DeclContext *spec_clang_decl_ctx =
1398                      GetClangDeclContextForDIE(spec_die);
1399                  if (spec_clang_decl_ctx) {
1400                    LinkDeclContextToDIE(spec_clang_decl_ctx, die);
1401                  } else {
1402                    dwarf->GetObjectFile()->GetModule()->ReportWarning(
1403                        "0x%8.8" PRIx64 ": DW_AT_specification(0x%8.8" PRIx64
1404                        ") has no decl\n",
1405                        die.GetID(), specification_die_form.Reference());
1406                  }
1407                  type_handled = true;
1408                } else if (abstract_origin_die_form.IsValid()) {
1409                  // We have a specification which we are going to base our
1410                  // function
1411                  // prototype off of, so we need this type to be completed so
1412                  // that the
1413                  // m_die_to_decl_ctx for the method in the abstract origin has
1414                  // a valid
1415                  // clang decl context.
1416                  class_type->GetForwardCompilerType();
1417
1418                  DWARFDIE abs_die = dwarf->DebugInfo()->GetDIE(
1419                      DIERef(abstract_origin_die_form));
1420                  clang::DeclContext *abs_clang_decl_ctx =
1421                      GetClangDeclContextForDIE(abs_die);
1422                  if (abs_clang_decl_ctx) {
1423                    LinkDeclContextToDIE(abs_clang_decl_ctx, die);
1424                  } else {
1425                    dwarf->GetObjectFile()->GetModule()->ReportWarning(
1426                        "0x%8.8" PRIx64 ": DW_AT_abstract_origin(0x%8.8" PRIx64
1427                        ") has no decl\n",
1428                        die.GetID(), abstract_origin_die_form.Reference());
1429                  }
1430                  type_handled = true;
1431                } else {
1432                  CompilerType class_opaque_type =
1433                      class_type->GetForwardCompilerType();
1434                  if (ClangASTContext::IsCXXClassType(class_opaque_type)) {
1435                    if (class_opaque_type.IsBeingDefined() || alternate_defn) {
1436                      if (!is_static && !die.HasChildren()) {
1437                        // We have a C++ member function with no children (this
1438                        // pointer!)
1439                        // and clang will get mad if we try and make a function
1440                        // that isn't
1441                        // well formed in the DWARF, so we will just skip it...
1442                        type_handled = true;
1443                      } else {
1444                        bool add_method = true;
1445                        if (alternate_defn) {
1446                          // If an alternate definition for the class exists,
1447                          // then add the method only if an
1448                          // equivalent is not already present.
1449                          clang::CXXRecordDecl *record_decl =
1450                              m_ast.GetAsCXXRecordDecl(
1451                                  class_opaque_type.GetOpaqueQualType());
1452                          if (record_decl) {
1453                            for (auto method_iter = record_decl->method_begin();
1454                                 method_iter != record_decl->method_end();
1455                                 method_iter++) {
1456                              clang::CXXMethodDecl *method_decl = *method_iter;
1457                              if (method_decl->getNameInfo().getAsString() ==
1458                                  std::string(type_name_cstr)) {
1459                                if (method_decl->getType() ==
1460                                    ClangUtil::GetQualType(clang_type)) {
1461                                  add_method = false;
1462                                  LinkDeclContextToDIE(
1463                                      ClangASTContext::GetAsDeclContext(
1464                                          method_decl),
1465                                      die);
1466                                  type_handled = true;
1467
1468                                  break;
1469                                }
1470                              }
1471                            }
1472                          }
1473                        }
1474
1475                        if (add_method) {
1476                          llvm::PrettyStackTraceFormat stack_trace(
1477                              "SymbolFileDWARF::ParseType() is adding a method "
1478                              "%s to class %s in DIE 0x%8.8" PRIx64 " from %s",
1479                              type_name_cstr,
1480                              class_type->GetName().GetCString(), die.GetID(),
1481                              dwarf->GetObjectFile()
1482                                  ->GetFileSpec()
1483                                  .GetPath()
1484                                  .c_str());
1485
1486                          const bool is_attr_used = false;
1487                          // Neither GCC 4.2 nor clang++ currently set a valid
1488                          // accessibility
1489                          // in the DWARF for C++ methods... Default to public
1490                          // for now...
1491                          if (accessibility == eAccessNone)
1492                            accessibility = eAccessPublic;
1493
1494                          clang::CXXMethodDecl *cxx_method_decl =
1495                              m_ast.AddMethodToCXXRecordType(
1496                                  class_opaque_type.GetOpaqueQualType(),
1497                                  type_name_cstr, clang_type, accessibility,
1498                                  is_virtual, is_static, is_inline, is_explicit,
1499                                  is_attr_used, is_artificial);
1500
1501                          type_handled = cxx_method_decl != NULL;
1502
1503                          if (type_handled) {
1504                            LinkDeclContextToDIE(
1505                                ClangASTContext::GetAsDeclContext(
1506                                    cxx_method_decl),
1507                                die);
1508
1509                            ClangASTMetadata metadata;
1510                            metadata.SetUserID(die.GetID());
1511
1512                            if (!object_pointer_name.empty()) {
1513                              metadata.SetObjectPtrName(
1514                                  object_pointer_name.c_str());
1515                              if (log)
1516                                log->Printf(
1517                                    "Setting object pointer name: %s on method "
1518                                    "object %p.\n",
1519                                    object_pointer_name.c_str(),
1520                                    static_cast<void *>(cxx_method_decl));
1521                            }
1522                            m_ast.SetMetadata(cxx_method_decl, metadata);
1523                          } else {
1524                            ignore_containing_context = true;
1525                          }
1526                        }
1527                      }
1528                    } else {
1529                      // We were asked to parse the type for a method in a
1530                      // class, yet the
1531                      // class hasn't been asked to complete itself through the
1532                      // clang::ExternalASTSource protocol, so we need to just
1533                      // have the
1534                      // class complete itself and do things the right way, then
1535                      // our
1536                      // DIE should then have an entry in the
1537                      // dwarf->GetDIEToType() map. First
1538                      // we need to modify the dwarf->GetDIEToType() so it
1539                      // doesn't think we are
1540                      // trying to parse this DIE anymore...
1541                      dwarf->GetDIEToType()[die.GetDIE()] = NULL;
1542
1543                      // Now we get the full type to force our class type to
1544                      // complete itself
1545                      // using the clang::ExternalASTSource protocol which will
1546                      // parse all
1547                      // base classes and all methods (including the method for
1548                      // this DIE).
1549                      class_type->GetFullCompilerType();
1550
1551                      // The type for this DIE should have been filled in the
1552                      // function call above
1553                      type_ptr = dwarf->GetDIEToType()[die.GetDIE()];
1554                      if (type_ptr && type_ptr != DIE_IS_BEING_PARSED) {
1555                        type_sp = type_ptr->shared_from_this();
1556                        break;
1557                      }
1558
1559                      // FIXME This is fixing some even uglier behavior but we
1560                      // really need to
1561                      // uniq the methods of each class as well as the class
1562                      // itself.
1563                      // <rdar://problem/11240464>
1564                      type_handled = true;
1565                    }
1566                  }
1567                }
1568              }
1569            }
1570          }
1571
1572          if (!type_handled) {
1573            clang::FunctionDecl *function_decl = nullptr;
1574
1575            if (abstract_origin_die_form.IsValid()) {
1576              DWARFDIE abs_die =
1577                  dwarf->DebugInfo()->GetDIE(DIERef(abstract_origin_die_form));
1578
1579              SymbolContext sc;
1580
1581              if (dwarf->ResolveType(abs_die)) {
1582                function_decl = llvm::dyn_cast_or_null<clang::FunctionDecl>(
1583                    GetCachedClangDeclContextForDIE(abs_die));
1584
1585                if (function_decl) {
1586                  LinkDeclContextToDIE(function_decl, die);
1587                }
1588              }
1589            }
1590
1591            if (!function_decl) {
1592              // We just have a function that isn't part of a class
1593              function_decl = m_ast.CreateFunctionDeclaration(
1594                  ignore_containing_context ? m_ast.GetTranslationUnitDecl()
1595                                            : containing_decl_ctx,
1596                  type_name_cstr, clang_type, storage, is_inline);
1597
1598              if (has_template_params) {
1599                ClangASTContext::TemplateParameterInfos template_param_infos;
1600                ParseTemplateParameterInfos(die, template_param_infos);
1601                clang::FunctionTemplateDecl *func_template_decl =
1602                    m_ast.CreateFunctionTemplateDecl(
1603                        containing_decl_ctx, function_decl, type_name_cstr,
1604                        template_param_infos);
1605                m_ast.CreateFunctionTemplateSpecializationInfo(
1606                    function_decl, func_template_decl, template_param_infos);
1607              }
1608
1609              lldbassert(function_decl);
1610
1611              if (function_decl) {
1612                LinkDeclContextToDIE(function_decl, die);
1613
1614                if (!function_param_decls.empty())
1615                  m_ast.SetFunctionParameters(function_decl,
1616                                              &function_param_decls.front(),
1617                                              function_param_decls.size());
1618
1619                ClangASTMetadata metadata;
1620                metadata.SetUserID(die.GetID());
1621
1622                if (!object_pointer_name.empty()) {
1623                  metadata.SetObjectPtrName(object_pointer_name.c_str());
1624                  if (log)
1625                    log->Printf("Setting object pointer name: %s on function "
1626                                "object %p.",
1627                                object_pointer_name.c_str(),
1628                                static_cast<void *>(function_decl));
1629                }
1630                m_ast.SetMetadata(function_decl, metadata);
1631              }
1632            }
1633          }
1634        }
1635        type_sp.reset(new Type(die.GetID(), dwarf, type_name_const_str, 0, NULL,
1636                               LLDB_INVALID_UID, Type::eEncodingIsUID, &decl,
1637                               clang_type, Type::eResolveStateFull));
1638        assert(type_sp.get());
1639      } break;
1640
1641      case DW_TAG_array_type: {
1642        // Set a bit that lets us know that we are currently parsing this
1643        dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED;
1644
1645        DWARFFormValue type_die_form;
1646        int64_t first_index = 0;
1647        uint32_t byte_stride = 0;
1648        uint32_t bit_stride = 0;
1649        bool is_vector = false;
1650        const size_t num_attributes = die.GetAttributes(attributes);
1651
1652        if (num_attributes > 0) {
1653          uint32_t i;
1654          for (i = 0; i < num_attributes; ++i) {
1655            attr = attributes.AttributeAtIndex(i);
1656            if (attributes.ExtractFormValueAtIndex(i, form_value)) {
1657              switch (attr) {
1658              case DW_AT_decl_file:
1659                decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
1660                    form_value.Unsigned()));
1661                break;
1662              case DW_AT_decl_line:
1663                decl.SetLine(form_value.Unsigned());
1664                break;
1665              case DW_AT_decl_column:
1666                decl.SetColumn(form_value.Unsigned());
1667                break;
1668              case DW_AT_name:
1669                type_name_cstr = form_value.AsCString();
1670                type_name_const_str.SetCString(type_name_cstr);
1671                break;
1672
1673              case DW_AT_type:
1674                type_die_form = form_value;
1675                break;
1676              case DW_AT_byte_size:
1677                break; // byte_size = form_value.Unsigned(); break;
1678              case DW_AT_byte_stride:
1679                byte_stride = form_value.Unsigned();
1680                break;
1681              case DW_AT_bit_stride:
1682                bit_stride = form_value.Unsigned();
1683                break;
1684              case DW_AT_GNU_vector:
1685                is_vector = form_value.Boolean();
1686                break;
1687              case DW_AT_accessibility:
1688                break; // accessibility =
1689                       // DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
1690              case DW_AT_declaration:
1691                break; // is_forward_declaration = form_value.Boolean(); break;
1692              case DW_AT_allocated:
1693              case DW_AT_associated:
1694              case DW_AT_data_location:
1695              case DW_AT_description:
1696              case DW_AT_ordering:
1697              case DW_AT_start_scope:
1698              case DW_AT_visibility:
1699              case DW_AT_specification:
1700              case DW_AT_abstract_origin:
1701              case DW_AT_sibling:
1702                break;
1703              }
1704            }
1705          }
1706
1707          DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(),
1708                       DW_TAG_value_to_name(tag), type_name_cstr);
1709
1710          DIERef type_die_ref(type_die_form);
1711          Type *element_type = dwarf->ResolveTypeUID(type_die_ref);
1712
1713          if (element_type) {
1714            std::vector<uint64_t> element_orders;
1715            ParseChildArrayInfo(sc, die, first_index, element_orders,
1716                                byte_stride, bit_stride);
1717            if (byte_stride == 0 && bit_stride == 0)
1718              byte_stride = element_type->GetByteSize();
1719            CompilerType array_element_type =
1720                element_type->GetForwardCompilerType();
1721
1722            if (ClangASTContext::IsCXXClassType(array_element_type) &&
1723                array_element_type.GetCompleteType() == false) {
1724              ModuleSP module_sp = die.GetModule();
1725              if (module_sp) {
1726                if (die.GetCU()->GetProducer() ==
1727                    DWARFCompileUnit::eProducerClang)
1728                  module_sp->ReportError(
1729                      "DWARF DW_TAG_array_type DIE at 0x%8.8x has a "
1730                      "class/union/struct element type DIE 0x%8.8x that is a "
1731                      "forward declaration, not a complete definition.\nTry "
1732                      "compiling the source file with -fno-limit-debug-info or "
1733                      "disable -gmodule",
1734                      die.GetOffset(), type_die_ref.die_offset);
1735                else
1736                  module_sp->ReportError(
1737                      "DWARF DW_TAG_array_type DIE at 0x%8.8x has a "
1738                      "class/union/struct element type DIE 0x%8.8x that is a "
1739                      "forward declaration, not a complete definition.\nPlease "
1740                      "file a bug against the compiler and include the "
1741                      "preprocessed output for %s",
1742                      die.GetOffset(), type_die_ref.die_offset,
1743                      die.GetLLDBCompileUnit()
1744                          ? die.GetLLDBCompileUnit()->GetPath().c_str()
1745                          : "the source file");
1746              }
1747
1748              // We have no choice other than to pretend that the element class
1749              // type
1750              // is complete. If we don't do this, clang will crash when trying
1751              // to layout the class. Since we provide layout assistance, all
1752              // ivars in this class and other classes will be fine, this is
1753              // the best we can do short of crashing.
1754              if (ClangASTContext::StartTagDeclarationDefinition(
1755                      array_element_type)) {
1756                ClangASTContext::CompleteTagDeclarationDefinition(
1757                    array_element_type);
1758              } else {
1759                module_sp->ReportError("DWARF DIE at 0x%8.8x was not able to "
1760                                       "start its definition.\nPlease file a "
1761                                       "bug and attach the file at the start "
1762                                       "of this error message",
1763                                       type_die_ref.die_offset);
1764              }
1765            }
1766
1767            uint64_t array_element_bit_stride = byte_stride * 8 + bit_stride;
1768            if (element_orders.size() > 0) {
1769              uint64_t num_elements = 0;
1770              std::vector<uint64_t>::const_reverse_iterator pos;
1771              std::vector<uint64_t>::const_reverse_iterator end =
1772                  element_orders.rend();
1773              for (pos = element_orders.rbegin(); pos != end; ++pos) {
1774                num_elements = *pos;
1775                clang_type = m_ast.CreateArrayType(array_element_type,
1776                                                   num_elements, is_vector);
1777                array_element_type = clang_type;
1778                array_element_bit_stride =
1779                    num_elements ? array_element_bit_stride * num_elements
1780                                 : array_element_bit_stride;
1781              }
1782            } else {
1783              clang_type =
1784                  m_ast.CreateArrayType(array_element_type, 0, is_vector);
1785            }
1786            ConstString empty_name;
1787            type_sp.reset(new Type(
1788                die.GetID(), dwarf, empty_name, array_element_bit_stride / 8,
1789                NULL, DIERef(type_die_form).GetUID(dwarf), Type::eEncodingIsUID,
1790                &decl, clang_type, Type::eResolveStateFull));
1791            type_sp->SetEncodingType(element_type);
1792          }
1793        }
1794      } break;
1795
1796      case DW_TAG_ptr_to_member_type: {
1797        DWARFFormValue type_die_form;
1798        DWARFFormValue containing_type_die_form;
1799
1800        const size_t num_attributes = die.GetAttributes(attributes);
1801
1802        if (num_attributes > 0) {
1803          uint32_t i;
1804          for (i = 0; i < num_attributes; ++i) {
1805            attr = attributes.AttributeAtIndex(i);
1806            if (attributes.ExtractFormValueAtIndex(i, form_value)) {
1807              switch (attr) {
1808              case DW_AT_type:
1809                type_die_form = form_value;
1810                break;
1811              case DW_AT_containing_type:
1812                containing_type_die_form = form_value;
1813                break;
1814              }
1815            }
1816          }
1817
1818          Type *pointee_type = dwarf->ResolveTypeUID(DIERef(type_die_form));
1819          Type *class_type =
1820              dwarf->ResolveTypeUID(DIERef(containing_type_die_form));
1821
1822          CompilerType pointee_clang_type =
1823              pointee_type->GetForwardCompilerType();
1824          CompilerType class_clang_type = class_type->GetLayoutCompilerType();
1825
1826          clang_type = ClangASTContext::CreateMemberPointerType(
1827              class_clang_type, pointee_clang_type);
1828
1829          byte_size = clang_type.GetByteSize(nullptr);
1830
1831          type_sp.reset(new Type(die.GetID(), dwarf, type_name_const_str,
1832                                 byte_size, NULL, LLDB_INVALID_UID,
1833                                 Type::eEncodingIsUID, NULL, clang_type,
1834                                 Type::eResolveStateForward));
1835        }
1836
1837        break;
1838      }
1839      default:
1840        dwarf->GetObjectFile()->GetModule()->ReportError(
1841            "{0x%8.8x}: unhandled type tag 0x%4.4x (%s), please file a bug and "
1842            "attach the file at the start of this error message",
1843            die.GetOffset(), tag, DW_TAG_value_to_name(tag));
1844        break;
1845      }
1846
1847      if (type_sp.get()) {
1848        DWARFDIE sc_parent_die =
1849            SymbolFileDWARF::GetParentSymbolContextDIE(die);
1850        dw_tag_t sc_parent_tag = sc_parent_die.Tag();
1851
1852        SymbolContextScope *symbol_context_scope = NULL;
1853        if (sc_parent_tag == DW_TAG_compile_unit) {
1854          symbol_context_scope = sc.comp_unit;
1855        } else if (sc.function != NULL && sc_parent_die) {
1856          symbol_context_scope =
1857              sc.function->GetBlock(true).FindBlockByID(sc_parent_die.GetID());
1858          if (symbol_context_scope == NULL)
1859            symbol_context_scope = sc.function;
1860        }
1861
1862        if (symbol_context_scope != NULL) {
1863          type_sp->SetSymbolContextScope(symbol_context_scope);
1864        }
1865
1866        // We are ready to put this type into the uniqued list up at the module
1867        // level
1868        type_list->Insert(type_sp);
1869
1870        dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
1871      }
1872    } else if (type_ptr != DIE_IS_BEING_PARSED) {
1873      type_sp = type_ptr->shared_from_this();
1874    }
1875  }
1876  return type_sp;
1877}
1878
1879// DWARF parsing functions
1880
1881class DWARFASTParserClang::DelayedAddObjCClassProperty {
1882public:
1883  DelayedAddObjCClassProperty(
1884      const CompilerType &class_opaque_type, const char *property_name,
1885      const CompilerType &property_opaque_type, // The property type is only
1886                                                // required if you don't have an
1887                                                // ivar decl
1888      clang::ObjCIvarDecl *ivar_decl, const char *property_setter_name,
1889      const char *property_getter_name, uint32_t property_attributes,
1890      const ClangASTMetadata *metadata)
1891      : m_class_opaque_type(class_opaque_type), m_property_name(property_name),
1892        m_property_opaque_type(property_opaque_type), m_ivar_decl(ivar_decl),
1893        m_property_setter_name(property_setter_name),
1894        m_property_getter_name(property_getter_name),
1895        m_property_attributes(property_attributes) {
1896    if (metadata != NULL) {
1897      m_metadata_ap.reset(new ClangASTMetadata());
1898      *m_metadata_ap = *metadata;
1899    }
1900  }
1901
1902  DelayedAddObjCClassProperty(const DelayedAddObjCClassProperty &rhs) {
1903    *this = rhs;
1904  }
1905
1906  DelayedAddObjCClassProperty &
1907  operator=(const DelayedAddObjCClassProperty &rhs) {
1908    m_class_opaque_type = rhs.m_class_opaque_type;
1909    m_property_name = rhs.m_property_name;
1910    m_property_opaque_type = rhs.m_property_opaque_type;
1911    m_ivar_decl = rhs.m_ivar_decl;
1912    m_property_setter_name = rhs.m_property_setter_name;
1913    m_property_getter_name = rhs.m_property_getter_name;
1914    m_property_attributes = rhs.m_property_attributes;
1915
1916    if (rhs.m_metadata_ap.get()) {
1917      m_metadata_ap.reset(new ClangASTMetadata());
1918      *m_metadata_ap = *rhs.m_metadata_ap;
1919    }
1920    return *this;
1921  }
1922
1923  bool Finalize() {
1924    return ClangASTContext::AddObjCClassProperty(
1925        m_class_opaque_type, m_property_name, m_property_opaque_type,
1926        m_ivar_decl, m_property_setter_name, m_property_getter_name,
1927        m_property_attributes, m_metadata_ap.get());
1928  }
1929
1930private:
1931  CompilerType m_class_opaque_type;
1932  const char *m_property_name;
1933  CompilerType m_property_opaque_type;
1934  clang::ObjCIvarDecl *m_ivar_decl;
1935  const char *m_property_setter_name;
1936  const char *m_property_getter_name;
1937  uint32_t m_property_attributes;
1938  std::unique_ptr<ClangASTMetadata> m_metadata_ap;
1939};
1940
1941bool DWARFASTParserClang::ParseTemplateDIE(
1942    const DWARFDIE &die,
1943    ClangASTContext::TemplateParameterInfos &template_param_infos) {
1944  const dw_tag_t tag = die.Tag();
1945
1946  switch (tag) {
1947  case DW_TAG_GNU_template_parameter_pack: {
1948    template_param_infos.packed_args.reset(
1949      new ClangASTContext::TemplateParameterInfos);
1950    for (DWARFDIE child_die = die.GetFirstChild(); child_die.IsValid();
1951         child_die = child_die.GetSibling()) {
1952      if (!ParseTemplateDIE(child_die, *template_param_infos.packed_args))
1953        return false;
1954    }
1955    if (const char *name = die.GetName()) {
1956      template_param_infos.pack_name = name;
1957    }
1958    return true;
1959  }
1960  case DW_TAG_template_type_parameter:
1961  case DW_TAG_template_value_parameter: {
1962    DWARFAttributes attributes;
1963    const size_t num_attributes = die.GetAttributes(attributes);
1964    const char *name = nullptr;
1965    CompilerType clang_type;
1966    uint64_t uval64 = 0;
1967    bool uval64_valid = false;
1968    if (num_attributes > 0) {
1969      DWARFFormValue form_value;
1970      for (size_t i = 0; i < num_attributes; ++i) {
1971        const dw_attr_t attr = attributes.AttributeAtIndex(i);
1972
1973        switch (attr) {
1974        case DW_AT_name:
1975          if (attributes.ExtractFormValueAtIndex(i, form_value))
1976            name = form_value.AsCString();
1977          break;
1978
1979        case DW_AT_type:
1980          if (attributes.ExtractFormValueAtIndex(i, form_value)) {
1981            Type *lldb_type = die.ResolveTypeUID(DIERef(form_value));
1982            if (lldb_type)
1983              clang_type = lldb_type->GetForwardCompilerType();
1984          }
1985          break;
1986
1987        case DW_AT_const_value:
1988          if (attributes.ExtractFormValueAtIndex(i, form_value)) {
1989            uval64_valid = true;
1990            uval64 = form_value.Unsigned();
1991          }
1992          break;
1993        default:
1994          break;
1995        }
1996      }
1997
1998      clang::ASTContext *ast = m_ast.getASTContext();
1999      if (!clang_type)
2000        clang_type = m_ast.GetBasicType(eBasicTypeVoid);
2001
2002      if (clang_type) {
2003        bool is_signed = false;
2004        if (name && name[0])
2005          template_param_infos.names.push_back(name);
2006        else
2007          template_param_infos.names.push_back(NULL);
2008
2009        // Get the signed value for any integer or enumeration if available
2010        clang_type.IsIntegerOrEnumerationType(is_signed);
2011
2012        if (tag == DW_TAG_template_value_parameter && uval64_valid) {
2013          llvm::APInt apint(clang_type.GetBitSize(nullptr), uval64, is_signed);
2014          template_param_infos.args.push_back(
2015              clang::TemplateArgument(*ast, llvm::APSInt(apint, !is_signed),
2016                                      ClangUtil::GetQualType(clang_type)));
2017        } else {
2018          template_param_infos.args.push_back(
2019              clang::TemplateArgument(ClangUtil::GetQualType(clang_type)));
2020        }
2021      } else {
2022        return false;
2023      }
2024    }
2025  }
2026    return true;
2027
2028  default:
2029    break;
2030  }
2031  return false;
2032}
2033
2034bool DWARFASTParserClang::ParseTemplateParameterInfos(
2035    const DWARFDIE &parent_die,
2036    ClangASTContext::TemplateParameterInfos &template_param_infos) {
2037
2038  if (!parent_die)
2039    return false;
2040
2041  Args template_parameter_names;
2042  for (DWARFDIE die = parent_die.GetFirstChild(); die.IsValid();
2043       die = die.GetSibling()) {
2044    const dw_tag_t tag = die.Tag();
2045
2046    switch (tag) {
2047    case DW_TAG_template_type_parameter:
2048    case DW_TAG_template_value_parameter:
2049    case DW_TAG_GNU_template_parameter_pack:
2050      ParseTemplateDIE(die, template_param_infos);
2051      break;
2052
2053    default:
2054      break;
2055    }
2056  }
2057  if (template_param_infos.args.empty())
2058    return false;
2059  return template_param_infos.args.size() == template_param_infos.names.size();
2060}
2061
2062bool DWARFASTParserClang::CompleteTypeFromDWARF(const DWARFDIE &die,
2063                                                lldb_private::Type *type,
2064                                                CompilerType &clang_type) {
2065  SymbolFileDWARF *dwarf = die.GetDWARF();
2066
2067  std::lock_guard<std::recursive_mutex> guard(
2068      dwarf->GetObjectFile()->GetModule()->GetMutex());
2069
2070  // Disable external storage for this type so we don't get anymore
2071  // clang::ExternalASTSource queries for this type.
2072  m_ast.SetHasExternalStorage(clang_type.GetOpaqueQualType(), false);
2073
2074  if (!die)
2075    return false;
2076
2077#if defined LLDB_CONFIGURATION_DEBUG
2078  //----------------------------------------------------------------------
2079  // For debugging purposes, the LLDB_DWARF_DONT_COMPLETE_TYPENAMES
2080  // environment variable can be set with one or more typenames separated
2081  // by ';' characters. This will cause this function to not complete any
2082  // types whose names match.
2083  //
2084  // Examples of setting this environment variable:
2085  //
2086  // LLDB_DWARF_DONT_COMPLETE_TYPENAMES=Foo
2087  // LLDB_DWARF_DONT_COMPLETE_TYPENAMES=Foo;Bar;Baz
2088  //----------------------------------------------------------------------
2089  const char *dont_complete_typenames_cstr =
2090      getenv("LLDB_DWARF_DONT_COMPLETE_TYPENAMES");
2091  if (dont_complete_typenames_cstr && dont_complete_typenames_cstr[0]) {
2092    const char *die_name = die.GetName();
2093    if (die_name && die_name[0]) {
2094      const char *match = strstr(dont_complete_typenames_cstr, die_name);
2095      if (match) {
2096        size_t die_name_length = strlen(die_name);
2097        while (match) {
2098          const char separator_char = ';';
2099          const char next_char = match[die_name_length];
2100          if (next_char == '\0' || next_char == separator_char) {
2101            if (match == dont_complete_typenames_cstr ||
2102                match[-1] == separator_char)
2103              return false;
2104          }
2105          match = strstr(match + 1, die_name);
2106        }
2107      }
2108    }
2109  }
2110#endif
2111
2112  const dw_tag_t tag = die.Tag();
2113
2114  Log *log =
2115      nullptr; // (LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO|DWARF_LOG_TYPE_COMPLETION));
2116  if (log)
2117    dwarf->GetObjectFile()->GetModule()->LogMessageVerboseBacktrace(
2118        log, "0x%8.8" PRIx64 ": %s '%s' resolving forward declaration...",
2119        die.GetID(), die.GetTagAsCString(), type->GetName().AsCString());
2120  assert(clang_type);
2121  DWARFAttributes attributes;
2122  switch (tag) {
2123  case DW_TAG_structure_type:
2124  case DW_TAG_union_type:
2125  case DW_TAG_class_type: {
2126    ClangASTImporter::LayoutInfo layout_info;
2127
2128    {
2129      if (die.HasChildren()) {
2130        LanguageType class_language = eLanguageTypeUnknown;
2131        if (ClangASTContext::IsObjCObjectOrInterfaceType(clang_type)) {
2132          class_language = eLanguageTypeObjC;
2133          // For objective C we don't start the definition when
2134          // the class is created.
2135          ClangASTContext::StartTagDeclarationDefinition(clang_type);
2136        }
2137
2138        int tag_decl_kind = -1;
2139        AccessType default_accessibility = eAccessNone;
2140        if (tag == DW_TAG_structure_type) {
2141          tag_decl_kind = clang::TTK_Struct;
2142          default_accessibility = eAccessPublic;
2143        } else if (tag == DW_TAG_union_type) {
2144          tag_decl_kind = clang::TTK_Union;
2145          default_accessibility = eAccessPublic;
2146        } else if (tag == DW_TAG_class_type) {
2147          tag_decl_kind = clang::TTK_Class;
2148          default_accessibility = eAccessPrivate;
2149        }
2150
2151        SymbolContext sc(die.GetLLDBCompileUnit());
2152        std::vector<clang::CXXBaseSpecifier *> base_classes;
2153        std::vector<int> member_accessibilities;
2154        bool is_a_class = false;
2155        // Parse members and base classes first
2156        DWARFDIECollection member_function_dies;
2157
2158        DelayedPropertyList delayed_properties;
2159        ParseChildMembers(sc, die, clang_type, class_language, base_classes,
2160                          member_accessibilities, member_function_dies,
2161                          delayed_properties, default_accessibility, is_a_class,
2162                          layout_info);
2163
2164        // Now parse any methods if there were any...
2165        size_t num_functions = member_function_dies.Size();
2166        if (num_functions > 0) {
2167          for (size_t i = 0; i < num_functions; ++i) {
2168            dwarf->ResolveType(member_function_dies.GetDIEAtIndex(i));
2169          }
2170        }
2171
2172        if (class_language == eLanguageTypeObjC) {
2173          ConstString class_name(clang_type.GetTypeName());
2174          if (class_name) {
2175            DIEArray method_die_offsets;
2176            dwarf->GetObjCMethodDIEOffsets(class_name, method_die_offsets);
2177
2178            if (!method_die_offsets.empty()) {
2179              DWARFDebugInfo *debug_info = dwarf->DebugInfo();
2180
2181              const size_t num_matches = method_die_offsets.size();
2182              for (size_t i = 0; i < num_matches; ++i) {
2183                const DIERef &die_ref = method_die_offsets[i];
2184                DWARFDIE method_die = debug_info->GetDIE(die_ref);
2185
2186                if (method_die)
2187                  method_die.ResolveType();
2188              }
2189            }
2190
2191            for (DelayedPropertyList::iterator pi = delayed_properties.begin(),
2192                                               pe = delayed_properties.end();
2193                 pi != pe; ++pi)
2194              pi->Finalize();
2195          }
2196        }
2197
2198        // If we have a DW_TAG_structure_type instead of a DW_TAG_class_type we
2199        // need to tell the clang type it is actually a class.
2200        if (class_language != eLanguageTypeObjC) {
2201          if (is_a_class && tag_decl_kind != clang::TTK_Class)
2202            m_ast.SetTagTypeKind(ClangUtil::GetQualType(clang_type),
2203                                 clang::TTK_Class);
2204        }
2205
2206        // Since DW_TAG_structure_type gets used for both classes
2207        // and structures, we may need to set any DW_TAG_member
2208        // fields to have a "private" access if none was specified.
2209        // When we parsed the child members we tracked that actual
2210        // accessibility value for each DW_TAG_member in the
2211        // "member_accessibilities" array. If the value for the
2212        // member is zero, then it was set to the "default_accessibility"
2213        // which for structs was "public". Below we correct this
2214        // by setting any fields to "private" that weren't correctly
2215        // set.
2216        if (is_a_class && !member_accessibilities.empty()) {
2217          // This is a class and all members that didn't have
2218          // their access specified are private.
2219          m_ast.SetDefaultAccessForRecordFields(
2220              m_ast.GetAsRecordDecl(clang_type), eAccessPrivate,
2221              &member_accessibilities.front(), member_accessibilities.size());
2222        }
2223
2224        if (!base_classes.empty()) {
2225          // Make sure all base classes refer to complete types and not
2226          // forward declarations. If we don't do this, clang will crash
2227          // with an assertion in the call to
2228          // clang_type.SetBaseClassesForClassType()
2229          for (auto &base_class : base_classes) {
2230            clang::TypeSourceInfo *type_source_info =
2231                base_class->getTypeSourceInfo();
2232            if (type_source_info) {
2233              CompilerType base_class_type(
2234                  &m_ast, type_source_info->getType().getAsOpaquePtr());
2235              if (base_class_type.GetCompleteType() == false) {
2236                auto module = dwarf->GetObjectFile()->GetModule();
2237                module->ReportError(":: Class '%s' has a base class '%s' which "
2238                                    "does not have a complete definition.",
2239                                    die.GetName(),
2240                                    base_class_type.GetTypeName().GetCString());
2241                if (die.GetCU()->GetProducer() ==
2242                    DWARFCompileUnit::eProducerClang)
2243                  module->ReportError(":: Try compiling the source file with "
2244                                      "-fno-limit-debug-info.");
2245
2246                // We have no choice other than to pretend that the base class
2247                // is complete. If we don't do this, clang will crash when we
2248                // call setBases() inside of
2249                // "clang_type.SetBaseClassesForClassType()"
2250                // below. Since we provide layout assistance, all ivars in this
2251                // class and other classes will be fine, this is the best we can
2252                // do
2253                // short of crashing.
2254                if (ClangASTContext::StartTagDeclarationDefinition(
2255                        base_class_type)) {
2256                  ClangASTContext::CompleteTagDeclarationDefinition(
2257                      base_class_type);
2258                }
2259              }
2260            }
2261          }
2262          m_ast.SetBaseClassesForClassType(clang_type.GetOpaqueQualType(),
2263                                           &base_classes.front(),
2264                                           base_classes.size());
2265
2266          // Clang will copy each CXXBaseSpecifier in "base_classes"
2267          // so we have to free them all.
2268          ClangASTContext::DeleteBaseClassSpecifiers(&base_classes.front(),
2269                                                     base_classes.size());
2270        }
2271      }
2272    }
2273
2274    ClangASTContext::BuildIndirectFields(clang_type);
2275    ClangASTContext::CompleteTagDeclarationDefinition(clang_type);
2276
2277    if (!layout_info.field_offsets.empty() ||
2278        !layout_info.base_offsets.empty() ||
2279        !layout_info.vbase_offsets.empty()) {
2280      if (type)
2281        layout_info.bit_size = type->GetByteSize() * 8;
2282      if (layout_info.bit_size == 0)
2283        layout_info.bit_size =
2284            die.GetAttributeValueAsUnsigned(DW_AT_byte_size, 0) * 8;
2285
2286      clang::CXXRecordDecl *record_decl =
2287          m_ast.GetAsCXXRecordDecl(clang_type.GetOpaqueQualType());
2288      if (record_decl) {
2289        if (log) {
2290          ModuleSP module_sp = dwarf->GetObjectFile()->GetModule();
2291
2292          if (module_sp) {
2293            module_sp->LogMessage(
2294                log,
2295                "ClangASTContext::CompleteTypeFromDWARF (clang_type = %p) "
2296                "caching layout info for record_decl = %p, bit_size = %" PRIu64
2297                ", alignment = %" PRIu64
2298                ", field_offsets[%u], base_offsets[%u], vbase_offsets[%u])",
2299                static_cast<void *>(clang_type.GetOpaqueQualType()),
2300                static_cast<void *>(record_decl), layout_info.bit_size,
2301                layout_info.alignment,
2302                static_cast<uint32_t>(layout_info.field_offsets.size()),
2303                static_cast<uint32_t>(layout_info.base_offsets.size()),
2304                static_cast<uint32_t>(layout_info.vbase_offsets.size()));
2305
2306            uint32_t idx;
2307            {
2308              llvm::DenseMap<const clang::FieldDecl *, uint64_t>::const_iterator
2309                  pos,
2310                  end = layout_info.field_offsets.end();
2311              for (idx = 0, pos = layout_info.field_offsets.begin(); pos != end;
2312                   ++pos, ++idx) {
2313                module_sp->LogMessage(
2314                    log, "ClangASTContext::CompleteTypeFromDWARF (clang_type = "
2315                         "%p) field[%u] = { bit_offset=%u, name='%s' }",
2316                    static_cast<void *>(clang_type.GetOpaqueQualType()), idx,
2317                    static_cast<uint32_t>(pos->second),
2318                    pos->first->getNameAsString().c_str());
2319              }
2320            }
2321
2322            {
2323              llvm::DenseMap<const clang::CXXRecordDecl *,
2324                             clang::CharUnits>::const_iterator base_pos,
2325                  base_end = layout_info.base_offsets.end();
2326              for (idx = 0, base_pos = layout_info.base_offsets.begin();
2327                   base_pos != base_end; ++base_pos, ++idx) {
2328                module_sp->LogMessage(
2329                    log, "ClangASTContext::CompleteTypeFromDWARF (clang_type = "
2330                         "%p) base[%u] = { byte_offset=%u, name='%s' }",
2331                    clang_type.GetOpaqueQualType(), idx,
2332                    (uint32_t)base_pos->second.getQuantity(),
2333                    base_pos->first->getNameAsString().c_str());
2334              }
2335            }
2336            {
2337              llvm::DenseMap<const clang::CXXRecordDecl *,
2338                             clang::CharUnits>::const_iterator vbase_pos,
2339                  vbase_end = layout_info.vbase_offsets.end();
2340              for (idx = 0, vbase_pos = layout_info.vbase_offsets.begin();
2341                   vbase_pos != vbase_end; ++vbase_pos, ++idx) {
2342                module_sp->LogMessage(
2343                    log, "ClangASTContext::CompleteTypeFromDWARF (clang_type = "
2344                         "%p) vbase[%u] = { byte_offset=%u, name='%s' }",
2345                    static_cast<void *>(clang_type.GetOpaqueQualType()), idx,
2346                    static_cast<uint32_t>(vbase_pos->second.getQuantity()),
2347                    vbase_pos->first->getNameAsString().c_str());
2348              }
2349            }
2350          }
2351        }
2352        GetClangASTImporter().InsertRecordDecl(record_decl, layout_info);
2353      }
2354    }
2355  }
2356
2357    return (bool)clang_type;
2358
2359  case DW_TAG_enumeration_type:
2360    if (ClangASTContext::StartTagDeclarationDefinition(clang_type)) {
2361      if (die.HasChildren()) {
2362        SymbolContext sc(die.GetLLDBCompileUnit());
2363        bool is_signed = false;
2364        clang_type.IsIntegerType(is_signed);
2365        ParseChildEnumerators(sc, clang_type, is_signed, type->GetByteSize(),
2366                              die);
2367      }
2368      ClangASTContext::CompleteTagDeclarationDefinition(clang_type);
2369    }
2370    return (bool)clang_type;
2371
2372  default:
2373    assert(false && "not a forward clang type decl!");
2374    break;
2375  }
2376
2377  return false;
2378}
2379
2380std::vector<DWARFDIE> DWARFASTParserClang::GetDIEForDeclContext(
2381    lldb_private::CompilerDeclContext decl_context) {
2382  std::vector<DWARFDIE> result;
2383  for (auto it = m_decl_ctx_to_die.find(
2384           (clang::DeclContext *)decl_context.GetOpaqueDeclContext());
2385       it != m_decl_ctx_to_die.end(); it++)
2386    result.push_back(it->second);
2387  return result;
2388}
2389
2390CompilerDecl DWARFASTParserClang::GetDeclForUIDFromDWARF(const DWARFDIE &die) {
2391  clang::Decl *clang_decl = GetClangDeclForDIE(die);
2392  if (clang_decl != nullptr)
2393    return CompilerDecl(&m_ast, clang_decl);
2394  return CompilerDecl();
2395}
2396
2397CompilerDeclContext
2398DWARFASTParserClang::GetDeclContextForUIDFromDWARF(const DWARFDIE &die) {
2399  clang::DeclContext *clang_decl_ctx = GetClangDeclContextForDIE(die);
2400  if (clang_decl_ctx)
2401    return CompilerDeclContext(&m_ast, clang_decl_ctx);
2402  return CompilerDeclContext();
2403}
2404
2405CompilerDeclContext
2406DWARFASTParserClang::GetDeclContextContainingUIDFromDWARF(const DWARFDIE &die) {
2407  clang::DeclContext *clang_decl_ctx =
2408      GetClangDeclContextContainingDIE(die, nullptr);
2409  if (clang_decl_ctx)
2410    return CompilerDeclContext(&m_ast, clang_decl_ctx);
2411  return CompilerDeclContext();
2412}
2413
2414size_t DWARFASTParserClang::ParseChildEnumerators(
2415    const SymbolContext &sc, lldb_private::CompilerType &clang_type,
2416    bool is_signed, uint32_t enumerator_byte_size, const DWARFDIE &parent_die) {
2417  if (!parent_die)
2418    return 0;
2419
2420  size_t enumerators_added = 0;
2421
2422  for (DWARFDIE die = parent_die.GetFirstChild(); die.IsValid();
2423       die = die.GetSibling()) {
2424    const dw_tag_t tag = die.Tag();
2425    if (tag == DW_TAG_enumerator) {
2426      DWARFAttributes attributes;
2427      const size_t num_child_attributes = die.GetAttributes(attributes);
2428      if (num_child_attributes > 0) {
2429        const char *name = NULL;
2430        bool got_value = false;
2431        int64_t enum_value = 0;
2432        Declaration decl;
2433
2434        uint32_t i;
2435        for (i = 0; i < num_child_attributes; ++i) {
2436          const dw_attr_t attr = attributes.AttributeAtIndex(i);
2437          DWARFFormValue form_value;
2438          if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2439            switch (attr) {
2440            case DW_AT_const_value:
2441              got_value = true;
2442              if (is_signed)
2443                enum_value = form_value.Signed();
2444              else
2445                enum_value = form_value.Unsigned();
2446              break;
2447
2448            case DW_AT_name:
2449              name = form_value.AsCString();
2450              break;
2451
2452            case DW_AT_description:
2453            default:
2454            case DW_AT_decl_file:
2455              decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
2456                  form_value.Unsigned()));
2457              break;
2458            case DW_AT_decl_line:
2459              decl.SetLine(form_value.Unsigned());
2460              break;
2461            case DW_AT_decl_column:
2462              decl.SetColumn(form_value.Unsigned());
2463              break;
2464            case DW_AT_sibling:
2465              break;
2466            }
2467          }
2468        }
2469
2470        if (name && name[0] && got_value) {
2471          m_ast.AddEnumerationValueToEnumerationType(
2472              clang_type.GetOpaqueQualType(),
2473              m_ast.GetEnumerationIntegerType(clang_type.GetOpaqueQualType()),
2474              decl, name, enum_value, enumerator_byte_size * 8);
2475          ++enumerators_added;
2476        }
2477      }
2478    }
2479  }
2480  return enumerators_added;
2481}
2482
2483#if defined(LLDB_CONFIGURATION_DEBUG) || defined(LLDB_CONFIGURATION_RELEASE)
2484
2485class DIEStack {
2486public:
2487  void Push(const DWARFDIE &die) { m_dies.push_back(die); }
2488
2489  void LogDIEs(Log *log) {
2490    StreamString log_strm;
2491    const size_t n = m_dies.size();
2492    log_strm.Printf("DIEStack[%" PRIu64 "]:\n", (uint64_t)n);
2493    for (size_t i = 0; i < n; i++) {
2494      std::string qualified_name;
2495      const DWARFDIE &die = m_dies[i];
2496      die.GetQualifiedName(qualified_name);
2497      log_strm.Printf("[%" PRIu64 "] 0x%8.8x: %s name='%s'\n", (uint64_t)i,
2498                      die.GetOffset(), die.GetTagAsCString(),
2499                      qualified_name.c_str());
2500    }
2501    log->PutCString(log_strm.GetData());
2502  }
2503  void Pop() { m_dies.pop_back(); }
2504
2505  class ScopedPopper {
2506  public:
2507    ScopedPopper(DIEStack &die_stack)
2508        : m_die_stack(die_stack), m_valid(false) {}
2509
2510    void Push(const DWARFDIE &die) {
2511      m_valid = true;
2512      m_die_stack.Push(die);
2513    }
2514
2515    ~ScopedPopper() {
2516      if (m_valid)
2517        m_die_stack.Pop();
2518    }
2519
2520  protected:
2521    DIEStack &m_die_stack;
2522    bool m_valid;
2523  };
2524
2525protected:
2526  typedef std::vector<DWARFDIE> Stack;
2527  Stack m_dies;
2528};
2529#endif
2530
2531Function *DWARFASTParserClang::ParseFunctionFromDWARF(const SymbolContext &sc,
2532                                                      const DWARFDIE &die) {
2533  DWARFRangeList func_ranges;
2534  const char *name = NULL;
2535  const char *mangled = NULL;
2536  int decl_file = 0;
2537  int decl_line = 0;
2538  int decl_column = 0;
2539  int call_file = 0;
2540  int call_line = 0;
2541  int call_column = 0;
2542  DWARFExpression frame_base(die.GetCU());
2543
2544  const dw_tag_t tag = die.Tag();
2545
2546  if (tag != DW_TAG_subprogram)
2547    return NULL;
2548
2549  if (die.GetDIENamesAndRanges(name, mangled, func_ranges, decl_file, decl_line,
2550                               decl_column, call_file, call_line, call_column,
2551                               &frame_base)) {
2552
2553    // Union of all ranges in the function DIE (if the function is
2554    // discontiguous)
2555    AddressRange func_range;
2556    lldb::addr_t lowest_func_addr = func_ranges.GetMinRangeBase(0);
2557    lldb::addr_t highest_func_addr = func_ranges.GetMaxRangeEnd(0);
2558    if (lowest_func_addr != LLDB_INVALID_ADDRESS &&
2559        lowest_func_addr <= highest_func_addr) {
2560      ModuleSP module_sp(die.GetModule());
2561      func_range.GetBaseAddress().ResolveAddressUsingFileSections(
2562          lowest_func_addr, module_sp->GetSectionList());
2563      if (func_range.GetBaseAddress().IsValid())
2564        func_range.SetByteSize(highest_func_addr - lowest_func_addr);
2565    }
2566
2567    if (func_range.GetBaseAddress().IsValid()) {
2568      Mangled func_name;
2569      if (mangled)
2570        func_name.SetValue(ConstString(mangled), true);
2571      else if (die.GetParent().Tag() == DW_TAG_compile_unit &&
2572               Language::LanguageIsCPlusPlus(die.GetLanguage()) && name &&
2573               strcmp(name, "main") != 0) {
2574        // If the mangled name is not present in the DWARF, generate the
2575        // demangled name
2576        // using the decl context. We skip if the function is "main" as its name
2577        // is
2578        // never mangled.
2579        bool is_static = false;
2580        bool is_variadic = false;
2581        bool has_template_params = false;
2582        unsigned type_quals = 0;
2583        std::vector<CompilerType> param_types;
2584        std::vector<clang::ParmVarDecl *> param_decls;
2585        DWARFDeclContext decl_ctx;
2586        StreamString sstr;
2587
2588        die.GetDWARFDeclContext(decl_ctx);
2589        sstr << decl_ctx.GetQualifiedName();
2590
2591        clang::DeclContext *containing_decl_ctx =
2592            GetClangDeclContextContainingDIE(die, nullptr);
2593        ParseChildParameters(sc, containing_decl_ctx, die, true, is_static,
2594                             is_variadic, has_template_params, param_types,
2595                             param_decls, type_quals);
2596        sstr << "(";
2597        for (size_t i = 0; i < param_types.size(); i++) {
2598          if (i > 0)
2599            sstr << ", ";
2600          sstr << param_types[i].GetTypeName();
2601        }
2602        if (is_variadic)
2603          sstr << ", ...";
2604        sstr << ")";
2605        if (type_quals & clang::Qualifiers::Const)
2606          sstr << " const";
2607
2608        func_name.SetValue(ConstString(sstr.GetString()), false);
2609      } else
2610        func_name.SetValue(ConstString(name), false);
2611
2612      FunctionSP func_sp;
2613      std::unique_ptr<Declaration> decl_ap;
2614      if (decl_file != 0 || decl_line != 0 || decl_column != 0)
2615        decl_ap.reset(new Declaration(
2616            sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(decl_file),
2617            decl_line, decl_column));
2618
2619      SymbolFileDWARF *dwarf = die.GetDWARF();
2620      // Supply the type _only_ if it has already been parsed
2621      Type *func_type = dwarf->GetDIEToType().lookup(die.GetDIE());
2622
2623      assert(func_type == NULL || func_type != DIE_IS_BEING_PARSED);
2624
2625      if (dwarf->FixupAddress(func_range.GetBaseAddress())) {
2626        const user_id_t func_user_id = die.GetID();
2627        func_sp.reset(new Function(sc.comp_unit,
2628                                   func_user_id, // UserID is the DIE offset
2629                                   func_user_id, func_name, func_type,
2630                                   func_range)); // first address range
2631
2632        if (func_sp.get() != NULL) {
2633          if (frame_base.IsValid())
2634            func_sp->GetFrameBaseExpression() = frame_base;
2635          sc.comp_unit->AddFunction(func_sp);
2636          return func_sp.get();
2637        }
2638      }
2639    }
2640  }
2641  return NULL;
2642}
2643
2644bool DWARFASTParserClang::ParseChildMembers(
2645    const SymbolContext &sc, const DWARFDIE &parent_die,
2646    CompilerType &class_clang_type, const LanguageType class_language,
2647    std::vector<clang::CXXBaseSpecifier *> &base_classes,
2648    std::vector<int> &member_accessibilities,
2649    DWARFDIECollection &member_function_dies,
2650    DelayedPropertyList &delayed_properties, AccessType &default_accessibility,
2651    bool &is_a_class, ClangASTImporter::LayoutInfo &layout_info) {
2652  if (!parent_die)
2653    return 0;
2654
2655  // Get the parent byte size so we can verify any members will fit
2656  const uint64_t parent_byte_size =
2657      parent_die.GetAttributeValueAsUnsigned(DW_AT_byte_size, UINT64_MAX);
2658  const uint64_t parent_bit_size =
2659      parent_byte_size == UINT64_MAX ? UINT64_MAX : parent_byte_size * 8;
2660
2661  uint32_t member_idx = 0;
2662  BitfieldInfo last_field_info;
2663
2664  ModuleSP module_sp = parent_die.GetDWARF()->GetObjectFile()->GetModule();
2665  ClangASTContext *ast =
2666      llvm::dyn_cast_or_null<ClangASTContext>(class_clang_type.GetTypeSystem());
2667  if (ast == nullptr)
2668    return 0;
2669
2670  for (DWARFDIE die = parent_die.GetFirstChild(); die.IsValid();
2671       die = die.GetSibling()) {
2672    dw_tag_t tag = die.Tag();
2673
2674    switch (tag) {
2675    case DW_TAG_member:
2676    case DW_TAG_APPLE_property: {
2677      DWARFAttributes attributes;
2678      const size_t num_attributes = die.GetAttributes(attributes);
2679      if (num_attributes > 0) {
2680        Declaration decl;
2681        // DWARFExpression location;
2682        const char *name = NULL;
2683        const char *prop_name = NULL;
2684        const char *prop_getter_name = NULL;
2685        const char *prop_setter_name = NULL;
2686        uint32_t prop_attributes = 0;
2687
2688        bool is_artificial = false;
2689        DWARFFormValue encoding_form;
2690        AccessType accessibility = eAccessNone;
2691        uint32_t member_byte_offset =
2692            (parent_die.Tag() == DW_TAG_union_type) ? 0 : UINT32_MAX;
2693        size_t byte_size = 0;
2694        int64_t bit_offset = 0;
2695        uint64_t data_bit_offset = UINT64_MAX;
2696        size_t bit_size = 0;
2697        bool is_external =
2698            false; // On DW_TAG_members, this means the member is static
2699        uint32_t i;
2700        for (i = 0; i < num_attributes && !is_artificial; ++i) {
2701          const dw_attr_t attr = attributes.AttributeAtIndex(i);
2702          DWARFFormValue form_value;
2703          if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2704            switch (attr) {
2705            case DW_AT_decl_file:
2706              decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
2707                  form_value.Unsigned()));
2708              break;
2709            case DW_AT_decl_line:
2710              decl.SetLine(form_value.Unsigned());
2711              break;
2712            case DW_AT_decl_column:
2713              decl.SetColumn(form_value.Unsigned());
2714              break;
2715            case DW_AT_name:
2716              name = form_value.AsCString();
2717              break;
2718            case DW_AT_type:
2719              encoding_form = form_value;
2720              break;
2721            case DW_AT_bit_offset:
2722              bit_offset = form_value.Signed();
2723              break;
2724            case DW_AT_bit_size:
2725              bit_size = form_value.Unsigned();
2726              break;
2727            case DW_AT_byte_size:
2728              byte_size = form_value.Unsigned();
2729              break;
2730            case DW_AT_data_bit_offset:
2731              data_bit_offset = form_value.Unsigned();
2732              break;
2733            case DW_AT_data_member_location:
2734              if (form_value.BlockData()) {
2735                Value initialValue(0);
2736                Value memberOffset(0);
2737                const DWARFDataExtractor &debug_info_data =
2738                    die.GetDWARF()->get_debug_info_data();
2739                uint32_t block_length = form_value.Unsigned();
2740                uint32_t block_offset =
2741                    form_value.BlockData() - debug_info_data.GetDataStart();
2742                if (DWARFExpression::Evaluate(
2743                        nullptr, // ExecutionContext *
2744                        nullptr, // ClangExpressionVariableList *
2745                        nullptr, // ClangExpressionDeclMap *
2746                        nullptr, // RegisterContext *
2747                        module_sp, debug_info_data, die.GetCU(), block_offset,
2748                        block_length, eRegisterKindDWARF, &initialValue,
2749                        nullptr, memberOffset, nullptr)) {
2750                  member_byte_offset = memberOffset.ResolveValue(NULL).UInt();
2751                }
2752              } else {
2753                // With DWARF 3 and later, if the value is an integer constant,
2754                // this form value is the offset in bytes from the beginning
2755                // of the containing entity.
2756                member_byte_offset = form_value.Unsigned();
2757              }
2758              break;
2759
2760            case DW_AT_accessibility:
2761              accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
2762              break;
2763            case DW_AT_artificial:
2764              is_artificial = form_value.Boolean();
2765              break;
2766            case DW_AT_APPLE_property_name:
2767              prop_name = form_value.AsCString();
2768              break;
2769            case DW_AT_APPLE_property_getter:
2770              prop_getter_name = form_value.AsCString();
2771              break;
2772            case DW_AT_APPLE_property_setter:
2773              prop_setter_name = form_value.AsCString();
2774              break;
2775            case DW_AT_APPLE_property_attribute:
2776              prop_attributes = form_value.Unsigned();
2777              break;
2778            case DW_AT_external:
2779              is_external = form_value.Boolean();
2780              break;
2781
2782            default:
2783            case DW_AT_declaration:
2784            case DW_AT_description:
2785            case DW_AT_mutable:
2786            case DW_AT_visibility:
2787            case DW_AT_sibling:
2788              break;
2789            }
2790          }
2791        }
2792
2793        if (prop_name) {
2794          ConstString fixed_getter;
2795          ConstString fixed_setter;
2796
2797          // Check if the property getter/setter were provided as full
2798          // names.  We want basenames, so we extract them.
2799
2800          if (prop_getter_name && prop_getter_name[0] == '-') {
2801            ObjCLanguage::MethodName prop_getter_method(prop_getter_name, true);
2802            prop_getter_name = prop_getter_method.GetSelector().GetCString();
2803          }
2804
2805          if (prop_setter_name && prop_setter_name[0] == '-') {
2806            ObjCLanguage::MethodName prop_setter_method(prop_setter_name, true);
2807            prop_setter_name = prop_setter_method.GetSelector().GetCString();
2808          }
2809
2810          // If the names haven't been provided, they need to be
2811          // filled in.
2812
2813          if (!prop_getter_name) {
2814            prop_getter_name = prop_name;
2815          }
2816          if (!prop_setter_name && prop_name[0] &&
2817              !(prop_attributes & DW_APPLE_PROPERTY_readonly)) {
2818            StreamString ss;
2819
2820            ss.Printf("set%c%s:", toupper(prop_name[0]), &prop_name[1]);
2821
2822            fixed_setter.SetString(ss.GetString());
2823            prop_setter_name = fixed_setter.GetCString();
2824          }
2825        }
2826
2827        // Clang has a DWARF generation bug where sometimes it
2828        // represents fields that are references with bad byte size
2829        // and bit size/offset information such as:
2830        //
2831        //  DW_AT_byte_size( 0x00 )
2832        //  DW_AT_bit_size( 0x40 )
2833        //  DW_AT_bit_offset( 0xffffffffffffffc0 )
2834        //
2835        // So check the bit offset to make sure it is sane, and if
2836        // the values are not sane, remove them. If we don't do this
2837        // then we will end up with a crash if we try to use this
2838        // type in an expression when clang becomes unhappy with its
2839        // recycled debug info.
2840
2841        if (byte_size == 0 && bit_offset < 0) {
2842          bit_size = 0;
2843          bit_offset = 0;
2844        }
2845
2846        // FIXME: Make Clang ignore Objective-C accessibility for expressions
2847        if (class_language == eLanguageTypeObjC ||
2848            class_language == eLanguageTypeObjC_plus_plus)
2849          accessibility = eAccessNone;
2850
2851        if (member_idx == 0 && !is_artificial && name &&
2852            (strstr(name, "_vptr$") == name)) {
2853          // Not all compilers will mark the vtable pointer
2854          // member as artificial (llvm-gcc). We can't have
2855          // the virtual members in our classes otherwise it
2856          // throws off all child offsets since we end up
2857          // having and extra pointer sized member in our
2858          // class layouts.
2859          is_artificial = true;
2860        }
2861
2862        // Handle static members
2863        if (is_external && member_byte_offset == UINT32_MAX) {
2864          Type *var_type = die.ResolveTypeUID(DIERef(encoding_form));
2865
2866          if (var_type) {
2867            if (accessibility == eAccessNone)
2868              accessibility = eAccessPublic;
2869            ClangASTContext::AddVariableToRecordType(
2870                class_clang_type, name, var_type->GetLayoutCompilerType(),
2871                accessibility);
2872          }
2873          break;
2874        }
2875
2876        if (is_artificial == false) {
2877          Type *member_type = die.ResolveTypeUID(DIERef(encoding_form));
2878
2879          clang::FieldDecl *field_decl = NULL;
2880          if (tag == DW_TAG_member) {
2881            if (member_type) {
2882              if (accessibility == eAccessNone)
2883                accessibility = default_accessibility;
2884              member_accessibilities.push_back(accessibility);
2885
2886              uint64_t field_bit_offset =
2887                  (member_byte_offset == UINT32_MAX ? 0
2888                                                    : (member_byte_offset * 8));
2889              if (bit_size > 0) {
2890
2891                BitfieldInfo this_field_info;
2892                this_field_info.bit_offset = field_bit_offset;
2893                this_field_info.bit_size = bit_size;
2894
2895                /////////////////////////////////////////////////////////////
2896                // How to locate a field given the DWARF debug information
2897                //
2898                // AT_byte_size indicates the size of the word in which the
2899                // bit offset must be interpreted.
2900                //
2901                // AT_data_member_location indicates the byte offset of the
2902                // word from the base address of the structure.
2903                //
2904                // AT_bit_offset indicates how many bits into the word
2905                // (according to the host endianness) the low-order bit of
2906                // the field starts.  AT_bit_offset can be negative.
2907                //
2908                // AT_bit_size indicates the size of the field in bits.
2909                /////////////////////////////////////////////////////////////
2910
2911                if (data_bit_offset != UINT64_MAX) {
2912                  this_field_info.bit_offset = data_bit_offset;
2913                } else {
2914                  if (byte_size == 0)
2915                    byte_size = member_type->GetByteSize();
2916
2917                  ObjectFile *objfile = die.GetDWARF()->GetObjectFile();
2918                  if (objfile->GetByteOrder() == eByteOrderLittle) {
2919                    this_field_info.bit_offset += byte_size * 8;
2920                    this_field_info.bit_offset -= (bit_offset + bit_size);
2921                  } else {
2922                    this_field_info.bit_offset += bit_offset;
2923                  }
2924                }
2925
2926                if ((this_field_info.bit_offset >= parent_bit_size) ||
2927                    !last_field_info.NextBitfieldOffsetIsValid(
2928                        this_field_info.bit_offset)) {
2929                  ObjectFile *objfile = die.GetDWARF()->GetObjectFile();
2930                  objfile->GetModule()->ReportWarning(
2931                      "0x%8.8" PRIx64 ": %s bitfield named \"%s\" has invalid "
2932                                      "bit offset (0x%8.8" PRIx64
2933                      ") member will be ignored. Please file a bug against the "
2934                      "compiler and include the preprocessed output for %s\n",
2935                      die.GetID(), DW_TAG_value_to_name(tag), name,
2936                      this_field_info.bit_offset,
2937                      sc.comp_unit ? sc.comp_unit->GetPath().c_str()
2938                                   : "the source file");
2939                  this_field_info.Clear();
2940                  continue;
2941                }
2942
2943                // Update the field bit offset we will report for layout
2944                field_bit_offset = this_field_info.bit_offset;
2945
2946                // If the member to be emitted did not start on a character
2947                // boundary and there is
2948                // empty space between the last field and this one, then we need
2949                // to emit an
2950                // anonymous member filling up the space up to its start.  There
2951                // are three cases
2952                // here:
2953                //
2954                // 1 If the previous member ended on a character boundary, then
2955                // we can emit an
2956                //   anonymous member starting at the most recent character
2957                //   boundary.
2958                //
2959                // 2 If the previous member did not end on a character boundary
2960                // and the distance
2961                //   from the end of the previous member to the current member
2962                //   is less than a
2963                //   word width, then we can emit an anonymous member starting
2964                //   right after the
2965                //   previous member and right before this member.
2966                //
2967                // 3 If the previous member did not end on a character boundary
2968                // and the distance
2969                //   from the end of the previous member to the current member
2970                //   is greater than
2971                //   or equal a word width, then we act as in Case 1.
2972
2973                const uint64_t character_width = 8;
2974                const uint64_t word_width = 32;
2975
2976                // Objective-C has invalid DW_AT_bit_offset values in older
2977                // versions
2978                // of clang, so we have to be careful and only insert unnamed
2979                // bitfields
2980                // if we have a new enough clang.
2981                bool detect_unnamed_bitfields = true;
2982
2983                if (class_language == eLanguageTypeObjC ||
2984                    class_language == eLanguageTypeObjC_plus_plus)
2985                  detect_unnamed_bitfields =
2986                      die.GetCU()->Supports_unnamed_objc_bitfields();
2987
2988                if (detect_unnamed_bitfields) {
2989                  BitfieldInfo anon_field_info;
2990
2991                  if ((this_field_info.bit_offset % character_width) !=
2992                      0) // not char aligned
2993                  {
2994                    uint64_t last_field_end = 0;
2995
2996                    if (last_field_info.IsValid())
2997                      last_field_end =
2998                          last_field_info.bit_offset + last_field_info.bit_size;
2999
3000                    if (this_field_info.bit_offset != last_field_end) {
3001                      if (((last_field_end % character_width) == 0) || // case 1
3002                          (this_field_info.bit_offset - last_field_end >=
3003                           word_width)) // case 3
3004                      {
3005                        anon_field_info.bit_size =
3006                            this_field_info.bit_offset % character_width;
3007                        anon_field_info.bit_offset =
3008                            this_field_info.bit_offset -
3009                            anon_field_info.bit_size;
3010                      } else // case 2
3011                      {
3012                        anon_field_info.bit_size =
3013                            this_field_info.bit_offset - last_field_end;
3014                        anon_field_info.bit_offset = last_field_end;
3015                      }
3016                    }
3017                  }
3018
3019                  if (anon_field_info.IsValid()) {
3020                    clang::FieldDecl *unnamed_bitfield_decl =
3021                        ClangASTContext::AddFieldToRecordType(
3022                            class_clang_type, NULL,
3023                            m_ast.GetBuiltinTypeForEncodingAndBitSize(
3024                                eEncodingSint, word_width),
3025                            accessibility, anon_field_info.bit_size);
3026
3027                    layout_info.field_offsets.insert(std::make_pair(
3028                        unnamed_bitfield_decl, anon_field_info.bit_offset));
3029                  }
3030                }
3031                last_field_info = this_field_info;
3032              } else {
3033                last_field_info.Clear();
3034              }
3035
3036              CompilerType member_clang_type =
3037                  member_type->GetLayoutCompilerType();
3038              if (!member_clang_type.IsCompleteType())
3039                member_clang_type.GetCompleteType();
3040
3041              {
3042                // Older versions of clang emit array[0] and array[1] in the
3043                // same way (<rdar://problem/12566646>).
3044                // If the current field is at the end of the structure, then
3045                // there is definitely no room for extra
3046                // elements and we override the type to array[0].
3047
3048                CompilerType member_array_element_type;
3049                uint64_t member_array_size;
3050                bool member_array_is_incomplete;
3051
3052                if (member_clang_type.IsArrayType(
3053                        &member_array_element_type, &member_array_size,
3054                        &member_array_is_incomplete) &&
3055                    !member_array_is_incomplete) {
3056                  uint64_t parent_byte_size =
3057                      parent_die.GetAttributeValueAsUnsigned(DW_AT_byte_size,
3058                                                             UINT64_MAX);
3059
3060                  if (member_byte_offset >= parent_byte_size) {
3061                    if (member_array_size != 1 &&
3062                        (member_array_size != 0 ||
3063                         member_byte_offset > parent_byte_size)) {
3064                      module_sp->ReportError(
3065                          "0x%8.8" PRIx64
3066                          ": DW_TAG_member '%s' refers to type 0x%8.8" PRIx64
3067                          " which extends beyond the bounds of 0x%8.8" PRIx64,
3068                          die.GetID(), name, encoding_form.Reference(),
3069                          parent_die.GetID());
3070                    }
3071
3072                    member_clang_type = m_ast.CreateArrayType(
3073                        member_array_element_type, 0, false);
3074                  }
3075                }
3076              }
3077
3078              if (ClangASTContext::IsCXXClassType(member_clang_type) &&
3079                  member_clang_type.GetCompleteType() == false) {
3080                if (die.GetCU()->GetProducer() ==
3081                    DWARFCompileUnit::eProducerClang)
3082                  module_sp->ReportError(
3083                      "DWARF DIE at 0x%8.8x (class %s) has a member variable "
3084                      "0x%8.8x (%s) whose type is a forward declaration, not a "
3085                      "complete definition.\nTry compiling the source file "
3086                      "with -fno-limit-debug-info",
3087                      parent_die.GetOffset(), parent_die.GetName(),
3088                      die.GetOffset(), name);
3089                else
3090                  module_sp->ReportError(
3091                      "DWARF DIE at 0x%8.8x (class %s) has a member variable "
3092                      "0x%8.8x (%s) whose type is a forward declaration, not a "
3093                      "complete definition.\nPlease file a bug against the "
3094                      "compiler and include the preprocessed output for %s",
3095                      parent_die.GetOffset(), parent_die.GetName(),
3096                      die.GetOffset(), name,
3097                      sc.comp_unit ? sc.comp_unit->GetPath().c_str()
3098                                   : "the source file");
3099                // We have no choice other than to pretend that the member class
3100                // is complete. If we don't do this, clang will crash when
3101                // trying
3102                // to layout the class. Since we provide layout assistance, all
3103                // ivars in this class and other classes will be fine, this is
3104                // the best we can do short of crashing.
3105                if (ClangASTContext::StartTagDeclarationDefinition(
3106                        member_clang_type)) {
3107                  ClangASTContext::CompleteTagDeclarationDefinition(
3108                      member_clang_type);
3109                } else {
3110                  module_sp->ReportError(
3111                      "DWARF DIE at 0x%8.8x (class %s) has a member variable "
3112                      "0x%8.8x (%s) whose type claims to be a C++ class but we "
3113                      "were not able to start its definition.\nPlease file a "
3114                      "bug and attach the file at the start of this error "
3115                      "message",
3116                      parent_die.GetOffset(), parent_die.GetName(),
3117                      die.GetOffset(), name);
3118                }
3119              }
3120
3121              field_decl = ClangASTContext::AddFieldToRecordType(
3122                  class_clang_type, name, member_clang_type, accessibility,
3123                  bit_size);
3124
3125              m_ast.SetMetadataAsUserID(field_decl, die.GetID());
3126
3127              layout_info.field_offsets.insert(
3128                  std::make_pair(field_decl, field_bit_offset));
3129            } else {
3130              if (name)
3131                module_sp->ReportError(
3132                    "0x%8.8" PRIx64
3133                    ": DW_TAG_member '%s' refers to type 0x%8.8" PRIx64
3134                    " which was unable to be parsed",
3135                    die.GetID(), name, encoding_form.Reference());
3136              else
3137                module_sp->ReportError(
3138                    "0x%8.8" PRIx64
3139                    ": DW_TAG_member refers to type 0x%8.8" PRIx64
3140                    " which was unable to be parsed",
3141                    die.GetID(), encoding_form.Reference());
3142            }
3143          }
3144
3145          if (prop_name != NULL && member_type) {
3146            clang::ObjCIvarDecl *ivar_decl = NULL;
3147
3148            if (field_decl) {
3149              ivar_decl = clang::dyn_cast<clang::ObjCIvarDecl>(field_decl);
3150              assert(ivar_decl != NULL);
3151            }
3152
3153            ClangASTMetadata metadata;
3154            metadata.SetUserID(die.GetID());
3155            delayed_properties.push_back(DelayedAddObjCClassProperty(
3156                class_clang_type, prop_name,
3157                member_type->GetLayoutCompilerType(), ivar_decl,
3158                prop_setter_name, prop_getter_name, prop_attributes,
3159                &metadata));
3160
3161            if (ivar_decl)
3162              m_ast.SetMetadataAsUserID(ivar_decl, die.GetID());
3163          }
3164        }
3165      }
3166      ++member_idx;
3167    } break;
3168
3169    case DW_TAG_subprogram:
3170      // Let the type parsing code handle this one for us.
3171      member_function_dies.Append(die);
3172      break;
3173
3174    case DW_TAG_inheritance: {
3175      is_a_class = true;
3176      if (default_accessibility == eAccessNone)
3177        default_accessibility = eAccessPrivate;
3178      // TODO: implement DW_TAG_inheritance type parsing
3179      DWARFAttributes attributes;
3180      const size_t num_attributes = die.GetAttributes(attributes);
3181      if (num_attributes > 0) {
3182        Declaration decl;
3183        DWARFExpression location(die.GetCU());
3184        DWARFFormValue encoding_form;
3185        AccessType accessibility = default_accessibility;
3186        bool is_virtual = false;
3187        bool is_base_of_class = true;
3188        off_t member_byte_offset = 0;
3189        uint32_t i;
3190        for (i = 0; i < num_attributes; ++i) {
3191          const dw_attr_t attr = attributes.AttributeAtIndex(i);
3192          DWARFFormValue form_value;
3193          if (attributes.ExtractFormValueAtIndex(i, form_value)) {
3194            switch (attr) {
3195            case DW_AT_decl_file:
3196              decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
3197                  form_value.Unsigned()));
3198              break;
3199            case DW_AT_decl_line:
3200              decl.SetLine(form_value.Unsigned());
3201              break;
3202            case DW_AT_decl_column:
3203              decl.SetColumn(form_value.Unsigned());
3204              break;
3205            case DW_AT_type:
3206              encoding_form = form_value;
3207              break;
3208            case DW_AT_data_member_location:
3209              if (form_value.BlockData()) {
3210                Value initialValue(0);
3211                Value memberOffset(0);
3212                const DWARFDataExtractor &debug_info_data =
3213                    die.GetDWARF()->get_debug_info_data();
3214                uint32_t block_length = form_value.Unsigned();
3215                uint32_t block_offset =
3216                    form_value.BlockData() - debug_info_data.GetDataStart();
3217                if (DWARFExpression::Evaluate(
3218                        nullptr, nullptr, nullptr, nullptr, module_sp,
3219                        debug_info_data, die.GetCU(), block_offset,
3220                        block_length, eRegisterKindDWARF, &initialValue,
3221                        nullptr, memberOffset, nullptr)) {
3222                  member_byte_offset = memberOffset.ResolveValue(NULL).UInt();
3223                }
3224              } else {
3225                // With DWARF 3 and later, if the value is an integer constant,
3226                // this form value is the offset in bytes from the beginning
3227                // of the containing entity.
3228                member_byte_offset = form_value.Unsigned();
3229              }
3230              break;
3231
3232            case DW_AT_accessibility:
3233              accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
3234              break;
3235
3236            case DW_AT_virtuality:
3237              is_virtual = form_value.Boolean();
3238              break;
3239
3240            case DW_AT_sibling:
3241              break;
3242
3243            default:
3244              break;
3245            }
3246          }
3247        }
3248
3249        Type *base_class_type = die.ResolveTypeUID(DIERef(encoding_form));
3250        if (base_class_type == NULL) {
3251          module_sp->ReportError("0x%8.8x: DW_TAG_inheritance failed to "
3252                                 "resolve the base class at 0x%8.8" PRIx64
3253                                 " from enclosing type 0x%8.8x. \nPlease file "
3254                                 "a bug and attach the file at the start of "
3255                                 "this error message",
3256                                 die.GetOffset(), encoding_form.Reference(),
3257                                 parent_die.GetOffset());
3258          break;
3259        }
3260
3261        CompilerType base_class_clang_type =
3262            base_class_type->GetFullCompilerType();
3263        assert(base_class_clang_type);
3264        if (class_language == eLanguageTypeObjC) {
3265          ast->SetObjCSuperClass(class_clang_type, base_class_clang_type);
3266        } else {
3267          base_classes.push_back(ast->CreateBaseClassSpecifier(
3268              base_class_clang_type.GetOpaqueQualType(), accessibility,
3269              is_virtual, is_base_of_class));
3270
3271          if (is_virtual) {
3272            // Do not specify any offset for virtual inheritance. The DWARF
3273            // produced by clang doesn't
3274            // give us a constant offset, but gives us a DWARF expressions that
3275            // requires an actual object
3276            // in memory. the DW_AT_data_member_location for a virtual base
3277            // class looks like:
3278            //      DW_AT_data_member_location( DW_OP_dup, DW_OP_deref,
3279            //      DW_OP_constu(0x00000018), DW_OP_minus, DW_OP_deref,
3280            //      DW_OP_plus )
3281            // Given this, there is really no valid response we can give to
3282            // clang for virtual base
3283            // class offsets, and this should eventually be removed from
3284            // LayoutRecordType() in the external
3285            // AST source in clang.
3286          } else {
3287            layout_info.base_offsets.insert(std::make_pair(
3288                ast->GetAsCXXRecordDecl(
3289                    base_class_clang_type.GetOpaqueQualType()),
3290                clang::CharUnits::fromQuantity(member_byte_offset)));
3291          }
3292        }
3293      }
3294    } break;
3295
3296    default:
3297      break;
3298    }
3299  }
3300
3301  return true;
3302}
3303
3304size_t DWARFASTParserClang::ParseChildParameters(
3305    const SymbolContext &sc, clang::DeclContext *containing_decl_ctx,
3306    const DWARFDIE &parent_die, bool skip_artificial, bool &is_static,
3307    bool &is_variadic, bool &has_template_params,
3308    std::vector<CompilerType> &function_param_types,
3309    std::vector<clang::ParmVarDecl *> &function_param_decls,
3310    unsigned &type_quals) {
3311  if (!parent_die)
3312    return 0;
3313
3314  size_t arg_idx = 0;
3315  for (DWARFDIE die = parent_die.GetFirstChild(); die.IsValid();
3316       die = die.GetSibling()) {
3317    const dw_tag_t tag = die.Tag();
3318    switch (tag) {
3319    case DW_TAG_formal_parameter: {
3320      DWARFAttributes attributes;
3321      const size_t num_attributes = die.GetAttributes(attributes);
3322      if (num_attributes > 0) {
3323        const char *name = NULL;
3324        Declaration decl;
3325        DWARFFormValue param_type_die_form;
3326        bool is_artificial = false;
3327        // one of None, Auto, Register, Extern, Static, PrivateExtern
3328
3329        clang::StorageClass storage = clang::SC_None;
3330        uint32_t i;
3331        for (i = 0; i < num_attributes; ++i) {
3332          const dw_attr_t attr = attributes.AttributeAtIndex(i);
3333          DWARFFormValue form_value;
3334          if (attributes.ExtractFormValueAtIndex(i, form_value)) {
3335            switch (attr) {
3336            case DW_AT_decl_file:
3337              decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
3338                  form_value.Unsigned()));
3339              break;
3340            case DW_AT_decl_line:
3341              decl.SetLine(form_value.Unsigned());
3342              break;
3343            case DW_AT_decl_column:
3344              decl.SetColumn(form_value.Unsigned());
3345              break;
3346            case DW_AT_name:
3347              name = form_value.AsCString();
3348              break;
3349            case DW_AT_type:
3350              param_type_die_form = form_value;
3351              break;
3352            case DW_AT_artificial:
3353              is_artificial = form_value.Boolean();
3354              break;
3355            case DW_AT_location:
3356            //                          if (form_value.BlockData())
3357            //                          {
3358            //                              const DWARFDataExtractor&
3359            //                              debug_info_data = debug_info();
3360            //                              uint32_t block_length =
3361            //                              form_value.Unsigned();
3362            //                              DWARFDataExtractor
3363            //                              location(debug_info_data,
3364            //                              form_value.BlockData() -
3365            //                              debug_info_data.GetDataStart(),
3366            //                              block_length);
3367            //                          }
3368            //                          else
3369            //                          {
3370            //                          }
3371            //                          break;
3372            case DW_AT_const_value:
3373            case DW_AT_default_value:
3374            case DW_AT_description:
3375            case DW_AT_endianity:
3376            case DW_AT_is_optional:
3377            case DW_AT_segment:
3378            case DW_AT_variable_parameter:
3379            default:
3380            case DW_AT_abstract_origin:
3381            case DW_AT_sibling:
3382              break;
3383            }
3384          }
3385        }
3386
3387        bool skip = false;
3388        if (skip_artificial) {
3389          if (is_artificial) {
3390            // In order to determine if a C++ member function is
3391            // "const" we have to look at the const-ness of "this"...
3392            // Ugly, but that
3393            if (arg_idx == 0) {
3394              if (DeclKindIsCXXClass(containing_decl_ctx->getDeclKind())) {
3395                // Often times compilers omit the "this" name for the
3396                // specification DIEs, so we can't rely upon the name
3397                // being in the formal parameter DIE...
3398                if (name == NULL || ::strcmp(name, "this") == 0) {
3399                  Type *this_type =
3400                      die.ResolveTypeUID(DIERef(param_type_die_form));
3401                  if (this_type) {
3402                    uint32_t encoding_mask = this_type->GetEncodingMask();
3403                    if (encoding_mask & Type::eEncodingIsPointerUID) {
3404                      is_static = false;
3405
3406                      if (encoding_mask & (1u << Type::eEncodingIsConstUID))
3407                        type_quals |= clang::Qualifiers::Const;
3408                      if (encoding_mask & (1u << Type::eEncodingIsVolatileUID))
3409                        type_quals |= clang::Qualifiers::Volatile;
3410                    }
3411                  }
3412                }
3413              }
3414            }
3415            skip = true;
3416          } else {
3417
3418            // HACK: Objective C formal parameters "self" and "_cmd"
3419            // are not marked as artificial in the DWARF...
3420            CompileUnit *comp_unit = die.GetLLDBCompileUnit();
3421            if (comp_unit) {
3422              switch (comp_unit->GetLanguage()) {
3423              case eLanguageTypeObjC:
3424              case eLanguageTypeObjC_plus_plus:
3425                if (name && name[0] &&
3426                    (strcmp(name, "self") == 0 || strcmp(name, "_cmd") == 0))
3427                  skip = true;
3428                break;
3429              default:
3430                break;
3431              }
3432            }
3433          }
3434        }
3435
3436        if (!skip) {
3437          Type *type = die.ResolveTypeUID(DIERef(param_type_die_form));
3438          if (type) {
3439            function_param_types.push_back(type->GetForwardCompilerType());
3440
3441            clang::ParmVarDecl *param_var_decl =
3442                m_ast.CreateParameterDeclaration(
3443                    name, type->GetForwardCompilerType(), storage);
3444            assert(param_var_decl);
3445            function_param_decls.push_back(param_var_decl);
3446
3447            m_ast.SetMetadataAsUserID(param_var_decl, die.GetID());
3448          }
3449        }
3450      }
3451      arg_idx++;
3452    } break;
3453
3454    case DW_TAG_unspecified_parameters:
3455      is_variadic = true;
3456      break;
3457
3458    case DW_TAG_template_type_parameter:
3459    case DW_TAG_template_value_parameter:
3460    case DW_TAG_GNU_template_parameter_pack:
3461      // The one caller of this was never using the template_param_infos,
3462      // and the local variable was taking up a large amount of stack space
3463      // in SymbolFileDWARF::ParseType() so this was removed. If we ever need
3464      // the template params back, we can add them back.
3465      // ParseTemplateDIE (dwarf_cu, die, template_param_infos);
3466      has_template_params = true;
3467      break;
3468
3469    default:
3470      break;
3471    }
3472  }
3473  return arg_idx;
3474}
3475
3476void DWARFASTParserClang::ParseChildArrayInfo(
3477    const SymbolContext &sc, const DWARFDIE &parent_die, int64_t &first_index,
3478    std::vector<uint64_t> &element_orders, uint32_t &byte_stride,
3479    uint32_t &bit_stride) {
3480  if (!parent_die)
3481    return;
3482
3483  for (DWARFDIE die = parent_die.GetFirstChild(); die.IsValid();
3484       die = die.GetSibling()) {
3485    const dw_tag_t tag = die.Tag();
3486    switch (tag) {
3487    case DW_TAG_subrange_type: {
3488      DWARFAttributes attributes;
3489      const size_t num_child_attributes = die.GetAttributes(attributes);
3490      if (num_child_attributes > 0) {
3491        uint64_t num_elements = 0;
3492        uint64_t lower_bound = 0;
3493        uint64_t upper_bound = 0;
3494        bool upper_bound_valid = false;
3495        uint32_t i;
3496        for (i = 0; i < num_child_attributes; ++i) {
3497          const dw_attr_t attr = attributes.AttributeAtIndex(i);
3498          DWARFFormValue form_value;
3499          if (attributes.ExtractFormValueAtIndex(i, form_value)) {
3500            switch (attr) {
3501            case DW_AT_name:
3502              break;
3503
3504            case DW_AT_count:
3505              num_elements = form_value.Unsigned();
3506              break;
3507
3508            case DW_AT_bit_stride:
3509              bit_stride = form_value.Unsigned();
3510              break;
3511
3512            case DW_AT_byte_stride:
3513              byte_stride = form_value.Unsigned();
3514              break;
3515
3516            case DW_AT_lower_bound:
3517              lower_bound = form_value.Unsigned();
3518              break;
3519
3520            case DW_AT_upper_bound:
3521              upper_bound_valid = true;
3522              upper_bound = form_value.Unsigned();
3523              break;
3524
3525            default:
3526            case DW_AT_abstract_origin:
3527            case DW_AT_accessibility:
3528            case DW_AT_allocated:
3529            case DW_AT_associated:
3530            case DW_AT_data_location:
3531            case DW_AT_declaration:
3532            case DW_AT_description:
3533            case DW_AT_sibling:
3534            case DW_AT_threads_scaled:
3535            case DW_AT_type:
3536            case DW_AT_visibility:
3537              break;
3538            }
3539          }
3540        }
3541
3542        if (num_elements == 0) {
3543          if (upper_bound_valid && upper_bound >= lower_bound)
3544            num_elements = upper_bound - lower_bound + 1;
3545        }
3546
3547        element_orders.push_back(num_elements);
3548      }
3549    } break;
3550    }
3551  }
3552}
3553
3554Type *DWARFASTParserClang::GetTypeForDIE(const DWARFDIE &die) {
3555  if (die) {
3556    SymbolFileDWARF *dwarf = die.GetDWARF();
3557    DWARFAttributes attributes;
3558    const size_t num_attributes = die.GetAttributes(attributes);
3559    if (num_attributes > 0) {
3560      DWARFFormValue type_die_form;
3561      for (size_t i = 0; i < num_attributes; ++i) {
3562        dw_attr_t attr = attributes.AttributeAtIndex(i);
3563        DWARFFormValue form_value;
3564
3565        if (attr == DW_AT_type &&
3566            attributes.ExtractFormValueAtIndex(i, form_value))
3567          return dwarf->ResolveTypeUID(dwarf->GetDIE(DIERef(form_value)), true);
3568      }
3569    }
3570  }
3571
3572  return nullptr;
3573}
3574
3575clang::Decl *DWARFASTParserClang::GetClangDeclForDIE(const DWARFDIE &die) {
3576  if (!die)
3577    return nullptr;
3578
3579  switch (die.Tag()) {
3580  case DW_TAG_variable:
3581  case DW_TAG_constant:
3582  case DW_TAG_formal_parameter:
3583  case DW_TAG_imported_declaration:
3584  case DW_TAG_imported_module:
3585    break;
3586  default:
3587    return nullptr;
3588  }
3589
3590  DIEToDeclMap::iterator cache_pos = m_die_to_decl.find(die.GetDIE());
3591  if (cache_pos != m_die_to_decl.end())
3592    return cache_pos->second;
3593
3594  if (DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification)) {
3595    clang::Decl *decl = GetClangDeclForDIE(spec_die);
3596    m_die_to_decl[die.GetDIE()] = decl;
3597    m_decl_to_die[decl].insert(die.GetDIE());
3598    return decl;
3599  }
3600
3601  if (DWARFDIE abstract_origin_die =
3602          die.GetReferencedDIE(DW_AT_abstract_origin)) {
3603    clang::Decl *decl = GetClangDeclForDIE(abstract_origin_die);
3604    m_die_to_decl[die.GetDIE()] = decl;
3605    m_decl_to_die[decl].insert(die.GetDIE());
3606    return decl;
3607  }
3608
3609  clang::Decl *decl = nullptr;
3610  switch (die.Tag()) {
3611  case DW_TAG_variable:
3612  case DW_TAG_constant:
3613  case DW_TAG_formal_parameter: {
3614    SymbolFileDWARF *dwarf = die.GetDWARF();
3615    Type *type = GetTypeForDIE(die);
3616    if (dwarf && type) {
3617      const char *name = die.GetName();
3618      clang::DeclContext *decl_context =
3619          ClangASTContext::DeclContextGetAsDeclContext(
3620              dwarf->GetDeclContextContainingUID(die.GetID()));
3621      decl = m_ast.CreateVariableDeclaration(
3622          decl_context, name,
3623          ClangUtil::GetQualType(type->GetForwardCompilerType()));
3624    }
3625    break;
3626  }
3627  case DW_TAG_imported_declaration: {
3628    SymbolFileDWARF *dwarf = die.GetDWARF();
3629    DWARFDIE imported_uid = die.GetAttributeValueAsReferenceDIE(DW_AT_import);
3630    if (imported_uid) {
3631      CompilerDecl imported_decl = imported_uid.GetDecl();
3632      if (imported_decl) {
3633        clang::DeclContext *decl_context =
3634            ClangASTContext::DeclContextGetAsDeclContext(
3635                dwarf->GetDeclContextContainingUID(die.GetID()));
3636        if (clang::NamedDecl *clang_imported_decl =
3637                llvm::dyn_cast<clang::NamedDecl>(
3638                    (clang::Decl *)imported_decl.GetOpaqueDecl()))
3639          decl =
3640              m_ast.CreateUsingDeclaration(decl_context, clang_imported_decl);
3641      }
3642    }
3643    break;
3644  }
3645  case DW_TAG_imported_module: {
3646    SymbolFileDWARF *dwarf = die.GetDWARF();
3647    DWARFDIE imported_uid = die.GetAttributeValueAsReferenceDIE(DW_AT_import);
3648
3649    if (imported_uid) {
3650      CompilerDeclContext imported_decl_ctx = imported_uid.GetDeclContext();
3651      if (imported_decl_ctx) {
3652        clang::DeclContext *decl_context =
3653            ClangASTContext::DeclContextGetAsDeclContext(
3654                dwarf->GetDeclContextContainingUID(die.GetID()));
3655        if (clang::NamespaceDecl *ns_decl =
3656                ClangASTContext::DeclContextGetAsNamespaceDecl(
3657                    imported_decl_ctx))
3658          decl = m_ast.CreateUsingDirectiveDeclaration(decl_context, ns_decl);
3659      }
3660    }
3661    break;
3662  }
3663  default:
3664    break;
3665  }
3666
3667  m_die_to_decl[die.GetDIE()] = decl;
3668  m_decl_to_die[decl].insert(die.GetDIE());
3669
3670  return decl;
3671}
3672
3673clang::DeclContext *
3674DWARFASTParserClang::GetClangDeclContextForDIE(const DWARFDIE &die) {
3675  if (die) {
3676    clang::DeclContext *decl_ctx = GetCachedClangDeclContextForDIE(die);
3677    if (decl_ctx)
3678      return decl_ctx;
3679
3680    bool try_parsing_type = true;
3681    switch (die.Tag()) {
3682    case DW_TAG_compile_unit:
3683      decl_ctx = m_ast.GetTranslationUnitDecl();
3684      try_parsing_type = false;
3685      break;
3686
3687    case DW_TAG_namespace:
3688      decl_ctx = ResolveNamespaceDIE(die);
3689      try_parsing_type = false;
3690      break;
3691
3692    case DW_TAG_lexical_block:
3693      decl_ctx = GetDeclContextForBlock(die);
3694      try_parsing_type = false;
3695      break;
3696
3697    default:
3698      break;
3699    }
3700
3701    if (decl_ctx == nullptr && try_parsing_type) {
3702      Type *type = die.GetDWARF()->ResolveType(die);
3703      if (type)
3704        decl_ctx = GetCachedClangDeclContextForDIE(die);
3705    }
3706
3707    if (decl_ctx) {
3708      LinkDeclContextToDIE(decl_ctx, die);
3709      return decl_ctx;
3710    }
3711  }
3712  return nullptr;
3713}
3714
3715static bool IsSubroutine(const DWARFDIE &die) {
3716  switch (die.Tag()) {
3717  case DW_TAG_subprogram:
3718  case DW_TAG_inlined_subroutine:
3719    return true;
3720  default:
3721    return false;
3722  }
3723}
3724
3725static DWARFDIE GetContainingFunctionWithAbstractOrigin(const DWARFDIE &die) {
3726  for (DWARFDIE candidate = die; candidate; candidate = candidate.GetParent()) {
3727    if (IsSubroutine(candidate)) {
3728      if (candidate.GetReferencedDIE(DW_AT_abstract_origin)) {
3729        return candidate;
3730      } else {
3731        return DWARFDIE();
3732      }
3733    }
3734  }
3735  assert(0 && "Shouldn't call GetContainingFunctionWithAbstractOrigin on "
3736              "something not in a function");
3737  return DWARFDIE();
3738}
3739
3740static DWARFDIE FindAnyChildWithAbstractOrigin(const DWARFDIE &context) {
3741  for (DWARFDIE candidate = context.GetFirstChild(); candidate.IsValid();
3742       candidate = candidate.GetSibling()) {
3743    if (candidate.GetReferencedDIE(DW_AT_abstract_origin)) {
3744      return candidate;
3745    }
3746  }
3747  return DWARFDIE();
3748}
3749
3750static DWARFDIE FindFirstChildWithAbstractOrigin(const DWARFDIE &block,
3751                                                 const DWARFDIE &function) {
3752  assert(IsSubroutine(function));
3753  for (DWARFDIE context = block; context != function.GetParent();
3754       context = context.GetParent()) {
3755    assert(!IsSubroutine(context) || context == function);
3756    if (DWARFDIE child = FindAnyChildWithAbstractOrigin(context)) {
3757      return child;
3758    }
3759  }
3760  return DWARFDIE();
3761}
3762
3763clang::DeclContext *
3764DWARFASTParserClang::GetDeclContextForBlock(const DWARFDIE &die) {
3765  assert(die.Tag() == DW_TAG_lexical_block);
3766  DWARFDIE containing_function_with_abstract_origin =
3767      GetContainingFunctionWithAbstractOrigin(die);
3768  if (!containing_function_with_abstract_origin) {
3769    return (clang::DeclContext *)ResolveBlockDIE(die);
3770  }
3771  DWARFDIE child = FindFirstChildWithAbstractOrigin(
3772      die, containing_function_with_abstract_origin);
3773  CompilerDeclContext decl_context =
3774      GetDeclContextContainingUIDFromDWARF(child);
3775  return (clang::DeclContext *)decl_context.GetOpaqueDeclContext();
3776}
3777
3778clang::BlockDecl *DWARFASTParserClang::ResolveBlockDIE(const DWARFDIE &die) {
3779  if (die && die.Tag() == DW_TAG_lexical_block) {
3780    clang::BlockDecl *decl =
3781        llvm::cast_or_null<clang::BlockDecl>(m_die_to_decl_ctx[die.GetDIE()]);
3782
3783    if (!decl) {
3784      DWARFDIE decl_context_die;
3785      clang::DeclContext *decl_context =
3786          GetClangDeclContextContainingDIE(die, &decl_context_die);
3787      decl = m_ast.CreateBlockDeclaration(decl_context);
3788
3789      if (decl)
3790        LinkDeclContextToDIE((clang::DeclContext *)decl, die);
3791    }
3792
3793    return decl;
3794  }
3795  return nullptr;
3796}
3797
3798clang::NamespaceDecl *
3799DWARFASTParserClang::ResolveNamespaceDIE(const DWARFDIE &die) {
3800  if (die && die.Tag() == DW_TAG_namespace) {
3801    // See if we already parsed this namespace DIE and associated it with a
3802    // uniqued namespace declaration
3803    clang::NamespaceDecl *namespace_decl =
3804        static_cast<clang::NamespaceDecl *>(m_die_to_decl_ctx[die.GetDIE()]);
3805    if (namespace_decl)
3806      return namespace_decl;
3807    else {
3808      const char *namespace_name = die.GetName();
3809      clang::DeclContext *containing_decl_ctx =
3810          GetClangDeclContextContainingDIE(die, nullptr);
3811      namespace_decl = m_ast.GetUniqueNamespaceDeclaration(namespace_name,
3812                                                           containing_decl_ctx);
3813      Log *log =
3814          nullptr; // (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
3815      if (log) {
3816        SymbolFileDWARF *dwarf = die.GetDWARF();
3817        if (namespace_name) {
3818          dwarf->GetObjectFile()->GetModule()->LogMessage(
3819              log, "ASTContext => %p: 0x%8.8" PRIx64
3820                   ": DW_TAG_namespace with DW_AT_name(\"%s\") => "
3821                   "clang::NamespaceDecl *%p (original = %p)",
3822              static_cast<void *>(m_ast.getASTContext()), die.GetID(),
3823              namespace_name, static_cast<void *>(namespace_decl),
3824              static_cast<void *>(namespace_decl->getOriginalNamespace()));
3825        } else {
3826          dwarf->GetObjectFile()->GetModule()->LogMessage(
3827              log, "ASTContext => %p: 0x%8.8" PRIx64
3828                   ": DW_TAG_namespace (anonymous) => clang::NamespaceDecl *%p "
3829                   "(original = %p)",
3830              static_cast<void *>(m_ast.getASTContext()), die.GetID(),
3831              static_cast<void *>(namespace_decl),
3832              static_cast<void *>(namespace_decl->getOriginalNamespace()));
3833        }
3834      }
3835
3836      if (namespace_decl)
3837        LinkDeclContextToDIE((clang::DeclContext *)namespace_decl, die);
3838      return namespace_decl;
3839    }
3840  }
3841  return nullptr;
3842}
3843
3844clang::DeclContext *DWARFASTParserClang::GetClangDeclContextContainingDIE(
3845    const DWARFDIE &die, DWARFDIE *decl_ctx_die_copy) {
3846  SymbolFileDWARF *dwarf = die.GetDWARF();
3847
3848  DWARFDIE decl_ctx_die = dwarf->GetDeclContextDIEContainingDIE(die);
3849
3850  if (decl_ctx_die_copy)
3851    *decl_ctx_die_copy = decl_ctx_die;
3852
3853  if (decl_ctx_die) {
3854    clang::DeclContext *clang_decl_ctx =
3855        GetClangDeclContextForDIE(decl_ctx_die);
3856    if (clang_decl_ctx)
3857      return clang_decl_ctx;
3858  }
3859  return m_ast.GetTranslationUnitDecl();
3860}
3861
3862clang::DeclContext *
3863DWARFASTParserClang::GetCachedClangDeclContextForDIE(const DWARFDIE &die) {
3864  if (die) {
3865    DIEToDeclContextMap::iterator pos = m_die_to_decl_ctx.find(die.GetDIE());
3866    if (pos != m_die_to_decl_ctx.end())
3867      return pos->second;
3868  }
3869  return nullptr;
3870}
3871
3872void DWARFASTParserClang::LinkDeclContextToDIE(clang::DeclContext *decl_ctx,
3873                                               const DWARFDIE &die) {
3874  m_die_to_decl_ctx[die.GetDIE()] = decl_ctx;
3875  // There can be many DIEs for a single decl context
3876  // m_decl_ctx_to_die[decl_ctx].insert(die.GetDIE());
3877  m_decl_ctx_to_die.insert(std::make_pair(decl_ctx, die));
3878}
3879
3880bool DWARFASTParserClang::CopyUniqueClassMethodTypes(
3881    const DWARFDIE &src_class_die, const DWARFDIE &dst_class_die,
3882    lldb_private::Type *class_type, DWARFDIECollection &failures) {
3883  if (!class_type || !src_class_die || !dst_class_die)
3884    return false;
3885  if (src_class_die.Tag() != dst_class_die.Tag())
3886    return false;
3887
3888  // We need to complete the class type so we can get all of the method types
3889  // parsed so we can then unique those types to their equivalent counterparts
3890  // in "dst_cu" and "dst_class_die"
3891  class_type->GetFullCompilerType();
3892
3893  DWARFDIE src_die;
3894  DWARFDIE dst_die;
3895  UniqueCStringMap<DWARFDIE> src_name_to_die;
3896  UniqueCStringMap<DWARFDIE> dst_name_to_die;
3897  UniqueCStringMap<DWARFDIE> src_name_to_die_artificial;
3898  UniqueCStringMap<DWARFDIE> dst_name_to_die_artificial;
3899  for (src_die = src_class_die.GetFirstChild(); src_die.IsValid();
3900       src_die = src_die.GetSibling()) {
3901    if (src_die.Tag() == DW_TAG_subprogram) {
3902      // Make sure this is a declaration and not a concrete instance by looking
3903      // for DW_AT_declaration set to 1. Sometimes concrete function instances
3904      // are placed inside the class definitions and shouldn't be included in
3905      // the list of things are are tracking here.
3906      if (src_die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0) == 1) {
3907        const char *src_name = src_die.GetMangledName();
3908        if (src_name) {
3909          ConstString src_const_name(src_name);
3910          if (src_die.GetAttributeValueAsUnsigned(DW_AT_artificial, 0))
3911            src_name_to_die_artificial.Append(src_const_name, src_die);
3912          else
3913            src_name_to_die.Append(src_const_name, src_die);
3914        }
3915      }
3916    }
3917  }
3918  for (dst_die = dst_class_die.GetFirstChild(); dst_die.IsValid();
3919       dst_die = dst_die.GetSibling()) {
3920    if (dst_die.Tag() == DW_TAG_subprogram) {
3921      // Make sure this is a declaration and not a concrete instance by looking
3922      // for DW_AT_declaration set to 1. Sometimes concrete function instances
3923      // are placed inside the class definitions and shouldn't be included in
3924      // the list of things are are tracking here.
3925      if (dst_die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0) == 1) {
3926        const char *dst_name = dst_die.GetMangledName();
3927        if (dst_name) {
3928          ConstString dst_const_name(dst_name);
3929          if (dst_die.GetAttributeValueAsUnsigned(DW_AT_artificial, 0))
3930            dst_name_to_die_artificial.Append(dst_const_name, dst_die);
3931          else
3932            dst_name_to_die.Append(dst_const_name, dst_die);
3933        }
3934      }
3935    }
3936  }
3937  const uint32_t src_size = src_name_to_die.GetSize();
3938  const uint32_t dst_size = dst_name_to_die.GetSize();
3939  Log *log = nullptr; // (LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO |
3940                      // DWARF_LOG_TYPE_COMPLETION));
3941
3942  // Is everything kosher so we can go through the members at top speed?
3943  bool fast_path = true;
3944
3945  if (src_size != dst_size) {
3946    if (src_size != 0 && dst_size != 0) {
3947      if (log)
3948        log->Printf("warning: trying to unique class DIE 0x%8.8x to 0x%8.8x, "
3949                    "but they didn't have the same size (src=%d, dst=%d)",
3950                    src_class_die.GetOffset(), dst_class_die.GetOffset(),
3951                    src_size, dst_size);
3952    }
3953
3954    fast_path = false;
3955  }
3956
3957  uint32_t idx;
3958
3959  if (fast_path) {
3960    for (idx = 0; idx < src_size; ++idx) {
3961      src_die = src_name_to_die.GetValueAtIndexUnchecked(idx);
3962      dst_die = dst_name_to_die.GetValueAtIndexUnchecked(idx);
3963
3964      if (src_die.Tag() != dst_die.Tag()) {
3965        if (log)
3966          log->Printf("warning: tried to unique class DIE 0x%8.8x to 0x%8.8x, "
3967                      "but 0x%8.8x (%s) tags didn't match 0x%8.8x (%s)",
3968                      src_class_die.GetOffset(), dst_class_die.GetOffset(),
3969                      src_die.GetOffset(), src_die.GetTagAsCString(),
3970                      dst_die.GetOffset(), dst_die.GetTagAsCString());
3971        fast_path = false;
3972      }
3973
3974      const char *src_name = src_die.GetMangledName();
3975      const char *dst_name = dst_die.GetMangledName();
3976
3977      // Make sure the names match
3978      if (src_name == dst_name || (strcmp(src_name, dst_name) == 0))
3979        continue;
3980
3981      if (log)
3982        log->Printf("warning: tried to unique class DIE 0x%8.8x to 0x%8.8x, "
3983                    "but 0x%8.8x (%s) names didn't match 0x%8.8x (%s)",
3984                    src_class_die.GetOffset(), dst_class_die.GetOffset(),
3985                    src_die.GetOffset(), src_name, dst_die.GetOffset(),
3986                    dst_name);
3987
3988      fast_path = false;
3989    }
3990  }
3991
3992  DWARFASTParserClang *src_dwarf_ast_parser =
3993      (DWARFASTParserClang *)src_die.GetDWARFParser();
3994  DWARFASTParserClang *dst_dwarf_ast_parser =
3995      (DWARFASTParserClang *)dst_die.GetDWARFParser();
3996
3997  // Now do the work of linking the DeclContexts and Types.
3998  if (fast_path) {
3999    // We can do this quickly.  Just run across the tables index-for-index since
4000    // we know each node has matching names and tags.
4001    for (idx = 0; idx < src_size; ++idx) {
4002      src_die = src_name_to_die.GetValueAtIndexUnchecked(idx);
4003      dst_die = dst_name_to_die.GetValueAtIndexUnchecked(idx);
4004
4005      clang::DeclContext *src_decl_ctx =
4006          src_dwarf_ast_parser->m_die_to_decl_ctx[src_die.GetDIE()];
4007      if (src_decl_ctx) {
4008        if (log)
4009          log->Printf("uniquing decl context %p from 0x%8.8x for 0x%8.8x",
4010                      static_cast<void *>(src_decl_ctx), src_die.GetOffset(),
4011                      dst_die.GetOffset());
4012        dst_dwarf_ast_parser->LinkDeclContextToDIE(src_decl_ctx, dst_die);
4013      } else {
4014        if (log)
4015          log->Printf("warning: tried to unique decl context from 0x%8.8x for "
4016                      "0x%8.8x, but none was found",
4017                      src_die.GetOffset(), dst_die.GetOffset());
4018      }
4019
4020      Type *src_child_type =
4021          dst_die.GetDWARF()->GetDIEToType()[src_die.GetDIE()];
4022      if (src_child_type) {
4023        if (log)
4024          log->Printf(
4025              "uniquing type %p (uid=0x%" PRIx64 ") from 0x%8.8x for 0x%8.8x",
4026              static_cast<void *>(src_child_type), src_child_type->GetID(),
4027              src_die.GetOffset(), dst_die.GetOffset());
4028        dst_die.GetDWARF()->GetDIEToType()[dst_die.GetDIE()] = src_child_type;
4029      } else {
4030        if (log)
4031          log->Printf("warning: tried to unique lldb_private::Type from "
4032                      "0x%8.8x for 0x%8.8x, but none was found",
4033                      src_die.GetOffset(), dst_die.GetOffset());
4034      }
4035    }
4036  } else {
4037    // We must do this slowly.  For each member of the destination, look
4038    // up a member in the source with the same name, check its tag, and
4039    // unique them if everything matches up.  Report failures.
4040
4041    if (!src_name_to_die.IsEmpty() && !dst_name_to_die.IsEmpty()) {
4042      src_name_to_die.Sort();
4043
4044      for (idx = 0; idx < dst_size; ++idx) {
4045        ConstString dst_name = dst_name_to_die.GetCStringAtIndex(idx);
4046        dst_die = dst_name_to_die.GetValueAtIndexUnchecked(idx);
4047        src_die = src_name_to_die.Find(dst_name, DWARFDIE());
4048
4049        if (src_die && (src_die.Tag() == dst_die.Tag())) {
4050          clang::DeclContext *src_decl_ctx =
4051              src_dwarf_ast_parser->m_die_to_decl_ctx[src_die.GetDIE()];
4052          if (src_decl_ctx) {
4053            if (log)
4054              log->Printf("uniquing decl context %p from 0x%8.8x for 0x%8.8x",
4055                          static_cast<void *>(src_decl_ctx),
4056                          src_die.GetOffset(), dst_die.GetOffset());
4057            dst_dwarf_ast_parser->LinkDeclContextToDIE(src_decl_ctx, dst_die);
4058          } else {
4059            if (log)
4060              log->Printf("warning: tried to unique decl context from 0x%8.8x "
4061                          "for 0x%8.8x, but none was found",
4062                          src_die.GetOffset(), dst_die.GetOffset());
4063          }
4064
4065          Type *src_child_type =
4066              dst_die.GetDWARF()->GetDIEToType()[src_die.GetDIE()];
4067          if (src_child_type) {
4068            if (log)
4069              log->Printf("uniquing type %p (uid=0x%" PRIx64
4070                          ") from 0x%8.8x for 0x%8.8x",
4071                          static_cast<void *>(src_child_type),
4072                          src_child_type->GetID(), src_die.GetOffset(),
4073                          dst_die.GetOffset());
4074            dst_die.GetDWARF()->GetDIEToType()[dst_die.GetDIE()] =
4075                src_child_type;
4076          } else {
4077            if (log)
4078              log->Printf("warning: tried to unique lldb_private::Type from "
4079                          "0x%8.8x for 0x%8.8x, but none was found",
4080                          src_die.GetOffset(), dst_die.GetOffset());
4081          }
4082        } else {
4083          if (log)
4084            log->Printf("warning: couldn't find a match for 0x%8.8x",
4085                        dst_die.GetOffset());
4086
4087          failures.Append(dst_die);
4088        }
4089      }
4090    }
4091  }
4092
4093  const uint32_t src_size_artificial = src_name_to_die_artificial.GetSize();
4094  const uint32_t dst_size_artificial = dst_name_to_die_artificial.GetSize();
4095
4096  if (src_size_artificial && dst_size_artificial) {
4097    dst_name_to_die_artificial.Sort();
4098
4099    for (idx = 0; idx < src_size_artificial; ++idx) {
4100      ConstString src_name_artificial =
4101          src_name_to_die_artificial.GetCStringAtIndex(idx);
4102      src_die = src_name_to_die_artificial.GetValueAtIndexUnchecked(idx);
4103      dst_die =
4104          dst_name_to_die_artificial.Find(src_name_artificial, DWARFDIE());
4105
4106      if (dst_die) {
4107        // Both classes have the artificial types, link them
4108        clang::DeclContext *src_decl_ctx =
4109            src_dwarf_ast_parser->m_die_to_decl_ctx[src_die.GetDIE()];
4110        if (src_decl_ctx) {
4111          if (log)
4112            log->Printf("uniquing decl context %p from 0x%8.8x for 0x%8.8x",
4113                        static_cast<void *>(src_decl_ctx), src_die.GetOffset(),
4114                        dst_die.GetOffset());
4115          dst_dwarf_ast_parser->LinkDeclContextToDIE(src_decl_ctx, dst_die);
4116        } else {
4117          if (log)
4118            log->Printf("warning: tried to unique decl context from 0x%8.8x "
4119                        "for 0x%8.8x, but none was found",
4120                        src_die.GetOffset(), dst_die.GetOffset());
4121        }
4122
4123        Type *src_child_type =
4124            dst_die.GetDWARF()->GetDIEToType()[src_die.GetDIE()];
4125        if (src_child_type) {
4126          if (log)
4127            log->Printf(
4128                "uniquing type %p (uid=0x%" PRIx64 ") from 0x%8.8x for 0x%8.8x",
4129                static_cast<void *>(src_child_type), src_child_type->GetID(),
4130                src_die.GetOffset(), dst_die.GetOffset());
4131          dst_die.GetDWARF()->GetDIEToType()[dst_die.GetDIE()] = src_child_type;
4132        } else {
4133          if (log)
4134            log->Printf("warning: tried to unique lldb_private::Type from "
4135                        "0x%8.8x for 0x%8.8x, but none was found",
4136                        src_die.GetOffset(), dst_die.GetOffset());
4137        }
4138      }
4139    }
4140  }
4141
4142  if (dst_size_artificial) {
4143    for (idx = 0; idx < dst_size_artificial; ++idx) {
4144      ConstString dst_name_artificial =
4145          dst_name_to_die_artificial.GetCStringAtIndex(idx);
4146      dst_die = dst_name_to_die_artificial.GetValueAtIndexUnchecked(idx);
4147      if (log)
4148        log->Printf("warning: need to create artificial method for 0x%8.8x for "
4149                    "method '%s'",
4150                    dst_die.GetOffset(), dst_name_artificial.GetCString());
4151
4152      failures.Append(dst_die);
4153    }
4154  }
4155
4156  return (failures.Size() != 0);
4157}
4158