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