PdbAstBuilder.cpp revision 360784
1#include "PdbAstBuilder.h"
2
3#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
4#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
5#include "llvm/DebugInfo/CodeView/RecordName.h"
6#include "llvm/DebugInfo/CodeView/SymbolDeserializer.h"
7#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
8#include "llvm/DebugInfo/CodeView/SymbolRecordHelpers.h"
9#include "llvm/DebugInfo/CodeView/TypeDeserializer.h"
10#include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h"
11#include "llvm/DebugInfo/PDB/Native/DbiStream.h"
12#include "llvm/DebugInfo/PDB/Native/PublicsStream.h"
13#include "llvm/DebugInfo/PDB/Native/SymbolStream.h"
14#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
15#include "llvm/Demangle/MicrosoftDemangle.h"
16
17#include "Plugins/Language/CPlusPlus/MSVCUndecoratedNameParser.h"
18#include "lldb/Core/Module.h"
19#include "lldb/Symbol/ClangASTContext.h"
20#include "lldb/Symbol/ClangASTMetadata.h"
21#include "lldb/Symbol/ClangUtil.h"
22#include "lldb/Symbol/ObjectFile.h"
23#include "lldb/Utility/LLDBAssert.h"
24
25#include "PdbUtil.h"
26#include "UdtRecordCompleter.h"
27
28using namespace lldb_private;
29using namespace lldb_private::npdb;
30using namespace llvm::codeview;
31using namespace llvm::pdb;
32
33static llvm::Optional<PdbCompilandSymId> FindSymbolScope(PdbIndex &index,
34                                                         PdbCompilandSymId id) {
35  CVSymbol sym = index.ReadSymbolRecord(id);
36  if (symbolOpensScope(sym.kind())) {
37    // If this exact symbol opens a scope, we can just directly access its
38    // parent.
39    id.offset = getScopeParentOffset(sym);
40    // Global symbols have parent offset of 0.  Return llvm::None to indicate
41    // this.
42    if (id.offset == 0)
43      return llvm::None;
44    return id;
45  }
46
47  // Otherwise we need to start at the beginning and iterate forward until we
48  // reach (or pass) this particular symbol
49  CompilandIndexItem &cii = index.compilands().GetOrCreateCompiland(id.modi);
50  const CVSymbolArray &syms = cii.m_debug_stream.getSymbolArray();
51
52  auto begin = syms.begin();
53  auto end = syms.at(id.offset);
54  std::vector<PdbCompilandSymId> scope_stack;
55
56  while (begin != end) {
57    if (id.offset == begin.offset()) {
58      // We have a match!  Return the top of the stack
59      if (scope_stack.empty())
60        return llvm::None;
61      return scope_stack.back();
62    }
63    if (begin.offset() > id.offset) {
64      // We passed it.  We couldn't even find this symbol record.
65      lldbassert(false && "Invalid compiland symbol id!");
66      return llvm::None;
67    }
68
69    // We haven't found the symbol yet.  Check if we need to open or close the
70    // scope stack.
71    if (symbolOpensScope(begin->kind())) {
72      // We can use the end offset of the scope to determine whether or not
73      // we can just outright skip this entire scope.
74      uint32_t scope_end = getScopeEndOffset(*begin);
75      if (scope_end < id.modi) {
76        begin = syms.at(scope_end);
77      } else {
78        // The symbol we're looking for is somewhere in this scope.
79        scope_stack.emplace_back(id.modi, begin.offset());
80      }
81    } else if (symbolEndsScope(begin->kind())) {
82      scope_stack.pop_back();
83    }
84    ++begin;
85  }
86
87  return llvm::None;
88}
89
90static clang::TagTypeKind TranslateUdtKind(const TagRecord &cr) {
91  switch (cr.Kind) {
92  case TypeRecordKind::Class:
93    return clang::TTK_Class;
94  case TypeRecordKind::Struct:
95    return clang::TTK_Struct;
96  case TypeRecordKind::Union:
97    return clang::TTK_Union;
98  case TypeRecordKind::Interface:
99    return clang::TTK_Interface;
100  case TypeRecordKind::Enum:
101    return clang::TTK_Enum;
102  default:
103    lldbassert(false && "Invalid tag record kind!");
104    return clang::TTK_Struct;
105  }
106}
107
108static bool IsCVarArgsFunction(llvm::ArrayRef<TypeIndex> args) {
109  if (args.empty())
110    return false;
111  return args.back() == TypeIndex::None();
112}
113
114static bool
115AnyScopesHaveTemplateParams(llvm::ArrayRef<llvm::ms_demangle::Node *> scopes) {
116  for (llvm::ms_demangle::Node *n : scopes) {
117    auto *idn = static_cast<llvm::ms_demangle::IdentifierNode *>(n);
118    if (idn->TemplateParams)
119      return true;
120  }
121  return false;
122}
123
124static llvm::Optional<clang::CallingConv>
125TranslateCallingConvention(llvm::codeview::CallingConvention conv) {
126  using CC = llvm::codeview::CallingConvention;
127  switch (conv) {
128
129  case CC::NearC:
130  case CC::FarC:
131    return clang::CallingConv::CC_C;
132  case CC::NearPascal:
133  case CC::FarPascal:
134    return clang::CallingConv::CC_X86Pascal;
135  case CC::NearFast:
136  case CC::FarFast:
137    return clang::CallingConv::CC_X86FastCall;
138  case CC::NearStdCall:
139  case CC::FarStdCall:
140    return clang::CallingConv::CC_X86StdCall;
141  case CC::ThisCall:
142    return clang::CallingConv::CC_X86ThisCall;
143  case CC::NearVector:
144    return clang::CallingConv::CC_X86VectorCall;
145  default:
146    return llvm::None;
147  }
148}
149
150static llvm::Optional<CVTagRecord>
151GetNestedTagDefinition(const NestedTypeRecord &Record,
152                       const CVTagRecord &parent, TpiStream &tpi) {
153  // An LF_NESTTYPE is essentially a nested typedef / using declaration, but it
154  // is also used to indicate the primary definition of a nested class.  That is
155  // to say, if you have:
156  // struct A {
157  //   struct B {};
158  //   using C = B;
159  // };
160  // Then in the debug info, this will appear as:
161  // LF_STRUCTURE `A::B` [type index = N]
162  // LF_STRUCTURE `A`
163  //   LF_NESTTYPE [name = `B`, index = N]
164  //   LF_NESTTYPE [name = `C`, index = N]
165  // In order to accurately reconstruct the decl context hierarchy, we need to
166  // know which ones are actual definitions and which ones are just aliases.
167
168  // If it's a simple type, then this is something like `using foo = int`.
169  if (Record.Type.isSimple())
170    return llvm::None;
171
172  CVType cvt = tpi.getType(Record.Type);
173
174  if (!IsTagRecord(cvt))
175    return llvm::None;
176
177  // If it's an inner definition, then treat whatever name we have here as a
178  // single component of a mangled name.  So we can inject it into the parent's
179  // mangled name to see if it matches.
180  CVTagRecord child = CVTagRecord::create(cvt);
181  std::string qname = parent.asTag().getUniqueName();
182  if (qname.size() < 4 || child.asTag().getUniqueName().size() < 4)
183    return llvm::None;
184
185  // qname[3] is the tag type identifier (struct, class, union, etc).  Since the
186  // inner tag type is not necessarily the same as the outer tag type, re-write
187  // it to match the inner tag type.
188  qname[3] = child.asTag().getUniqueName()[3];
189  std::string piece;
190  if (qname[3] == 'W')
191    piece = "4";
192  piece += Record.Name;
193  piece.push_back('@');
194  qname.insert(4, std::move(piece));
195  if (qname != child.asTag().UniqueName)
196    return llvm::None;
197
198  return std::move(child);
199}
200
201static bool IsAnonymousNamespaceName(llvm::StringRef name) {
202  return name == "`anonymous namespace'" || name == "`anonymous-namespace'";
203}
204
205PdbAstBuilder::PdbAstBuilder(ObjectFile &obj, PdbIndex &index, ClangASTContext &clang)
206    : m_index(index), m_clang(clang) {
207  BuildParentMap();
208}
209
210lldb_private::CompilerDeclContext PdbAstBuilder::GetTranslationUnitDecl() {
211  return ToCompilerDeclContext(*m_clang.GetTranslationUnitDecl());
212}
213
214std::pair<clang::DeclContext *, std::string>
215PdbAstBuilder::CreateDeclInfoForType(const TagRecord &record, TypeIndex ti) {
216  // FIXME: Move this to GetDeclContextContainingUID.
217  if (!record.hasUniqueName())
218    return CreateDeclInfoForUndecoratedName(record.Name);
219
220  llvm::ms_demangle::Demangler demangler;
221  StringView sv(record.UniqueName.begin(), record.UniqueName.size());
222  llvm::ms_demangle::TagTypeNode *ttn = demangler.parseTagUniqueName(sv);
223  if (demangler.Error)
224    return {m_clang.GetTranslationUnitDecl(), record.UniqueName};
225
226  llvm::ms_demangle::IdentifierNode *idn =
227      ttn->QualifiedName->getUnqualifiedIdentifier();
228  std::string uname = idn->toString(llvm::ms_demangle::OF_NoTagSpecifier);
229
230  llvm::ms_demangle::NodeArrayNode *name_components =
231      ttn->QualifiedName->Components;
232  llvm::ArrayRef<llvm::ms_demangle::Node *> scopes(name_components->Nodes,
233                                                   name_components->Count - 1);
234
235  clang::DeclContext *context = m_clang.GetTranslationUnitDecl();
236
237  // If this type doesn't have a parent type in the debug info, then the best we
238  // can do is to say that it's either a series of namespaces (if the scope is
239  // non-empty), or the translation unit (if the scope is empty).
240  auto parent_iter = m_parent_types.find(ti);
241  if (parent_iter == m_parent_types.end()) {
242    if (scopes.empty())
243      return {context, uname};
244
245    // If there is no parent in the debug info, but some of the scopes have
246    // template params, then this is a case of bad debug info.  See, for
247    // example, llvm.org/pr39607.  We don't want to create an ambiguity between
248    // a NamespaceDecl and a CXXRecordDecl, so instead we create a class at
249    // global scope with the fully qualified name.
250    if (AnyScopesHaveTemplateParams(scopes))
251      return {context, record.Name};
252
253    for (llvm::ms_demangle::Node *scope : scopes) {
254      auto *nii = static_cast<llvm::ms_demangle::NamedIdentifierNode *>(scope);
255      std::string str = nii->toString();
256      context = GetOrCreateNamespaceDecl(str.c_str(), *context);
257    }
258    return {context, uname};
259  }
260
261  // Otherwise, all we need to do is get the parent type of this type and
262  // recurse into our lazy type creation / AST reconstruction logic to get an
263  // LLDB TypeSP for the parent.  This will cause the AST to automatically get
264  // the right DeclContext created for any parent.
265  clang::QualType parent_qt = GetOrCreateType(parent_iter->second);
266
267  context = clang::TagDecl::castToDeclContext(parent_qt->getAsTagDecl());
268  return {context, uname};
269}
270
271void PdbAstBuilder::BuildParentMap() {
272  LazyRandomTypeCollection &types = m_index.tpi().typeCollection();
273
274  llvm::DenseMap<TypeIndex, TypeIndex> forward_to_full;
275  llvm::DenseMap<TypeIndex, TypeIndex> full_to_forward;
276
277  struct RecordIndices {
278    TypeIndex forward;
279    TypeIndex full;
280  };
281
282  llvm::StringMap<RecordIndices> record_indices;
283
284  for (auto ti = types.getFirst(); ti; ti = types.getNext(*ti)) {
285    CVType type = types.getType(*ti);
286    if (!IsTagRecord(type))
287      continue;
288
289    CVTagRecord tag = CVTagRecord::create(type);
290
291    RecordIndices &indices = record_indices[tag.asTag().getUniqueName()];
292    if (tag.asTag().isForwardRef())
293      indices.forward = *ti;
294    else
295      indices.full = *ti;
296
297    if (indices.full != TypeIndex::None() &&
298        indices.forward != TypeIndex::None()) {
299      forward_to_full[indices.forward] = indices.full;
300      full_to_forward[indices.full] = indices.forward;
301    }
302
303    // We're looking for LF_NESTTYPE records in the field list, so ignore
304    // forward references (no field list), and anything without a nested class
305    // (since there won't be any LF_NESTTYPE records).
306    if (tag.asTag().isForwardRef() || !tag.asTag().containsNestedClass())
307      continue;
308
309    struct ProcessTpiStream : public TypeVisitorCallbacks {
310      ProcessTpiStream(PdbIndex &index, TypeIndex parent,
311                       const CVTagRecord &parent_cvt,
312                       llvm::DenseMap<TypeIndex, TypeIndex> &parents)
313          : index(index), parents(parents), parent(parent),
314            parent_cvt(parent_cvt) {}
315
316      PdbIndex &index;
317      llvm::DenseMap<TypeIndex, TypeIndex> &parents;
318
319      unsigned unnamed_type_index = 1;
320      TypeIndex parent;
321      const CVTagRecord &parent_cvt;
322
323      llvm::Error visitKnownMember(CVMemberRecord &CVR,
324                                   NestedTypeRecord &Record) override {
325        std::string unnamed_type_name;
326        if (Record.Name.empty()) {
327          unnamed_type_name =
328              llvm::formatv("<unnamed-type-$S{0}>", unnamed_type_index).str();
329          Record.Name = unnamed_type_name;
330          ++unnamed_type_index;
331        }
332        llvm::Optional<CVTagRecord> tag =
333            GetNestedTagDefinition(Record, parent_cvt, index.tpi());
334        if (!tag)
335          return llvm::ErrorSuccess();
336
337        parents[Record.Type] = parent;
338        return llvm::ErrorSuccess();
339      }
340    };
341
342    CVType field_list = m_index.tpi().getType(tag.asTag().FieldList);
343    ProcessTpiStream process(m_index, *ti, tag, m_parent_types);
344    llvm::Error error = visitMemberRecordStream(field_list.data(), process);
345    if (error)
346      llvm::consumeError(std::move(error));
347  }
348
349  // Now that we know the forward -> full mapping of all type indices, we can
350  // re-write all the indices.  At the end of this process, we want a mapping
351  // consisting of fwd -> full and full -> full for all child -> parent indices.
352  // We can re-write the values in place, but for the keys, we must save them
353  // off so that we don't modify the map in place while also iterating it.
354  std::vector<TypeIndex> full_keys;
355  std::vector<TypeIndex> fwd_keys;
356  for (auto &entry : m_parent_types) {
357    TypeIndex key = entry.first;
358    TypeIndex value = entry.second;
359
360    auto iter = forward_to_full.find(value);
361    if (iter != forward_to_full.end())
362      entry.second = iter->second;
363
364    iter = forward_to_full.find(key);
365    if (iter != forward_to_full.end())
366      fwd_keys.push_back(key);
367    else
368      full_keys.push_back(key);
369  }
370  for (TypeIndex fwd : fwd_keys) {
371    TypeIndex full = forward_to_full[fwd];
372    m_parent_types[full] = m_parent_types[fwd];
373  }
374  for (TypeIndex full : full_keys) {
375    TypeIndex fwd = full_to_forward[full];
376    m_parent_types[fwd] = m_parent_types[full];
377  }
378
379  // Now that
380}
381
382static bool isLocalVariableType(SymbolKind K) {
383  switch (K) {
384  case S_REGISTER:
385  case S_REGREL32:
386  case S_LOCAL:
387    return true;
388  default:
389    break;
390  }
391  return false;
392}
393
394static std::string
395RenderScopeList(llvm::ArrayRef<llvm::ms_demangle::Node *> nodes) {
396  lldbassert(!nodes.empty());
397
398  std::string result = nodes.front()->toString();
399  nodes = nodes.drop_front();
400  while (!nodes.empty()) {
401    result += "::";
402    result += nodes.front()->toString(llvm::ms_demangle::OF_NoTagSpecifier);
403    nodes = nodes.drop_front();
404  }
405  return result;
406}
407
408static llvm::Optional<PublicSym32> FindPublicSym(const SegmentOffset &addr,
409                                                 SymbolStream &syms,
410                                                 PublicsStream &publics) {
411  llvm::FixedStreamArray<ulittle32_t> addr_map = publics.getAddressMap();
412  auto iter = std::lower_bound(
413      addr_map.begin(), addr_map.end(), addr,
414      [&](const ulittle32_t &x, const SegmentOffset &y) {
415        CVSymbol s1 = syms.readRecord(x);
416        lldbassert(s1.kind() == S_PUB32);
417        PublicSym32 p1;
418        llvm::cantFail(SymbolDeserializer::deserializeAs<PublicSym32>(s1, p1));
419        if (p1.Segment < y.segment)
420          return true;
421        return p1.Offset < y.offset;
422      });
423  if (iter == addr_map.end())
424    return llvm::None;
425  CVSymbol sym = syms.readRecord(*iter);
426  lldbassert(sym.kind() == S_PUB32);
427  PublicSym32 p;
428  llvm::cantFail(SymbolDeserializer::deserializeAs<PublicSym32>(sym, p));
429  if (p.Segment == addr.segment && p.Offset == addr.offset)
430    return p;
431  return llvm::None;
432}
433
434clang::Decl *PdbAstBuilder::GetOrCreateSymbolForId(PdbCompilandSymId id) {
435  CVSymbol cvs = m_index.ReadSymbolRecord(id);
436
437  if (isLocalVariableType(cvs.kind())) {
438    clang::DeclContext *scope = GetParentDeclContext(id);
439    clang::Decl *scope_decl = clang::Decl::castFromDeclContext(scope);
440    PdbCompilandSymId scope_id(id.modi, m_decl_to_status[scope_decl].uid);
441    return GetOrCreateVariableDecl(scope_id, id);
442  }
443
444  switch (cvs.kind()) {
445  case S_GPROC32:
446  case S_LPROC32:
447    return GetOrCreateFunctionDecl(id);
448  case S_GDATA32:
449  case S_LDATA32:
450  case S_GTHREAD32:
451  case S_CONSTANT:
452    // global variable
453    return nullptr;
454  case S_BLOCK32:
455    return GetOrCreateBlockDecl(id);
456  default:
457    return nullptr;
458  }
459}
460
461llvm::Optional<CompilerDecl> PdbAstBuilder::GetOrCreateDeclForUid(PdbSymUid uid) {
462  if (clang::Decl *result = TryGetDecl(uid))
463    return ToCompilerDecl(*result);
464
465  clang::Decl *result = nullptr;
466  switch (uid.kind()) {
467  case PdbSymUidKind::CompilandSym:
468    result = GetOrCreateSymbolForId(uid.asCompilandSym());
469    break;
470  case PdbSymUidKind::Type: {
471    clang::QualType qt = GetOrCreateType(uid.asTypeSym());
472    if (auto *tag = qt->getAsTagDecl()) {
473      result = tag;
474      break;
475    }
476    return llvm::None;
477  }
478  default:
479    return llvm::None;
480  }
481  m_uid_to_decl[toOpaqueUid(uid)] = result;
482  return ToCompilerDecl(*result);
483}
484
485clang::DeclContext *PdbAstBuilder::GetOrCreateDeclContextForUid(PdbSymUid uid) {
486  if (uid.kind() == PdbSymUidKind::CompilandSym) {
487    if (uid.asCompilandSym().offset == 0)
488      return FromCompilerDeclContext(GetTranslationUnitDecl());
489  }
490  auto option = GetOrCreateDeclForUid(uid);
491  if (!option)
492    return nullptr;
493  clang::Decl *decl = FromCompilerDecl(option.getValue());
494  if (!decl)
495    return nullptr;
496
497  return clang::Decl::castToDeclContext(decl);
498}
499
500std::pair<clang::DeclContext *, std::string>
501PdbAstBuilder::CreateDeclInfoForUndecoratedName(llvm::StringRef name) {
502  MSVCUndecoratedNameParser parser(name);
503  llvm::ArrayRef<MSVCUndecoratedNameSpecifier> specs = parser.GetSpecifiers();
504
505  auto context = FromCompilerDeclContext(GetTranslationUnitDecl());
506
507  llvm::StringRef uname = specs.back().GetBaseName();
508  specs = specs.drop_back();
509  if (specs.empty())
510    return {context, name};
511
512  llvm::StringRef scope_name = specs.back().GetFullName();
513
514  // It might be a class name, try that first.
515  std::vector<TypeIndex> types = m_index.tpi().findRecordsByName(scope_name);
516  while (!types.empty()) {
517    clang::QualType qt = GetOrCreateType(types.back());
518    clang::TagDecl *tag = qt->getAsTagDecl();
519    if (tag)
520      return {clang::TagDecl::castToDeclContext(tag), uname};
521    types.pop_back();
522  }
523
524  // If that fails, treat it as a series of namespaces.
525  for (const MSVCUndecoratedNameSpecifier &spec : specs) {
526    std::string ns_name = spec.GetBaseName().str();
527    context = GetOrCreateNamespaceDecl(ns_name.c_str(), *context);
528  }
529  return {context, uname};
530}
531
532clang::DeclContext *
533PdbAstBuilder::GetParentDeclContextForSymbol(const CVSymbol &sym) {
534  if (!SymbolHasAddress(sym))
535    return CreateDeclInfoForUndecoratedName(getSymbolName(sym)).first;
536  SegmentOffset addr = GetSegmentAndOffset(sym);
537  llvm::Optional<PublicSym32> pub =
538      FindPublicSym(addr, m_index.symrecords(), m_index.publics());
539  if (!pub)
540    return CreateDeclInfoForUndecoratedName(getSymbolName(sym)).first;
541
542  llvm::ms_demangle::Demangler demangler;
543  StringView name{pub->Name.begin(), pub->Name.size()};
544  llvm::ms_demangle::SymbolNode *node = demangler.parse(name);
545  if (!node)
546    return FromCompilerDeclContext(GetTranslationUnitDecl());
547  llvm::ArrayRef<llvm::ms_demangle::Node *> name_components{
548      node->Name->Components->Nodes, node->Name->Components->Count - 1};
549
550  if (!name_components.empty()) {
551    // Render the current list of scope nodes as a fully qualified name, and
552    // look it up in the debug info as a type name.  If we find something,
553    // this is a type (which may itself be prefixed by a namespace).  If we
554    // don't, this is a list of namespaces.
555    std::string qname = RenderScopeList(name_components);
556    std::vector<TypeIndex> matches = m_index.tpi().findRecordsByName(qname);
557    while (!matches.empty()) {
558      clang::QualType qt = GetOrCreateType(matches.back());
559      clang::TagDecl *tag = qt->getAsTagDecl();
560      if (tag)
561        return clang::TagDecl::castToDeclContext(tag);
562      matches.pop_back();
563    }
564  }
565
566  // It's not a type.  It must be a series of namespaces.
567  auto context = FromCompilerDeclContext(GetTranslationUnitDecl());
568  while (!name_components.empty()) {
569    std::string ns = name_components.front()->toString();
570    context = GetOrCreateNamespaceDecl(ns.c_str(), *context);
571    name_components = name_components.drop_front();
572  }
573  return context;
574}
575
576clang::DeclContext *PdbAstBuilder::GetParentDeclContext(PdbSymUid uid) {
577  // We must do this *without* calling GetOrCreate on the current uid, as
578  // that would be an infinite recursion.
579  switch (uid.kind()) {
580  case PdbSymUidKind::CompilandSym: {
581    llvm::Optional<PdbCompilandSymId> scope =
582        FindSymbolScope(m_index, uid.asCompilandSym());
583    if (scope)
584      return GetOrCreateDeclContextForUid(*scope);
585
586    CVSymbol sym = m_index.ReadSymbolRecord(uid.asCompilandSym());
587    return GetParentDeclContextForSymbol(sym);
588  }
589  case PdbSymUidKind::Type: {
590    // It could be a namespace, class, or global.  We don't support nested
591    // functions yet.  Anyway, we just need to consult the parent type map.
592    PdbTypeSymId type_id = uid.asTypeSym();
593    auto iter = m_parent_types.find(type_id.index);
594    if (iter == m_parent_types.end())
595      return FromCompilerDeclContext(GetTranslationUnitDecl());
596    return GetOrCreateDeclContextForUid(PdbTypeSymId(iter->second));
597  }
598  case PdbSymUidKind::FieldListMember:
599    // In this case the parent DeclContext is the one for the class that this
600    // member is inside of.
601    break;
602  case PdbSymUidKind::GlobalSym: {
603    // If this refers to a compiland symbol, just recurse in with that symbol.
604    // The only other possibilities are S_CONSTANT and S_UDT, in which case we
605    // need to parse the undecorated name to figure out the scope, then look
606    // that up in the TPI stream.  If it's found, it's a type, othewrise it's
607    // a series of namespaces.
608    // FIXME: do this.
609    CVSymbol global = m_index.ReadSymbolRecord(uid.asGlobalSym());
610    switch (global.kind()) {
611    case SymbolKind::S_GDATA32:
612    case SymbolKind::S_LDATA32:
613      return GetParentDeclContextForSymbol(global);
614    case SymbolKind::S_PROCREF:
615    case SymbolKind::S_LPROCREF: {
616      ProcRefSym ref{global.kind()};
617      llvm::cantFail(
618          SymbolDeserializer::deserializeAs<ProcRefSym>(global, ref));
619      PdbCompilandSymId cu_sym_id{ref.modi(), ref.SymOffset};
620      return GetParentDeclContext(cu_sym_id);
621    }
622    case SymbolKind::S_CONSTANT:
623    case SymbolKind::S_UDT:
624      return CreateDeclInfoForUndecoratedName(getSymbolName(global)).first;
625    default:
626      break;
627    }
628    break;
629  }
630  default:
631    break;
632  }
633  return FromCompilerDeclContext(GetTranslationUnitDecl());
634}
635
636bool PdbAstBuilder::CompleteType(clang::QualType qt) {
637  clang::TagDecl *tag = qt->getAsTagDecl();
638  if (!tag)
639    return false;
640
641  return CompleteTagDecl(*tag);
642}
643
644bool PdbAstBuilder::CompleteTagDecl(clang::TagDecl &tag) {
645  // If this is not in our map, it's an error.
646  auto status_iter = m_decl_to_status.find(&tag);
647  lldbassert(status_iter != m_decl_to_status.end());
648
649  // If it's already complete, just return.
650  DeclStatus &status = status_iter->second;
651  if (status.resolved)
652    return true;
653
654  PdbTypeSymId type_id = PdbSymUid(status.uid).asTypeSym();
655
656  lldbassert(IsTagRecord(type_id, m_index.tpi()));
657
658  clang::QualType tag_qt = m_clang.getASTContext().getTypeDeclType(&tag);
659  ClangASTContext::SetHasExternalStorage(tag_qt.getAsOpaquePtr(), false);
660
661  TypeIndex tag_ti = type_id.index;
662  CVType cvt = m_index.tpi().getType(tag_ti);
663  if (cvt.kind() == LF_MODIFIER)
664    tag_ti = LookThroughModifierRecord(cvt);
665
666  PdbTypeSymId best_ti = GetBestPossibleDecl(tag_ti, m_index.tpi());
667  cvt = m_index.tpi().getType(best_ti.index);
668  lldbassert(IsTagRecord(cvt));
669
670  if (IsForwardRefUdt(cvt)) {
671    // If we can't find a full decl for this forward ref anywhere in the debug
672    // info, then we have no way to complete it.
673    return false;
674  }
675
676  TypeIndex field_list_ti = GetFieldListIndex(cvt);
677  CVType field_list_cvt = m_index.tpi().getType(field_list_ti);
678  if (field_list_cvt.kind() != LF_FIELDLIST)
679    return false;
680
681  // Visit all members of this class, then perform any finalization necessary
682  // to complete the class.
683  CompilerType ct = ToCompilerType(tag_qt);
684  UdtRecordCompleter completer(best_ti, ct, tag, *this, m_index.tpi());
685  auto error =
686      llvm::codeview::visitMemberRecordStream(field_list_cvt.data(), completer);
687  completer.complete();
688
689  status.resolved = true;
690  if (!error)
691    return true;
692
693  llvm::consumeError(std::move(error));
694  return false;
695}
696
697clang::QualType PdbAstBuilder::CreateSimpleType(TypeIndex ti) {
698  if (ti == TypeIndex::NullptrT())
699    return GetBasicType(lldb::eBasicTypeNullPtr);
700
701  if (ti.getSimpleMode() != SimpleTypeMode::Direct) {
702    clang::QualType direct_type = GetOrCreateType(ti.makeDirect());
703    return m_clang.getASTContext().getPointerType(direct_type);
704  }
705
706  if (ti.getSimpleKind() == SimpleTypeKind::NotTranslated)
707    return {};
708
709  lldb::BasicType bt = GetCompilerTypeForSimpleKind(ti.getSimpleKind());
710  if (bt == lldb::eBasicTypeInvalid)
711    return {};
712
713  return GetBasicType(bt);
714}
715
716clang::QualType PdbAstBuilder::CreatePointerType(const PointerRecord &pointer) {
717  clang::QualType pointee_type = GetOrCreateType(pointer.ReferentType);
718
719  // This can happen for pointers to LF_VTSHAPE records, which we shouldn't
720  // create in the AST.
721  if (pointee_type.isNull())
722    return {};
723
724  if (pointer.isPointerToMember()) {
725    MemberPointerInfo mpi = pointer.getMemberInfo();
726    clang::QualType class_type = GetOrCreateType(mpi.ContainingType);
727
728    return m_clang.getASTContext().getMemberPointerType(
729        pointee_type, class_type.getTypePtr());
730  }
731
732  clang::QualType pointer_type;
733  if (pointer.getMode() == PointerMode::LValueReference)
734    pointer_type = m_clang.getASTContext().getLValueReferenceType(pointee_type);
735  else if (pointer.getMode() == PointerMode::RValueReference)
736    pointer_type = m_clang.getASTContext().getRValueReferenceType(pointee_type);
737  else
738    pointer_type = m_clang.getASTContext().getPointerType(pointee_type);
739
740  if ((pointer.getOptions() & PointerOptions::Const) != PointerOptions::None)
741    pointer_type.addConst();
742
743  if ((pointer.getOptions() & PointerOptions::Volatile) != PointerOptions::None)
744    pointer_type.addVolatile();
745
746  if ((pointer.getOptions() & PointerOptions::Restrict) != PointerOptions::None)
747    pointer_type.addRestrict();
748
749  return pointer_type;
750}
751
752clang::QualType
753PdbAstBuilder::CreateModifierType(const ModifierRecord &modifier) {
754  clang::QualType unmodified_type = GetOrCreateType(modifier.ModifiedType);
755  if (unmodified_type.isNull())
756    return {};
757
758  if ((modifier.Modifiers & ModifierOptions::Const) != ModifierOptions::None)
759    unmodified_type.addConst();
760  if ((modifier.Modifiers & ModifierOptions::Volatile) != ModifierOptions::None)
761    unmodified_type.addVolatile();
762
763  return unmodified_type;
764}
765
766clang::QualType PdbAstBuilder::CreateRecordType(PdbTypeSymId id,
767                                                const TagRecord &record) {
768  clang::DeclContext *context = nullptr;
769  std::string uname;
770  std::tie(context, uname) = CreateDeclInfoForType(record, id.index);
771  clang::TagTypeKind ttk = TranslateUdtKind(record);
772  lldb::AccessType access =
773      (ttk == clang::TTK_Class) ? lldb::eAccessPrivate : lldb::eAccessPublic;
774
775  ClangASTMetadata metadata;
776  metadata.SetUserID(toOpaqueUid(id));
777  metadata.SetIsDynamicCXXType(false);
778
779  CompilerType ct = m_clang.CreateRecordType(
780      context, access, uname, ttk, lldb::eLanguageTypeC_plus_plus, &metadata);
781
782  lldbassert(ct.IsValid());
783
784  ClangASTContext::StartTagDeclarationDefinition(ct);
785
786  // Even if it's possible, don't complete it at this point. Just mark it
787  // forward resolved, and if/when LLDB needs the full definition, it can
788  // ask us.
789  clang::QualType result =
790      clang::QualType::getFromOpaquePtr(ct.GetOpaqueQualType());
791
792  ClangASTContext::SetHasExternalStorage(result.getAsOpaquePtr(), true);
793  return result;
794}
795
796clang::Decl *PdbAstBuilder::TryGetDecl(PdbSymUid uid) const {
797  auto iter = m_uid_to_decl.find(toOpaqueUid(uid));
798  if (iter != m_uid_to_decl.end())
799    return iter->second;
800  return nullptr;
801}
802
803clang::NamespaceDecl *
804PdbAstBuilder::GetOrCreateNamespaceDecl(const char *name,
805                                        clang::DeclContext &context) {
806  return m_clang.GetUniqueNamespaceDeclaration(
807      IsAnonymousNamespaceName(name) ? nullptr : name, &context);
808}
809
810clang::BlockDecl *
811PdbAstBuilder::GetOrCreateBlockDecl(PdbCompilandSymId block_id) {
812  if (clang::Decl *decl = TryGetDecl(block_id))
813    return llvm::dyn_cast<clang::BlockDecl>(decl);
814
815  clang::DeclContext *scope = GetParentDeclContext(block_id);
816
817  clang::BlockDecl *block_decl = m_clang.CreateBlockDeclaration(scope);
818  m_uid_to_decl.insert({toOpaqueUid(block_id), block_decl});
819
820  DeclStatus status;
821  status.resolved = true;
822  status.uid = toOpaqueUid(block_id);
823  m_decl_to_status.insert({block_decl, status});
824
825  return block_decl;
826}
827
828clang::VarDecl *PdbAstBuilder::CreateVariableDecl(PdbSymUid uid, CVSymbol sym,
829                                                  clang::DeclContext &scope) {
830  VariableInfo var_info = GetVariableNameInfo(sym);
831  clang::QualType qt = GetOrCreateType(var_info.type);
832
833  clang::VarDecl *var_decl = m_clang.CreateVariableDeclaration(
834      &scope, var_info.name.str().c_str(), qt);
835
836  m_uid_to_decl[toOpaqueUid(uid)] = var_decl;
837  DeclStatus status;
838  status.resolved = true;
839  status.uid = toOpaqueUid(uid);
840  m_decl_to_status.insert({var_decl, status});
841  return var_decl;
842}
843
844clang::VarDecl *
845PdbAstBuilder::GetOrCreateVariableDecl(PdbCompilandSymId scope_id,
846                                       PdbCompilandSymId var_id) {
847  if (clang::Decl *decl = TryGetDecl(var_id))
848    return llvm::dyn_cast<clang::VarDecl>(decl);
849
850  clang::DeclContext *scope = GetOrCreateDeclContextForUid(scope_id);
851
852  CVSymbol sym = m_index.ReadSymbolRecord(var_id);
853  return CreateVariableDecl(PdbSymUid(var_id), sym, *scope);
854}
855
856clang::VarDecl *PdbAstBuilder::GetOrCreateVariableDecl(PdbGlobalSymId var_id) {
857  if (clang::Decl *decl = TryGetDecl(var_id))
858    return llvm::dyn_cast<clang::VarDecl>(decl);
859
860  CVSymbol sym = m_index.ReadSymbolRecord(var_id);
861  auto context = FromCompilerDeclContext(GetTranslationUnitDecl());
862  return CreateVariableDecl(PdbSymUid(var_id), sym, *context);
863}
864
865clang::TypedefNameDecl *
866PdbAstBuilder::GetOrCreateTypedefDecl(PdbGlobalSymId id) {
867  if (clang::Decl *decl = TryGetDecl(id))
868    return llvm::dyn_cast<clang::TypedefNameDecl>(decl);
869
870  CVSymbol sym = m_index.ReadSymbolRecord(id);
871  lldbassert(sym.kind() == S_UDT);
872  UDTSym udt = llvm::cantFail(SymbolDeserializer::deserializeAs<UDTSym>(sym));
873
874  clang::DeclContext *scope = GetParentDeclContext(id);
875
876  PdbTypeSymId real_type_id{udt.Type, false};
877  clang::QualType qt = GetOrCreateType(real_type_id);
878
879  std::string uname = DropNameScope(udt.Name);
880
881  CompilerType ct = m_clang.CreateTypedefType(ToCompilerType(qt), uname.c_str(),
882                                              ToCompilerDeclContext(*scope));
883  clang::TypedefNameDecl *tnd = m_clang.GetAsTypedefDecl(ct);
884  DeclStatus status;
885  status.resolved = true;
886  status.uid = toOpaqueUid(id);
887  m_decl_to_status.insert({tnd, status});
888  return tnd;
889}
890
891clang::QualType PdbAstBuilder::GetBasicType(lldb::BasicType type) {
892  CompilerType ct = m_clang.GetBasicType(type);
893  return clang::QualType::getFromOpaquePtr(ct.GetOpaqueQualType());
894}
895
896clang::QualType PdbAstBuilder::CreateType(PdbTypeSymId type) {
897  if (type.index.isSimple())
898    return CreateSimpleType(type.index);
899
900  CVType cvt = m_index.tpi().getType(type.index);
901
902  if (cvt.kind() == LF_MODIFIER) {
903    ModifierRecord modifier;
904    llvm::cantFail(
905        TypeDeserializer::deserializeAs<ModifierRecord>(cvt, modifier));
906    return CreateModifierType(modifier);
907  }
908
909  if (cvt.kind() == LF_POINTER) {
910    PointerRecord pointer;
911    llvm::cantFail(
912        TypeDeserializer::deserializeAs<PointerRecord>(cvt, pointer));
913    return CreatePointerType(pointer);
914  }
915
916  if (IsTagRecord(cvt)) {
917    CVTagRecord tag = CVTagRecord::create(cvt);
918    if (tag.kind() == CVTagRecord::Union)
919      return CreateRecordType(type.index, tag.asUnion());
920    if (tag.kind() == CVTagRecord::Enum)
921      return CreateEnumType(type.index, tag.asEnum());
922    return CreateRecordType(type.index, tag.asClass());
923  }
924
925  if (cvt.kind() == LF_ARRAY) {
926    ArrayRecord ar;
927    llvm::cantFail(TypeDeserializer::deserializeAs<ArrayRecord>(cvt, ar));
928    return CreateArrayType(ar);
929  }
930
931  if (cvt.kind() == LF_PROCEDURE) {
932    ProcedureRecord pr;
933    llvm::cantFail(TypeDeserializer::deserializeAs<ProcedureRecord>(cvt, pr));
934    return CreateFunctionType(pr.ArgumentList, pr.ReturnType, pr.CallConv);
935  }
936
937  if (cvt.kind() == LF_MFUNCTION) {
938    MemberFunctionRecord mfr;
939    llvm::cantFail(
940        TypeDeserializer::deserializeAs<MemberFunctionRecord>(cvt, mfr));
941    return CreateFunctionType(mfr.ArgumentList, mfr.ReturnType, mfr.CallConv);
942  }
943
944  return {};
945}
946
947clang::QualType PdbAstBuilder::GetOrCreateType(PdbTypeSymId type) {
948  lldb::user_id_t uid = toOpaqueUid(type);
949  auto iter = m_uid_to_type.find(uid);
950  if (iter != m_uid_to_type.end())
951    return iter->second;
952
953  PdbTypeSymId best_type = GetBestPossibleDecl(type, m_index.tpi());
954
955  clang::QualType qt;
956  if (best_type.index != type.index) {
957    // This is a forward decl.  Call GetOrCreate on the full decl, then map the
958    // forward decl id to the full decl QualType.
959    clang::QualType qt = GetOrCreateType(best_type);
960    m_uid_to_type[toOpaqueUid(type)] = qt;
961    return qt;
962  }
963
964  // This is either a full decl, or a forward decl with no matching full decl
965  // in the debug info.
966  qt = CreateType(type);
967  m_uid_to_type[toOpaqueUid(type)] = qt;
968  if (IsTagRecord(type, m_index.tpi())) {
969    clang::TagDecl *tag = qt->getAsTagDecl();
970    lldbassert(m_decl_to_status.count(tag) == 0);
971
972    DeclStatus &status = m_decl_to_status[tag];
973    status.uid = uid;
974    status.resolved = false;
975  }
976  return qt;
977}
978
979clang::FunctionDecl *
980PdbAstBuilder::GetOrCreateFunctionDecl(PdbCompilandSymId func_id) {
981  if (clang::Decl *decl = TryGetDecl(func_id))
982    return llvm::dyn_cast<clang::FunctionDecl>(decl);
983
984  clang::DeclContext *parent = GetParentDeclContext(PdbSymUid(func_id));
985  std::string context_name;
986  if (clang::NamespaceDecl *ns = llvm::dyn_cast<clang::NamespaceDecl>(parent)) {
987    context_name = ns->getQualifiedNameAsString();
988  } else if (clang::TagDecl *tag = llvm::dyn_cast<clang::TagDecl>(parent)) {
989    context_name = tag->getQualifiedNameAsString();
990  }
991
992  CVSymbol cvs = m_index.ReadSymbolRecord(func_id);
993  ProcSym proc(static_cast<SymbolRecordKind>(cvs.kind()));
994  llvm::cantFail(SymbolDeserializer::deserializeAs<ProcSym>(cvs, proc));
995
996  PdbTypeSymId type_id(proc.FunctionType);
997  clang::QualType qt = GetOrCreateType(type_id);
998  if (qt.isNull())
999    return nullptr;
1000
1001  clang::StorageClass storage = clang::SC_None;
1002  if (proc.Kind == SymbolRecordKind::ProcSym)
1003    storage = clang::SC_Static;
1004
1005  const clang::FunctionProtoType *func_type =
1006      llvm::dyn_cast<clang::FunctionProtoType>(qt);
1007
1008  CompilerType func_ct = ToCompilerType(qt);
1009
1010  llvm::StringRef proc_name = proc.Name;
1011  proc_name.consume_front(context_name);
1012  proc_name.consume_front("::");
1013
1014  clang::FunctionDecl *function_decl = m_clang.CreateFunctionDeclaration(
1015      parent, proc_name.str().c_str(), func_ct, storage, false);
1016
1017  lldbassert(m_uid_to_decl.count(toOpaqueUid(func_id)) == 0);
1018  m_uid_to_decl[toOpaqueUid(func_id)] = function_decl;
1019  DeclStatus status;
1020  status.resolved = true;
1021  status.uid = toOpaqueUid(func_id);
1022  m_decl_to_status.insert({function_decl, status});
1023
1024  CreateFunctionParameters(func_id, *function_decl, func_type->getNumParams());
1025
1026  return function_decl;
1027}
1028
1029void PdbAstBuilder::CreateFunctionParameters(PdbCompilandSymId func_id,
1030                                             clang::FunctionDecl &function_decl,
1031                                             uint32_t param_count) {
1032  CompilandIndexItem *cii = m_index.compilands().GetCompiland(func_id.modi);
1033  CVSymbolArray scope =
1034      cii->m_debug_stream.getSymbolArrayForScope(func_id.offset);
1035
1036  auto begin = scope.begin();
1037  auto end = scope.end();
1038  std::vector<clang::ParmVarDecl *> params;
1039  while (begin != end && param_count > 0) {
1040    uint32_t record_offset = begin.offset();
1041    CVSymbol sym = *begin++;
1042
1043    TypeIndex param_type;
1044    llvm::StringRef param_name;
1045    switch (sym.kind()) {
1046    case S_REGREL32: {
1047      RegRelativeSym reg(SymbolRecordKind::RegRelativeSym);
1048      cantFail(SymbolDeserializer::deserializeAs<RegRelativeSym>(sym, reg));
1049      param_type = reg.Type;
1050      param_name = reg.Name;
1051      break;
1052    }
1053    case S_REGISTER: {
1054      RegisterSym reg(SymbolRecordKind::RegisterSym);
1055      cantFail(SymbolDeserializer::deserializeAs<RegisterSym>(sym, reg));
1056      param_type = reg.Index;
1057      param_name = reg.Name;
1058      break;
1059    }
1060    case S_LOCAL: {
1061      LocalSym local(SymbolRecordKind::LocalSym);
1062      cantFail(SymbolDeserializer::deserializeAs<LocalSym>(sym, local));
1063      if ((local.Flags & LocalSymFlags::IsParameter) == LocalSymFlags::None)
1064        continue;
1065      param_type = local.Type;
1066      param_name = local.Name;
1067      break;
1068    }
1069    case S_BLOCK32:
1070      // All parameters should come before the first block.  If that isn't the
1071      // case, then perhaps this is bad debug info that doesn't contain
1072      // information about all parameters.
1073      return;
1074    default:
1075      continue;
1076    }
1077
1078    PdbCompilandSymId param_uid(func_id.modi, record_offset);
1079    clang::QualType qt = GetOrCreateType(param_type);
1080
1081    CompilerType param_type_ct = m_clang.GetType(qt);
1082    clang::ParmVarDecl *param = m_clang.CreateParameterDeclaration(
1083        &function_decl, param_name.str().c_str(), param_type_ct,
1084        clang::SC_None, true);
1085    lldbassert(m_uid_to_decl.count(toOpaqueUid(param_uid)) == 0);
1086
1087    m_uid_to_decl[toOpaqueUid(param_uid)] = param;
1088    params.push_back(param);
1089    --param_count;
1090  }
1091
1092  if (!params.empty())
1093    m_clang.SetFunctionParameters(&function_decl, params.data(), params.size());
1094}
1095
1096clang::QualType PdbAstBuilder::CreateEnumType(PdbTypeSymId id,
1097                                              const EnumRecord &er) {
1098  clang::DeclContext *decl_context = nullptr;
1099  std::string uname;
1100  std::tie(decl_context, uname) = CreateDeclInfoForType(er, id.index);
1101  clang::QualType underlying_type = GetOrCreateType(er.UnderlyingType);
1102
1103  Declaration declaration;
1104  CompilerType enum_ct = m_clang.CreateEnumerationType(
1105      uname.c_str(), decl_context, declaration, ToCompilerType(underlying_type),
1106      er.isScoped());
1107
1108  ClangASTContext::StartTagDeclarationDefinition(enum_ct);
1109  ClangASTContext::SetHasExternalStorage(enum_ct.GetOpaqueQualType(), true);
1110
1111  return clang::QualType::getFromOpaquePtr(enum_ct.GetOpaqueQualType());
1112}
1113
1114clang::QualType PdbAstBuilder::CreateArrayType(const ArrayRecord &ar) {
1115  clang::QualType element_type = GetOrCreateType(ar.ElementType);
1116
1117  uint64_t element_count =
1118      ar.Size / GetSizeOfType({ar.ElementType}, m_index.tpi());
1119
1120  CompilerType array_ct = m_clang.CreateArrayType(ToCompilerType(element_type),
1121                                                  element_count, false);
1122  return clang::QualType::getFromOpaquePtr(array_ct.GetOpaqueQualType());
1123}
1124
1125clang::QualType PdbAstBuilder::CreateFunctionType(
1126    TypeIndex args_type_idx, TypeIndex return_type_idx,
1127    llvm::codeview::CallingConvention calling_convention) {
1128  TpiStream &stream = m_index.tpi();
1129  CVType args_cvt = stream.getType(args_type_idx);
1130  ArgListRecord args;
1131  llvm::cantFail(
1132      TypeDeserializer::deserializeAs<ArgListRecord>(args_cvt, args));
1133
1134  llvm::ArrayRef<TypeIndex> arg_indices = llvm::makeArrayRef(args.ArgIndices);
1135  bool is_variadic = IsCVarArgsFunction(arg_indices);
1136  if (is_variadic)
1137    arg_indices = arg_indices.drop_back();
1138
1139  std::vector<CompilerType> arg_types;
1140  arg_types.reserve(arg_indices.size());
1141
1142  for (TypeIndex arg_index : arg_indices) {
1143    clang::QualType arg_type = GetOrCreateType(arg_index);
1144    arg_types.push_back(ToCompilerType(arg_type));
1145  }
1146
1147  clang::QualType return_type = GetOrCreateType(return_type_idx);
1148
1149  llvm::Optional<clang::CallingConv> cc =
1150      TranslateCallingConvention(calling_convention);
1151  if (!cc)
1152    return {};
1153
1154  CompilerType return_ct = ToCompilerType(return_type);
1155  CompilerType func_sig_ast_type = m_clang.CreateFunctionType(
1156      return_ct, arg_types.data(), arg_types.size(), is_variadic, 0, *cc);
1157
1158  return clang::QualType::getFromOpaquePtr(
1159      func_sig_ast_type.GetOpaqueQualType());
1160}
1161
1162static bool isTagDecl(clang::DeclContext &context) {
1163  return !!llvm::dyn_cast<clang::TagDecl>(&context);
1164}
1165
1166static bool isFunctionDecl(clang::DeclContext &context) {
1167  return !!llvm::dyn_cast<clang::FunctionDecl>(&context);
1168}
1169
1170static bool isBlockDecl(clang::DeclContext &context) {
1171  return !!llvm::dyn_cast<clang::BlockDecl>(&context);
1172}
1173
1174void PdbAstBuilder::ParseAllNamespacesPlusChildrenOf(
1175    llvm::Optional<llvm::StringRef> parent) {
1176  TypeIndex ti{m_index.tpi().TypeIndexBegin()};
1177  for (const CVType &cvt : m_index.tpi().typeArray()) {
1178    PdbTypeSymId tid{ti};
1179    ++ti;
1180
1181    if (!IsTagRecord(cvt))
1182      continue;
1183
1184    CVTagRecord tag = CVTagRecord::create(cvt);
1185
1186    if (!parent.hasValue()) {
1187      clang::QualType qt = GetOrCreateType(tid);
1188      CompleteType(qt);
1189      continue;
1190    }
1191
1192    // Call CreateDeclInfoForType unconditionally so that the namespace info
1193    // gets created.  But only call CreateRecordType if the namespace name
1194    // matches.
1195    clang::DeclContext *context = nullptr;
1196    std::string uname;
1197    std::tie(context, uname) = CreateDeclInfoForType(tag.asTag(), tid.index);
1198    if (!context->isNamespace())
1199      continue;
1200
1201    clang::NamespaceDecl *ns = llvm::dyn_cast<clang::NamespaceDecl>(context);
1202    std::string actual_ns = ns->getQualifiedNameAsString();
1203    if (llvm::StringRef(actual_ns).startswith(*parent)) {
1204      clang::QualType qt = GetOrCreateType(tid);
1205      CompleteType(qt);
1206      continue;
1207    }
1208  }
1209
1210  uint32_t module_count = m_index.dbi().modules().getModuleCount();
1211  for (uint16_t modi = 0; modi < module_count; ++modi) {
1212    CompilandIndexItem &cii = m_index.compilands().GetOrCreateCompiland(modi);
1213    const CVSymbolArray &symbols = cii.m_debug_stream.getSymbolArray();
1214    auto iter = symbols.begin();
1215    while (iter != symbols.end()) {
1216      PdbCompilandSymId sym_id{modi, iter.offset()};
1217
1218      switch (iter->kind()) {
1219      case S_GPROC32:
1220      case S_LPROC32:
1221        GetOrCreateFunctionDecl(sym_id);
1222        iter = symbols.at(getScopeEndOffset(*iter));
1223        break;
1224      case S_GDATA32:
1225      case S_GTHREAD32:
1226      case S_LDATA32:
1227      case S_LTHREAD32:
1228        GetOrCreateVariableDecl(PdbCompilandSymId(modi, 0), sym_id);
1229        ++iter;
1230        break;
1231      default:
1232        ++iter;
1233        continue;
1234      }
1235    }
1236  }
1237}
1238
1239static CVSymbolArray skipFunctionParameters(clang::Decl &decl,
1240                                            const CVSymbolArray &symbols) {
1241  clang::FunctionDecl *func_decl = llvm::dyn_cast<clang::FunctionDecl>(&decl);
1242  if (!func_decl)
1243    return symbols;
1244  unsigned int params = func_decl->getNumParams();
1245  if (params == 0)
1246    return symbols;
1247
1248  CVSymbolArray result = symbols;
1249
1250  while (!result.empty()) {
1251    if (params == 0)
1252      return result;
1253
1254    CVSymbol sym = *result.begin();
1255    result.drop_front();
1256
1257    if (!isLocalVariableType(sym.kind()))
1258      continue;
1259
1260    --params;
1261  }
1262  return result;
1263}
1264
1265void PdbAstBuilder::ParseBlockChildren(PdbCompilandSymId block_id) {
1266  CVSymbol sym = m_index.ReadSymbolRecord(block_id);
1267  lldbassert(sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32 ||
1268             sym.kind() == S_BLOCK32);
1269  CompilandIndexItem &cii =
1270      m_index.compilands().GetOrCreateCompiland(block_id.modi);
1271  CVSymbolArray symbols =
1272      cii.m_debug_stream.getSymbolArrayForScope(block_id.offset);
1273
1274  // Function parameters should already have been created when the function was
1275  // parsed.
1276  if (sym.kind() == S_GPROC32 || sym.kind() == S_LPROC32)
1277    symbols =
1278        skipFunctionParameters(*m_uid_to_decl[toOpaqueUid(block_id)], symbols);
1279
1280  auto begin = symbols.begin();
1281  while (begin != symbols.end()) {
1282    PdbCompilandSymId child_sym_id(block_id.modi, begin.offset());
1283    GetOrCreateSymbolForId(child_sym_id);
1284    if (begin->kind() == S_BLOCK32) {
1285      ParseBlockChildren(child_sym_id);
1286      begin = symbols.at(getScopeEndOffset(*begin));
1287    }
1288    ++begin;
1289  }
1290}
1291
1292void PdbAstBuilder::ParseDeclsForSimpleContext(clang::DeclContext &context) {
1293
1294  clang::Decl *decl = clang::Decl::castFromDeclContext(&context);
1295  lldbassert(decl);
1296
1297  auto iter = m_decl_to_status.find(decl);
1298  lldbassert(iter != m_decl_to_status.end());
1299
1300  if (auto *tag = llvm::dyn_cast<clang::TagDecl>(&context)) {
1301    CompleteTagDecl(*tag);
1302    return;
1303  }
1304
1305  if (isFunctionDecl(context) || isBlockDecl(context)) {
1306    PdbCompilandSymId block_id = PdbSymUid(iter->second.uid).asCompilandSym();
1307    ParseBlockChildren(block_id);
1308  }
1309}
1310
1311void PdbAstBuilder::ParseDeclsForContext(clang::DeclContext &context) {
1312  // Namespaces aren't explicitly represented in the debug info, and the only
1313  // way to parse them is to parse all type info, demangling every single type
1314  // and trying to reconstruct the DeclContext hierarchy this way.  Since this
1315  // is an expensive operation, we have to special case it so that we do other
1316  // work (such as parsing the items that appear within the namespaces) at the
1317  // same time.
1318  if (context.isTranslationUnit()) {
1319    ParseAllNamespacesPlusChildrenOf(llvm::None);
1320    return;
1321  }
1322
1323  if (context.isNamespace()) {
1324    clang::NamespaceDecl &ns = *llvm::dyn_cast<clang::NamespaceDecl>(&context);
1325    std::string qname = ns.getQualifiedNameAsString();
1326    ParseAllNamespacesPlusChildrenOf(llvm::StringRef{qname});
1327    return;
1328  }
1329
1330  if (isTagDecl(context) || isFunctionDecl(context) || isBlockDecl(context)) {
1331    ParseDeclsForSimpleContext(context);
1332    return;
1333  }
1334}
1335
1336CompilerDecl PdbAstBuilder::ToCompilerDecl(clang::Decl &decl) {
1337  return {&m_clang, &decl};
1338}
1339
1340CompilerType PdbAstBuilder::ToCompilerType(clang::QualType qt) {
1341  return {&m_clang, qt.getAsOpaquePtr()};
1342}
1343
1344CompilerDeclContext
1345PdbAstBuilder::ToCompilerDeclContext(clang::DeclContext &context) {
1346  return m_clang.CreateDeclContext(&context);
1347}
1348
1349clang::Decl * PdbAstBuilder::FromCompilerDecl(CompilerDecl decl) {
1350  return static_cast<clang::Decl *>(decl.GetOpaqueDecl());
1351}
1352
1353clang::DeclContext *
1354PdbAstBuilder::FromCompilerDeclContext(CompilerDeclContext context) {
1355  return static_cast<clang::DeclContext *>(context.GetOpaqueDeclContext());
1356}
1357
1358void PdbAstBuilder::Dump(Stream &stream) { m_clang.Dump(stream); }
1359