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