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