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