DWARFASTParserClang.cpp revision 344779
1//===-- DWARFASTParserClang.cpp ---------------------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include <stdlib.h>
11
12#include "DWARFASTParserClang.h"
13#include "DWARFDIE.h"
14#include "DWARFDIECollection.h"
15#include "DWARFDebugInfo.h"
16#include "DWARFDeclContext.h"
17#include "DWARFDefines.h"
18#include "SymbolFileDWARF.h"
19#include "SymbolFileDWARFDwo.h"
20#include "SymbolFileDWARFDebugMap.h"
21#include "UniqueDWARFASTType.h"
22
23#include "Plugins/Language/ObjC/ObjCLanguage.h"
24#include "lldb/Core/Module.h"
25#include "lldb/Core/Value.h"
26#include "lldb/Host/Host.h"
27#include "lldb/Symbol/ClangASTImporter.h"
28#include "lldb/Symbol/ClangExternalASTSourceCommon.h"
29#include "lldb/Symbol/ClangUtil.h"
30#include "lldb/Symbol/CompileUnit.h"
31#include "lldb/Symbol/Function.h"
32#include "lldb/Symbol/ObjectFile.h"
33#include "lldb/Symbol/SymbolVendor.h"
34#include "lldb/Symbol/TypeList.h"
35#include "lldb/Symbol/TypeMap.h"
36#include "lldb/Target/Language.h"
37#include "lldb/Utility/LLDBAssert.h"
38#include "lldb/Utility/Log.h"
39#include "lldb/Utility/StreamString.h"
40
41#include "clang/AST/CXXInheritance.h"
42#include "clang/AST/DeclCXX.h"
43#include "clang/AST/DeclObjC.h"
44#include "clang/AST/DeclTemplate.h"
45
46#include <map>
47#include <vector>
48
49//#define ENABLE_DEBUG_PRINTF // COMMENT OUT THIS LINE PRIOR TO CHECKIN
50
51#ifdef ENABLE_DEBUG_PRINTF
52#include <stdio.h>
53#define DEBUG_PRINTF(fmt, ...) printf(fmt, __VA_ARGS__)
54#else
55#define DEBUG_PRINTF(fmt, ...)
56#endif
57
58using namespace lldb;
59using namespace lldb_private;
60DWARFASTParserClang::DWARFASTParserClang(ClangASTContext &ast)
61    : m_ast(ast), m_die_to_decl_ctx(), m_decl_ctx_to_die() {}
62
63DWARFASTParserClang::~DWARFASTParserClang() {}
64
65static AccessType DW_ACCESS_to_AccessType(uint32_t dwarf_accessibility) {
66  switch (dwarf_accessibility) {
67  case DW_ACCESS_public:
68    return eAccessPublic;
69  case DW_ACCESS_private:
70    return eAccessPrivate;
71  case DW_ACCESS_protected:
72    return eAccessProtected;
73  default:
74    break;
75  }
76  return eAccessNone;
77}
78
79static bool DeclKindIsCXXClass(clang::Decl::Kind decl_kind) {
80  switch (decl_kind) {
81  case clang::Decl::CXXRecord:
82  case clang::Decl::ClassTemplateSpecialization:
83    return true;
84  default:
85    break;
86  }
87  return false;
88}
89
90struct BitfieldInfo {
91  uint64_t bit_size;
92  uint64_t bit_offset;
93
94  BitfieldInfo()
95      : bit_size(LLDB_INVALID_ADDRESS), bit_offset(LLDB_INVALID_ADDRESS) {}
96
97  void Clear() {
98    bit_size = LLDB_INVALID_ADDRESS;
99    bit_offset = LLDB_INVALID_ADDRESS;
100  }
101
102  bool IsValid() const {
103    return (bit_size != LLDB_INVALID_ADDRESS) &&
104           (bit_offset != LLDB_INVALID_ADDRESS);
105  }
106
107  bool NextBitfieldOffsetIsValid(const uint64_t next_bit_offset) const {
108    if (IsValid()) {
109      // This bitfield info is valid, so any subsequent bitfields must not
110      // overlap and must be at a higher bit offset than any previous bitfield
111      // + size.
112      return (bit_size + bit_offset) <= next_bit_offset;
113    } else {
114      // If the this BitfieldInfo is not valid, then any offset isOK
115      return true;
116    }
117  }
118};
119
120ClangASTImporter &DWARFASTParserClang::GetClangASTImporter() {
121  if (!m_clang_ast_importer_ap) {
122    m_clang_ast_importer_ap.reset(new ClangASTImporter);
123  }
124  return *m_clang_ast_importer_ap;
125}
126
127/// Detect a forward declaration that is nested in a DW_TAG_module.
128static bool IsClangModuleFwdDecl(const DWARFDIE &Die) {
129  if (!Die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0))
130    return false;
131  auto Parent = Die.GetParent();
132  while (Parent.IsValid()) {
133    if (Parent.Tag() == DW_TAG_module)
134      return true;
135    Parent = Parent.GetParent();
136  }
137  return false;
138}
139
140TypeSP DWARFASTParserClang::ParseTypeFromDWO(const DWARFDIE &die, Log *log) {
141  ModuleSP dwo_module_sp = die.GetContainingDWOModule();
142  if (!dwo_module_sp)
143    return TypeSP();
144
145  // If this type comes from a Clang module, look in the DWARF section
146  // of the pcm file in the module cache. Clang generates DWO skeleton
147  // units as breadcrumbs to find them.
148  std::vector<CompilerContext> decl_context;
149  die.GetDeclContext(decl_context);
150  TypeMap dwo_types;
151
152  if (!dwo_module_sp->GetSymbolVendor()->FindTypes(decl_context, true,
153                                                   dwo_types)) {
154    if (!IsClangModuleFwdDecl(die))
155      return TypeSP();
156
157    // Since this this type is defined in one of the Clang modules imported by
158    // this symbol file, search all of them.
159    auto *sym_file = die.GetCU()->GetSymbolFileDWARF();
160    for (const auto &name_module : sym_file->getExternalTypeModules()) {
161      if (!name_module.second)
162        continue;
163      SymbolVendor *sym_vendor = name_module.second->GetSymbolVendor();
164      if (sym_vendor->FindTypes(decl_context, true, dwo_types))
165        break;
166    }
167  }
168
169  if (dwo_types.GetSize() != 1)
170    return TypeSP();
171
172  // We found a real definition for this type in the Clang module, so lets use
173  // it and cache the fact that we found a complete type for this die.
174  TypeSP dwo_type_sp = dwo_types.GetTypeAtIndex(0);
175  if (!dwo_type_sp)
176    return TypeSP();
177
178  lldb_private::CompilerType dwo_type = dwo_type_sp->GetForwardCompilerType();
179
180  lldb_private::CompilerType type =
181      GetClangASTImporter().CopyType(m_ast, dwo_type);
182
183  if (!type)
184    return TypeSP();
185
186  SymbolFileDWARF *dwarf = die.GetDWARF();
187  TypeSP type_sp(new Type(
188      die.GetID(), dwarf, dwo_type_sp->GetName(), dwo_type_sp->GetByteSize(),
189      NULL, LLDB_INVALID_UID, Type::eEncodingInvalid,
190      &dwo_type_sp->GetDeclaration(), type, Type::eResolveStateForward));
191
192  dwarf->GetTypeList()->Insert(type_sp);
193  dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
194  clang::TagDecl *tag_decl = ClangASTContext::GetAsTagDecl(type);
195  if (tag_decl)
196    LinkDeclContextToDIE(tag_decl, die);
197  else {
198    clang::DeclContext *defn_decl_ctx = GetCachedClangDeclContextForDIE(die);
199    if (defn_decl_ctx)
200      LinkDeclContextToDIE(defn_decl_ctx, die);
201  }
202
203  return type_sp;
204}
205
206static void CompleteExternalTagDeclType(ClangASTImporter &ast_importer,
207                                        clang::DeclContext *decl_ctx,
208                                        DWARFDIE die,
209                                        const char *type_name_cstr) {
210  auto *tag_decl_ctx = clang::dyn_cast<clang::TagDecl>(decl_ctx);
211  if (!tag_decl_ctx)
212    return;
213
214  // If this type was not imported from an external AST, there's nothing to do.
215  CompilerType type = ClangASTContext::GetTypeForDecl(tag_decl_ctx);
216  if (!type || !ast_importer.CanImport(type))
217    return;
218
219  auto qual_type = ClangUtil::GetQualType(type);
220  if (!ast_importer.RequireCompleteType(qual_type)) {
221    die.GetDWARF()->GetObjectFile()->GetModule()->ReportError(
222        "Unable to complete the Decl context for DIE '%s' at offset "
223        "0x%8.8x.\nPlease file a bug report.",
224        type_name_cstr ? type_name_cstr : "", die.GetOffset());
225    // We need to make the type look complete otherwise, we might crash in
226    // Clang when adding children.
227    if (ClangASTContext::StartTagDeclarationDefinition(type))
228      ClangASTContext::CompleteTagDeclarationDefinition(type);
229  }
230}
231
232TypeSP DWARFASTParserClang::ParseTypeFromDWARF(const SymbolContext &sc,
233                                               const DWARFDIE &die, Log *log,
234                                               bool *type_is_new_ptr) {
235  TypeSP type_sp;
236
237  if (type_is_new_ptr)
238    *type_is_new_ptr = false;
239
240  AccessType accessibility = eAccessNone;
241  if (die) {
242    SymbolFileDWARF *dwarf = die.GetDWARF();
243    if (log) {
244      DWARFDIE context_die;
245      clang::DeclContext *context =
246          GetClangDeclContextContainingDIE(die, &context_die);
247
248      dwarf->GetObjectFile()->GetModule()->LogMessage(
249          log, "SymbolFileDWARF::ParseType (die = 0x%8.8x, decl_ctx = %p (die "
250               "0x%8.8x)) %s name = '%s')",
251          die.GetOffset(), static_cast<void *>(context),
252          context_die.GetOffset(), die.GetTagAsCString(), die.GetName());
253    }
254    Type *type_ptr = dwarf->GetDIEToType().lookup(die.GetDIE());
255    TypeList *type_list = dwarf->GetTypeList();
256    if (type_ptr == NULL) {
257      if (type_is_new_ptr)
258        *type_is_new_ptr = true;
259
260      const dw_tag_t tag = die.Tag();
261
262      bool is_forward_declaration = false;
263      DWARFAttributes attributes;
264      const char *type_name_cstr = NULL;
265      const char *mangled_name_cstr = NULL;
266      ConstString type_name_const_str;
267      Type::ResolveState resolve_state = Type::eResolveStateUnresolved;
268      uint64_t byte_size = 0;
269      Declaration decl;
270
271      Type::EncodingDataType encoding_data_type = Type::eEncodingIsUID;
272      CompilerType clang_type;
273      DWARFFormValue form_value;
274
275      dw_attr_t attr;
276
277      switch (tag) {
278      case DW_TAG_typedef:
279      case DW_TAG_base_type:
280      case DW_TAG_pointer_type:
281      case DW_TAG_reference_type:
282      case DW_TAG_rvalue_reference_type:
283      case DW_TAG_const_type:
284      case DW_TAG_restrict_type:
285      case DW_TAG_volatile_type:
286      case DW_TAG_unspecified_type: {
287        // Set a bit that lets us know that we are currently parsing this
288        dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED;
289
290        const size_t num_attributes = die.GetAttributes(attributes);
291        uint32_t encoding = 0;
292        DWARFFormValue encoding_uid;
293
294        if (num_attributes > 0) {
295          uint32_t i;
296          for (i = 0; i < num_attributes; ++i) {
297            attr = attributes.AttributeAtIndex(i);
298            if (attributes.ExtractFormValueAtIndex(i, form_value)) {
299              switch (attr) {
300              case DW_AT_decl_file:
301                decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
302                    form_value.Unsigned()));
303                break;
304              case DW_AT_decl_line:
305                decl.SetLine(form_value.Unsigned());
306                break;
307              case DW_AT_decl_column:
308                decl.SetColumn(form_value.Unsigned());
309                break;
310              case DW_AT_name:
311                type_name_cstr = form_value.AsCString();
312                if (type_name_cstr)
313                  type_name_const_str.SetCString(type_name_cstr);
314                break;
315              case DW_AT_byte_size:
316                byte_size = form_value.Unsigned();
317                break;
318              case DW_AT_encoding:
319                encoding = form_value.Unsigned();
320                break;
321              case DW_AT_type:
322                encoding_uid = form_value;
323                break;
324              default:
325              case DW_AT_sibling:
326                break;
327              }
328            }
329          }
330        }
331
332        if (tag == DW_TAG_typedef && encoding_uid.IsValid()) {
333          // Try to parse a typedef from the DWO file first as modules can
334          // contain typedef'ed structures that have no names like:
335          //
336          //  typedef struct { int a; } Foo;
337          //
338          // In this case we will have a structure with no name and a typedef
339          // named "Foo" that points to this unnamed structure. The name in the
340          // typedef is the only identifier for the struct, so always try to
341          // get typedefs from DWO files if possible.
342          //
343          // The type_sp returned will be empty if the typedef doesn't exist in
344          // a DWO file, so it is cheap to call this function just to check.
345          //
346          // If we don't do this we end up creating a TypeSP that says this is
347          // a typedef to type 0x123 (the DW_AT_type value would be 0x123 in
348          // the DW_TAG_typedef), and this is the unnamed structure type. We
349          // will have a hard time tracking down an unnammed structure type in
350          // the module DWO file, so we make sure we don't get into this
351          // situation by always resolving typedefs from the DWO file.
352          const DWARFDIE encoding_die = dwarf->GetDIE(DIERef(encoding_uid));
353
354          // First make sure that the die that this is typedef'ed to _is_ just
355          // a declaration (DW_AT_declaration == 1), not a full definition
356          // since template types can't be represented in modules since only
357          // concrete instances of templates are ever emitted and modules won't
358          // contain those
359          if (encoding_die &&
360              encoding_die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0) ==
361                  1) {
362            type_sp = ParseTypeFromDWO(die, log);
363            if (type_sp)
364              return type_sp;
365          }
366        }
367
368        DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\") type => 0x%8.8lx\n",
369                     die.GetID(), DW_TAG_value_to_name(tag), type_name_cstr,
370                     encoding_uid.Reference());
371
372        switch (tag) {
373        default:
374          break;
375
376        case DW_TAG_unspecified_type:
377          if (strcmp(type_name_cstr, "nullptr_t") == 0 ||
378              strcmp(type_name_cstr, "decltype(nullptr)") == 0) {
379            resolve_state = Type::eResolveStateFull;
380            clang_type = m_ast.GetBasicType(eBasicTypeNullPtr);
381            break;
382          }
383          // Fall through to base type below in case we can handle the type
384          // there...
385          LLVM_FALLTHROUGH;
386
387        case DW_TAG_base_type:
388          resolve_state = Type::eResolveStateFull;
389          clang_type = m_ast.GetBuiltinTypeForDWARFEncodingAndBitSize(
390              type_name_cstr, encoding, byte_size * 8);
391          break;
392
393        case DW_TAG_pointer_type:
394          encoding_data_type = Type::eEncodingIsPointerUID;
395          break;
396        case DW_TAG_reference_type:
397          encoding_data_type = Type::eEncodingIsLValueReferenceUID;
398          break;
399        case DW_TAG_rvalue_reference_type:
400          encoding_data_type = Type::eEncodingIsRValueReferenceUID;
401          break;
402        case DW_TAG_typedef:
403          encoding_data_type = Type::eEncodingIsTypedefUID;
404          break;
405        case DW_TAG_const_type:
406          encoding_data_type = Type::eEncodingIsConstUID;
407          break;
408        case DW_TAG_restrict_type:
409          encoding_data_type = Type::eEncodingIsRestrictUID;
410          break;
411        case DW_TAG_volatile_type:
412          encoding_data_type = Type::eEncodingIsVolatileUID;
413          break;
414        }
415
416        if (!clang_type &&
417            (encoding_data_type == Type::eEncodingIsPointerUID ||
418             encoding_data_type == Type::eEncodingIsTypedefUID)) {
419          if (tag == DW_TAG_pointer_type) {
420            DWARFDIE target_die = die.GetReferencedDIE(DW_AT_type);
421
422            if (target_die.GetAttributeValueAsUnsigned(DW_AT_APPLE_block, 0)) {
423              // Blocks have a __FuncPtr inside them which is a pointer to a
424              // function of the proper type.
425
426              for (DWARFDIE child_die = target_die.GetFirstChild();
427                   child_die.IsValid(); child_die = child_die.GetSibling()) {
428                if (!strcmp(child_die.GetAttributeValueAsString(DW_AT_name, ""),
429                            "__FuncPtr")) {
430                  DWARFDIE function_pointer_type =
431                      child_die.GetReferencedDIE(DW_AT_type);
432
433                  if (function_pointer_type) {
434                    DWARFDIE function_type =
435                        function_pointer_type.GetReferencedDIE(DW_AT_type);
436
437                    bool function_type_is_new_pointer;
438                    TypeSP lldb_function_type_sp = ParseTypeFromDWARF(
439                        sc, function_type, log, &function_type_is_new_pointer);
440
441                    if (lldb_function_type_sp) {
442                      clang_type = m_ast.CreateBlockPointerType(
443                          lldb_function_type_sp->GetForwardCompilerType());
444                      encoding_data_type = Type::eEncodingIsUID;
445                      encoding_uid.Clear();
446                      resolve_state = Type::eResolveStateFull;
447                    }
448                  }
449
450                  break;
451                }
452              }
453            }
454          }
455
456          bool translation_unit_is_objc =
457              (sc.comp_unit->GetLanguage() == eLanguageTypeObjC ||
458               sc.comp_unit->GetLanguage() == eLanguageTypeObjC_plus_plus);
459
460          if (translation_unit_is_objc) {
461            if (type_name_cstr != NULL) {
462              static ConstString g_objc_type_name_id("id");
463              static ConstString g_objc_type_name_Class("Class");
464              static ConstString g_objc_type_name_selector("SEL");
465
466              if (type_name_const_str == g_objc_type_name_id) {
467                if (log)
468                  dwarf->GetObjectFile()->GetModule()->LogMessage(
469                      log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' "
470                           "is Objective-C 'id' built-in type.",
471                      die.GetOffset(), die.GetTagAsCString(), die.GetName());
472                clang_type = m_ast.GetBasicType(eBasicTypeObjCID);
473                encoding_data_type = Type::eEncodingIsUID;
474                encoding_uid.Clear();
475                resolve_state = Type::eResolveStateFull;
476
477              } else if (type_name_const_str == g_objc_type_name_Class) {
478                if (log)
479                  dwarf->GetObjectFile()->GetModule()->LogMessage(
480                      log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' "
481                           "is Objective-C 'Class' built-in type.",
482                      die.GetOffset(), die.GetTagAsCString(), die.GetName());
483                clang_type = m_ast.GetBasicType(eBasicTypeObjCClass);
484                encoding_data_type = Type::eEncodingIsUID;
485                encoding_uid.Clear();
486                resolve_state = Type::eResolveStateFull;
487              } else if (type_name_const_str == g_objc_type_name_selector) {
488                if (log)
489                  dwarf->GetObjectFile()->GetModule()->LogMessage(
490                      log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' "
491                           "is Objective-C 'selector' built-in type.",
492                      die.GetOffset(), die.GetTagAsCString(), die.GetName());
493                clang_type = m_ast.GetBasicType(eBasicTypeObjCSel);
494                encoding_data_type = Type::eEncodingIsUID;
495                encoding_uid.Clear();
496                resolve_state = Type::eResolveStateFull;
497              }
498            } else if (encoding_data_type == Type::eEncodingIsPointerUID &&
499                       encoding_uid.IsValid()) {
500              // Clang sometimes erroneously emits id as objc_object*.  In that
501              // case we fix up the type to "id".
502
503              const DWARFDIE encoding_die = dwarf->GetDIE(DIERef(encoding_uid));
504
505              if (encoding_die && encoding_die.Tag() == DW_TAG_structure_type) {
506                if (const char *struct_name = encoding_die.GetName()) {
507                  if (!strcmp(struct_name, "objc_object")) {
508                    if (log)
509                      dwarf->GetObjectFile()->GetModule()->LogMessage(
510                          log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s "
511                               "'%s' is 'objc_object*', which we overrode to "
512                               "'id'.",
513                          die.GetOffset(), die.GetTagAsCString(),
514                          die.GetName());
515                    clang_type = m_ast.GetBasicType(eBasicTypeObjCID);
516                    encoding_data_type = Type::eEncodingIsUID;
517                    encoding_uid.Clear();
518                    resolve_state = Type::eResolveStateFull;
519                  }
520                }
521              }
522            }
523          }
524        }
525
526        type_sp.reset(
527            new Type(die.GetID(), dwarf, type_name_const_str, byte_size, NULL,
528                     DIERef(encoding_uid).GetUID(dwarf), encoding_data_type,
529                     &decl, clang_type, resolve_state));
530
531        dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
532      } break;
533
534      case DW_TAG_structure_type:
535      case DW_TAG_union_type:
536      case DW_TAG_class_type: {
537        // Set a bit that lets us know that we are currently parsing this
538        dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED;
539        bool byte_size_valid = false;
540
541        LanguageType class_language = eLanguageTypeUnknown;
542        bool is_complete_objc_class = false;
543        size_t calling_convention
544                = llvm::dwarf::CallingConvention::DW_CC_normal;
545
546        const size_t num_attributes = die.GetAttributes(attributes);
547        if (num_attributes > 0) {
548          uint32_t i;
549          for (i = 0; i < num_attributes; ++i) {
550            attr = attributes.AttributeAtIndex(i);
551            if (attributes.ExtractFormValueAtIndex(i, form_value)) {
552              switch (attr) {
553              case DW_AT_decl_file:
554                decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
555                    form_value.Unsigned()));
556                break;
557
558              case DW_AT_decl_line:
559                decl.SetLine(form_value.Unsigned());
560                break;
561
562              case DW_AT_decl_column:
563                decl.SetColumn(form_value.Unsigned());
564                break;
565
566              case DW_AT_name:
567                type_name_cstr = form_value.AsCString();
568                type_name_const_str.SetCString(type_name_cstr);
569                break;
570
571              case DW_AT_byte_size:
572                byte_size = form_value.Unsigned();
573                byte_size_valid = true;
574                break;
575
576              case DW_AT_accessibility:
577                accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
578                break;
579
580              case DW_AT_declaration:
581                is_forward_declaration = form_value.Boolean();
582                break;
583
584              case DW_AT_APPLE_runtime_class:
585                class_language = (LanguageType)form_value.Signed();
586                break;
587
588              case DW_AT_APPLE_objc_complete_type:
589                is_complete_objc_class = form_value.Signed();
590                break;
591              case DW_AT_calling_convention:
592                calling_convention = form_value.Unsigned();
593                break;
594
595              case DW_AT_allocated:
596              case DW_AT_associated:
597              case DW_AT_data_location:
598              case DW_AT_description:
599              case DW_AT_start_scope:
600              case DW_AT_visibility:
601              default:
602              case DW_AT_sibling:
603                break;
604              }
605            }
606          }
607        }
608
609        // UniqueDWARFASTType is large, so don't create a local variables on
610        // the stack, put it on the heap. This function is often called
611        // recursively and clang isn't good and sharing the stack space for
612        // variables in different blocks.
613        std::unique_ptr<UniqueDWARFASTType> unique_ast_entry_ap(
614            new UniqueDWARFASTType());
615
616        ConstString unique_typename(type_name_const_str);
617        Declaration unique_decl(decl);
618
619        if (type_name_const_str) {
620          LanguageType die_language = die.GetLanguage();
621          if (Language::LanguageIsCPlusPlus(die_language)) {
622            // For C++, we rely solely upon the one definition rule that says
623            // only one thing can exist at a given decl context. We ignore the
624            // file and line that things are declared on.
625            std::string qualified_name;
626            if (die.GetQualifiedName(qualified_name))
627              unique_typename = ConstString(qualified_name);
628            unique_decl.Clear();
629          }
630
631          if (dwarf->GetUniqueDWARFASTTypeMap().Find(
632                  unique_typename, die, unique_decl,
633                  byte_size_valid ? byte_size : -1, *unique_ast_entry_ap)) {
634            type_sp = unique_ast_entry_ap->m_type_sp;
635            if (type_sp) {
636              dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
637              return type_sp;
638            }
639          }
640        }
641
642        DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(),
643                     DW_TAG_value_to_name(tag), type_name_cstr);
644
645        int tag_decl_kind = -1;
646        AccessType default_accessibility = eAccessNone;
647        if (tag == DW_TAG_structure_type) {
648          tag_decl_kind = clang::TTK_Struct;
649          default_accessibility = eAccessPublic;
650        } else if (tag == DW_TAG_union_type) {
651          tag_decl_kind = clang::TTK_Union;
652          default_accessibility = eAccessPublic;
653        } else if (tag == DW_TAG_class_type) {
654          tag_decl_kind = clang::TTK_Class;
655          default_accessibility = eAccessPrivate;
656        }
657
658        if (byte_size_valid && byte_size == 0 && type_name_cstr &&
659            !die.HasChildren() &&
660            sc.comp_unit->GetLanguage() == eLanguageTypeObjC) {
661          // Work around an issue with clang at the moment where forward
662          // declarations for objective C classes are emitted as:
663          //  DW_TAG_structure_type [2]
664          //  DW_AT_name( "ForwardObjcClass" )
665          //  DW_AT_byte_size( 0x00 )
666          //  DW_AT_decl_file( "..." )
667          //  DW_AT_decl_line( 1 )
668          //
669          // Note that there is no DW_AT_declaration and there are no children,
670          // and the byte size is zero.
671          is_forward_declaration = true;
672        }
673
674        if (class_language == eLanguageTypeObjC ||
675            class_language == eLanguageTypeObjC_plus_plus) {
676          if (!is_complete_objc_class &&
677              die.Supports_DW_AT_APPLE_objc_complete_type()) {
678            // We have a valid eSymbolTypeObjCClass class symbol whose name
679            // matches the current objective C class that we are trying to find
680            // and this DIE isn't the complete definition (we checked
681            // is_complete_objc_class above and know it is false), so the real
682            // definition is in here somewhere
683            type_sp = dwarf->FindCompleteObjCDefinitionTypeForDIE(
684                die, type_name_const_str, true);
685
686            if (!type_sp) {
687              SymbolFileDWARFDebugMap *debug_map_symfile =
688                  dwarf->GetDebugMapSymfile();
689              if (debug_map_symfile) {
690                // We weren't able to find a full declaration in this DWARF,
691                // see if we have a declaration anywhere else...
692                type_sp =
693                    debug_map_symfile->FindCompleteObjCDefinitionTypeForDIE(
694                        die, type_name_const_str, true);
695              }
696            }
697
698            if (type_sp) {
699              if (log) {
700                dwarf->GetObjectFile()->GetModule()->LogMessage(
701                    log, "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is an "
702                         "incomplete objc type, complete type is 0x%8.8" PRIx64,
703                    static_cast<void *>(this), die.GetOffset(),
704                    DW_TAG_value_to_name(tag), type_name_cstr,
705                    type_sp->GetID());
706              }
707
708              // We found a real definition for this type elsewhere so lets use
709              // it and cache the fact that we found a complete type for this
710              // die
711              dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
712              return type_sp;
713            }
714          }
715        }
716
717        if (is_forward_declaration) {
718          // We have a forward declaration to a type and we need to try and
719          // find a full declaration. We look in the current type index just in
720          // case we have a forward declaration followed by an actual
721          // declarations in the DWARF. If this fails, we need to look
722          // elsewhere...
723          if (log) {
724            dwarf->GetObjectFile()->GetModule()->LogMessage(
725                log, "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a "
726                     "forward declaration, trying to find complete type",
727                static_cast<void *>(this), die.GetOffset(),
728                DW_TAG_value_to_name(tag), type_name_cstr);
729          }
730
731          // See if the type comes from a DWO module and if so, track down that
732          // type.
733          type_sp = ParseTypeFromDWO(die, log);
734          if (type_sp)
735            return type_sp;
736
737          DWARFDeclContext die_decl_ctx;
738          die.GetDWARFDeclContext(die_decl_ctx);
739
740          // type_sp = FindDefinitionTypeForDIE (dwarf_cu, die,
741          // type_name_const_str);
742          type_sp = dwarf->FindDefinitionTypeForDWARFDeclContext(die_decl_ctx);
743
744          if (!type_sp) {
745            SymbolFileDWARFDebugMap *debug_map_symfile =
746                dwarf->GetDebugMapSymfile();
747            if (debug_map_symfile) {
748              // We weren't able to find a full declaration in this DWARF, see
749              // if we have a declaration anywhere else...
750              type_sp =
751                  debug_map_symfile->FindDefinitionTypeForDWARFDeclContext(
752                      die_decl_ctx);
753            }
754          }
755
756          if (type_sp) {
757            if (log) {
758              dwarf->GetObjectFile()->GetModule()->LogMessage(
759                  log, "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a "
760                       "forward declaration, complete type is 0x%8.8" PRIx64,
761                  static_cast<void *>(this), die.GetOffset(),
762                  DW_TAG_value_to_name(tag), type_name_cstr, type_sp->GetID());
763            }
764
765            // We found a real definition for this type elsewhere so lets use
766            // it and cache the fact that we found a complete type for this die
767            dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
768            clang::DeclContext *defn_decl_ctx = GetCachedClangDeclContextForDIE(
769                dwarf->DebugInfo()->GetDIE(DIERef(type_sp->GetID(), dwarf)));
770            if (defn_decl_ctx)
771              LinkDeclContextToDIE(defn_decl_ctx, die);
772            return type_sp;
773          }
774        }
775        assert(tag_decl_kind != -1);
776        bool clang_type_was_created = false;
777        clang_type.SetCompilerType(
778            &m_ast, dwarf->GetForwardDeclDieToClangType().lookup(die.GetDIE()));
779        if (!clang_type) {
780          clang::DeclContext *decl_ctx =
781              GetClangDeclContextContainingDIE(die, nullptr);
782
783          // If your decl context is a record that was imported from another
784          // AST context (in the gmodules case), we need to make sure the type
785          // backing the Decl is complete before adding children to it. This is
786          // not an issue in the non-gmodules case because the debug info will
787          // always contain a full definition of parent types in that case.
788          CompleteExternalTagDeclType(GetClangASTImporter(), decl_ctx, die,
789                                      type_name_cstr);
790
791          if (accessibility == eAccessNone && decl_ctx) {
792            // Check the decl context that contains this class/struct/union. If
793            // it is a class we must give it an accessibility.
794            const clang::Decl::Kind containing_decl_kind =
795                decl_ctx->getDeclKind();
796            if (DeclKindIsCXXClass(containing_decl_kind))
797              accessibility = default_accessibility;
798          }
799
800          ClangASTMetadata metadata;
801          metadata.SetUserID(die.GetID());
802          metadata.SetIsDynamicCXXType(dwarf->ClassOrStructIsVirtual(die));
803
804          if (type_name_cstr && strchr(type_name_cstr, '<')) {
805            ClangASTContext::TemplateParameterInfos template_param_infos;
806            if (ParseTemplateParameterInfos(die, template_param_infos)) {
807              clang::ClassTemplateDecl *class_template_decl =
808                  m_ast.ParseClassTemplateDecl(decl_ctx, accessibility,
809                                               type_name_cstr, tag_decl_kind,
810                                               template_param_infos);
811              if (!class_template_decl) {
812                if (log) {
813                  dwarf->GetObjectFile()->GetModule()->LogMessage(
814                    log, "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" "
815                         "clang::ClassTemplateDecl failed to return a decl.",
816                    static_cast<void *>(this), die.GetOffset(),
817                    DW_TAG_value_to_name(tag), type_name_cstr);
818                }
819                return TypeSP();
820              }
821
822              clang::ClassTemplateSpecializationDecl
823                  *class_specialization_decl =
824                      m_ast.CreateClassTemplateSpecializationDecl(
825                          decl_ctx, class_template_decl, tag_decl_kind,
826                          template_param_infos);
827              clang_type = m_ast.CreateClassTemplateSpecializationType(
828                  class_specialization_decl);
829              clang_type_was_created = true;
830
831              m_ast.SetMetadata(class_template_decl, metadata);
832              m_ast.SetMetadata(class_specialization_decl, metadata);
833            }
834          }
835
836          if (!clang_type_was_created) {
837            clang_type_was_created = true;
838            clang_type = m_ast.CreateRecordType(decl_ctx, accessibility,
839                                                type_name_cstr, tag_decl_kind,
840                                                class_language, &metadata);
841          }
842        }
843
844        // Store a forward declaration to this class type in case any
845        // parameters in any class methods need it for the clang types for
846        // function prototypes.
847        LinkDeclContextToDIE(m_ast.GetDeclContextForType(clang_type), die);
848        type_sp.reset(new Type(die.GetID(), dwarf, type_name_const_str,
849                               byte_size, NULL, LLDB_INVALID_UID,
850                               Type::eEncodingIsUID, &decl, clang_type,
851                               Type::eResolveStateForward));
852
853        type_sp->SetIsCompleteObjCClass(is_complete_objc_class);
854
855        // Add our type to the unique type map so we don't end up creating many
856        // copies of the same type over and over in the ASTContext for our
857        // module
858        unique_ast_entry_ap->m_type_sp = type_sp;
859        unique_ast_entry_ap->m_die = die;
860        unique_ast_entry_ap->m_declaration = unique_decl;
861        unique_ast_entry_ap->m_byte_size = byte_size;
862        dwarf->GetUniqueDWARFASTTypeMap().Insert(unique_typename,
863                                                 *unique_ast_entry_ap);
864
865        if (is_forward_declaration && die.HasChildren()) {
866          // Check to see if the DIE actually has a definition, some version of
867          // GCC will
868          // emit DIEs with DW_AT_declaration set to true, but yet still have
869          // subprogram, members, or inheritance, so we can't trust it
870          DWARFDIE child_die = die.GetFirstChild();
871          while (child_die) {
872            switch (child_die.Tag()) {
873            case DW_TAG_inheritance:
874            case DW_TAG_subprogram:
875            case DW_TAG_member:
876            case DW_TAG_APPLE_property:
877            case DW_TAG_class_type:
878            case DW_TAG_structure_type:
879            case DW_TAG_enumeration_type:
880            case DW_TAG_typedef:
881            case DW_TAG_union_type:
882              child_die.Clear();
883              is_forward_declaration = false;
884              break;
885            default:
886              child_die = child_die.GetSibling();
887              break;
888            }
889          }
890        }
891
892        if (!is_forward_declaration) {
893          // Always start the definition for a class type so that if the class
894          // has child classes or types that require the class to be created
895          // for use as their decl contexts the class will be ready to accept
896          // these child definitions.
897          if (!die.HasChildren()) {
898            // No children for this struct/union/class, lets finish it
899            if (ClangASTContext::StartTagDeclarationDefinition(clang_type)) {
900              ClangASTContext::CompleteTagDeclarationDefinition(clang_type);
901            } else {
902              dwarf->GetObjectFile()->GetModule()->ReportError(
903                  "DWARF DIE at 0x%8.8x named \"%s\" was not able to start its "
904                  "definition.\nPlease file a bug and attach the file at the "
905                  "start of this error message",
906                  die.GetOffset(), type_name_cstr);
907            }
908
909            if (tag == DW_TAG_structure_type) // this only applies in C
910            {
911              clang::RecordDecl *record_decl =
912                  ClangASTContext::GetAsRecordDecl(clang_type);
913
914              if (record_decl) {
915                GetClangASTImporter().InsertRecordDecl(
916                    record_decl, ClangASTImporter::LayoutInfo());
917              }
918            }
919          } else if (clang_type_was_created) {
920            // Start the definition if the class is not objective C since the
921            // underlying decls respond to isCompleteDefinition(). Objective
922            // C decls don't respond to isCompleteDefinition() so we can't
923            // start the declaration definition right away. For C++
924            // class/union/structs we want to start the definition in case the
925            // class is needed as the declaration context for a contained class
926            // or type without the need to complete that type..
927
928            if (class_language != eLanguageTypeObjC &&
929                class_language != eLanguageTypeObjC_plus_plus)
930              ClangASTContext::StartTagDeclarationDefinition(clang_type);
931
932            // Leave this as a forward declaration until we need to know the
933            // details of the type. lldb_private::Type will automatically call
934            // the SymbolFile virtual function
935            // "SymbolFileDWARF::CompleteType(Type *)" When the definition
936            // needs to be defined.
937            assert(!dwarf->GetForwardDeclClangTypeToDie().count(
938                       ClangUtil::RemoveFastQualifiers(clang_type)
939                           .GetOpaqueQualType()) &&
940                   "Type already in the forward declaration map!");
941            // Can't assume m_ast.GetSymbolFile() is actually a
942            // SymbolFileDWARF, it can be a SymbolFileDWARFDebugMap for Apple
943            // binaries.
944            dwarf->GetForwardDeclDieToClangType()[die.GetDIE()] =
945                clang_type.GetOpaqueQualType();
946            dwarf->GetForwardDeclClangTypeToDie()
947                [ClangUtil::RemoveFastQualifiers(clang_type)
948                     .GetOpaqueQualType()] = die.GetDIERef();
949            m_ast.SetHasExternalStorage(clang_type.GetOpaqueQualType(), true);
950          }
951        }
952
953        // If we made a clang type, set the trivial abi if applicable: We only
954        // do this for pass by value - which implies the Trivial ABI. There
955        // isn't a way to assert that something that would normally be pass by
956        // value is pass by reference, so we ignore that attribute if set.
957        if (calling_convention == llvm::dwarf::DW_CC_pass_by_value) {
958          clang::CXXRecordDecl *record_decl =
959                  m_ast.GetAsCXXRecordDecl(clang_type.GetOpaqueQualType());
960          if (record_decl) {
961            record_decl->setHasTrivialSpecialMemberForCall();
962          }
963        }
964
965      } break;
966
967      case DW_TAG_enumeration_type: {
968        // Set a bit that lets us know that we are currently parsing this
969        dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED;
970
971        bool is_scoped = false;
972        DWARFFormValue encoding_form;
973
974        const size_t num_attributes = die.GetAttributes(attributes);
975        if (num_attributes > 0) {
976          uint32_t i;
977
978          for (i = 0; i < num_attributes; ++i) {
979            attr = attributes.AttributeAtIndex(i);
980            if (attributes.ExtractFormValueAtIndex(i, form_value)) {
981              switch (attr) {
982              case DW_AT_decl_file:
983                decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
984                    form_value.Unsigned()));
985                break;
986              case DW_AT_decl_line:
987                decl.SetLine(form_value.Unsigned());
988                break;
989              case DW_AT_decl_column:
990                decl.SetColumn(form_value.Unsigned());
991                break;
992              case DW_AT_name:
993                type_name_cstr = form_value.AsCString();
994                type_name_const_str.SetCString(type_name_cstr);
995                break;
996              case DW_AT_type:
997                encoding_form = form_value;
998                break;
999              case DW_AT_byte_size:
1000                byte_size = form_value.Unsigned();
1001                break;
1002              case DW_AT_accessibility:
1003                break; // accessibility =
1004                       // DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
1005              case DW_AT_declaration:
1006                is_forward_declaration = form_value.Boolean();
1007                break;
1008              case DW_AT_enum_class:
1009                is_scoped = form_value.Boolean();
1010                break;
1011              case DW_AT_allocated:
1012              case DW_AT_associated:
1013              case DW_AT_bit_stride:
1014              case DW_AT_byte_stride:
1015              case DW_AT_data_location:
1016              case DW_AT_description:
1017              case DW_AT_start_scope:
1018              case DW_AT_visibility:
1019              case DW_AT_specification:
1020              case DW_AT_abstract_origin:
1021              case DW_AT_sibling:
1022                break;
1023              }
1024            }
1025          }
1026
1027          if (is_forward_declaration) {
1028            type_sp = ParseTypeFromDWO(die, log);
1029            if (type_sp)
1030              return type_sp;
1031
1032            DWARFDeclContext die_decl_ctx;
1033            die.GetDWARFDeclContext(die_decl_ctx);
1034
1035            type_sp =
1036                dwarf->FindDefinitionTypeForDWARFDeclContext(die_decl_ctx);
1037
1038            if (!type_sp) {
1039              SymbolFileDWARFDebugMap *debug_map_symfile =
1040                  dwarf->GetDebugMapSymfile();
1041              if (debug_map_symfile) {
1042                // We weren't able to find a full declaration in this DWARF,
1043                // see if we have a declaration anywhere else...
1044                type_sp =
1045                    debug_map_symfile->FindDefinitionTypeForDWARFDeclContext(
1046                        die_decl_ctx);
1047              }
1048            }
1049
1050            if (type_sp) {
1051              if (log) {
1052                dwarf->GetObjectFile()->GetModule()->LogMessage(
1053                    log, "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a "
1054                         "forward declaration, complete type is 0x%8.8" PRIx64,
1055                    static_cast<void *>(this), die.GetOffset(),
1056                    DW_TAG_value_to_name(tag), type_name_cstr,
1057                    type_sp->GetID());
1058              }
1059
1060              // We found a real definition for this type elsewhere so lets use
1061              // it and cache the fact that we found a complete type for this
1062              // die
1063              dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
1064              clang::DeclContext *defn_decl_ctx =
1065                  GetCachedClangDeclContextForDIE(dwarf->DebugInfo()->GetDIE(
1066                      DIERef(type_sp->GetID(), dwarf)));
1067              if (defn_decl_ctx)
1068                LinkDeclContextToDIE(defn_decl_ctx, die);
1069              return type_sp;
1070            }
1071          }
1072          DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(),
1073                       DW_TAG_value_to_name(tag), type_name_cstr);
1074
1075          CompilerType enumerator_clang_type;
1076          clang_type.SetCompilerType(
1077              &m_ast,
1078              dwarf->GetForwardDeclDieToClangType().lookup(die.GetDIE()));
1079          if (!clang_type) {
1080            if (encoding_form.IsValid()) {
1081              Type *enumerator_type =
1082                  dwarf->ResolveTypeUID(DIERef(encoding_form));
1083              if (enumerator_type)
1084                enumerator_clang_type = enumerator_type->GetFullCompilerType();
1085            }
1086
1087            if (!enumerator_clang_type) {
1088              if (byte_size > 0) {
1089                enumerator_clang_type =
1090                    m_ast.GetBuiltinTypeForDWARFEncodingAndBitSize(
1091                        NULL, DW_ATE_signed, byte_size * 8);
1092              } else {
1093                enumerator_clang_type = m_ast.GetBasicType(eBasicTypeInt);
1094              }
1095            }
1096
1097            clang_type = m_ast.CreateEnumerationType(
1098                type_name_cstr, GetClangDeclContextContainingDIE(die, nullptr),
1099                decl, enumerator_clang_type, is_scoped);
1100          } else {
1101            enumerator_clang_type =
1102                m_ast.GetEnumerationIntegerType(clang_type.GetOpaqueQualType());
1103          }
1104
1105          LinkDeclContextToDIE(
1106              ClangASTContext::GetDeclContextForType(clang_type), die);
1107
1108          type_sp.reset(new Type(
1109              die.GetID(), dwarf, type_name_const_str, byte_size, NULL,
1110              DIERef(encoding_form).GetUID(dwarf), Type::eEncodingIsUID, &decl,
1111              clang_type, Type::eResolveStateForward));
1112
1113          if (ClangASTContext::StartTagDeclarationDefinition(clang_type)) {
1114            if (die.HasChildren()) {
1115              SymbolContext cu_sc(die.GetLLDBCompileUnit());
1116              bool is_signed = false;
1117              enumerator_clang_type.IsIntegerType(is_signed);
1118              ParseChildEnumerators(cu_sc, clang_type, is_signed,
1119                                    type_sp->GetByteSize(), die);
1120            }
1121            ClangASTContext::CompleteTagDeclarationDefinition(clang_type);
1122          } else {
1123            dwarf->GetObjectFile()->GetModule()->ReportError(
1124                "DWARF DIE at 0x%8.8x named \"%s\" was not able to start its "
1125                "definition.\nPlease file a bug and attach the file at the "
1126                "start of this error message",
1127                die.GetOffset(), type_name_cstr);
1128          }
1129        }
1130      } break;
1131
1132      case DW_TAG_inlined_subroutine:
1133      case DW_TAG_subprogram:
1134      case DW_TAG_subroutine_type: {
1135        // Set a bit that lets us know that we are currently parsing this
1136        dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED;
1137
1138        DWARFFormValue type_die_form;
1139        bool is_variadic = false;
1140        bool is_inline = false;
1141        bool is_static = false;
1142        bool is_virtual = false;
1143        bool is_explicit = false;
1144        bool is_artificial = false;
1145        bool has_template_params = false;
1146        DWARFFormValue specification_die_form;
1147        DWARFFormValue abstract_origin_die_form;
1148        dw_offset_t object_pointer_die_offset = DW_INVALID_OFFSET;
1149
1150        unsigned type_quals = 0;
1151        clang::StorageClass storage =
1152            clang::SC_None; //, Extern, Static, PrivateExtern
1153
1154        const size_t num_attributes = die.GetAttributes(attributes);
1155        if (num_attributes > 0) {
1156          uint32_t i;
1157          for (i = 0; i < num_attributes; ++i) {
1158            attr = attributes.AttributeAtIndex(i);
1159            if (attributes.ExtractFormValueAtIndex(i, form_value)) {
1160              switch (attr) {
1161              case DW_AT_decl_file:
1162                decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
1163                    form_value.Unsigned()));
1164                break;
1165              case DW_AT_decl_line:
1166                decl.SetLine(form_value.Unsigned());
1167                break;
1168              case DW_AT_decl_column:
1169                decl.SetColumn(form_value.Unsigned());
1170                break;
1171              case DW_AT_name:
1172                type_name_cstr = form_value.AsCString();
1173                type_name_const_str.SetCString(type_name_cstr);
1174                break;
1175
1176              case DW_AT_linkage_name:
1177              case DW_AT_MIPS_linkage_name:
1178                mangled_name_cstr = form_value.AsCString();
1179                break;
1180              case DW_AT_type:
1181                type_die_form = form_value;
1182                break;
1183              case DW_AT_accessibility:
1184                accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
1185                break;
1186              case DW_AT_declaration:
1187                break; // is_forward_declaration = form_value.Boolean(); break;
1188              case DW_AT_inline:
1189                is_inline = form_value.Boolean();
1190                break;
1191              case DW_AT_virtuality:
1192                is_virtual = form_value.Boolean();
1193                break;
1194              case DW_AT_explicit:
1195                is_explicit = form_value.Boolean();
1196                break;
1197              case DW_AT_artificial:
1198                is_artificial = form_value.Boolean();
1199                break;
1200
1201              case DW_AT_external:
1202                if (form_value.Unsigned()) {
1203                  if (storage == clang::SC_None)
1204                    storage = clang::SC_Extern;
1205                  else
1206                    storage = clang::SC_PrivateExtern;
1207                }
1208                break;
1209
1210              case DW_AT_specification:
1211                specification_die_form = form_value;
1212                break;
1213
1214              case DW_AT_abstract_origin:
1215                abstract_origin_die_form = form_value;
1216                break;
1217
1218              case DW_AT_object_pointer:
1219                object_pointer_die_offset = form_value.Reference();
1220                break;
1221
1222              case DW_AT_allocated:
1223              case DW_AT_associated:
1224              case DW_AT_address_class:
1225              case DW_AT_calling_convention:
1226              case DW_AT_data_location:
1227              case DW_AT_elemental:
1228              case DW_AT_entry_pc:
1229              case DW_AT_frame_base:
1230              case DW_AT_high_pc:
1231              case DW_AT_low_pc:
1232              case DW_AT_prototyped:
1233              case DW_AT_pure:
1234              case DW_AT_ranges:
1235              case DW_AT_recursive:
1236              case DW_AT_return_addr:
1237              case DW_AT_segment:
1238              case DW_AT_start_scope:
1239              case DW_AT_static_link:
1240              case DW_AT_trampoline:
1241              case DW_AT_visibility:
1242              case DW_AT_vtable_elem_location:
1243              case DW_AT_description:
1244              case DW_AT_sibling:
1245                break;
1246              }
1247            }
1248          }
1249        }
1250
1251        std::string object_pointer_name;
1252        if (object_pointer_die_offset != DW_INVALID_OFFSET) {
1253          DWARFDIE object_pointer_die = die.GetDIE(object_pointer_die_offset);
1254          if (object_pointer_die) {
1255            const char *object_pointer_name_cstr = object_pointer_die.GetName();
1256            if (object_pointer_name_cstr)
1257              object_pointer_name = object_pointer_name_cstr;
1258          }
1259        }
1260
1261        DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(),
1262                     DW_TAG_value_to_name(tag), type_name_cstr);
1263
1264        CompilerType return_clang_type;
1265        Type *func_type = NULL;
1266
1267        if (type_die_form.IsValid())
1268          func_type = dwarf->ResolveTypeUID(DIERef(type_die_form));
1269
1270        if (func_type)
1271          return_clang_type = func_type->GetForwardCompilerType();
1272        else
1273          return_clang_type = m_ast.GetBasicType(eBasicTypeVoid);
1274
1275        std::vector<CompilerType> function_param_types;
1276        std::vector<clang::ParmVarDecl *> function_param_decls;
1277
1278        // Parse the function children for the parameters
1279
1280        DWARFDIE decl_ctx_die;
1281        clang::DeclContext *containing_decl_ctx =
1282            GetClangDeclContextContainingDIE(die, &decl_ctx_die);
1283        const clang::Decl::Kind containing_decl_kind =
1284            containing_decl_ctx->getDeclKind();
1285
1286        bool is_cxx_method = DeclKindIsCXXClass(containing_decl_kind);
1287        // Start off static. This will be set to false in
1288        // ParseChildParameters(...) if we find a "this" parameters as the
1289        // first parameter
1290        if (is_cxx_method) {
1291          is_static = true;
1292        }
1293
1294        if (die.HasChildren()) {
1295          bool skip_artificial = true;
1296          ParseChildParameters(*sc.comp_unit, containing_decl_ctx, die,
1297                               skip_artificial, is_static, is_variadic,
1298                               has_template_params, function_param_types,
1299                               function_param_decls, type_quals);
1300        }
1301
1302        bool ignore_containing_context = false;
1303        // Check for templatized class member functions. If we had any
1304        // DW_TAG_template_type_parameter or DW_TAG_template_value_parameter
1305        // the DW_TAG_subprogram DIE, then we can't let this become a method in
1306        // a class. Why? Because templatized functions are only emitted if one
1307        // of the templatized methods is used in the current compile unit and
1308        // we will end up with classes that may or may not include these member
1309        // functions and this means one class won't match another class
1310        // definition and it affects our ability to use a class in the clang
1311        // expression parser. So for the greater good, we currently must not
1312        // allow any template member functions in a class definition.
1313        if (is_cxx_method && has_template_params) {
1314          ignore_containing_context = true;
1315          is_cxx_method = false;
1316        }
1317
1318        // clang_type will get the function prototype clang type after this
1319        // call
1320        clang_type = m_ast.CreateFunctionType(
1321            return_clang_type, function_param_types.data(),
1322            function_param_types.size(), is_variadic, type_quals);
1323
1324        if (type_name_cstr) {
1325          bool type_handled = false;
1326          if (tag == DW_TAG_subprogram || tag == DW_TAG_inlined_subroutine) {
1327            ObjCLanguage::MethodName objc_method(type_name_cstr, true);
1328            if (objc_method.IsValid(true)) {
1329              CompilerType class_opaque_type;
1330              ConstString class_name(objc_method.GetClassName());
1331              if (class_name) {
1332                TypeSP complete_objc_class_type_sp(
1333                    dwarf->FindCompleteObjCDefinitionTypeForDIE(
1334                        DWARFDIE(), class_name, false));
1335
1336                if (complete_objc_class_type_sp) {
1337                  CompilerType type_clang_forward_type =
1338                      complete_objc_class_type_sp->GetForwardCompilerType();
1339                  if (ClangASTContext::IsObjCObjectOrInterfaceType(
1340                          type_clang_forward_type))
1341                    class_opaque_type = type_clang_forward_type;
1342                }
1343              }
1344
1345              if (class_opaque_type) {
1346                // If accessibility isn't set to anything valid, assume public
1347                // for now...
1348                if (accessibility == eAccessNone)
1349                  accessibility = eAccessPublic;
1350
1351                clang::ObjCMethodDecl *objc_method_decl =
1352                    m_ast.AddMethodToObjCObjectType(
1353                        class_opaque_type, type_name_cstr, clang_type,
1354                        accessibility, is_artificial, is_variadic);
1355                type_handled = objc_method_decl != NULL;
1356                if (type_handled) {
1357                  LinkDeclContextToDIE(
1358                      ClangASTContext::GetAsDeclContext(objc_method_decl), die);
1359                  m_ast.SetMetadataAsUserID(objc_method_decl, die.GetID());
1360                } else {
1361                  dwarf->GetObjectFile()->GetModule()->ReportError(
1362                      "{0x%8.8x}: invalid Objective-C method 0x%4.4x (%s), "
1363                      "please file a bug and attach the file at the start of "
1364                      "this error message",
1365                      die.GetOffset(), tag, DW_TAG_value_to_name(tag));
1366                }
1367              }
1368            } else if (is_cxx_method) {
1369              // Look at the parent of this DIE and see if is is a class or
1370              // struct and see if this is actually a C++ method
1371              Type *class_type = dwarf->ResolveType(decl_ctx_die);
1372              if (class_type) {
1373                bool alternate_defn = false;
1374                if (class_type->GetID() != decl_ctx_die.GetID() ||
1375                    decl_ctx_die.GetContainingDWOModuleDIE()) {
1376                  alternate_defn = true;
1377
1378                  // We uniqued the parent class of this function to another
1379                  // class so we now need to associate all dies under
1380                  // "decl_ctx_die" to DIEs in the DIE for "class_type"...
1381                  SymbolFileDWARF *class_symfile = NULL;
1382                  DWARFDIE class_type_die;
1383
1384                  SymbolFileDWARFDebugMap *debug_map_symfile =
1385                      dwarf->GetDebugMapSymfile();
1386                  if (debug_map_symfile) {
1387                    class_symfile = debug_map_symfile->GetSymbolFileByOSOIndex(
1388                        SymbolFileDWARFDebugMap::GetOSOIndexFromUserID(
1389                            class_type->GetID()));
1390                    class_type_die = class_symfile->DebugInfo()->GetDIE(
1391                        DIERef(class_type->GetID(), dwarf));
1392                  } else {
1393                    class_symfile = dwarf;
1394                    class_type_die = dwarf->DebugInfo()->GetDIE(
1395                        DIERef(class_type->GetID(), dwarf));
1396                  }
1397                  if (class_type_die) {
1398                    DWARFDIECollection failures;
1399
1400                    CopyUniqueClassMethodTypes(decl_ctx_die, class_type_die,
1401                                               class_type, failures);
1402
1403                    // FIXME do something with these failures that's smarter
1404                    // than
1405                    // just dropping them on the ground.  Unfortunately classes
1406                    // don't like having stuff added to them after their
1407                    // definitions are complete...
1408
1409                    type_ptr = dwarf->GetDIEToType()[die.GetDIE()];
1410                    if (type_ptr && type_ptr != DIE_IS_BEING_PARSED) {
1411                      type_sp = type_ptr->shared_from_this();
1412                      break;
1413                    }
1414                  }
1415                }
1416
1417                if (specification_die_form.IsValid()) {
1418                  // We have a specification which we are going to base our
1419                  // function prototype off of, so we need this type to be
1420                  // completed so that the m_die_to_decl_ctx for the method in
1421                  // the specification has a valid clang decl context.
1422                  class_type->GetForwardCompilerType();
1423                  // If we have a specification, then the function type should
1424                  // have been made with the specification and not with this
1425                  // die.
1426                  DWARFDIE spec_die = dwarf->DebugInfo()->GetDIE(
1427                      DIERef(specification_die_form));
1428                  clang::DeclContext *spec_clang_decl_ctx =
1429                      GetClangDeclContextForDIE(spec_die);
1430                  if (spec_clang_decl_ctx) {
1431                    LinkDeclContextToDIE(spec_clang_decl_ctx, die);
1432                  } else {
1433                    dwarf->GetObjectFile()->GetModule()->ReportWarning(
1434                        "0x%8.8" PRIx64 ": DW_AT_specification(0x%8.8" PRIx64
1435                        ") has no decl\n",
1436                        die.GetID(), specification_die_form.Reference());
1437                  }
1438                  type_handled = true;
1439                } else if (abstract_origin_die_form.IsValid()) {
1440                  // We have a specification which we are going to base our
1441                  // function prototype off of, so we need this type to be
1442                  // completed so that the m_die_to_decl_ctx for the method in
1443                  // the abstract origin has a valid clang decl context.
1444                  class_type->GetForwardCompilerType();
1445
1446                  DWARFDIE abs_die = dwarf->DebugInfo()->GetDIE(
1447                      DIERef(abstract_origin_die_form));
1448                  clang::DeclContext *abs_clang_decl_ctx =
1449                      GetClangDeclContextForDIE(abs_die);
1450                  if (abs_clang_decl_ctx) {
1451                    LinkDeclContextToDIE(abs_clang_decl_ctx, die);
1452                  } else {
1453                    dwarf->GetObjectFile()->GetModule()->ReportWarning(
1454                        "0x%8.8" PRIx64 ": DW_AT_abstract_origin(0x%8.8" PRIx64
1455                        ") has no decl\n",
1456                        die.GetID(), abstract_origin_die_form.Reference());
1457                  }
1458                  type_handled = true;
1459                } else {
1460                  CompilerType class_opaque_type =
1461                      class_type->GetForwardCompilerType();
1462                  if (ClangASTContext::IsCXXClassType(class_opaque_type)) {
1463                    if (class_opaque_type.IsBeingDefined() || alternate_defn) {
1464                      if (!is_static && !die.HasChildren()) {
1465                        // We have a C++ member function with no children (this
1466                        // pointer!) and clang will get mad if we try and make
1467                        // a function that isn't well formed in the DWARF, so
1468                        // we will just skip it...
1469                        type_handled = true;
1470                      } else {
1471                        bool add_method = true;
1472                        if (alternate_defn) {
1473                          // If an alternate definition for the class exists,
1474                          // then add the method only if an equivalent is not
1475                          // already present.
1476                          clang::CXXRecordDecl *record_decl =
1477                              m_ast.GetAsCXXRecordDecl(
1478                                  class_opaque_type.GetOpaqueQualType());
1479                          if (record_decl) {
1480                            for (auto method_iter = record_decl->method_begin();
1481                                 method_iter != record_decl->method_end();
1482                                 method_iter++) {
1483                              clang::CXXMethodDecl *method_decl = *method_iter;
1484                              if (method_decl->getNameInfo().getAsString() ==
1485                                  std::string(type_name_cstr)) {
1486                                if (method_decl->getType() ==
1487                                    ClangUtil::GetQualType(clang_type)) {
1488                                  add_method = false;
1489                                  LinkDeclContextToDIE(
1490                                      ClangASTContext::GetAsDeclContext(
1491                                          method_decl),
1492                                      die);
1493                                  type_handled = true;
1494
1495                                  break;
1496                                }
1497                              }
1498                            }
1499                          }
1500                        }
1501
1502                        if (add_method) {
1503                          llvm::PrettyStackTraceFormat stack_trace(
1504                              "SymbolFileDWARF::ParseType() is adding a method "
1505                              "%s to class %s in DIE 0x%8.8" PRIx64 " from %s",
1506                              type_name_cstr,
1507                              class_type->GetName().GetCString(), die.GetID(),
1508                              dwarf->GetObjectFile()
1509                                  ->GetFileSpec()
1510                                  .GetPath()
1511                                  .c_str());
1512
1513                          const bool is_attr_used = false;
1514                          // Neither GCC 4.2 nor clang++ currently set a valid
1515                          // accessibility in the DWARF for C++ methods...
1516                          // Default to public for now...
1517                          if (accessibility == eAccessNone)
1518                            accessibility = eAccessPublic;
1519
1520                          clang::CXXMethodDecl *cxx_method_decl =
1521                              m_ast.AddMethodToCXXRecordType(
1522                                  class_opaque_type.GetOpaqueQualType(),
1523                                  type_name_cstr, mangled_name_cstr, clang_type,
1524                                  accessibility, is_virtual, is_static,
1525                                  is_inline, is_explicit, is_attr_used,
1526                                  is_artificial);
1527
1528                          type_handled = cxx_method_decl != NULL;
1529
1530                          if (type_handled) {
1531                            LinkDeclContextToDIE(
1532                                ClangASTContext::GetAsDeclContext(
1533                                    cxx_method_decl),
1534                                die);
1535
1536                            ClangASTMetadata metadata;
1537                            metadata.SetUserID(die.GetID());
1538
1539                            if (!object_pointer_name.empty()) {
1540                              metadata.SetObjectPtrName(
1541                                  object_pointer_name.c_str());
1542                              if (log)
1543                                log->Printf(
1544                                    "Setting object pointer name: %s on method "
1545                                    "object %p.\n",
1546                                    object_pointer_name.c_str(),
1547                                    static_cast<void *>(cxx_method_decl));
1548                            }
1549                            m_ast.SetMetadata(cxx_method_decl, metadata);
1550                          } else {
1551                            ignore_containing_context = true;
1552                          }
1553                        }
1554                      }
1555                    } else {
1556                      // We were asked to parse the type for a method in a
1557                      // class, yet the class hasn't been asked to complete
1558                      // itself through the clang::ExternalASTSource protocol,
1559                      // so we need to just have the class complete itself and
1560                      // do things the right way, then our
1561                      // DIE should then have an entry in the
1562                      // dwarf->GetDIEToType() map. First
1563                      // we need to modify the dwarf->GetDIEToType() so it
1564                      // doesn't think we are trying to parse this DIE
1565                      // anymore...
1566                      dwarf->GetDIEToType()[die.GetDIE()] = NULL;
1567
1568                      // Now we get the full type to force our class type to
1569                      // complete itself using the clang::ExternalASTSource
1570                      // protocol which will parse all base classes and all
1571                      // methods (including the method for this DIE).
1572                      class_type->GetFullCompilerType();
1573
1574                      // The type for this DIE should have been filled in the
1575                      // function call above
1576                      type_ptr = dwarf->GetDIEToType()[die.GetDIE()];
1577                      if (type_ptr && type_ptr != DIE_IS_BEING_PARSED) {
1578                        type_sp = type_ptr->shared_from_this();
1579                        break;
1580                      }
1581
1582                      // FIXME This is fixing some even uglier behavior but we
1583                      // really need to
1584                      // uniq the methods of each class as well as the class
1585                      // itself. <rdar://problem/11240464>
1586                      type_handled = true;
1587                    }
1588                  }
1589                }
1590              }
1591            }
1592          }
1593
1594          if (!type_handled) {
1595            clang::FunctionDecl *function_decl = nullptr;
1596
1597            if (abstract_origin_die_form.IsValid()) {
1598              DWARFDIE abs_die =
1599                  dwarf->DebugInfo()->GetDIE(DIERef(abstract_origin_die_form));
1600
1601              SymbolContext sc;
1602
1603              if (dwarf->ResolveType(abs_die)) {
1604                function_decl = llvm::dyn_cast_or_null<clang::FunctionDecl>(
1605                    GetCachedClangDeclContextForDIE(abs_die));
1606
1607                if (function_decl) {
1608                  LinkDeclContextToDIE(function_decl, die);
1609                }
1610              }
1611            }
1612
1613            if (!function_decl) {
1614              // We just have a function that isn't part of a class
1615              function_decl = m_ast.CreateFunctionDeclaration(
1616                  ignore_containing_context ? m_ast.GetTranslationUnitDecl()
1617                                            : containing_decl_ctx,
1618                  type_name_cstr, clang_type, storage, is_inline);
1619
1620              if (has_template_params) {
1621                ClangASTContext::TemplateParameterInfos template_param_infos;
1622                ParseTemplateParameterInfos(die, template_param_infos);
1623                clang::FunctionTemplateDecl *func_template_decl =
1624                    m_ast.CreateFunctionTemplateDecl(
1625                        containing_decl_ctx, function_decl, type_name_cstr,
1626                        template_param_infos);
1627                m_ast.CreateFunctionTemplateSpecializationInfo(
1628                    function_decl, func_template_decl, template_param_infos);
1629              }
1630
1631              lldbassert(function_decl);
1632
1633              if (function_decl) {
1634                LinkDeclContextToDIE(function_decl, die);
1635
1636                if (!function_param_decls.empty())
1637                  m_ast.SetFunctionParameters(function_decl,
1638                                              &function_param_decls.front(),
1639                                              function_param_decls.size());
1640
1641                ClangASTMetadata metadata;
1642                metadata.SetUserID(die.GetID());
1643
1644                if (!object_pointer_name.empty()) {
1645                  metadata.SetObjectPtrName(object_pointer_name.c_str());
1646                  if (log)
1647                    log->Printf("Setting object pointer name: %s on function "
1648                                "object %p.",
1649                                object_pointer_name.c_str(),
1650                                static_cast<void *>(function_decl));
1651                }
1652                m_ast.SetMetadata(function_decl, metadata);
1653              }
1654            }
1655          }
1656        }
1657        type_sp.reset(new Type(die.GetID(), dwarf, type_name_const_str, 0, NULL,
1658                               LLDB_INVALID_UID, Type::eEncodingIsUID, &decl,
1659                               clang_type, Type::eResolveStateFull));
1660        assert(type_sp.get());
1661      } break;
1662
1663      case DW_TAG_array_type: {
1664        // Set a bit that lets us know that we are currently parsing this
1665        dwarf->GetDIEToType()[die.GetDIE()] = DIE_IS_BEING_PARSED;
1666
1667        DWARFFormValue type_die_form;
1668        int64_t first_index = 0;
1669        uint32_t byte_stride = 0;
1670        uint32_t bit_stride = 0;
1671        bool is_vector = false;
1672        const size_t num_attributes = die.GetAttributes(attributes);
1673
1674        if (num_attributes > 0) {
1675          uint32_t i;
1676          for (i = 0; i < num_attributes; ++i) {
1677            attr = attributes.AttributeAtIndex(i);
1678            if (attributes.ExtractFormValueAtIndex(i, form_value)) {
1679              switch (attr) {
1680              case DW_AT_decl_file:
1681                decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
1682                    form_value.Unsigned()));
1683                break;
1684              case DW_AT_decl_line:
1685                decl.SetLine(form_value.Unsigned());
1686                break;
1687              case DW_AT_decl_column:
1688                decl.SetColumn(form_value.Unsigned());
1689                break;
1690              case DW_AT_name:
1691                type_name_cstr = form_value.AsCString();
1692                type_name_const_str.SetCString(type_name_cstr);
1693                break;
1694
1695              case DW_AT_type:
1696                type_die_form = form_value;
1697                break;
1698              case DW_AT_byte_size:
1699                break; // byte_size = form_value.Unsigned(); break;
1700              case DW_AT_byte_stride:
1701                byte_stride = form_value.Unsigned();
1702                break;
1703              case DW_AT_bit_stride:
1704                bit_stride = form_value.Unsigned();
1705                break;
1706              case DW_AT_GNU_vector:
1707                is_vector = form_value.Boolean();
1708                break;
1709              case DW_AT_accessibility:
1710                break; // accessibility =
1711                       // DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
1712              case DW_AT_declaration:
1713                break; // is_forward_declaration = form_value.Boolean(); break;
1714              case DW_AT_allocated:
1715              case DW_AT_associated:
1716              case DW_AT_data_location:
1717              case DW_AT_description:
1718              case DW_AT_ordering:
1719              case DW_AT_start_scope:
1720              case DW_AT_visibility:
1721              case DW_AT_specification:
1722              case DW_AT_abstract_origin:
1723              case DW_AT_sibling:
1724                break;
1725              }
1726            }
1727          }
1728
1729          DEBUG_PRINTF("0x%8.8" PRIx64 ": %s (\"%s\")\n", die.GetID(),
1730                       DW_TAG_value_to_name(tag), type_name_cstr);
1731
1732          DIERef type_die_ref(type_die_form);
1733          Type *element_type = dwarf->ResolveTypeUID(type_die_ref);
1734
1735          if (element_type) {
1736            auto array_info = ParseChildArrayInfo(die);
1737            if (array_info) {
1738              first_index = array_info->first_index;
1739              byte_stride = array_info->byte_stride;
1740              bit_stride = array_info->bit_stride;
1741            }
1742            if (byte_stride == 0 && bit_stride == 0)
1743              byte_stride = element_type->GetByteSize();
1744            CompilerType array_element_type =
1745                element_type->GetForwardCompilerType();
1746
1747            if (ClangASTContext::IsCXXClassType(array_element_type) &&
1748                !array_element_type.GetCompleteType()) {
1749              ModuleSP module_sp = die.GetModule();
1750              if (module_sp) {
1751                if (die.GetCU()->GetProducer() == eProducerClang)
1752                  module_sp->ReportError(
1753                      "DWARF DW_TAG_array_type DIE at 0x%8.8x has a "
1754                      "class/union/struct element type DIE 0x%8.8x that is a "
1755                      "forward declaration, not a complete definition.\nTry "
1756                      "compiling the source file with -fstandalone-debug or "
1757                      "disable -gmodules",
1758                      die.GetOffset(), type_die_ref.die_offset);
1759                else
1760                  module_sp->ReportError(
1761                      "DWARF DW_TAG_array_type DIE at 0x%8.8x has a "
1762                      "class/union/struct element type DIE 0x%8.8x that is a "
1763                      "forward declaration, not a complete definition.\nPlease "
1764                      "file a bug against the compiler and include the "
1765                      "preprocessed output for %s",
1766                      die.GetOffset(), type_die_ref.die_offset,
1767                      die.GetLLDBCompileUnit()
1768                          ? die.GetLLDBCompileUnit()->GetPath().c_str()
1769                          : "the source file");
1770              }
1771
1772              // We have no choice other than to pretend that the element class
1773              // type is complete. If we don't do this, clang will crash when
1774              // trying to layout the class. Since we provide layout
1775              // assistance, all ivars in this class and other classes will be
1776              // fine, this is the best we can do short of crashing.
1777              if (ClangASTContext::StartTagDeclarationDefinition(
1778                      array_element_type)) {
1779                ClangASTContext::CompleteTagDeclarationDefinition(
1780                    array_element_type);
1781              } else {
1782                module_sp->ReportError("DWARF DIE at 0x%8.8x was not able to "
1783                                       "start its definition.\nPlease file a "
1784                                       "bug and attach the file at the start "
1785                                       "of this error message",
1786                                       type_die_ref.die_offset);
1787              }
1788            }
1789
1790            uint64_t array_element_bit_stride = byte_stride * 8 + bit_stride;
1791            if (array_info && array_info->element_orders.size() > 0) {
1792              uint64_t num_elements = 0;
1793              auto end = array_info->element_orders.rend();
1794              for (auto pos = array_info->element_orders.rbegin(); pos != end;
1795                   ++pos) {
1796                num_elements = *pos;
1797                clang_type = m_ast.CreateArrayType(array_element_type,
1798                                                   num_elements, is_vector);
1799                array_element_type = clang_type;
1800                array_element_bit_stride =
1801                    num_elements ? array_element_bit_stride * num_elements
1802                                 : array_element_bit_stride;
1803              }
1804            } else {
1805              clang_type =
1806                  m_ast.CreateArrayType(array_element_type, 0, is_vector);
1807            }
1808            ConstString empty_name;
1809            type_sp.reset(new Type(
1810                die.GetID(), dwarf, empty_name, array_element_bit_stride / 8,
1811                NULL, DIERef(type_die_form).GetUID(dwarf), Type::eEncodingIsUID,
1812                &decl, clang_type, Type::eResolveStateFull));
1813            type_sp->SetEncodingType(element_type);
1814            m_ast.SetMetadataAsUserID(clang_type.GetOpaqueQualType(),
1815                                      die.GetID());
1816          }
1817        }
1818      } break;
1819
1820      case DW_TAG_ptr_to_member_type: {
1821        DWARFFormValue type_die_form;
1822        DWARFFormValue containing_type_die_form;
1823
1824        const size_t num_attributes = die.GetAttributes(attributes);
1825
1826        if (num_attributes > 0) {
1827          uint32_t i;
1828          for (i = 0; i < num_attributes; ++i) {
1829            attr = attributes.AttributeAtIndex(i);
1830            if (attributes.ExtractFormValueAtIndex(i, form_value)) {
1831              switch (attr) {
1832              case DW_AT_type:
1833                type_die_form = form_value;
1834                break;
1835              case DW_AT_containing_type:
1836                containing_type_die_form = form_value;
1837                break;
1838              }
1839            }
1840          }
1841
1842          Type *pointee_type = dwarf->ResolveTypeUID(DIERef(type_die_form));
1843          Type *class_type =
1844              dwarf->ResolveTypeUID(DIERef(containing_type_die_form));
1845
1846          CompilerType pointee_clang_type =
1847              pointee_type->GetForwardCompilerType();
1848          CompilerType class_clang_type = class_type->GetLayoutCompilerType();
1849
1850          clang_type = ClangASTContext::CreateMemberPointerType(
1851              class_clang_type, pointee_clang_type);
1852
1853          if (llvm::Optional<uint64_t> clang_type_size =
1854                  clang_type.GetByteSize(nullptr)) {
1855            byte_size = *clang_type_size;
1856            type_sp.reset(new Type(die.GetID(), dwarf, type_name_const_str,
1857                                   byte_size, NULL, LLDB_INVALID_UID,
1858                                   Type::eEncodingIsUID, NULL, clang_type,
1859                                   Type::eResolveStateForward));
1860          }
1861        }
1862
1863        break;
1864      }
1865      default:
1866        dwarf->GetObjectFile()->GetModule()->ReportError(
1867            "{0x%8.8x}: unhandled type tag 0x%4.4x (%s), please file a bug and "
1868            "attach the file at the start of this error message",
1869            die.GetOffset(), tag, DW_TAG_value_to_name(tag));
1870        break;
1871      }
1872
1873      if (type_sp.get()) {
1874        DWARFDIE sc_parent_die =
1875            SymbolFileDWARF::GetParentSymbolContextDIE(die);
1876        dw_tag_t sc_parent_tag = sc_parent_die.Tag();
1877
1878        SymbolContextScope *symbol_context_scope = NULL;
1879        if (sc_parent_tag == DW_TAG_compile_unit ||
1880            sc_parent_tag == DW_TAG_partial_unit) {
1881          symbol_context_scope = sc.comp_unit;
1882        } else if (sc.function != NULL && sc_parent_die) {
1883          symbol_context_scope =
1884              sc.function->GetBlock(true).FindBlockByID(sc_parent_die.GetID());
1885          if (symbol_context_scope == NULL)
1886            symbol_context_scope = sc.function;
1887        }
1888
1889        if (symbol_context_scope != NULL) {
1890          type_sp->SetSymbolContextScope(symbol_context_scope);
1891        }
1892
1893        // We are ready to put this type into the uniqued list up at the module
1894        // level
1895        type_list->Insert(type_sp);
1896
1897        dwarf->GetDIEToType()[die.GetDIE()] = type_sp.get();
1898      }
1899    } else if (type_ptr != DIE_IS_BEING_PARSED) {
1900      type_sp = type_ptr->shared_from_this();
1901    }
1902  }
1903  return type_sp;
1904}
1905
1906// DWARF parsing functions
1907
1908class DWARFASTParserClang::DelayedAddObjCClassProperty {
1909public:
1910  DelayedAddObjCClassProperty(
1911      const CompilerType &class_opaque_type, const char *property_name,
1912      const CompilerType &property_opaque_type, // The property type is only
1913                                                // required if you don't have an
1914                                                // ivar decl
1915      clang::ObjCIvarDecl *ivar_decl, const char *property_setter_name,
1916      const char *property_getter_name, uint32_t property_attributes,
1917      const ClangASTMetadata *metadata)
1918      : m_class_opaque_type(class_opaque_type), m_property_name(property_name),
1919        m_property_opaque_type(property_opaque_type), m_ivar_decl(ivar_decl),
1920        m_property_setter_name(property_setter_name),
1921        m_property_getter_name(property_getter_name),
1922        m_property_attributes(property_attributes) {
1923    if (metadata != NULL) {
1924      m_metadata_ap.reset(new ClangASTMetadata());
1925      *m_metadata_ap = *metadata;
1926    }
1927  }
1928
1929  DelayedAddObjCClassProperty(const DelayedAddObjCClassProperty &rhs) {
1930    *this = rhs;
1931  }
1932
1933  DelayedAddObjCClassProperty &
1934  operator=(const DelayedAddObjCClassProperty &rhs) {
1935    m_class_opaque_type = rhs.m_class_opaque_type;
1936    m_property_name = rhs.m_property_name;
1937    m_property_opaque_type = rhs.m_property_opaque_type;
1938    m_ivar_decl = rhs.m_ivar_decl;
1939    m_property_setter_name = rhs.m_property_setter_name;
1940    m_property_getter_name = rhs.m_property_getter_name;
1941    m_property_attributes = rhs.m_property_attributes;
1942
1943    if (rhs.m_metadata_ap.get()) {
1944      m_metadata_ap.reset(new ClangASTMetadata());
1945      *m_metadata_ap = *rhs.m_metadata_ap;
1946    }
1947    return *this;
1948  }
1949
1950  bool Finalize() {
1951    return ClangASTContext::AddObjCClassProperty(
1952        m_class_opaque_type, m_property_name, m_property_opaque_type,
1953        m_ivar_decl, m_property_setter_name, m_property_getter_name,
1954        m_property_attributes, m_metadata_ap.get());
1955  }
1956
1957private:
1958  CompilerType m_class_opaque_type;
1959  const char *m_property_name;
1960  CompilerType m_property_opaque_type;
1961  clang::ObjCIvarDecl *m_ivar_decl;
1962  const char *m_property_setter_name;
1963  const char *m_property_getter_name;
1964  uint32_t m_property_attributes;
1965  std::unique_ptr<ClangASTMetadata> m_metadata_ap;
1966};
1967
1968bool DWARFASTParserClang::ParseTemplateDIE(
1969    const DWARFDIE &die,
1970    ClangASTContext::TemplateParameterInfos &template_param_infos) {
1971  const dw_tag_t tag = die.Tag();
1972  bool is_template_template_argument = false;
1973
1974  switch (tag) {
1975  case DW_TAG_GNU_template_parameter_pack: {
1976    template_param_infos.packed_args.reset(
1977      new ClangASTContext::TemplateParameterInfos);
1978    for (DWARFDIE child_die = die.GetFirstChild(); child_die.IsValid();
1979         child_die = child_die.GetSibling()) {
1980      if (!ParseTemplateDIE(child_die, *template_param_infos.packed_args))
1981        return false;
1982    }
1983    if (const char *name = die.GetName()) {
1984      template_param_infos.pack_name = name;
1985    }
1986    return true;
1987  }
1988  case DW_TAG_GNU_template_template_param:
1989    is_template_template_argument = true;
1990    LLVM_FALLTHROUGH;
1991  case DW_TAG_template_type_parameter:
1992  case DW_TAG_template_value_parameter: {
1993    DWARFAttributes attributes;
1994    const size_t num_attributes = die.GetAttributes(attributes);
1995    const char *name = nullptr;
1996    const char *template_name = nullptr;
1997    CompilerType clang_type;
1998    uint64_t uval64 = 0;
1999    bool uval64_valid = false;
2000    if (num_attributes > 0) {
2001      DWARFFormValue form_value;
2002      for (size_t i = 0; i < num_attributes; ++i) {
2003        const dw_attr_t attr = attributes.AttributeAtIndex(i);
2004
2005        switch (attr) {
2006        case DW_AT_name:
2007          if (attributes.ExtractFormValueAtIndex(i, form_value))
2008            name = form_value.AsCString();
2009          break;
2010
2011        case DW_AT_GNU_template_name:
2012          if (attributes.ExtractFormValueAtIndex(i, form_value))
2013            template_name = form_value.AsCString();
2014          break;
2015
2016        case DW_AT_type:
2017          if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2018            Type *lldb_type = die.ResolveTypeUID(DIERef(form_value));
2019            if (lldb_type)
2020              clang_type = lldb_type->GetForwardCompilerType();
2021          }
2022          break;
2023
2024        case DW_AT_const_value:
2025          if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2026            uval64_valid = true;
2027            uval64 = form_value.Unsigned();
2028          }
2029          break;
2030        default:
2031          break;
2032        }
2033      }
2034
2035      clang::ASTContext *ast = m_ast.getASTContext();
2036      if (!clang_type)
2037        clang_type = m_ast.GetBasicType(eBasicTypeVoid);
2038
2039      if (!is_template_template_argument) {
2040        bool is_signed = false;
2041        if (name && name[0])
2042          template_param_infos.names.push_back(name);
2043        else
2044          template_param_infos.names.push_back(NULL);
2045
2046        // Get the signed value for any integer or enumeration if available
2047        clang_type.IsIntegerOrEnumerationType(is_signed);
2048
2049        if (tag == DW_TAG_template_value_parameter && uval64_valid) {
2050          llvm::Optional<uint64_t> size = clang_type.GetBitSize(nullptr);
2051          if (!size)
2052            return false;
2053          llvm::APInt apint(*size, uval64, is_signed);
2054          template_param_infos.args.push_back(
2055              clang::TemplateArgument(*ast, llvm::APSInt(apint, !is_signed),
2056                                      ClangUtil::GetQualType(clang_type)));
2057        } else {
2058          template_param_infos.args.push_back(
2059              clang::TemplateArgument(ClangUtil::GetQualType(clang_type)));
2060        }
2061      } else {
2062        auto *tplt_type = m_ast.CreateTemplateTemplateParmDecl(template_name);
2063        template_param_infos.names.push_back(name);
2064        template_param_infos.args.push_back(
2065            clang::TemplateArgument(clang::TemplateName(tplt_type)));
2066      }
2067    }
2068  }
2069    return true;
2070
2071  default:
2072    break;
2073  }
2074  return false;
2075}
2076
2077bool DWARFASTParserClang::ParseTemplateParameterInfos(
2078    const DWARFDIE &parent_die,
2079    ClangASTContext::TemplateParameterInfos &template_param_infos) {
2080
2081  if (!parent_die)
2082    return false;
2083
2084  for (DWARFDIE die = parent_die.GetFirstChild(); die.IsValid();
2085       die = die.GetSibling()) {
2086    const dw_tag_t tag = die.Tag();
2087
2088    switch (tag) {
2089    case DW_TAG_template_type_parameter:
2090    case DW_TAG_template_value_parameter:
2091    case DW_TAG_GNU_template_parameter_pack:
2092    case DW_TAG_GNU_template_template_param:
2093      ParseTemplateDIE(die, template_param_infos);
2094      break;
2095
2096    default:
2097      break;
2098    }
2099  }
2100  if (template_param_infos.args.empty())
2101    return false;
2102  return template_param_infos.args.size() == template_param_infos.names.size();
2103}
2104
2105bool DWARFASTParserClang::CompleteTypeFromDWARF(const DWARFDIE &die,
2106                                                lldb_private::Type *type,
2107                                                CompilerType &clang_type) {
2108  SymbolFileDWARF *dwarf = die.GetDWARF();
2109
2110  std::lock_guard<std::recursive_mutex> guard(
2111      dwarf->GetObjectFile()->GetModule()->GetMutex());
2112
2113  // Disable external storage for this type so we don't get anymore
2114  // clang::ExternalASTSource queries for this type.
2115  m_ast.SetHasExternalStorage(clang_type.GetOpaqueQualType(), false);
2116
2117  if (!die)
2118    return false;
2119
2120#if defined LLDB_CONFIGURATION_DEBUG
2121  //----------------------------------------------------------------------
2122  // For debugging purposes, the LLDB_DWARF_DONT_COMPLETE_TYPENAMES environment
2123  // variable can be set with one or more typenames separated by ';'
2124  // characters. This will cause this function to not complete any types whose
2125  // names match.
2126  //
2127  // Examples of setting this environment variable:
2128  //
2129  // LLDB_DWARF_DONT_COMPLETE_TYPENAMES=Foo
2130  // LLDB_DWARF_DONT_COMPLETE_TYPENAMES=Foo;Bar;Baz
2131  //----------------------------------------------------------------------
2132  const char *dont_complete_typenames_cstr =
2133      getenv("LLDB_DWARF_DONT_COMPLETE_TYPENAMES");
2134  if (dont_complete_typenames_cstr && dont_complete_typenames_cstr[0]) {
2135    const char *die_name = die.GetName();
2136    if (die_name && die_name[0]) {
2137      const char *match = strstr(dont_complete_typenames_cstr, die_name);
2138      if (match) {
2139        size_t die_name_length = strlen(die_name);
2140        while (match) {
2141          const char separator_char = ';';
2142          const char next_char = match[die_name_length];
2143          if (next_char == '\0' || next_char == separator_char) {
2144            if (match == dont_complete_typenames_cstr ||
2145                match[-1] == separator_char)
2146              return false;
2147          }
2148          match = strstr(match + 1, die_name);
2149        }
2150      }
2151    }
2152  }
2153#endif
2154
2155  const dw_tag_t tag = die.Tag();
2156
2157  Log *log =
2158      nullptr; // (LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO|DWARF_LOG_TYPE_COMPLETION));
2159  if (log)
2160    dwarf->GetObjectFile()->GetModule()->LogMessageVerboseBacktrace(
2161        log, "0x%8.8" PRIx64 ": %s '%s' resolving forward declaration...",
2162        die.GetID(), die.GetTagAsCString(), type->GetName().AsCString());
2163  assert(clang_type);
2164  DWARFAttributes attributes;
2165  switch (tag) {
2166  case DW_TAG_structure_type:
2167  case DW_TAG_union_type:
2168  case DW_TAG_class_type: {
2169    ClangASTImporter::LayoutInfo layout_info;
2170
2171    {
2172      if (die.HasChildren()) {
2173        LanguageType class_language = eLanguageTypeUnknown;
2174        if (ClangASTContext::IsObjCObjectOrInterfaceType(clang_type)) {
2175          class_language = eLanguageTypeObjC;
2176          // For objective C we don't start the definition when the class is
2177          // created.
2178          ClangASTContext::StartTagDeclarationDefinition(clang_type);
2179        }
2180
2181        int tag_decl_kind = -1;
2182        AccessType default_accessibility = eAccessNone;
2183        if (tag == DW_TAG_structure_type) {
2184          tag_decl_kind = clang::TTK_Struct;
2185          default_accessibility = eAccessPublic;
2186        } else if (tag == DW_TAG_union_type) {
2187          tag_decl_kind = clang::TTK_Union;
2188          default_accessibility = eAccessPublic;
2189        } else if (tag == DW_TAG_class_type) {
2190          tag_decl_kind = clang::TTK_Class;
2191          default_accessibility = eAccessPrivate;
2192        }
2193
2194        SymbolContext sc(die.GetLLDBCompileUnit());
2195        std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> bases;
2196        std::vector<int> member_accessibilities;
2197        bool is_a_class = false;
2198        // Parse members and base classes first
2199        DWARFDIECollection member_function_dies;
2200
2201        DelayedPropertyList delayed_properties;
2202        ParseChildMembers(sc, die, clang_type, class_language, bases,
2203                          member_accessibilities, member_function_dies,
2204                          delayed_properties, default_accessibility, is_a_class,
2205                          layout_info);
2206
2207        // Now parse any methods if there were any...
2208        size_t num_functions = member_function_dies.Size();
2209        if (num_functions > 0) {
2210          for (size_t i = 0; i < num_functions; ++i) {
2211            dwarf->ResolveType(member_function_dies.GetDIEAtIndex(i));
2212          }
2213        }
2214
2215        if (class_language == eLanguageTypeObjC) {
2216          ConstString class_name(clang_type.GetTypeName());
2217          if (class_name) {
2218            DIEArray method_die_offsets;
2219            dwarf->GetObjCMethodDIEOffsets(class_name, method_die_offsets);
2220
2221            if (!method_die_offsets.empty()) {
2222              DWARFDebugInfo *debug_info = dwarf->DebugInfo();
2223
2224              const size_t num_matches = method_die_offsets.size();
2225              for (size_t i = 0; i < num_matches; ++i) {
2226                const DIERef &die_ref = method_die_offsets[i];
2227                DWARFDIE method_die = debug_info->GetDIE(die_ref);
2228
2229                if (method_die)
2230                  method_die.ResolveType();
2231              }
2232            }
2233
2234            for (DelayedPropertyList::iterator pi = delayed_properties.begin(),
2235                                               pe = delayed_properties.end();
2236                 pi != pe; ++pi)
2237              pi->Finalize();
2238          }
2239        }
2240
2241        // If we have a DW_TAG_structure_type instead of a DW_TAG_class_type we
2242        // need to tell the clang type it is actually a class.
2243        if (class_language != eLanguageTypeObjC) {
2244          if (is_a_class && tag_decl_kind != clang::TTK_Class)
2245            m_ast.SetTagTypeKind(ClangUtil::GetQualType(clang_type),
2246                                 clang::TTK_Class);
2247        }
2248
2249        // Since DW_TAG_structure_type gets used for both classes and
2250        // structures, we may need to set any DW_TAG_member fields to have a
2251        // "private" access if none was specified. When we parsed the child
2252        // members we tracked that actual accessibility value for each
2253        // DW_TAG_member in the "member_accessibilities" array. If the value
2254        // for the member is zero, then it was set to the
2255        // "default_accessibility" which for structs was "public". Below we
2256        // correct this by setting any fields to "private" that weren't
2257        // correctly set.
2258        if (is_a_class && !member_accessibilities.empty()) {
2259          // This is a class and all members that didn't have their access
2260          // specified are private.
2261          m_ast.SetDefaultAccessForRecordFields(
2262              m_ast.GetAsRecordDecl(clang_type), eAccessPrivate,
2263              &member_accessibilities.front(), member_accessibilities.size());
2264        }
2265
2266        if (!bases.empty()) {
2267          // Make sure all base classes refer to complete types and not forward
2268          // declarations. If we don't do this, clang will crash with an
2269          // assertion in the call to clang_type.TransferBaseClasses()
2270          for (const auto &base_class : bases) {
2271            clang::TypeSourceInfo *type_source_info =
2272                base_class->getTypeSourceInfo();
2273            if (type_source_info) {
2274              CompilerType base_class_type(
2275                  &m_ast, type_source_info->getType().getAsOpaquePtr());
2276              if (!base_class_type.GetCompleteType()) {
2277                auto module = dwarf->GetObjectFile()->GetModule();
2278                module->ReportError(":: Class '%s' has a base class '%s' which "
2279                                    "does not have a complete definition.",
2280                                    die.GetName(),
2281                                    base_class_type.GetTypeName().GetCString());
2282                if (die.GetCU()->GetProducer() == eProducerClang)
2283                  module->ReportError(":: Try compiling the source file with "
2284                                      "-fstandalone-debug.");
2285
2286                // We have no choice other than to pretend that the base class
2287                // is complete. If we don't do this, clang will crash when we
2288                // call setBases() inside of
2289                // "clang_type.TransferBaseClasses()" below. Since we
2290                // provide layout assistance, all ivars in this class and other
2291                // classes will be fine, this is the best we can do short of
2292                // crashing.
2293                if (ClangASTContext::StartTagDeclarationDefinition(
2294                        base_class_type)) {
2295                  ClangASTContext::CompleteTagDeclarationDefinition(
2296                      base_class_type);
2297                }
2298              }
2299            }
2300          }
2301
2302          m_ast.TransferBaseClasses(clang_type.GetOpaqueQualType(),
2303                                    std::move(bases));
2304        }
2305      }
2306    }
2307
2308    m_ast.AddMethodOverridesForCXXRecordType(clang_type.GetOpaqueQualType());
2309    ClangASTContext::BuildIndirectFields(clang_type);
2310    ClangASTContext::CompleteTagDeclarationDefinition(clang_type);
2311
2312    if (!layout_info.field_offsets.empty() ||
2313        !layout_info.base_offsets.empty() ||
2314        !layout_info.vbase_offsets.empty()) {
2315      if (type)
2316        layout_info.bit_size = type->GetByteSize() * 8;
2317      if (layout_info.bit_size == 0)
2318        layout_info.bit_size =
2319            die.GetAttributeValueAsUnsigned(DW_AT_byte_size, 0) * 8;
2320
2321      clang::CXXRecordDecl *record_decl =
2322          m_ast.GetAsCXXRecordDecl(clang_type.GetOpaqueQualType());
2323      if (record_decl) {
2324        if (log) {
2325          ModuleSP module_sp = dwarf->GetObjectFile()->GetModule();
2326
2327          if (module_sp) {
2328            module_sp->LogMessage(
2329                log,
2330                "ClangASTContext::CompleteTypeFromDWARF (clang_type = %p) "
2331                "caching layout info for record_decl = %p, bit_size = %" PRIu64
2332                ", alignment = %" PRIu64
2333                ", field_offsets[%u], base_offsets[%u], vbase_offsets[%u])",
2334                static_cast<void *>(clang_type.GetOpaqueQualType()),
2335                static_cast<void *>(record_decl), layout_info.bit_size,
2336                layout_info.alignment,
2337                static_cast<uint32_t>(layout_info.field_offsets.size()),
2338                static_cast<uint32_t>(layout_info.base_offsets.size()),
2339                static_cast<uint32_t>(layout_info.vbase_offsets.size()));
2340
2341            uint32_t idx;
2342            {
2343              llvm::DenseMap<const clang::FieldDecl *, uint64_t>::const_iterator
2344                  pos,
2345                  end = layout_info.field_offsets.end();
2346              for (idx = 0, pos = layout_info.field_offsets.begin(); pos != end;
2347                   ++pos, ++idx) {
2348                module_sp->LogMessage(
2349                    log, "ClangASTContext::CompleteTypeFromDWARF (clang_type = "
2350                         "%p) field[%u] = { bit_offset=%u, name='%s' }",
2351                    static_cast<void *>(clang_type.GetOpaqueQualType()), idx,
2352                    static_cast<uint32_t>(pos->second),
2353                    pos->first->getNameAsString().c_str());
2354              }
2355            }
2356
2357            {
2358              llvm::DenseMap<const clang::CXXRecordDecl *,
2359                             clang::CharUnits>::const_iterator base_pos,
2360                  base_end = layout_info.base_offsets.end();
2361              for (idx = 0, base_pos = layout_info.base_offsets.begin();
2362                   base_pos != base_end; ++base_pos, ++idx) {
2363                module_sp->LogMessage(
2364                    log, "ClangASTContext::CompleteTypeFromDWARF (clang_type = "
2365                         "%p) base[%u] = { byte_offset=%u, name='%s' }",
2366                    clang_type.GetOpaqueQualType(), idx,
2367                    (uint32_t)base_pos->second.getQuantity(),
2368                    base_pos->first->getNameAsString().c_str());
2369              }
2370            }
2371            {
2372              llvm::DenseMap<const clang::CXXRecordDecl *,
2373                             clang::CharUnits>::const_iterator vbase_pos,
2374                  vbase_end = layout_info.vbase_offsets.end();
2375              for (idx = 0, vbase_pos = layout_info.vbase_offsets.begin();
2376                   vbase_pos != vbase_end; ++vbase_pos, ++idx) {
2377                module_sp->LogMessage(
2378                    log, "ClangASTContext::CompleteTypeFromDWARF (clang_type = "
2379                         "%p) vbase[%u] = { byte_offset=%u, name='%s' }",
2380                    static_cast<void *>(clang_type.GetOpaqueQualType()), idx,
2381                    static_cast<uint32_t>(vbase_pos->second.getQuantity()),
2382                    vbase_pos->first->getNameAsString().c_str());
2383              }
2384            }
2385          }
2386        }
2387        GetClangASTImporter().InsertRecordDecl(record_decl, layout_info);
2388      }
2389    }
2390  }
2391
2392    return (bool)clang_type;
2393
2394  case DW_TAG_enumeration_type:
2395    if (ClangASTContext::StartTagDeclarationDefinition(clang_type)) {
2396      if (die.HasChildren()) {
2397        SymbolContext sc(die.GetLLDBCompileUnit());
2398        bool is_signed = false;
2399        clang_type.IsIntegerType(is_signed);
2400        ParseChildEnumerators(sc, clang_type, is_signed, type->GetByteSize(),
2401                              die);
2402      }
2403      ClangASTContext::CompleteTagDeclarationDefinition(clang_type);
2404    }
2405    return (bool)clang_type;
2406
2407  default:
2408    assert(false && "not a forward clang type decl!");
2409    break;
2410  }
2411
2412  return false;
2413}
2414
2415std::vector<DWARFDIE> DWARFASTParserClang::GetDIEForDeclContext(
2416    lldb_private::CompilerDeclContext decl_context) {
2417  std::vector<DWARFDIE> result;
2418  for (auto it = m_decl_ctx_to_die.find(
2419           (clang::DeclContext *)decl_context.GetOpaqueDeclContext());
2420       it != m_decl_ctx_to_die.end(); it++)
2421    result.push_back(it->second);
2422  return result;
2423}
2424
2425CompilerDecl DWARFASTParserClang::GetDeclForUIDFromDWARF(const DWARFDIE &die) {
2426  clang::Decl *clang_decl = GetClangDeclForDIE(die);
2427  if (clang_decl != nullptr)
2428    return CompilerDecl(&m_ast, clang_decl);
2429  return CompilerDecl();
2430}
2431
2432CompilerDeclContext
2433DWARFASTParserClang::GetDeclContextForUIDFromDWARF(const DWARFDIE &die) {
2434  clang::DeclContext *clang_decl_ctx = GetClangDeclContextForDIE(die);
2435  if (clang_decl_ctx)
2436    return CompilerDeclContext(&m_ast, clang_decl_ctx);
2437  return CompilerDeclContext();
2438}
2439
2440CompilerDeclContext
2441DWARFASTParserClang::GetDeclContextContainingUIDFromDWARF(const DWARFDIE &die) {
2442  clang::DeclContext *clang_decl_ctx =
2443      GetClangDeclContextContainingDIE(die, nullptr);
2444  if (clang_decl_ctx)
2445    return CompilerDeclContext(&m_ast, clang_decl_ctx);
2446  return CompilerDeclContext();
2447}
2448
2449size_t DWARFASTParserClang::ParseChildEnumerators(
2450    const SymbolContext &sc, lldb_private::CompilerType &clang_type,
2451    bool is_signed, uint32_t enumerator_byte_size, const DWARFDIE &parent_die) {
2452  if (!parent_die)
2453    return 0;
2454
2455  size_t enumerators_added = 0;
2456
2457  for (DWARFDIE die = parent_die.GetFirstChild(); die.IsValid();
2458       die = die.GetSibling()) {
2459    const dw_tag_t tag = die.Tag();
2460    if (tag == DW_TAG_enumerator) {
2461      DWARFAttributes attributes;
2462      const size_t num_child_attributes = die.GetAttributes(attributes);
2463      if (num_child_attributes > 0) {
2464        const char *name = NULL;
2465        bool got_value = false;
2466        int64_t enum_value = 0;
2467        Declaration decl;
2468
2469        uint32_t i;
2470        for (i = 0; i < num_child_attributes; ++i) {
2471          const dw_attr_t attr = attributes.AttributeAtIndex(i);
2472          DWARFFormValue form_value;
2473          if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2474            switch (attr) {
2475            case DW_AT_const_value:
2476              got_value = true;
2477              if (is_signed)
2478                enum_value = form_value.Signed();
2479              else
2480                enum_value = form_value.Unsigned();
2481              break;
2482
2483            case DW_AT_name:
2484              name = form_value.AsCString();
2485              break;
2486
2487            case DW_AT_description:
2488            default:
2489            case DW_AT_decl_file:
2490              decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
2491                  form_value.Unsigned()));
2492              break;
2493            case DW_AT_decl_line:
2494              decl.SetLine(form_value.Unsigned());
2495              break;
2496            case DW_AT_decl_column:
2497              decl.SetColumn(form_value.Unsigned());
2498              break;
2499            case DW_AT_sibling:
2500              break;
2501            }
2502          }
2503        }
2504
2505        if (name && name[0] && got_value) {
2506          m_ast.AddEnumerationValueToEnumerationType(
2507              clang_type, decl, name, enum_value, enumerator_byte_size * 8);
2508          ++enumerators_added;
2509        }
2510      }
2511    }
2512  }
2513  return enumerators_added;
2514}
2515
2516#if defined(LLDB_CONFIGURATION_DEBUG) || defined(LLDB_CONFIGURATION_RELEASE)
2517
2518class DIEStack {
2519public:
2520  void Push(const DWARFDIE &die) { m_dies.push_back(die); }
2521
2522  void LogDIEs(Log *log) {
2523    StreamString log_strm;
2524    const size_t n = m_dies.size();
2525    log_strm.Printf("DIEStack[%" PRIu64 "]:\n", (uint64_t)n);
2526    for (size_t i = 0; i < n; i++) {
2527      std::string qualified_name;
2528      const DWARFDIE &die = m_dies[i];
2529      die.GetQualifiedName(qualified_name);
2530      log_strm.Printf("[%" PRIu64 "] 0x%8.8x: %s name='%s'\n", (uint64_t)i,
2531                      die.GetOffset(), die.GetTagAsCString(),
2532                      qualified_name.c_str());
2533    }
2534    log->PutCString(log_strm.GetData());
2535  }
2536  void Pop() { m_dies.pop_back(); }
2537
2538  class ScopedPopper {
2539  public:
2540    ScopedPopper(DIEStack &die_stack)
2541        : m_die_stack(die_stack), m_valid(false) {}
2542
2543    void Push(const DWARFDIE &die) {
2544      m_valid = true;
2545      m_die_stack.Push(die);
2546    }
2547
2548    ~ScopedPopper() {
2549      if (m_valid)
2550        m_die_stack.Pop();
2551    }
2552
2553  protected:
2554    DIEStack &m_die_stack;
2555    bool m_valid;
2556  };
2557
2558protected:
2559  typedef std::vector<DWARFDIE> Stack;
2560  Stack m_dies;
2561};
2562#endif
2563
2564Function *DWARFASTParserClang::ParseFunctionFromDWARF(CompileUnit &comp_unit,
2565                                                      const DWARFDIE &die) {
2566  DWARFRangeList func_ranges;
2567  const char *name = NULL;
2568  const char *mangled = NULL;
2569  int decl_file = 0;
2570  int decl_line = 0;
2571  int decl_column = 0;
2572  int call_file = 0;
2573  int call_line = 0;
2574  int call_column = 0;
2575  DWARFExpression frame_base(die.GetCU());
2576
2577  const dw_tag_t tag = die.Tag();
2578
2579  if (tag != DW_TAG_subprogram)
2580    return NULL;
2581
2582  if (die.GetDIENamesAndRanges(name, mangled, func_ranges, decl_file, decl_line,
2583                               decl_column, call_file, call_line, call_column,
2584                               &frame_base)) {
2585
2586    // Union of all ranges in the function DIE (if the function is
2587    // discontiguous)
2588    AddressRange func_range;
2589    lldb::addr_t lowest_func_addr = func_ranges.GetMinRangeBase(0);
2590    lldb::addr_t highest_func_addr = func_ranges.GetMaxRangeEnd(0);
2591    if (lowest_func_addr != LLDB_INVALID_ADDRESS &&
2592        lowest_func_addr <= highest_func_addr) {
2593      ModuleSP module_sp(die.GetModule());
2594      func_range.GetBaseAddress().ResolveAddressUsingFileSections(
2595          lowest_func_addr, module_sp->GetSectionList());
2596      if (func_range.GetBaseAddress().IsValid())
2597        func_range.SetByteSize(highest_func_addr - lowest_func_addr);
2598    }
2599
2600    if (func_range.GetBaseAddress().IsValid()) {
2601      Mangled func_name;
2602      if (mangled)
2603        func_name.SetValue(ConstString(mangled), true);
2604      else if ((die.GetParent().Tag() == DW_TAG_compile_unit ||
2605                die.GetParent().Tag() == DW_TAG_partial_unit) &&
2606               Language::LanguageIsCPlusPlus(die.GetLanguage()) && name &&
2607               strcmp(name, "main") != 0) {
2608        // If the mangled name is not present in the DWARF, generate the
2609        // demangled name using the decl context. We skip if the function is
2610        // "main" as its name is never mangled.
2611        bool is_static = false;
2612        bool is_variadic = false;
2613        bool has_template_params = false;
2614        unsigned type_quals = 0;
2615        std::vector<CompilerType> param_types;
2616        std::vector<clang::ParmVarDecl *> param_decls;
2617        DWARFDeclContext decl_ctx;
2618        StreamString sstr;
2619
2620        die.GetDWARFDeclContext(decl_ctx);
2621        sstr << decl_ctx.GetQualifiedName();
2622
2623        clang::DeclContext *containing_decl_ctx =
2624            GetClangDeclContextContainingDIE(die, nullptr);
2625        ParseChildParameters(comp_unit, containing_decl_ctx, die, true,
2626                             is_static, is_variadic, has_template_params,
2627                             param_types, param_decls, type_quals);
2628        sstr << "(";
2629        for (size_t i = 0; i < param_types.size(); i++) {
2630          if (i > 0)
2631            sstr << ", ";
2632          sstr << param_types[i].GetTypeName();
2633        }
2634        if (is_variadic)
2635          sstr << ", ...";
2636        sstr << ")";
2637        if (type_quals & clang::Qualifiers::Const)
2638          sstr << " const";
2639
2640        func_name.SetValue(ConstString(sstr.GetString()), false);
2641      } else
2642        func_name.SetValue(ConstString(name), false);
2643
2644      FunctionSP func_sp;
2645      std::unique_ptr<Declaration> decl_ap;
2646      if (decl_file != 0 || decl_line != 0 || decl_column != 0)
2647        decl_ap.reset(new Declaration(
2648            comp_unit.GetSupportFiles().GetFileSpecAtIndex(decl_file),
2649            decl_line, decl_column));
2650
2651      SymbolFileDWARF *dwarf = die.GetDWARF();
2652      // Supply the type _only_ if it has already been parsed
2653      Type *func_type = dwarf->GetDIEToType().lookup(die.GetDIE());
2654
2655      assert(func_type == NULL || func_type != DIE_IS_BEING_PARSED);
2656
2657      if (dwarf->FixupAddress(func_range.GetBaseAddress())) {
2658        const user_id_t func_user_id = die.GetID();
2659        func_sp.reset(new Function(&comp_unit,
2660                                   func_user_id, // UserID is the DIE offset
2661                                   func_user_id, func_name, func_type,
2662                                   func_range)); // first address range
2663
2664        if (func_sp.get() != NULL) {
2665          if (frame_base.IsValid())
2666            func_sp->GetFrameBaseExpression() = frame_base;
2667          comp_unit.AddFunction(func_sp);
2668          return func_sp.get();
2669        }
2670      }
2671    }
2672  }
2673  return NULL;
2674}
2675
2676bool DWARFASTParserClang::ParseChildMembers(
2677    const SymbolContext &sc, const DWARFDIE &parent_die,
2678    CompilerType &class_clang_type, const LanguageType class_language,
2679    std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> &base_classes,
2680    std::vector<int> &member_accessibilities,
2681    DWARFDIECollection &member_function_dies,
2682    DelayedPropertyList &delayed_properties, AccessType &default_accessibility,
2683    bool &is_a_class, ClangASTImporter::LayoutInfo &layout_info) {
2684  if (!parent_die)
2685    return 0;
2686
2687  // Get the parent byte size so we can verify any members will fit
2688  const uint64_t parent_byte_size =
2689      parent_die.GetAttributeValueAsUnsigned(DW_AT_byte_size, UINT64_MAX);
2690  const uint64_t parent_bit_size =
2691      parent_byte_size == UINT64_MAX ? UINT64_MAX : parent_byte_size * 8;
2692
2693  uint32_t member_idx = 0;
2694  BitfieldInfo last_field_info;
2695
2696  ModuleSP module_sp = parent_die.GetDWARF()->GetObjectFile()->GetModule();
2697  ClangASTContext *ast =
2698      llvm::dyn_cast_or_null<ClangASTContext>(class_clang_type.GetTypeSystem());
2699  if (ast == nullptr)
2700    return 0;
2701
2702  for (DWARFDIE die = parent_die.GetFirstChild(); die.IsValid();
2703       die = die.GetSibling()) {
2704    dw_tag_t tag = die.Tag();
2705
2706    switch (tag) {
2707    case DW_TAG_member:
2708    case DW_TAG_APPLE_property: {
2709      DWARFAttributes attributes;
2710      const size_t num_attributes = die.GetAttributes(attributes);
2711      if (num_attributes > 0) {
2712        Declaration decl;
2713        // DWARFExpression location;
2714        const char *name = NULL;
2715        const char *prop_name = NULL;
2716        const char *prop_getter_name = NULL;
2717        const char *prop_setter_name = NULL;
2718        uint32_t prop_attributes = 0;
2719
2720        bool is_artificial = false;
2721        DWARFFormValue encoding_form;
2722        AccessType accessibility = eAccessNone;
2723        uint32_t member_byte_offset =
2724            (parent_die.Tag() == DW_TAG_union_type) ? 0 : UINT32_MAX;
2725        size_t byte_size = 0;
2726        int64_t bit_offset = 0;
2727        uint64_t data_bit_offset = UINT64_MAX;
2728        size_t bit_size = 0;
2729        bool is_external =
2730            false; // On DW_TAG_members, this means the member is static
2731        uint32_t i;
2732        for (i = 0; i < num_attributes && !is_artificial; ++i) {
2733          const dw_attr_t attr = attributes.AttributeAtIndex(i);
2734          DWARFFormValue form_value;
2735          if (attributes.ExtractFormValueAtIndex(i, form_value)) {
2736            switch (attr) {
2737            case DW_AT_decl_file:
2738              decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
2739                  form_value.Unsigned()));
2740              break;
2741            case DW_AT_decl_line:
2742              decl.SetLine(form_value.Unsigned());
2743              break;
2744            case DW_AT_decl_column:
2745              decl.SetColumn(form_value.Unsigned());
2746              break;
2747            case DW_AT_name:
2748              name = form_value.AsCString();
2749              break;
2750            case DW_AT_type:
2751              encoding_form = form_value;
2752              break;
2753            case DW_AT_bit_offset:
2754              bit_offset = form_value.Signed();
2755              break;
2756            case DW_AT_bit_size:
2757              bit_size = form_value.Unsigned();
2758              break;
2759            case DW_AT_byte_size:
2760              byte_size = form_value.Unsigned();
2761              break;
2762            case DW_AT_data_bit_offset:
2763              data_bit_offset = form_value.Unsigned();
2764              break;
2765            case DW_AT_data_member_location:
2766              if (form_value.BlockData()) {
2767                Value initialValue(0);
2768                Value memberOffset(0);
2769                const DWARFDataExtractor &debug_info_data = die.GetData();
2770                uint32_t block_length = form_value.Unsigned();
2771                uint32_t block_offset =
2772                    form_value.BlockData() - debug_info_data.GetDataStart();
2773                if (DWARFExpression::Evaluate(
2774                        nullptr, // ExecutionContext *
2775                        nullptr, // RegisterContext *
2776                        module_sp, debug_info_data, die.GetCU(), block_offset,
2777                        block_length, eRegisterKindDWARF, &initialValue,
2778                        nullptr, memberOffset, nullptr)) {
2779                  member_byte_offset = memberOffset.ResolveValue(NULL).UInt();
2780                }
2781              } else {
2782                // With DWARF 3 and later, if the value is an integer constant,
2783                // this form value is the offset in bytes from the beginning of
2784                // the containing entity.
2785                member_byte_offset = form_value.Unsigned();
2786              }
2787              break;
2788
2789            case DW_AT_accessibility:
2790              accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
2791              break;
2792            case DW_AT_artificial:
2793              is_artificial = form_value.Boolean();
2794              break;
2795            case DW_AT_APPLE_property_name:
2796              prop_name = form_value.AsCString();
2797              break;
2798            case DW_AT_APPLE_property_getter:
2799              prop_getter_name = form_value.AsCString();
2800              break;
2801            case DW_AT_APPLE_property_setter:
2802              prop_setter_name = form_value.AsCString();
2803              break;
2804            case DW_AT_APPLE_property_attribute:
2805              prop_attributes = form_value.Unsigned();
2806              break;
2807            case DW_AT_external:
2808              is_external = form_value.Boolean();
2809              break;
2810
2811            default:
2812            case DW_AT_declaration:
2813            case DW_AT_description:
2814            case DW_AT_mutable:
2815            case DW_AT_visibility:
2816            case DW_AT_sibling:
2817              break;
2818            }
2819          }
2820        }
2821
2822        if (prop_name) {
2823          ConstString fixed_getter;
2824          ConstString fixed_setter;
2825
2826          // Check if the property getter/setter were provided as full names.
2827          // We want basenames, so we extract them.
2828
2829          if (prop_getter_name && prop_getter_name[0] == '-') {
2830            ObjCLanguage::MethodName prop_getter_method(prop_getter_name, true);
2831            prop_getter_name = prop_getter_method.GetSelector().GetCString();
2832          }
2833
2834          if (prop_setter_name && prop_setter_name[0] == '-') {
2835            ObjCLanguage::MethodName prop_setter_method(prop_setter_name, true);
2836            prop_setter_name = prop_setter_method.GetSelector().GetCString();
2837          }
2838
2839          // If the names haven't been provided, they need to be filled in.
2840
2841          if (!prop_getter_name) {
2842            prop_getter_name = prop_name;
2843          }
2844          if (!prop_setter_name && prop_name[0] &&
2845              !(prop_attributes & DW_APPLE_PROPERTY_readonly)) {
2846            StreamString ss;
2847
2848            ss.Printf("set%c%s:", toupper(prop_name[0]), &prop_name[1]);
2849
2850            fixed_setter.SetString(ss.GetString());
2851            prop_setter_name = fixed_setter.GetCString();
2852          }
2853        }
2854
2855        // Clang has a DWARF generation bug where sometimes it represents
2856        // fields that are references with bad byte size and bit size/offset
2857        // information such as:
2858        //
2859        //  DW_AT_byte_size( 0x00 )
2860        //  DW_AT_bit_size( 0x40 )
2861        //  DW_AT_bit_offset( 0xffffffffffffffc0 )
2862        //
2863        // So check the bit offset to make sure it is sane, and if the values
2864        // are not sane, remove them. If we don't do this then we will end up
2865        // with a crash if we try to use this type in an expression when clang
2866        // becomes unhappy with its recycled debug info.
2867
2868        if (byte_size == 0 && bit_offset < 0) {
2869          bit_size = 0;
2870          bit_offset = 0;
2871        }
2872
2873        // FIXME: Make Clang ignore Objective-C accessibility for expressions
2874        if (class_language == eLanguageTypeObjC ||
2875            class_language == eLanguageTypeObjC_plus_plus)
2876          accessibility = eAccessNone;
2877
2878        // Handle static members
2879        if (is_external && member_byte_offset == UINT32_MAX) {
2880          Type *var_type = die.ResolveTypeUID(DIERef(encoding_form));
2881
2882          if (var_type) {
2883            if (accessibility == eAccessNone)
2884              accessibility = eAccessPublic;
2885            ClangASTContext::AddVariableToRecordType(
2886                class_clang_type, name, var_type->GetLayoutCompilerType(),
2887                accessibility);
2888          }
2889          break;
2890        }
2891
2892        if (!is_artificial) {
2893          Type *member_type = die.ResolveTypeUID(DIERef(encoding_form));
2894
2895          clang::FieldDecl *field_decl = NULL;
2896          if (tag == DW_TAG_member) {
2897            if (member_type) {
2898              if (accessibility == eAccessNone)
2899                accessibility = default_accessibility;
2900              member_accessibilities.push_back(accessibility);
2901
2902              uint64_t field_bit_offset =
2903                  (member_byte_offset == UINT32_MAX ? 0
2904                                                    : (member_byte_offset * 8));
2905              if (bit_size > 0) {
2906
2907                BitfieldInfo this_field_info;
2908                this_field_info.bit_offset = field_bit_offset;
2909                this_field_info.bit_size = bit_size;
2910
2911                /////////////////////////////////////////////////////////////
2912                // How to locate a field given the DWARF debug information
2913                //
2914                // AT_byte_size indicates the size of the word in which the bit
2915                // offset must be interpreted.
2916                //
2917                // AT_data_member_location indicates the byte offset of the
2918                // word from the base address of the structure.
2919                //
2920                // AT_bit_offset indicates how many bits into the word
2921                // (according to the host endianness) the low-order bit of the
2922                // field starts.  AT_bit_offset can be negative.
2923                //
2924                // AT_bit_size indicates the size of the field in bits.
2925                /////////////////////////////////////////////////////////////
2926
2927                if (data_bit_offset != UINT64_MAX) {
2928                  this_field_info.bit_offset = data_bit_offset;
2929                } else {
2930                  if (byte_size == 0)
2931                    byte_size = member_type->GetByteSize();
2932
2933                  ObjectFile *objfile = die.GetDWARF()->GetObjectFile();
2934                  if (objfile->GetByteOrder() == eByteOrderLittle) {
2935                    this_field_info.bit_offset += byte_size * 8;
2936                    this_field_info.bit_offset -= (bit_offset + bit_size);
2937                  } else {
2938                    this_field_info.bit_offset += bit_offset;
2939                  }
2940                }
2941
2942                if ((this_field_info.bit_offset >= parent_bit_size) ||
2943                    !last_field_info.NextBitfieldOffsetIsValid(
2944                        this_field_info.bit_offset)) {
2945                  ObjectFile *objfile = die.GetDWARF()->GetObjectFile();
2946                  objfile->GetModule()->ReportWarning(
2947                      "0x%8.8" PRIx64 ": %s bitfield named \"%s\" has invalid "
2948                                      "bit offset (0x%8.8" PRIx64
2949                      ") member will be ignored. Please file a bug against the "
2950                      "compiler and include the preprocessed output for %s\n",
2951                      die.GetID(), DW_TAG_value_to_name(tag), name,
2952                      this_field_info.bit_offset,
2953                      sc.comp_unit ? sc.comp_unit->GetPath().c_str()
2954                                   : "the source file");
2955                  this_field_info.Clear();
2956                  continue;
2957                }
2958
2959                // Update the field bit offset we will report for layout
2960                field_bit_offset = this_field_info.bit_offset;
2961
2962                // If the member to be emitted did not start on a character
2963                // boundary and there is empty space between the last field and
2964                // this one, then we need to emit an anonymous member filling
2965                // up the space up to its start.  There are three cases here:
2966                //
2967                // 1 If the previous member ended on a character boundary, then
2968                // we can emit an
2969                //   anonymous member starting at the most recent character
2970                //   boundary.
2971                //
2972                // 2 If the previous member did not end on a character boundary
2973                // and the distance
2974                //   from the end of the previous member to the current member
2975                //   is less than a
2976                //   word width, then we can emit an anonymous member starting
2977                //   right after the
2978                //   previous member and right before this member.
2979                //
2980                // 3 If the previous member did not end on a character boundary
2981                // and the distance
2982                //   from the end of the previous member to the current member
2983                //   is greater than
2984                //   or equal a word width, then we act as in Case 1.
2985
2986                const uint64_t character_width = 8;
2987                const uint64_t word_width = 32;
2988
2989                // Objective-C has invalid DW_AT_bit_offset values in older
2990                // versions of clang, so we have to be careful and only insert
2991                // unnamed bitfields if we have a new enough clang.
2992                bool detect_unnamed_bitfields = true;
2993
2994                if (class_language == eLanguageTypeObjC ||
2995                    class_language == eLanguageTypeObjC_plus_plus)
2996                  detect_unnamed_bitfields =
2997                      die.GetCU()->Supports_unnamed_objc_bitfields();
2998
2999                if (detect_unnamed_bitfields) {
3000                  BitfieldInfo anon_field_info;
3001
3002                  if ((this_field_info.bit_offset % character_width) !=
3003                      0) // not char aligned
3004                  {
3005                    uint64_t last_field_end = 0;
3006
3007                    if (last_field_info.IsValid())
3008                      last_field_end =
3009                          last_field_info.bit_offset + last_field_info.bit_size;
3010
3011                    if (this_field_info.bit_offset != last_field_end) {
3012                      if (((last_field_end % character_width) == 0) || // case 1
3013                          (this_field_info.bit_offset - last_field_end >=
3014                           word_width)) // case 3
3015                      {
3016                        anon_field_info.bit_size =
3017                            this_field_info.bit_offset % character_width;
3018                        anon_field_info.bit_offset =
3019                            this_field_info.bit_offset -
3020                            anon_field_info.bit_size;
3021                      } else // case 2
3022                      {
3023                        anon_field_info.bit_size =
3024                            this_field_info.bit_offset - last_field_end;
3025                        anon_field_info.bit_offset = last_field_end;
3026                      }
3027                    }
3028                  }
3029
3030                  if (anon_field_info.IsValid()) {
3031                    clang::FieldDecl *unnamed_bitfield_decl =
3032                        ClangASTContext::AddFieldToRecordType(
3033                            class_clang_type, llvm::StringRef(),
3034                            m_ast.GetBuiltinTypeForEncodingAndBitSize(
3035                                eEncodingSint, word_width),
3036                            accessibility, anon_field_info.bit_size);
3037
3038                    layout_info.field_offsets.insert(std::make_pair(
3039                        unnamed_bitfield_decl, anon_field_info.bit_offset));
3040                  }
3041                }
3042                last_field_info = this_field_info;
3043              } else {
3044                last_field_info.Clear();
3045              }
3046
3047              CompilerType member_clang_type =
3048                  member_type->GetLayoutCompilerType();
3049              if (!member_clang_type.IsCompleteType())
3050                member_clang_type.GetCompleteType();
3051
3052              {
3053                // Older versions of clang emit array[0] and array[1] in the
3054                // same way (<rdar://problem/12566646>). If the current field
3055                // is at the end of the structure, then there is definitely no
3056                // room for extra elements and we override the type to
3057                // array[0].
3058
3059                CompilerType member_array_element_type;
3060                uint64_t member_array_size;
3061                bool member_array_is_incomplete;
3062
3063                if (member_clang_type.IsArrayType(
3064                        &member_array_element_type, &member_array_size,
3065                        &member_array_is_incomplete) &&
3066                    !member_array_is_incomplete) {
3067                  uint64_t parent_byte_size =
3068                      parent_die.GetAttributeValueAsUnsigned(DW_AT_byte_size,
3069                                                             UINT64_MAX);
3070
3071                  if (member_byte_offset >= parent_byte_size) {
3072                    if (member_array_size != 1 &&
3073                        (member_array_size != 0 ||
3074                         member_byte_offset > parent_byte_size)) {
3075                      module_sp->ReportError(
3076                          "0x%8.8" PRIx64
3077                          ": DW_TAG_member '%s' refers to type 0x%8.8" PRIx64
3078                          " which extends beyond the bounds of 0x%8.8" PRIx64,
3079                          die.GetID(), name, encoding_form.Reference(),
3080                          parent_die.GetID());
3081                    }
3082
3083                    member_clang_type = m_ast.CreateArrayType(
3084                        member_array_element_type, 0, false);
3085                  }
3086                }
3087              }
3088
3089              if (ClangASTContext::IsCXXClassType(member_clang_type) &&
3090                  !member_clang_type.GetCompleteType()) {
3091                if (die.GetCU()->GetProducer() == eProducerClang)
3092                  module_sp->ReportError(
3093                      "DWARF DIE at 0x%8.8x (class %s) has a member variable "
3094                      "0x%8.8x (%s) whose type is a forward declaration, not a "
3095                      "complete definition.\nTry compiling the source file "
3096                      "with -fstandalone-debug",
3097                      parent_die.GetOffset(), parent_die.GetName(),
3098                      die.GetOffset(), name);
3099                else
3100                  module_sp->ReportError(
3101                      "DWARF DIE at 0x%8.8x (class %s) has a member variable "
3102                      "0x%8.8x (%s) whose type is a forward declaration, not a "
3103                      "complete definition.\nPlease file a bug against the "
3104                      "compiler and include the preprocessed output for %s",
3105                      parent_die.GetOffset(), parent_die.GetName(),
3106                      die.GetOffset(), name,
3107                      sc.comp_unit ? sc.comp_unit->GetPath().c_str()
3108                                   : "the source file");
3109                // We have no choice other than to pretend that the member
3110                // class is complete. If we don't do this, clang will crash
3111                // when trying to layout the class. Since we provide layout
3112                // assistance, all ivars in this class and other classes will
3113                // be fine, this is the best we can do short of crashing.
3114                if (ClangASTContext::StartTagDeclarationDefinition(
3115                        member_clang_type)) {
3116                  ClangASTContext::CompleteTagDeclarationDefinition(
3117                      member_clang_type);
3118                } else {
3119                  module_sp->ReportError(
3120                      "DWARF DIE at 0x%8.8x (class %s) has a member variable "
3121                      "0x%8.8x (%s) whose type claims to be a C++ class but we "
3122                      "were not able to start its definition.\nPlease file a "
3123                      "bug and attach the file at the start of this error "
3124                      "message",
3125                      parent_die.GetOffset(), parent_die.GetName(),
3126                      die.GetOffset(), name);
3127                }
3128              }
3129
3130              field_decl = ClangASTContext::AddFieldToRecordType(
3131                  class_clang_type, name, member_clang_type, accessibility,
3132                  bit_size);
3133
3134              m_ast.SetMetadataAsUserID(field_decl, die.GetID());
3135
3136              layout_info.field_offsets.insert(
3137                  std::make_pair(field_decl, field_bit_offset));
3138            } else {
3139              if (name)
3140                module_sp->ReportError(
3141                    "0x%8.8" PRIx64
3142                    ": DW_TAG_member '%s' refers to type 0x%8.8" PRIx64
3143                    " which was unable to be parsed",
3144                    die.GetID(), name, encoding_form.Reference());
3145              else
3146                module_sp->ReportError(
3147                    "0x%8.8" PRIx64
3148                    ": DW_TAG_member refers to type 0x%8.8" PRIx64
3149                    " which was unable to be parsed",
3150                    die.GetID(), encoding_form.Reference());
3151            }
3152          }
3153
3154          if (prop_name != NULL && member_type) {
3155            clang::ObjCIvarDecl *ivar_decl = NULL;
3156
3157            if (field_decl) {
3158              ivar_decl = clang::dyn_cast<clang::ObjCIvarDecl>(field_decl);
3159              assert(ivar_decl != NULL);
3160            }
3161
3162            ClangASTMetadata metadata;
3163            metadata.SetUserID(die.GetID());
3164            delayed_properties.push_back(DelayedAddObjCClassProperty(
3165                class_clang_type, prop_name,
3166                member_type->GetLayoutCompilerType(), ivar_decl,
3167                prop_setter_name, prop_getter_name, prop_attributes,
3168                &metadata));
3169
3170            if (ivar_decl)
3171              m_ast.SetMetadataAsUserID(ivar_decl, die.GetID());
3172          }
3173        }
3174      }
3175      ++member_idx;
3176    } break;
3177
3178    case DW_TAG_subprogram:
3179      // Let the type parsing code handle this one for us.
3180      member_function_dies.Append(die);
3181      break;
3182
3183    case DW_TAG_inheritance: {
3184      is_a_class = true;
3185      if (default_accessibility == eAccessNone)
3186        default_accessibility = eAccessPrivate;
3187      // TODO: implement DW_TAG_inheritance type parsing
3188      DWARFAttributes attributes;
3189      const size_t num_attributes = die.GetAttributes(attributes);
3190      if (num_attributes > 0) {
3191        Declaration decl;
3192        DWARFExpression location(die.GetCU());
3193        DWARFFormValue encoding_form;
3194        AccessType accessibility = default_accessibility;
3195        bool is_virtual = false;
3196        bool is_base_of_class = true;
3197        off_t member_byte_offset = 0;
3198        uint32_t i;
3199        for (i = 0; i < num_attributes; ++i) {
3200          const dw_attr_t attr = attributes.AttributeAtIndex(i);
3201          DWARFFormValue form_value;
3202          if (attributes.ExtractFormValueAtIndex(i, form_value)) {
3203            switch (attr) {
3204            case DW_AT_decl_file:
3205              decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
3206                  form_value.Unsigned()));
3207              break;
3208            case DW_AT_decl_line:
3209              decl.SetLine(form_value.Unsigned());
3210              break;
3211            case DW_AT_decl_column:
3212              decl.SetColumn(form_value.Unsigned());
3213              break;
3214            case DW_AT_type:
3215              encoding_form = form_value;
3216              break;
3217            case DW_AT_data_member_location:
3218              if (form_value.BlockData()) {
3219                Value initialValue(0);
3220                Value memberOffset(0);
3221                const DWARFDataExtractor &debug_info_data = die.GetData();
3222                uint32_t block_length = form_value.Unsigned();
3223                uint32_t block_offset =
3224                    form_value.BlockData() - debug_info_data.GetDataStart();
3225                if (DWARFExpression::Evaluate(nullptr, nullptr, module_sp,
3226                                              debug_info_data, die.GetCU(),
3227                                              block_offset, block_length,
3228                                              eRegisterKindDWARF, &initialValue,
3229                                              nullptr, memberOffset, nullptr)) {
3230                  member_byte_offset = memberOffset.ResolveValue(NULL).UInt();
3231                }
3232              } else {
3233                // With DWARF 3 and later, if the value is an integer constant,
3234                // this form value is the offset in bytes from the beginning of
3235                // the containing entity.
3236                member_byte_offset = form_value.Unsigned();
3237              }
3238              break;
3239
3240            case DW_AT_accessibility:
3241              accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
3242              break;
3243
3244            case DW_AT_virtuality:
3245              is_virtual = form_value.Boolean();
3246              break;
3247
3248            case DW_AT_sibling:
3249              break;
3250
3251            default:
3252              break;
3253            }
3254          }
3255        }
3256
3257        Type *base_class_type = die.ResolveTypeUID(DIERef(encoding_form));
3258        if (base_class_type == NULL) {
3259          module_sp->ReportError("0x%8.8x: DW_TAG_inheritance failed to "
3260                                 "resolve the base class at 0x%8.8" PRIx64
3261                                 " from enclosing type 0x%8.8x. \nPlease file "
3262                                 "a bug and attach the file at the start of "
3263                                 "this error message",
3264                                 die.GetOffset(), encoding_form.Reference(),
3265                                 parent_die.GetOffset());
3266          break;
3267        }
3268
3269        CompilerType base_class_clang_type =
3270            base_class_type->GetFullCompilerType();
3271        assert(base_class_clang_type);
3272        if (class_language == eLanguageTypeObjC) {
3273          ast->SetObjCSuperClass(class_clang_type, base_class_clang_type);
3274        } else {
3275          std::unique_ptr<clang::CXXBaseSpecifier> result =
3276              ast->CreateBaseClassSpecifier(
3277                  base_class_clang_type.GetOpaqueQualType(), accessibility,
3278                  is_virtual, is_base_of_class);
3279          if (!result)
3280            break;
3281
3282          base_classes.push_back(std::move(result));
3283
3284          if (is_virtual) {
3285            // Do not specify any offset for virtual inheritance. The DWARF
3286            // produced by clang doesn't give us a constant offset, but gives
3287            // us a DWARF expressions that requires an actual object in memory.
3288            // the DW_AT_data_member_location for a virtual base class looks
3289            // like:
3290            //      DW_AT_data_member_location( DW_OP_dup, DW_OP_deref,
3291            //      DW_OP_constu(0x00000018), DW_OP_minus, DW_OP_deref,
3292            //      DW_OP_plus )
3293            // Given this, there is really no valid response we can give to
3294            // clang for virtual base class offsets, and this should eventually
3295            // be removed from LayoutRecordType() in the external
3296            // AST source in clang.
3297          } else {
3298            layout_info.base_offsets.insert(std::make_pair(
3299                ast->GetAsCXXRecordDecl(
3300                    base_class_clang_type.GetOpaqueQualType()),
3301                clang::CharUnits::fromQuantity(member_byte_offset)));
3302          }
3303        }
3304      }
3305    } break;
3306
3307    default:
3308      break;
3309    }
3310  }
3311
3312  return true;
3313}
3314
3315size_t DWARFASTParserClang::ParseChildParameters(
3316    CompileUnit &comp_unit, clang::DeclContext *containing_decl_ctx,
3317    const DWARFDIE &parent_die, bool skip_artificial, bool &is_static,
3318    bool &is_variadic, bool &has_template_params,
3319    std::vector<CompilerType> &function_param_types,
3320    std::vector<clang::ParmVarDecl *> &function_param_decls,
3321    unsigned &type_quals) {
3322  if (!parent_die)
3323    return 0;
3324
3325  size_t arg_idx = 0;
3326  for (DWARFDIE die = parent_die.GetFirstChild(); die.IsValid();
3327       die = die.GetSibling()) {
3328    const dw_tag_t tag = die.Tag();
3329    switch (tag) {
3330    case DW_TAG_formal_parameter: {
3331      DWARFAttributes attributes;
3332      const size_t num_attributes = die.GetAttributes(attributes);
3333      if (num_attributes > 0) {
3334        const char *name = NULL;
3335        Declaration decl;
3336        DWARFFormValue param_type_die_form;
3337        bool is_artificial = false;
3338        // one of None, Auto, Register, Extern, Static, PrivateExtern
3339
3340        clang::StorageClass storage = clang::SC_None;
3341        uint32_t i;
3342        for (i = 0; i < num_attributes; ++i) {
3343          const dw_attr_t attr = attributes.AttributeAtIndex(i);
3344          DWARFFormValue form_value;
3345          if (attributes.ExtractFormValueAtIndex(i, form_value)) {
3346            switch (attr) {
3347            case DW_AT_decl_file:
3348              decl.SetFile(comp_unit.GetSupportFiles().GetFileSpecAtIndex(
3349                  form_value.Unsigned()));
3350              break;
3351            case DW_AT_decl_line:
3352              decl.SetLine(form_value.Unsigned());
3353              break;
3354            case DW_AT_decl_column:
3355              decl.SetColumn(form_value.Unsigned());
3356              break;
3357            case DW_AT_name:
3358              name = form_value.AsCString();
3359              break;
3360            case DW_AT_type:
3361              param_type_die_form = form_value;
3362              break;
3363            case DW_AT_artificial:
3364              is_artificial = form_value.Boolean();
3365              break;
3366            case DW_AT_location:
3367            case DW_AT_const_value:
3368            case DW_AT_default_value:
3369            case DW_AT_description:
3370            case DW_AT_endianity:
3371            case DW_AT_is_optional:
3372            case DW_AT_segment:
3373            case DW_AT_variable_parameter:
3374            default:
3375            case DW_AT_abstract_origin:
3376            case DW_AT_sibling:
3377              break;
3378            }
3379          }
3380        }
3381
3382        bool skip = false;
3383        if (skip_artificial && is_artificial) {
3384          // In order to determine if a C++ member function is "const" we
3385          // have to look at the const-ness of "this"...
3386          if (arg_idx == 0 &&
3387              DeclKindIsCXXClass(containing_decl_ctx->getDeclKind()) &&
3388              // Often times compilers omit the "this" name for the
3389              // specification DIEs, so we can't rely upon the name being in
3390              // the formal parameter DIE...
3391              (name == NULL || ::strcmp(name, "this") == 0)) {
3392            Type *this_type = die.ResolveTypeUID(DIERef(param_type_die_form));
3393            if (this_type) {
3394              uint32_t encoding_mask = this_type->GetEncodingMask();
3395              if (encoding_mask & Type::eEncodingIsPointerUID) {
3396                is_static = false;
3397
3398                if (encoding_mask & (1u << Type::eEncodingIsConstUID))
3399                  type_quals |= clang::Qualifiers::Const;
3400                if (encoding_mask & (1u << Type::eEncodingIsVolatileUID))
3401                  type_quals |= clang::Qualifiers::Volatile;
3402              }
3403            }
3404          }
3405          skip = true;
3406        }
3407
3408        if (!skip) {
3409          Type *type = die.ResolveTypeUID(DIERef(param_type_die_form));
3410          if (type) {
3411            function_param_types.push_back(type->GetForwardCompilerType());
3412
3413            clang::ParmVarDecl *param_var_decl =
3414                m_ast.CreateParameterDeclaration(containing_decl_ctx, name,
3415                                                 type->GetForwardCompilerType(),
3416                                                 storage);
3417            assert(param_var_decl);
3418            function_param_decls.push_back(param_var_decl);
3419
3420            m_ast.SetMetadataAsUserID(param_var_decl, die.GetID());
3421          }
3422        }
3423      }
3424      arg_idx++;
3425    } break;
3426
3427    case DW_TAG_unspecified_parameters:
3428      is_variadic = true;
3429      break;
3430
3431    case DW_TAG_template_type_parameter:
3432    case DW_TAG_template_value_parameter:
3433    case DW_TAG_GNU_template_parameter_pack:
3434      // The one caller of this was never using the template_param_infos, and
3435      // the local variable was taking up a large amount of stack space in
3436      // SymbolFileDWARF::ParseType() so this was removed. If we ever need the
3437      // template params back, we can add them back.
3438      // ParseTemplateDIE (dwarf_cu, die, template_param_infos);
3439      has_template_params = true;
3440      break;
3441
3442    default:
3443      break;
3444    }
3445  }
3446  return arg_idx;
3447}
3448
3449llvm::Optional<SymbolFile::ArrayInfo>
3450DWARFASTParser::ParseChildArrayInfo(const DWARFDIE &parent_die,
3451                                    const ExecutionContext *exe_ctx) {
3452  SymbolFile::ArrayInfo array_info;
3453  if (!parent_die)
3454    return llvm::None;
3455
3456  for (DWARFDIE die = parent_die.GetFirstChild(); die.IsValid();
3457       die = die.GetSibling()) {
3458    const dw_tag_t tag = die.Tag();
3459    switch (tag) {
3460    case DW_TAG_subrange_type: {
3461      DWARFAttributes attributes;
3462      const size_t num_child_attributes = die.GetAttributes(attributes);
3463      if (num_child_attributes > 0) {
3464        uint64_t num_elements = 0;
3465        uint64_t lower_bound = 0;
3466        uint64_t upper_bound = 0;
3467        bool upper_bound_valid = false;
3468        uint32_t i;
3469        for (i = 0; i < num_child_attributes; ++i) {
3470          const dw_attr_t attr = attributes.AttributeAtIndex(i);
3471          DWARFFormValue form_value;
3472          if (attributes.ExtractFormValueAtIndex(i, form_value)) {
3473            switch (attr) {
3474            case DW_AT_name:
3475              break;
3476
3477            case DW_AT_count:
3478              if (DWARFDIE var_die = die.GetReferencedDIE(DW_AT_count)) {
3479                if (var_die.Tag() == DW_TAG_variable)
3480                  if (exe_ctx) {
3481                    if (auto frame = exe_ctx->GetFrameSP()) {
3482                      Status error;
3483                      lldb::VariableSP var_sp;
3484                      auto valobj_sp = frame->GetValueForVariableExpressionPath(
3485                          var_die.GetName(), eNoDynamicValues, 0, var_sp,
3486                          error);
3487                      if (valobj_sp) {
3488                        num_elements = valobj_sp->GetValueAsUnsigned(0);
3489                        break;
3490                      }
3491                    }
3492                  }
3493              } else
3494                num_elements = form_value.Unsigned();
3495              break;
3496
3497            case DW_AT_bit_stride:
3498              array_info.bit_stride = form_value.Unsigned();
3499              break;
3500
3501            case DW_AT_byte_stride:
3502              array_info.byte_stride = form_value.Unsigned();
3503              break;
3504
3505            case DW_AT_lower_bound:
3506              lower_bound = form_value.Unsigned();
3507              break;
3508
3509            case DW_AT_upper_bound:
3510              upper_bound_valid = true;
3511              upper_bound = form_value.Unsigned();
3512              break;
3513
3514            default:
3515            case DW_AT_abstract_origin:
3516            case DW_AT_accessibility:
3517            case DW_AT_allocated:
3518            case DW_AT_associated:
3519            case DW_AT_data_location:
3520            case DW_AT_declaration:
3521            case DW_AT_description:
3522            case DW_AT_sibling:
3523            case DW_AT_threads_scaled:
3524            case DW_AT_type:
3525            case DW_AT_visibility:
3526              break;
3527            }
3528          }
3529        }
3530
3531        if (num_elements == 0) {
3532          if (upper_bound_valid && upper_bound >= lower_bound)
3533            num_elements = upper_bound - lower_bound + 1;
3534        }
3535
3536        array_info.element_orders.push_back(num_elements);
3537      }
3538    } break;
3539    }
3540  }
3541  return array_info;
3542}
3543
3544Type *DWARFASTParserClang::GetTypeForDIE(const DWARFDIE &die) {
3545  if (die) {
3546    SymbolFileDWARF *dwarf = die.GetDWARF();
3547    DWARFAttributes attributes;
3548    const size_t num_attributes = die.GetAttributes(attributes);
3549    if (num_attributes > 0) {
3550      DWARFFormValue type_die_form;
3551      for (size_t i = 0; i < num_attributes; ++i) {
3552        dw_attr_t attr = attributes.AttributeAtIndex(i);
3553        DWARFFormValue form_value;
3554
3555        if (attr == DW_AT_type &&
3556            attributes.ExtractFormValueAtIndex(i, form_value))
3557          return dwarf->ResolveTypeUID(dwarf->GetDIE(DIERef(form_value)), true);
3558      }
3559    }
3560  }
3561
3562  return nullptr;
3563}
3564
3565clang::Decl *DWARFASTParserClang::GetClangDeclForDIE(const DWARFDIE &die) {
3566  if (!die)
3567    return nullptr;
3568
3569  switch (die.Tag()) {
3570  case DW_TAG_variable:
3571  case DW_TAG_constant:
3572  case DW_TAG_formal_parameter:
3573  case DW_TAG_imported_declaration:
3574  case DW_TAG_imported_module:
3575    break;
3576  default:
3577    return nullptr;
3578  }
3579
3580  DIEToDeclMap::iterator cache_pos = m_die_to_decl.find(die.GetDIE());
3581  if (cache_pos != m_die_to_decl.end())
3582    return cache_pos->second;
3583
3584  if (DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification)) {
3585    clang::Decl *decl = GetClangDeclForDIE(spec_die);
3586    m_die_to_decl[die.GetDIE()] = decl;
3587    m_decl_to_die[decl].insert(die.GetDIE());
3588    return decl;
3589  }
3590
3591  if (DWARFDIE abstract_origin_die =
3592          die.GetReferencedDIE(DW_AT_abstract_origin)) {
3593    clang::Decl *decl = GetClangDeclForDIE(abstract_origin_die);
3594    m_die_to_decl[die.GetDIE()] = decl;
3595    m_decl_to_die[decl].insert(die.GetDIE());
3596    return decl;
3597  }
3598
3599  clang::Decl *decl = nullptr;
3600  switch (die.Tag()) {
3601  case DW_TAG_variable:
3602  case DW_TAG_constant:
3603  case DW_TAG_formal_parameter: {
3604    SymbolFileDWARF *dwarf = die.GetDWARF();
3605    Type *type = GetTypeForDIE(die);
3606    if (dwarf && type) {
3607      const char *name = die.GetName();
3608      clang::DeclContext *decl_context =
3609          ClangASTContext::DeclContextGetAsDeclContext(
3610              dwarf->GetDeclContextContainingUID(die.GetID()));
3611      decl = m_ast.CreateVariableDeclaration(
3612          decl_context, name,
3613          ClangUtil::GetQualType(type->GetForwardCompilerType()));
3614    }
3615    break;
3616  }
3617  case DW_TAG_imported_declaration: {
3618    SymbolFileDWARF *dwarf = die.GetDWARF();
3619    DWARFDIE imported_uid = die.GetAttributeValueAsReferenceDIE(DW_AT_import);
3620    if (imported_uid) {
3621      CompilerDecl imported_decl = imported_uid.GetDecl();
3622      if (imported_decl) {
3623        clang::DeclContext *decl_context =
3624            ClangASTContext::DeclContextGetAsDeclContext(
3625                dwarf->GetDeclContextContainingUID(die.GetID()));
3626        if (clang::NamedDecl *clang_imported_decl =
3627                llvm::dyn_cast<clang::NamedDecl>(
3628                    (clang::Decl *)imported_decl.GetOpaqueDecl()))
3629          decl =
3630              m_ast.CreateUsingDeclaration(decl_context, clang_imported_decl);
3631      }
3632    }
3633    break;
3634  }
3635  case DW_TAG_imported_module: {
3636    SymbolFileDWARF *dwarf = die.GetDWARF();
3637    DWARFDIE imported_uid = die.GetAttributeValueAsReferenceDIE(DW_AT_import);
3638
3639    if (imported_uid) {
3640      CompilerDeclContext imported_decl_ctx = imported_uid.GetDeclContext();
3641      if (imported_decl_ctx) {
3642        clang::DeclContext *decl_context =
3643            ClangASTContext::DeclContextGetAsDeclContext(
3644                dwarf->GetDeclContextContainingUID(die.GetID()));
3645        if (clang::NamespaceDecl *ns_decl =
3646                ClangASTContext::DeclContextGetAsNamespaceDecl(
3647                    imported_decl_ctx))
3648          decl = m_ast.CreateUsingDirectiveDeclaration(decl_context, ns_decl);
3649      }
3650    }
3651    break;
3652  }
3653  default:
3654    break;
3655  }
3656
3657  m_die_to_decl[die.GetDIE()] = decl;
3658  m_decl_to_die[decl].insert(die.GetDIE());
3659
3660  return decl;
3661}
3662
3663clang::DeclContext *
3664DWARFASTParserClang::GetClangDeclContextForDIE(const DWARFDIE &die) {
3665  if (die) {
3666    clang::DeclContext *decl_ctx = GetCachedClangDeclContextForDIE(die);
3667    if (decl_ctx)
3668      return decl_ctx;
3669
3670    bool try_parsing_type = true;
3671    switch (die.Tag()) {
3672    case DW_TAG_compile_unit:
3673    case DW_TAG_partial_unit:
3674      decl_ctx = m_ast.GetTranslationUnitDecl();
3675      try_parsing_type = false;
3676      break;
3677
3678    case DW_TAG_namespace:
3679      decl_ctx = ResolveNamespaceDIE(die);
3680      try_parsing_type = false;
3681      break;
3682
3683    case DW_TAG_lexical_block:
3684      decl_ctx = GetDeclContextForBlock(die);
3685      try_parsing_type = false;
3686      break;
3687
3688    default:
3689      break;
3690    }
3691
3692    if (decl_ctx == nullptr && try_parsing_type) {
3693      Type *type = die.GetDWARF()->ResolveType(die);
3694      if (type)
3695        decl_ctx = GetCachedClangDeclContextForDIE(die);
3696    }
3697
3698    if (decl_ctx) {
3699      LinkDeclContextToDIE(decl_ctx, die);
3700      return decl_ctx;
3701    }
3702  }
3703  return nullptr;
3704}
3705
3706static bool IsSubroutine(const DWARFDIE &die) {
3707  switch (die.Tag()) {
3708  case DW_TAG_subprogram:
3709  case DW_TAG_inlined_subroutine:
3710    return true;
3711  default:
3712    return false;
3713  }
3714}
3715
3716static DWARFDIE GetContainingFunctionWithAbstractOrigin(const DWARFDIE &die) {
3717  for (DWARFDIE candidate = die; candidate; candidate = candidate.GetParent()) {
3718    if (IsSubroutine(candidate)) {
3719      if (candidate.GetReferencedDIE(DW_AT_abstract_origin)) {
3720        return candidate;
3721      } else {
3722        return DWARFDIE();
3723      }
3724    }
3725  }
3726  assert(0 && "Shouldn't call GetContainingFunctionWithAbstractOrigin on "
3727              "something not in a function");
3728  return DWARFDIE();
3729}
3730
3731static DWARFDIE FindAnyChildWithAbstractOrigin(const DWARFDIE &context) {
3732  for (DWARFDIE candidate = context.GetFirstChild(); candidate.IsValid();
3733       candidate = candidate.GetSibling()) {
3734    if (candidate.GetReferencedDIE(DW_AT_abstract_origin)) {
3735      return candidate;
3736    }
3737  }
3738  return DWARFDIE();
3739}
3740
3741static DWARFDIE FindFirstChildWithAbstractOrigin(const DWARFDIE &block,
3742                                                 const DWARFDIE &function) {
3743  assert(IsSubroutine(function));
3744  for (DWARFDIE context = block; context != function.GetParent();
3745       context = context.GetParent()) {
3746    assert(!IsSubroutine(context) || context == function);
3747    if (DWARFDIE child = FindAnyChildWithAbstractOrigin(context)) {
3748      return child;
3749    }
3750  }
3751  return DWARFDIE();
3752}
3753
3754clang::DeclContext *
3755DWARFASTParserClang::GetDeclContextForBlock(const DWARFDIE &die) {
3756  assert(die.Tag() == DW_TAG_lexical_block);
3757  DWARFDIE containing_function_with_abstract_origin =
3758      GetContainingFunctionWithAbstractOrigin(die);
3759  if (!containing_function_with_abstract_origin) {
3760    return (clang::DeclContext *)ResolveBlockDIE(die);
3761  }
3762  DWARFDIE child = FindFirstChildWithAbstractOrigin(
3763      die, containing_function_with_abstract_origin);
3764  CompilerDeclContext decl_context =
3765      GetDeclContextContainingUIDFromDWARF(child);
3766  return (clang::DeclContext *)decl_context.GetOpaqueDeclContext();
3767}
3768
3769clang::BlockDecl *DWARFASTParserClang::ResolveBlockDIE(const DWARFDIE &die) {
3770  if (die && die.Tag() == DW_TAG_lexical_block) {
3771    clang::BlockDecl *decl =
3772        llvm::cast_or_null<clang::BlockDecl>(m_die_to_decl_ctx[die.GetDIE()]);
3773
3774    if (!decl) {
3775      DWARFDIE decl_context_die;
3776      clang::DeclContext *decl_context =
3777          GetClangDeclContextContainingDIE(die, &decl_context_die);
3778      decl = m_ast.CreateBlockDeclaration(decl_context);
3779
3780      if (decl)
3781        LinkDeclContextToDIE((clang::DeclContext *)decl, die);
3782    }
3783
3784    return decl;
3785  }
3786  return nullptr;
3787}
3788
3789clang::NamespaceDecl *
3790DWARFASTParserClang::ResolveNamespaceDIE(const DWARFDIE &die) {
3791  if (die && die.Tag() == DW_TAG_namespace) {
3792    // See if we already parsed this namespace DIE and associated it with a
3793    // uniqued namespace declaration
3794    clang::NamespaceDecl *namespace_decl =
3795        static_cast<clang::NamespaceDecl *>(m_die_to_decl_ctx[die.GetDIE()]);
3796    if (namespace_decl)
3797      return namespace_decl;
3798    else {
3799      const char *namespace_name = die.GetName();
3800      clang::DeclContext *containing_decl_ctx =
3801          GetClangDeclContextContainingDIE(die, nullptr);
3802      namespace_decl = m_ast.GetUniqueNamespaceDeclaration(namespace_name,
3803                                                           containing_decl_ctx);
3804      Log *log =
3805          nullptr; // (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
3806      if (log) {
3807        SymbolFileDWARF *dwarf = die.GetDWARF();
3808        if (namespace_name) {
3809          dwarf->GetObjectFile()->GetModule()->LogMessage(
3810              log, "ASTContext => %p: 0x%8.8" PRIx64
3811                   ": DW_TAG_namespace with DW_AT_name(\"%s\") => "
3812                   "clang::NamespaceDecl *%p (original = %p)",
3813              static_cast<void *>(m_ast.getASTContext()), die.GetID(),
3814              namespace_name, static_cast<void *>(namespace_decl),
3815              static_cast<void *>(namespace_decl->getOriginalNamespace()));
3816        } else {
3817          dwarf->GetObjectFile()->GetModule()->LogMessage(
3818              log, "ASTContext => %p: 0x%8.8" PRIx64
3819                   ": DW_TAG_namespace (anonymous) => clang::NamespaceDecl *%p "
3820                   "(original = %p)",
3821              static_cast<void *>(m_ast.getASTContext()), die.GetID(),
3822              static_cast<void *>(namespace_decl),
3823              static_cast<void *>(namespace_decl->getOriginalNamespace()));
3824        }
3825      }
3826
3827      if (namespace_decl)
3828        LinkDeclContextToDIE((clang::DeclContext *)namespace_decl, die);
3829      return namespace_decl;
3830    }
3831  }
3832  return nullptr;
3833}
3834
3835clang::DeclContext *DWARFASTParserClang::GetClangDeclContextContainingDIE(
3836    const DWARFDIE &die, DWARFDIE *decl_ctx_die_copy) {
3837  SymbolFileDWARF *dwarf = die.GetDWARF();
3838
3839  DWARFDIE decl_ctx_die = dwarf->GetDeclContextDIEContainingDIE(die);
3840
3841  if (decl_ctx_die_copy)
3842    *decl_ctx_die_copy = decl_ctx_die;
3843
3844  if (decl_ctx_die) {
3845    clang::DeclContext *clang_decl_ctx =
3846        GetClangDeclContextForDIE(decl_ctx_die);
3847    if (clang_decl_ctx)
3848      return clang_decl_ctx;
3849  }
3850  return m_ast.GetTranslationUnitDecl();
3851}
3852
3853clang::DeclContext *
3854DWARFASTParserClang::GetCachedClangDeclContextForDIE(const DWARFDIE &die) {
3855  if (die) {
3856    DIEToDeclContextMap::iterator pos = m_die_to_decl_ctx.find(die.GetDIE());
3857    if (pos != m_die_to_decl_ctx.end())
3858      return pos->second;
3859  }
3860  return nullptr;
3861}
3862
3863void DWARFASTParserClang::LinkDeclContextToDIE(clang::DeclContext *decl_ctx,
3864                                               const DWARFDIE &die) {
3865  m_die_to_decl_ctx[die.GetDIE()] = decl_ctx;
3866  // There can be many DIEs for a single decl context
3867  // m_decl_ctx_to_die[decl_ctx].insert(die.GetDIE());
3868  m_decl_ctx_to_die.insert(std::make_pair(decl_ctx, die));
3869}
3870
3871bool DWARFASTParserClang::CopyUniqueClassMethodTypes(
3872    const DWARFDIE &src_class_die, const DWARFDIE &dst_class_die,
3873    lldb_private::Type *class_type, DWARFDIECollection &failures) {
3874  if (!class_type || !src_class_die || !dst_class_die)
3875    return false;
3876  if (src_class_die.Tag() != dst_class_die.Tag())
3877    return false;
3878
3879  // We need to complete the class type so we can get all of the method types
3880  // parsed so we can then unique those types to their equivalent counterparts
3881  // in "dst_cu" and "dst_class_die"
3882  class_type->GetFullCompilerType();
3883
3884  DWARFDIE src_die;
3885  DWARFDIE dst_die;
3886  UniqueCStringMap<DWARFDIE> src_name_to_die;
3887  UniqueCStringMap<DWARFDIE> dst_name_to_die;
3888  UniqueCStringMap<DWARFDIE> src_name_to_die_artificial;
3889  UniqueCStringMap<DWARFDIE> dst_name_to_die_artificial;
3890  for (src_die = src_class_die.GetFirstChild(); src_die.IsValid();
3891       src_die = src_die.GetSibling()) {
3892    if (src_die.Tag() == DW_TAG_subprogram) {
3893      // Make sure this is a declaration and not a concrete instance by looking
3894      // for DW_AT_declaration set to 1. Sometimes concrete function instances
3895      // are placed inside the class definitions and shouldn't be included in
3896      // the list of things are are tracking here.
3897      if (src_die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0) == 1) {
3898        const char *src_name = src_die.GetMangledName();
3899        if (src_name) {
3900          ConstString src_const_name(src_name);
3901          if (src_die.GetAttributeValueAsUnsigned(DW_AT_artificial, 0))
3902            src_name_to_die_artificial.Append(src_const_name, src_die);
3903          else
3904            src_name_to_die.Append(src_const_name, src_die);
3905        }
3906      }
3907    }
3908  }
3909  for (dst_die = dst_class_die.GetFirstChild(); dst_die.IsValid();
3910       dst_die = dst_die.GetSibling()) {
3911    if (dst_die.Tag() == DW_TAG_subprogram) {
3912      // Make sure this is a declaration and not a concrete instance by looking
3913      // for DW_AT_declaration set to 1. Sometimes concrete function instances
3914      // are placed inside the class definitions and shouldn't be included in
3915      // the list of things are are tracking here.
3916      if (dst_die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0) == 1) {
3917        const char *dst_name = dst_die.GetMangledName();
3918        if (dst_name) {
3919          ConstString dst_const_name(dst_name);
3920          if (dst_die.GetAttributeValueAsUnsigned(DW_AT_artificial, 0))
3921            dst_name_to_die_artificial.Append(dst_const_name, dst_die);
3922          else
3923            dst_name_to_die.Append(dst_const_name, dst_die);
3924        }
3925      }
3926    }
3927  }
3928  const uint32_t src_size = src_name_to_die.GetSize();
3929  const uint32_t dst_size = dst_name_to_die.GetSize();
3930  Log *log = nullptr; // (LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO |
3931                      // DWARF_LOG_TYPE_COMPLETION));
3932
3933  // Is everything kosher so we can go through the members at top speed?
3934  bool fast_path = true;
3935
3936  if (src_size != dst_size) {
3937    if (src_size != 0 && dst_size != 0) {
3938      if (log)
3939        log->Printf("warning: trying to unique class DIE 0x%8.8x to 0x%8.8x, "
3940                    "but they didn't have the same size (src=%d, dst=%d)",
3941                    src_class_die.GetOffset(), dst_class_die.GetOffset(),
3942                    src_size, dst_size);
3943    }
3944
3945    fast_path = false;
3946  }
3947
3948  uint32_t idx;
3949
3950  if (fast_path) {
3951    for (idx = 0; idx < src_size; ++idx) {
3952      src_die = src_name_to_die.GetValueAtIndexUnchecked(idx);
3953      dst_die = dst_name_to_die.GetValueAtIndexUnchecked(idx);
3954
3955      if (src_die.Tag() != dst_die.Tag()) {
3956        if (log)
3957          log->Printf("warning: tried to unique class DIE 0x%8.8x to 0x%8.8x, "
3958                      "but 0x%8.8x (%s) tags didn't match 0x%8.8x (%s)",
3959                      src_class_die.GetOffset(), dst_class_die.GetOffset(),
3960                      src_die.GetOffset(), src_die.GetTagAsCString(),
3961                      dst_die.GetOffset(), dst_die.GetTagAsCString());
3962        fast_path = false;
3963      }
3964
3965      const char *src_name = src_die.GetMangledName();
3966      const char *dst_name = dst_die.GetMangledName();
3967
3968      // Make sure the names match
3969      if (src_name == dst_name || (strcmp(src_name, dst_name) == 0))
3970        continue;
3971
3972      if (log)
3973        log->Printf("warning: tried to unique class DIE 0x%8.8x to 0x%8.8x, "
3974                    "but 0x%8.8x (%s) names didn't match 0x%8.8x (%s)",
3975                    src_class_die.GetOffset(), dst_class_die.GetOffset(),
3976                    src_die.GetOffset(), src_name, dst_die.GetOffset(),
3977                    dst_name);
3978
3979      fast_path = false;
3980    }
3981  }
3982
3983  DWARFASTParserClang *src_dwarf_ast_parser =
3984      (DWARFASTParserClang *)src_die.GetDWARFParser();
3985  DWARFASTParserClang *dst_dwarf_ast_parser =
3986      (DWARFASTParserClang *)dst_die.GetDWARFParser();
3987
3988  // Now do the work of linking the DeclContexts and Types.
3989  if (fast_path) {
3990    // We can do this quickly.  Just run across the tables index-for-index
3991    // since we know each node has matching names and tags.
3992    for (idx = 0; idx < src_size; ++idx) {
3993      src_die = src_name_to_die.GetValueAtIndexUnchecked(idx);
3994      dst_die = dst_name_to_die.GetValueAtIndexUnchecked(idx);
3995
3996      clang::DeclContext *src_decl_ctx =
3997          src_dwarf_ast_parser->m_die_to_decl_ctx[src_die.GetDIE()];
3998      if (src_decl_ctx) {
3999        if (log)
4000          log->Printf("uniquing decl context %p from 0x%8.8x for 0x%8.8x",
4001                      static_cast<void *>(src_decl_ctx), src_die.GetOffset(),
4002                      dst_die.GetOffset());
4003        dst_dwarf_ast_parser->LinkDeclContextToDIE(src_decl_ctx, dst_die);
4004      } else {
4005        if (log)
4006          log->Printf("warning: tried to unique decl context from 0x%8.8x for "
4007                      "0x%8.8x, but none was found",
4008                      src_die.GetOffset(), dst_die.GetOffset());
4009      }
4010
4011      Type *src_child_type =
4012          dst_die.GetDWARF()->GetDIEToType()[src_die.GetDIE()];
4013      if (src_child_type) {
4014        if (log)
4015          log->Printf(
4016              "uniquing type %p (uid=0x%" PRIx64 ") from 0x%8.8x for 0x%8.8x",
4017              static_cast<void *>(src_child_type), src_child_type->GetID(),
4018              src_die.GetOffset(), dst_die.GetOffset());
4019        dst_die.GetDWARF()->GetDIEToType()[dst_die.GetDIE()] = src_child_type;
4020      } else {
4021        if (log)
4022          log->Printf("warning: tried to unique lldb_private::Type from "
4023                      "0x%8.8x for 0x%8.8x, but none was found",
4024                      src_die.GetOffset(), dst_die.GetOffset());
4025      }
4026    }
4027  } else {
4028    // We must do this slowly.  For each member of the destination, look up a
4029    // member in the source with the same name, check its tag, and unique them
4030    // if everything matches up.  Report failures.
4031
4032    if (!src_name_to_die.IsEmpty() && !dst_name_to_die.IsEmpty()) {
4033      src_name_to_die.Sort();
4034
4035      for (idx = 0; idx < dst_size; ++idx) {
4036        ConstString dst_name = dst_name_to_die.GetCStringAtIndex(idx);
4037        dst_die = dst_name_to_die.GetValueAtIndexUnchecked(idx);
4038        src_die = src_name_to_die.Find(dst_name, DWARFDIE());
4039
4040        if (src_die && (src_die.Tag() == dst_die.Tag())) {
4041          clang::DeclContext *src_decl_ctx =
4042              src_dwarf_ast_parser->m_die_to_decl_ctx[src_die.GetDIE()];
4043          if (src_decl_ctx) {
4044            if (log)
4045              log->Printf("uniquing decl context %p from 0x%8.8x for 0x%8.8x",
4046                          static_cast<void *>(src_decl_ctx),
4047                          src_die.GetOffset(), dst_die.GetOffset());
4048            dst_dwarf_ast_parser->LinkDeclContextToDIE(src_decl_ctx, dst_die);
4049          } else {
4050            if (log)
4051              log->Printf("warning: tried to unique decl context from 0x%8.8x "
4052                          "for 0x%8.8x, but none was found",
4053                          src_die.GetOffset(), dst_die.GetOffset());
4054          }
4055
4056          Type *src_child_type =
4057              dst_die.GetDWARF()->GetDIEToType()[src_die.GetDIE()];
4058          if (src_child_type) {
4059            if (log)
4060              log->Printf("uniquing type %p (uid=0x%" PRIx64
4061                          ") from 0x%8.8x for 0x%8.8x",
4062                          static_cast<void *>(src_child_type),
4063                          src_child_type->GetID(), src_die.GetOffset(),
4064                          dst_die.GetOffset());
4065            dst_die.GetDWARF()->GetDIEToType()[dst_die.GetDIE()] =
4066                src_child_type;
4067          } else {
4068            if (log)
4069              log->Printf("warning: tried to unique lldb_private::Type from "
4070                          "0x%8.8x for 0x%8.8x, but none was found",
4071                          src_die.GetOffset(), dst_die.GetOffset());
4072          }
4073        } else {
4074          if (log)
4075            log->Printf("warning: couldn't find a match for 0x%8.8x",
4076                        dst_die.GetOffset());
4077
4078          failures.Append(dst_die);
4079        }
4080      }
4081    }
4082  }
4083
4084  const uint32_t src_size_artificial = src_name_to_die_artificial.GetSize();
4085  const uint32_t dst_size_artificial = dst_name_to_die_artificial.GetSize();
4086
4087  if (src_size_artificial && dst_size_artificial) {
4088    dst_name_to_die_artificial.Sort();
4089
4090    for (idx = 0; idx < src_size_artificial; ++idx) {
4091      ConstString src_name_artificial =
4092          src_name_to_die_artificial.GetCStringAtIndex(idx);
4093      src_die = src_name_to_die_artificial.GetValueAtIndexUnchecked(idx);
4094      dst_die =
4095          dst_name_to_die_artificial.Find(src_name_artificial, DWARFDIE());
4096
4097      if (dst_die) {
4098        // Both classes have the artificial types, link them
4099        clang::DeclContext *src_decl_ctx =
4100            src_dwarf_ast_parser->m_die_to_decl_ctx[src_die.GetDIE()];
4101        if (src_decl_ctx) {
4102          if (log)
4103            log->Printf("uniquing decl context %p from 0x%8.8x for 0x%8.8x",
4104                        static_cast<void *>(src_decl_ctx), src_die.GetOffset(),
4105                        dst_die.GetOffset());
4106          dst_dwarf_ast_parser->LinkDeclContextToDIE(src_decl_ctx, dst_die);
4107        } else {
4108          if (log)
4109            log->Printf("warning: tried to unique decl context from 0x%8.8x "
4110                        "for 0x%8.8x, but none was found",
4111                        src_die.GetOffset(), dst_die.GetOffset());
4112        }
4113
4114        Type *src_child_type =
4115            dst_die.GetDWARF()->GetDIEToType()[src_die.GetDIE()];
4116        if (src_child_type) {
4117          if (log)
4118            log->Printf(
4119                "uniquing type %p (uid=0x%" PRIx64 ") from 0x%8.8x for 0x%8.8x",
4120                static_cast<void *>(src_child_type), src_child_type->GetID(),
4121                src_die.GetOffset(), dst_die.GetOffset());
4122          dst_die.GetDWARF()->GetDIEToType()[dst_die.GetDIE()] = src_child_type;
4123        } else {
4124          if (log)
4125            log->Printf("warning: tried to unique lldb_private::Type from "
4126                        "0x%8.8x for 0x%8.8x, but none was found",
4127                        src_die.GetOffset(), dst_die.GetOffset());
4128        }
4129      }
4130    }
4131  }
4132
4133  if (dst_size_artificial) {
4134    for (idx = 0; idx < dst_size_artificial; ++idx) {
4135      ConstString dst_name_artificial =
4136          dst_name_to_die_artificial.GetCStringAtIndex(idx);
4137      dst_die = dst_name_to_die_artificial.GetValueAtIndexUnchecked(idx);
4138      if (log)
4139        log->Printf("warning: need to create artificial method for 0x%8.8x for "
4140                    "method '%s'",
4141                    dst_die.GetOffset(), dst_name_artificial.GetCString());
4142
4143      failures.Append(dst_die);
4144    }
4145  }
4146
4147  return (failures.Size() != 0);
4148}
4149