1321369Sdim//===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===//
2303231Sdim//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6303231Sdim//
7303231Sdim//===----------------------------------------------------------------------===//
8303231Sdim//
9303231Sdim// This file contains support for writing Microsoft CodeView debug info.
10303231Sdim//
11303231Sdim//===----------------------------------------------------------------------===//
12303231Sdim
13303231Sdim#include "CodeViewDebug.h"
14327952Sdim#include "DwarfExpression.h"
15321369Sdim#include "llvm/ADT/APSInt.h"
16321369Sdim#include "llvm/ADT/ArrayRef.h"
17321369Sdim#include "llvm/ADT/DenseMap.h"
18321369Sdim#include "llvm/ADT/DenseSet.h"
19321369Sdim#include "llvm/ADT/MapVector.h"
20321369Sdim#include "llvm/ADT/None.h"
21321369Sdim#include "llvm/ADT/Optional.h"
22327952Sdim#include "llvm/ADT/STLExtras.h"
23321369Sdim#include "llvm/ADT/SmallString.h"
24321369Sdim#include "llvm/ADT/SmallVector.h"
25321369Sdim#include "llvm/ADT/StringRef.h"
26303231Sdim#include "llvm/ADT/TinyPtrVector.h"
27321369Sdim#include "llvm/ADT/Triple.h"
28321369Sdim#include "llvm/ADT/Twine.h"
29321369Sdim#include "llvm/BinaryFormat/COFF.h"
30321369Sdim#include "llvm/BinaryFormat/Dwarf.h"
31321369Sdim#include "llvm/CodeGen/AsmPrinter.h"
32321369Sdim#include "llvm/CodeGen/LexicalScopes.h"
33344779Sdim#include "llvm/CodeGen/MachineFrameInfo.h"
34321369Sdim#include "llvm/CodeGen/MachineFunction.h"
35321369Sdim#include "llvm/CodeGen/MachineInstr.h"
36321369Sdim#include "llvm/CodeGen/MachineModuleInfo.h"
37321369Sdim#include "llvm/CodeGen/MachineOperand.h"
38327952Sdim#include "llvm/CodeGen/TargetFrameLowering.h"
39327952Sdim#include "llvm/CodeGen/TargetRegisterInfo.h"
40327952Sdim#include "llvm/CodeGen/TargetSubtargetInfo.h"
41321369Sdim#include "llvm/Config/llvm-config.h"
42303231Sdim#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
43303231Sdim#include "llvm/DebugInfo/CodeView/CodeView.h"
44353358Sdim#include "llvm/DebugInfo/CodeView/CodeViewRecordIO.h"
45327952Sdim#include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h"
46321369Sdim#include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
47344779Sdim#include "llvm/DebugInfo/CodeView/EnumTables.h"
48303231Sdim#include "llvm/DebugInfo/CodeView/Line.h"
49303231Sdim#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
50314564Sdim#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
51303231Sdim#include "llvm/DebugInfo/CodeView/TypeIndex.h"
52303231Sdim#include "llvm/DebugInfo/CodeView/TypeRecord.h"
53321369Sdim#include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
54353358Sdim#include "llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h"
55303231Sdim#include "llvm/IR/Constants.h"
56321369Sdim#include "llvm/IR/DataLayout.h"
57321369Sdim#include "llvm/IR/DebugInfoMetadata.h"
58321369Sdim#include "llvm/IR/DebugLoc.h"
59321369Sdim#include "llvm/IR/Function.h"
60321369Sdim#include "llvm/IR/GlobalValue.h"
61321369Sdim#include "llvm/IR/GlobalVariable.h"
62321369Sdim#include "llvm/IR/Metadata.h"
63321369Sdim#include "llvm/IR/Module.h"
64314564Sdim#include "llvm/MC/MCAsmInfo.h"
65321369Sdim#include "llvm/MC/MCContext.h"
66303231Sdim#include "llvm/MC/MCSectionCOFF.h"
67321369Sdim#include "llvm/MC/MCStreamer.h"
68303231Sdim#include "llvm/MC/MCSymbol.h"
69321369Sdim#include "llvm/Support/BinaryByteStream.h"
70321369Sdim#include "llvm/Support/BinaryStreamReader.h"
71353358Sdim#include "llvm/Support/BinaryStreamWriter.h"
72321369Sdim#include "llvm/Support/Casting.h"
73327952Sdim#include "llvm/Support/CommandLine.h"
74321369Sdim#include "llvm/Support/Compiler.h"
75321369Sdim#include "llvm/Support/Endian.h"
76321369Sdim#include "llvm/Support/Error.h"
77321369Sdim#include "llvm/Support/ErrorHandling.h"
78327952Sdim#include "llvm/Support/FormatVariadic.h"
79344779Sdim#include "llvm/Support/Path.h"
80327952Sdim#include "llvm/Support/SMLoc.h"
81303231Sdim#include "llvm/Support/ScopedPrinter.h"
82341825Sdim#include "llvm/Target/TargetLoweringObjectFile.h"
83321369Sdim#include "llvm/Target/TargetMachine.h"
84321369Sdim#include <algorithm>
85321369Sdim#include <cassert>
86321369Sdim#include <cctype>
87321369Sdim#include <cstddef>
88321369Sdim#include <cstdint>
89321369Sdim#include <iterator>
90321369Sdim#include <limits>
91321369Sdim#include <string>
92321369Sdim#include <utility>
93321369Sdim#include <vector>
94303231Sdim
95303231Sdimusing namespace llvm;
96303231Sdimusing namespace llvm::codeview;
97303231Sdim
98353358Sdimnamespace {
99353358Sdimclass CVMCAdapter : public CodeViewRecordStreamer {
100353358Sdimpublic:
101360784Sdim  CVMCAdapter(MCStreamer &OS, TypeCollection &TypeTable)
102360784Sdim      : OS(&OS), TypeTable(TypeTable) {}
103353358Sdim
104353358Sdim  void EmitBytes(StringRef Data) { OS->EmitBytes(Data); }
105353358Sdim
106353358Sdim  void EmitIntValue(uint64_t Value, unsigned Size) {
107353358Sdim    OS->EmitIntValueInHex(Value, Size);
108353358Sdim  }
109353358Sdim
110353358Sdim  void EmitBinaryData(StringRef Data) { OS->EmitBinaryData(Data); }
111353358Sdim
112353358Sdim  void AddComment(const Twine &T) { OS->AddComment(T); }
113353358Sdim
114360784Sdim  void AddRawComment(const Twine &T) { OS->emitRawComment(T); }
115360784Sdim
116360784Sdim  bool isVerboseAsm() { return OS->isVerboseAsm(); }
117360784Sdim
118360784Sdim  std::string getTypeName(TypeIndex TI) {
119360784Sdim    std::string TypeName;
120360784Sdim    if (!TI.isNoneType()) {
121360784Sdim      if (TI.isSimple())
122360784Sdim        TypeName = TypeIndex::simpleTypeName(TI);
123360784Sdim      else
124360784Sdim        TypeName = TypeTable.getTypeName(TI);
125360784Sdim    }
126360784Sdim    return TypeName;
127360784Sdim  }
128360784Sdim
129353358Sdimprivate:
130353358Sdim  MCStreamer *OS = nullptr;
131360784Sdim  TypeCollection &TypeTable;
132353358Sdim};
133353358Sdim} // namespace
134353358Sdim
135344779Sdimstatic CPUType mapArchToCVCPUType(Triple::ArchType Type) {
136344779Sdim  switch (Type) {
137344779Sdim  case Triple::ArchType::x86:
138344779Sdim    return CPUType::Pentium3;
139344779Sdim  case Triple::ArchType::x86_64:
140344779Sdim    return CPUType::X64;
141344779Sdim  case Triple::ArchType::thumb:
142344779Sdim    return CPUType::Thumb;
143344779Sdim  case Triple::ArchType::aarch64:
144344779Sdim    return CPUType::ARM64;
145344779Sdim  default:
146344779Sdim    report_fatal_error("target architecture doesn't map to a CodeView CPUType");
147344779Sdim  }
148344779Sdim}
149327952Sdim
150303231SdimCodeViewDebug::CodeViewDebug(AsmPrinter *AP)
151321369Sdim    : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {
152303231Sdim  // If module doesn't have named metadata anchors or COFF debug section
153303231Sdim  // is not available, skip any debug info related stuff.
154303231Sdim  if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
155303231Sdim      !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
156303231Sdim    Asm = nullptr;
157344779Sdim    MMI->setDebugInfoAvailability(false);
158303231Sdim    return;
159303231Sdim  }
160303231Sdim  // Tell MMI that we have debug info.
161303231Sdim  MMI->setDebugInfoAvailability(true);
162344779Sdim
163344779Sdim  TheCPU =
164344779Sdim      mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
165344779Sdim
166344779Sdim  collectGlobalVariableInfo();
167344779Sdim
168344779Sdim  // Check if we should emit type record hashes.
169344779Sdim  ConstantInt *GH = mdconst::extract_or_null<ConstantInt>(
170344779Sdim      MMI->getModule()->getModuleFlag("CodeViewGHash"));
171344779Sdim  EmitDebugGlobalHashes = GH && !GH->isZero();
172303231Sdim}
173303231Sdim
174303231SdimStringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
175303231Sdim  std::string &Filepath = FileToFilepathMap[File];
176303231Sdim  if (!Filepath.empty())
177303231Sdim    return Filepath;
178303231Sdim
179303231Sdim  StringRef Dir = File->getDirectory(), Filename = File->getFilename();
180303231Sdim
181341825Sdim  // If this is a Unix-style path, just use it as is. Don't try to canonicalize
182341825Sdim  // it textually because one of the path components could be a symlink.
183344779Sdim  if (Dir.startswith("/") || Filename.startswith("/")) {
184344779Sdim    if (llvm::sys::path::is_absolute(Filename, llvm::sys::path::Style::posix))
185344779Sdim      return Filename;
186341825Sdim    Filepath = Dir;
187341825Sdim    if (Dir.back() != '/')
188341825Sdim      Filepath += '/';
189341825Sdim    Filepath += Filename;
190341825Sdim    return Filepath;
191341825Sdim  }
192341825Sdim
193303231Sdim  // Clang emits directory and relative filename info into the IR, but CodeView
194303231Sdim  // operates on full paths.  We could change Clang to emit full paths too, but
195303231Sdim  // that would increase the IR size and probably not needed for other users.
196303231Sdim  // For now, just concatenate and canonicalize the path here.
197303231Sdim  if (Filename.find(':') == 1)
198303231Sdim    Filepath = Filename;
199303231Sdim  else
200303231Sdim    Filepath = (Dir + "\\" + Filename).str();
201303231Sdim
202303231Sdim  // Canonicalize the path.  We have to do it textually because we may no longer
203303231Sdim  // have access the file in the filesystem.
204303231Sdim  // First, replace all slashes with backslashes.
205303231Sdim  std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
206303231Sdim
207303231Sdim  // Remove all "\.\" with "\".
208303231Sdim  size_t Cursor = 0;
209303231Sdim  while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
210303231Sdim    Filepath.erase(Cursor, 2);
211303231Sdim
212303231Sdim  // Replace all "\XXX\..\" with "\".  Don't try too hard though as the original
213303231Sdim  // path should be well-formatted, e.g. start with a drive letter, etc.
214303231Sdim  Cursor = 0;
215303231Sdim  while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
216303231Sdim    // Something's wrong if the path starts with "\..\", abort.
217303231Sdim    if (Cursor == 0)
218303231Sdim      break;
219303231Sdim
220303231Sdim    size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
221303231Sdim    if (PrevSlash == std::string::npos)
222303231Sdim      // Something's wrong, abort.
223303231Sdim      break;
224303231Sdim
225303231Sdim    Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
226303231Sdim    // The next ".." might be following the one we've just erased.
227303231Sdim    Cursor = PrevSlash;
228303231Sdim  }
229303231Sdim
230303231Sdim  // Remove all duplicate backslashes.
231303231Sdim  Cursor = 0;
232303231Sdim  while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
233303231Sdim    Filepath.erase(Cursor, 1);
234303231Sdim
235303231Sdim  return Filepath;
236303231Sdim}
237303231Sdim
238303231Sdimunsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
239327952Sdim  StringRef FullPath = getFullFilepath(F);
240303231Sdim  unsigned NextId = FileIdMap.size() + 1;
241327952Sdim  auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
242303231Sdim  if (Insertion.second) {
243303231Sdim    // We have to compute the full filepath and emit a .cv_file directive.
244341825Sdim    ArrayRef<uint8_t> ChecksumAsBytes;
245341825Sdim    FileChecksumKind CSKind = FileChecksumKind::None;
246341825Sdim    if (F->getChecksum()) {
247341825Sdim      std::string Checksum = fromHex(F->getChecksum()->Value);
248341825Sdim      void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
249341825Sdim      memcpy(CKMem, Checksum.data(), Checksum.size());
250341825Sdim      ChecksumAsBytes = ArrayRef<uint8_t>(
251341825Sdim          reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
252341825Sdim      switch (F->getChecksum()->Kind) {
253341825Sdim      case DIFile::CSK_MD5:  CSKind = FileChecksumKind::MD5; break;
254341825Sdim      case DIFile::CSK_SHA1: CSKind = FileChecksumKind::SHA1; break;
255341825Sdim      }
256341825Sdim    }
257327952Sdim    bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
258341825Sdim                                          static_cast<unsigned>(CSKind));
259314564Sdim    (void)Success;
260314564Sdim    assert(Success && ".cv_file directive failed");
261303231Sdim  }
262303231Sdim  return Insertion.first->second;
263303231Sdim}
264303231Sdim
265303231SdimCodeViewDebug::InlineSite &
266303231SdimCodeViewDebug::getInlineSite(const DILocation *InlinedAt,
267303231Sdim                             const DISubprogram *Inlinee) {
268303231Sdim  auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
269303231Sdim  InlineSite *Site = &SiteInsertion.first->second;
270303231Sdim  if (SiteInsertion.second) {
271314564Sdim    unsigned ParentFuncId = CurFn->FuncId;
272314564Sdim    if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
273314564Sdim      ParentFuncId =
274314564Sdim          getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
275314564Sdim              .SiteFuncId;
276314564Sdim
277303231Sdim    Site->SiteFuncId = NextFuncId++;
278314564Sdim    OS.EmitCVInlineSiteIdDirective(
279314564Sdim        Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
280314564Sdim        InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
281303231Sdim    Site->Inlinee = Inlinee;
282303231Sdim    InlinedSubprograms.insert(Inlinee);
283303231Sdim    getFuncIdForSubprogram(Inlinee);
284303231Sdim  }
285303231Sdim  return *Site;
286303231Sdim}
287303231Sdim
288303231Sdimstatic StringRef getPrettyScopeName(const DIScope *Scope) {
289303231Sdim  StringRef ScopeName = Scope->getName();
290303231Sdim  if (!ScopeName.empty())
291303231Sdim    return ScopeName;
292303231Sdim
293303231Sdim  switch (Scope->getTag()) {
294303231Sdim  case dwarf::DW_TAG_enumeration_type:
295303231Sdim  case dwarf::DW_TAG_class_type:
296303231Sdim  case dwarf::DW_TAG_structure_type:
297303231Sdim  case dwarf::DW_TAG_union_type:
298303231Sdim    return "<unnamed-tag>";
299303231Sdim  case dwarf::DW_TAG_namespace:
300303231Sdim    return "`anonymous namespace'";
301303231Sdim  }
302303231Sdim
303303231Sdim  return StringRef();
304303231Sdim}
305303231Sdim
306303231Sdimstatic const DISubprogram *getQualifiedNameComponents(
307303231Sdim    const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
308303231Sdim  const DISubprogram *ClosestSubprogram = nullptr;
309303231Sdim  while (Scope != nullptr) {
310303231Sdim    if (ClosestSubprogram == nullptr)
311303231Sdim      ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
312303231Sdim    StringRef ScopeName = getPrettyScopeName(Scope);
313303231Sdim    if (!ScopeName.empty())
314303231Sdim      QualifiedNameComponents.push_back(ScopeName);
315353358Sdim    Scope = Scope->getScope();
316303231Sdim  }
317303231Sdim  return ClosestSubprogram;
318303231Sdim}
319303231Sdim
320303231Sdimstatic std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
321303231Sdim                                    StringRef TypeName) {
322303231Sdim  std::string FullyQualifiedName;
323321369Sdim  for (StringRef QualifiedNameComponent :
324321369Sdim       llvm::reverse(QualifiedNameComponents)) {
325303231Sdim    FullyQualifiedName.append(QualifiedNameComponent);
326303231Sdim    FullyQualifiedName.append("::");
327303231Sdim  }
328303231Sdim  FullyQualifiedName.append(TypeName);
329303231Sdim  return FullyQualifiedName;
330303231Sdim}
331303231Sdim
332303231Sdimstatic std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
333303231Sdim  SmallVector<StringRef, 5> QualifiedNameComponents;
334303231Sdim  getQualifiedNameComponents(Scope, QualifiedNameComponents);
335303231Sdim  return getQualifiedName(QualifiedNameComponents, Name);
336303231Sdim}
337303231Sdim
338303231Sdimstruct CodeViewDebug::TypeLoweringScope {
339303231Sdim  TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
340303231Sdim  ~TypeLoweringScope() {
341303231Sdim    // Don't decrement TypeEmissionLevel until after emitting deferred types, so
342303231Sdim    // inner TypeLoweringScopes don't attempt to emit deferred types.
343303231Sdim    if (CVD.TypeEmissionLevel == 1)
344303231Sdim      CVD.emitDeferredCompleteTypes();
345303231Sdim    --CVD.TypeEmissionLevel;
346303231Sdim  }
347303231Sdim  CodeViewDebug &CVD;
348303231Sdim};
349303231Sdim
350303231Sdimstatic std::string getFullyQualifiedName(const DIScope *Ty) {
351353358Sdim  const DIScope *Scope = Ty->getScope();
352303231Sdim  return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
353303231Sdim}
354303231Sdim
355303231SdimTypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
356303231Sdim  // No scope means global scope and that uses the zero index.
357303231Sdim  if (!Scope || isa<DIFile>(Scope))
358303231Sdim    return TypeIndex();
359303231Sdim
360303231Sdim  assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
361303231Sdim
362303231Sdim  // Check if we've already translated this scope.
363303231Sdim  auto I = TypeIndices.find({Scope, nullptr});
364303231Sdim  if (I != TypeIndices.end())
365303231Sdim    return I->second;
366303231Sdim
367303231Sdim  // Build the fully qualified name of the scope.
368303231Sdim  std::string ScopeName = getFullyQualifiedName(Scope);
369314564Sdim  StringIdRecord SID(TypeIndex(), ScopeName);
370327952Sdim  auto TI = TypeTable.writeLeafType(SID);
371303231Sdim  return recordTypeIndexForDINode(Scope, TI);
372303231Sdim}
373303231Sdim
374303231SdimTypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
375304310Sdim  assert(SP);
376303231Sdim
377303231Sdim  // Check if we've already translated this subprogram.
378303231Sdim  auto I = TypeIndices.find({SP, nullptr});
379303231Sdim  if (I != TypeIndices.end())
380303231Sdim    return I->second;
381303231Sdim
382303231Sdim  // The display name includes function template arguments. Drop them to match
383303231Sdim  // MSVC.
384321369Sdim  StringRef DisplayName = SP->getName().split('<').first;
385303231Sdim
386353358Sdim  const DIScope *Scope = SP->getScope();
387303231Sdim  TypeIndex TI;
388303231Sdim  if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
389303231Sdim    // If the scope is a DICompositeType, then this must be a method. Member
390303231Sdim    // function types take some special handling, and require access to the
391303231Sdim    // subprogram.
392303231Sdim    TypeIndex ClassType = getTypeIndex(Class);
393303231Sdim    MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
394303231Sdim                               DisplayName);
395327952Sdim    TI = TypeTable.writeLeafType(MFuncId);
396303231Sdim  } else {
397303231Sdim    // Otherwise, this must be a free function.
398303231Sdim    TypeIndex ParentScope = getScopeIndex(Scope);
399303231Sdim    FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
400327952Sdim    TI = TypeTable.writeLeafType(FuncId);
401303231Sdim  }
402303231Sdim
403303231Sdim  return recordTypeIndexForDINode(SP, TI);
404303231Sdim}
405303231Sdim
406353358Sdimstatic bool isNonTrivial(const DICompositeType *DCTy) {
407353358Sdim  return ((DCTy->getFlags() & DINode::FlagNonTrivial) == DINode::FlagNonTrivial);
408344779Sdim}
409344779Sdim
410344779Sdimstatic FunctionOptions
411344779SdimgetFunctionOptions(const DISubroutineType *Ty,
412344779Sdim                   const DICompositeType *ClassTy = nullptr,
413344779Sdim                   StringRef SPName = StringRef("")) {
414344779Sdim  FunctionOptions FO = FunctionOptions::None;
415344779Sdim  const DIType *ReturnTy = nullptr;
416344779Sdim  if (auto TypeArray = Ty->getTypeArray()) {
417344779Sdim    if (TypeArray.size())
418353358Sdim      ReturnTy = TypeArray[0];
419344779Sdim  }
420344779Sdim
421344779Sdim  if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy)) {
422353358Sdim    if (isNonTrivial(ReturnDCTy))
423344779Sdim      FO |= FunctionOptions::CxxReturnUdt;
424344779Sdim  }
425344779Sdim
426344779Sdim  // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison.
427353358Sdim  if (ClassTy && isNonTrivial(ClassTy) && SPName == ClassTy->getName()) {
428344779Sdim    FO |= FunctionOptions::Constructor;
429344779Sdim
430344779Sdim  // TODO: put the FunctionOptions::ConstructorWithVirtualBases flag.
431344779Sdim
432344779Sdim  }
433344779Sdim  return FO;
434344779Sdim}
435344779Sdim
436303231SdimTypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
437303231Sdim                                               const DICompositeType *Class) {
438303231Sdim  // Always use the method declaration as the key for the function type. The
439303231Sdim  // method declaration contains the this adjustment.
440303231Sdim  if (SP->getDeclaration())
441303231Sdim    SP = SP->getDeclaration();
442303231Sdim  assert(!SP->getDeclaration() && "should use declaration as key");
443303231Sdim
444303231Sdim  // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
445303231Sdim  // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
446303231Sdim  auto I = TypeIndices.find({SP, Class});
447303231Sdim  if (I != TypeIndices.end())
448303231Sdim    return I->second;
449303231Sdim
450303231Sdim  // Make sure complete type info for the class is emitted *after* the member
451303231Sdim  // function type, as the complete class type is likely to reference this
452303231Sdim  // member function type.
453303231Sdim  TypeLoweringScope S(*this);
454327952Sdim  const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
455344779Sdim
456344779Sdim  FunctionOptions FO = getFunctionOptions(SP->getType(), Class, SP->getName());
457327952Sdim  TypeIndex TI = lowerTypeMemberFunction(
458344779Sdim      SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO);
459303231Sdim  return recordTypeIndexForDINode(SP, TI, Class);
460303231Sdim}
461303231Sdim
462303231SdimTypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
463303231Sdim                                                  TypeIndex TI,
464303231Sdim                                                  const DIType *ClassTy) {
465303231Sdim  auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
466303231Sdim  (void)InsertResult;
467303231Sdim  assert(InsertResult.second && "DINode was already assigned a type index");
468303231Sdim  return TI;
469303231Sdim}
470303231Sdim
471303231Sdimunsigned CodeViewDebug::getPointerSizeInBytes() {
472303231Sdim  return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
473303231Sdim}
474303231Sdim
475303231Sdimvoid CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
476341825Sdim                                        const LexicalScope *LS) {
477341825Sdim  if (const DILocation *InlinedAt = LS->getInlinedAt()) {
478303231Sdim    // This variable was inlined. Associate it with the InlineSite.
479303231Sdim    const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
480303231Sdim    InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
481303231Sdim    Site.InlinedLocals.emplace_back(Var);
482303231Sdim  } else {
483341825Sdim    // This variable goes into the corresponding lexical scope.
484341825Sdim    ScopeVariables[LS].emplace_back(Var);
485303231Sdim  }
486303231Sdim}
487303231Sdim
488303231Sdimstatic void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
489303231Sdim                               const DILocation *Loc) {
490303231Sdim  auto B = Locs.begin(), E = Locs.end();
491303231Sdim  if (std::find(B, E, Loc) == E)
492303231Sdim    Locs.push_back(Loc);
493303231Sdim}
494303231Sdim
495303231Sdimvoid CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
496303231Sdim                                        const MachineFunction *MF) {
497303231Sdim  // Skip this instruction if it has the same location as the previous one.
498321369Sdim  if (!DL || DL == PrevInstLoc)
499303231Sdim    return;
500303231Sdim
501303231Sdim  const DIScope *Scope = DL.get()->getScope();
502303231Sdim  if (!Scope)
503303231Sdim    return;
504303231Sdim
505303231Sdim  // Skip this line if it is longer than the maximum we can record.
506303231Sdim  LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
507303231Sdim  if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
508303231Sdim      LI.isNeverStepInto())
509303231Sdim    return;
510303231Sdim
511303231Sdim  ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
512303231Sdim  if (CI.getStartColumn() != DL.getCol())
513303231Sdim    return;
514303231Sdim
515303231Sdim  if (!CurFn->HaveLineInfo)
516303231Sdim    CurFn->HaveLineInfo = true;
517303231Sdim  unsigned FileId = 0;
518321369Sdim  if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
519303231Sdim    FileId = CurFn->LastFileId;
520303231Sdim  else
521303231Sdim    FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
522321369Sdim  PrevInstLoc = DL;
523303231Sdim
524303231Sdim  unsigned FuncId = CurFn->FuncId;
525303231Sdim  if (const DILocation *SiteLoc = DL->getInlinedAt()) {
526303231Sdim    const DILocation *Loc = DL.get();
527303231Sdim
528303231Sdim    // If this location was actually inlined from somewhere else, give it the ID
529303231Sdim    // of the inline call site.
530303231Sdim    FuncId =
531303231Sdim        getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
532303231Sdim
533303231Sdim    // Ensure we have links in the tree of inline call sites.
534303231Sdim    bool FirstLoc = true;
535303231Sdim    while ((SiteLoc = Loc->getInlinedAt())) {
536303231Sdim      InlineSite &Site =
537303231Sdim          getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
538303231Sdim      if (!FirstLoc)
539303231Sdim        addLocIfNotPresent(Site.ChildSites, Loc);
540303231Sdim      FirstLoc = false;
541303231Sdim      Loc = SiteLoc;
542303231Sdim    }
543303231Sdim    addLocIfNotPresent(CurFn->ChildSites, Loc);
544303231Sdim  }
545303231Sdim
546303231Sdim  OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
547314564Sdim                        /*PrologueEnd=*/false, /*IsStmt=*/false,
548314564Sdim                        DL->getFilename(), SMLoc());
549303231Sdim}
550303231Sdim
551303231Sdimvoid CodeViewDebug::emitCodeViewMagicVersion() {
552303231Sdim  OS.EmitValueToAlignment(4);
553303231Sdim  OS.AddComment("Debug section magic");
554303231Sdim  OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
555303231Sdim}
556303231Sdim
557303231Sdimvoid CodeViewDebug::endModule() {
558303231Sdim  if (!Asm || !MMI->hasDebugInfo())
559303231Sdim    return;
560303231Sdim
561303231Sdim  assert(Asm != nullptr);
562303231Sdim
563303231Sdim  // The COFF .debug$S section consists of several subsections, each starting
564303231Sdim  // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
565303231Sdim  // of the payload followed by the payload itself.  The subsections are 4-byte
566303231Sdim  // aligned.
567303231Sdim
568303231Sdim  // Use the generic .debug$S section, and make a subsection for all the inlined
569303231Sdim  // subprograms.
570303231Sdim  switchToDebugSectionForSymbol(nullptr);
571314564Sdim
572321369Sdim  MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
573314564Sdim  emitCompilerInformation();
574314564Sdim  endCVSubsection(CompilerInfo);
575314564Sdim
576303231Sdim  emitInlineeLinesSubsection();
577303231Sdim
578303231Sdim  // Emit per-function debug information.
579303231Sdim  for (auto &P : FnDebugInfo)
580303231Sdim    if (!P.first->isDeclarationForLinker())
581341825Sdim      emitDebugInfoForFunction(P.first, *P.second);
582303231Sdim
583303231Sdim  // Emit global variable debug information.
584303231Sdim  setCurrentSubprogram(nullptr);
585303231Sdim  emitDebugInfoForGlobals();
586303231Sdim
587303231Sdim  // Emit retained types.
588303231Sdim  emitDebugInfoForRetainedTypes();
589303231Sdim
590303231Sdim  // Switch back to the generic .debug$S section after potentially processing
591303231Sdim  // comdat symbol sections.
592303231Sdim  switchToDebugSectionForSymbol(nullptr);
593303231Sdim
594303231Sdim  // Emit UDT records for any types used by global variables.
595303231Sdim  if (!GlobalUDTs.empty()) {
596321369Sdim    MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
597303231Sdim    emitDebugInfoForUDTs(GlobalUDTs);
598303231Sdim    endCVSubsection(SymbolsEnd);
599303231Sdim  }
600303231Sdim
601303231Sdim  // This subsection holds a file index to offset in string table table.
602303231Sdim  OS.AddComment("File index to string table offset subsection");
603303231Sdim  OS.EmitCVFileChecksumsDirective();
604303231Sdim
605303231Sdim  // This subsection holds the string table.
606303231Sdim  OS.AddComment("String table");
607303231Sdim  OS.EmitCVStringTableDirective();
608303231Sdim
609344779Sdim  // Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol
610344779Sdim  // subsection in the generic .debug$S section at the end. There is no
611344779Sdim  // particular reason for this ordering other than to match MSVC.
612344779Sdim  emitBuildInfo();
613344779Sdim
614327952Sdim  // Emit type information and hashes last, so that any types we translate while
615327952Sdim  // emitting function info are included.
616303231Sdim  emitTypeInformation();
617303231Sdim
618327952Sdim  if (EmitDebugGlobalHashes)
619327952Sdim    emitTypeGlobalHashes();
620327952Sdim
621303231Sdim  clear();
622303231Sdim}
623303231Sdim
624353358Sdimstatic void
625353358SdimemitNullTerminatedSymbolName(MCStreamer &OS, StringRef S,
626353358Sdim                             unsigned MaxFixedRecordLength = 0xF00) {
627314564Sdim  // The maximum CV record length is 0xFF00. Most of the strings we emit appear
628314564Sdim  // after a fixed length portion of the record. The fixed length portion should
629314564Sdim  // always be less than 0xF00 (3840) bytes, so truncate the string so that the
630314564Sdim  // overall record size is less than the maximum allowed.
631314564Sdim  SmallString<32> NullTerminatedString(
632314564Sdim      S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
633303231Sdim  NullTerminatedString.push_back('\0');
634303231Sdim  OS.EmitBytes(NullTerminatedString);
635303231Sdim}
636303231Sdim
637303231Sdimvoid CodeViewDebug::emitTypeInformation() {
638303231Sdim  if (TypeTable.empty())
639303231Sdim    return;
640303231Sdim
641341825Sdim  // Start the .debug$T or .debug$P section with 0x4.
642303231Sdim  OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
643303231Sdim  emitCodeViewMagicVersion();
644303231Sdim
645321369Sdim  TypeTableCollection Table(TypeTable.records());
646353358Sdim  TypeVisitorCallbackPipeline Pipeline;
647353358Sdim
648353358Sdim  // To emit type record using Codeview MCStreamer adapter
649360784Sdim  CVMCAdapter CVMCOS(OS, Table);
650353358Sdim  TypeRecordMapping typeMapping(CVMCOS);
651353358Sdim  Pipeline.addCallbackToPipeline(typeMapping);
652353358Sdim
653321369Sdim  Optional<TypeIndex> B = Table.getFirst();
654321369Sdim  while (B) {
655321369Sdim    // This will fail if the record data is invalid.
656321369Sdim    CVType Record = Table.getType(*B);
657321369Sdim
658353358Sdim    Error E = codeview::visitTypeRecord(Record, *B, Pipeline);
659353358Sdim
660353358Sdim    if (E) {
661353358Sdim      logAllUnhandledErrors(std::move(E), errs(), "error: ");
662353358Sdim      llvm_unreachable("produced malformed type record");
663353358Sdim    }
664353358Sdim
665321369Sdim    B = Table.getNext(*B);
666321369Sdim  }
667303231Sdim}
668303231Sdim
669327952Sdimvoid CodeViewDebug::emitTypeGlobalHashes() {
670327952Sdim  if (TypeTable.empty())
671327952Sdim    return;
672314564Sdim
673327952Sdim  // Start the .debug$H section with the version and hash algorithm, currently
674327952Sdim  // hardcoded to version 0, SHA1.
675327952Sdim  OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
676327952Sdim
677327952Sdim  OS.EmitValueToAlignment(4);
678327952Sdim  OS.AddComment("Magic");
679327952Sdim  OS.EmitIntValue(COFF::DEBUG_HASHES_SECTION_MAGIC, 4);
680327952Sdim  OS.AddComment("Section Version");
681327952Sdim  OS.EmitIntValue(0, 2);
682327952Sdim  OS.AddComment("Hash Algorithm");
683341825Sdim  OS.EmitIntValue(uint16_t(GlobalTypeHashAlg::SHA1_8), 2);
684327952Sdim
685327952Sdim  TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
686327952Sdim  for (const auto &GHR : TypeTable.hashes()) {
687327952Sdim    if (OS.isVerboseAsm()) {
688327952Sdim      // Emit an EOL-comment describing which TypeIndex this hash corresponds
689327952Sdim      // to, as well as the stringified SHA1 hash.
690327952Sdim      SmallString<32> Comment;
691327952Sdim      raw_svector_ostream CommentOS(Comment);
692327952Sdim      CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
693327952Sdim      OS.AddComment(Comment);
694327952Sdim      ++TI;
695327952Sdim    }
696341825Sdim    assert(GHR.Hash.size() == 8);
697327952Sdim    StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
698327952Sdim                GHR.Hash.size());
699327952Sdim    OS.EmitBinaryData(S);
700327952Sdim  }
701327952Sdim}
702327952Sdim
703314564Sdimstatic SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
704314564Sdim  switch (DWLang) {
705314564Sdim  case dwarf::DW_LANG_C:
706314564Sdim  case dwarf::DW_LANG_C89:
707314564Sdim  case dwarf::DW_LANG_C99:
708314564Sdim  case dwarf::DW_LANG_C11:
709314564Sdim  case dwarf::DW_LANG_ObjC:
710314564Sdim    return SourceLanguage::C;
711314564Sdim  case dwarf::DW_LANG_C_plus_plus:
712314564Sdim  case dwarf::DW_LANG_C_plus_plus_03:
713314564Sdim  case dwarf::DW_LANG_C_plus_plus_11:
714314564Sdim  case dwarf::DW_LANG_C_plus_plus_14:
715314564Sdim    return SourceLanguage::Cpp;
716314564Sdim  case dwarf::DW_LANG_Fortran77:
717314564Sdim  case dwarf::DW_LANG_Fortran90:
718314564Sdim  case dwarf::DW_LANG_Fortran03:
719314564Sdim  case dwarf::DW_LANG_Fortran08:
720314564Sdim    return SourceLanguage::Fortran;
721314564Sdim  case dwarf::DW_LANG_Pascal83:
722314564Sdim    return SourceLanguage::Pascal;
723314564Sdim  case dwarf::DW_LANG_Cobol74:
724314564Sdim  case dwarf::DW_LANG_Cobol85:
725314564Sdim    return SourceLanguage::Cobol;
726314564Sdim  case dwarf::DW_LANG_Java:
727314564Sdim    return SourceLanguage::Java;
728327952Sdim  case dwarf::DW_LANG_D:
729327952Sdim    return SourceLanguage::D;
730353358Sdim  case dwarf::DW_LANG_Swift:
731353358Sdim    return SourceLanguage::Swift;
732314564Sdim  default:
733314564Sdim    // There's no CodeView representation for this language, and CV doesn't
734314564Sdim    // have an "unknown" option for the language field, so we'll use MASM,
735314564Sdim    // as it's very low level.
736314564Sdim    return SourceLanguage::Masm;
737314564Sdim  }
738314564Sdim}
739314564Sdim
740327952Sdimnamespace {
741314564Sdimstruct Version {
742314564Sdim  int Part[4];
743314564Sdim};
744327952Sdim} // end anonymous namespace
745314564Sdim
746314564Sdim// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
747314564Sdim// the version number.
748314564Sdimstatic Version parseVersion(StringRef Name) {
749314564Sdim  Version V = {{0}};
750314564Sdim  int N = 0;
751314564Sdim  for (const char C : Name) {
752314564Sdim    if (isdigit(C)) {
753314564Sdim      V.Part[N] *= 10;
754314564Sdim      V.Part[N] += C - '0';
755314564Sdim    } else if (C == '.') {
756314564Sdim      ++N;
757314564Sdim      if (N >= 4)
758314564Sdim        return V;
759314564Sdim    } else if (N > 0)
760314564Sdim      return V;
761314564Sdim  }
762314564Sdim  return V;
763314564Sdim}
764314564Sdim
765314564Sdimvoid CodeViewDebug::emitCompilerInformation() {
766344779Sdim  MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_COMPILE3);
767314564Sdim  uint32_t Flags = 0;
768314564Sdim
769314564Sdim  NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
770314564Sdim  const MDNode *Node = *CUs->operands().begin();
771314564Sdim  const auto *CU = cast<DICompileUnit>(Node);
772314564Sdim
773314564Sdim  // The low byte of the flags indicates the source language.
774314564Sdim  Flags = MapDWLangToCVLang(CU->getSourceLanguage());
775314564Sdim  // TODO:  Figure out which other flags need to be set.
776314564Sdim
777314564Sdim  OS.AddComment("Flags and language");
778314564Sdim  OS.EmitIntValue(Flags, 4);
779314564Sdim
780314564Sdim  OS.AddComment("CPUType");
781344779Sdim  OS.EmitIntValue(static_cast<uint64_t>(TheCPU), 2);
782314564Sdim
783314564Sdim  StringRef CompilerVersion = CU->getProducer();
784314564Sdim  Version FrontVer = parseVersion(CompilerVersion);
785314564Sdim  OS.AddComment("Frontend version");
786314564Sdim  for (int N = 0; N < 4; ++N)
787314564Sdim    OS.EmitIntValue(FrontVer.Part[N], 2);
788314564Sdim
789314564Sdim  // Some Microsoft tools, like Binscope, expect a backend version number of at
790314564Sdim  // least 8.something, so we'll coerce the LLVM version into a form that
791314564Sdim  // guarantees it'll be big enough without really lying about the version.
792314564Sdim  int Major = 1000 * LLVM_VERSION_MAJOR +
793314564Sdim              10 * LLVM_VERSION_MINOR +
794314564Sdim              LLVM_VERSION_PATCH;
795314564Sdim  // Clamp it for builds that use unusually large version numbers.
796314564Sdim  Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
797314564Sdim  Version BackVer = {{ Major, 0, 0, 0 }};
798314564Sdim  OS.AddComment("Backend version");
799314564Sdim  for (int N = 0; N < 4; ++N)
800314564Sdim    OS.EmitIntValue(BackVer.Part[N], 2);
801314564Sdim
802314564Sdim  OS.AddComment("Null-terminated compiler version string");
803314564Sdim  emitNullTerminatedSymbolName(OS, CompilerVersion);
804314564Sdim
805344779Sdim  endSymbolRecord(CompilerEnd);
806314564Sdim}
807314564Sdim
808344779Sdimstatic TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable,
809344779Sdim                                    StringRef S) {
810344779Sdim  StringIdRecord SIR(TypeIndex(0x0), S);
811344779Sdim  return TypeTable.writeLeafType(SIR);
812344779Sdim}
813344779Sdim
814344779Sdimvoid CodeViewDebug::emitBuildInfo() {
815344779Sdim  // First, make LF_BUILDINFO. It's a sequence of strings with various bits of
816344779Sdim  // build info. The known prefix is:
817344779Sdim  // - Absolute path of current directory
818344779Sdim  // - Compiler path
819344779Sdim  // - Main source file path, relative to CWD or absolute
820344779Sdim  // - Type server PDB file
821344779Sdim  // - Canonical compiler command line
822344779Sdim  // If frontend and backend compilation are separated (think llc or LTO), it's
823344779Sdim  // not clear if the compiler path should refer to the executable for the
824344779Sdim  // frontend or the backend. Leave it blank for now.
825344779Sdim  TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {};
826344779Sdim  NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
827344779Sdim  const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs.
828344779Sdim  const auto *CU = cast<DICompileUnit>(Node);
829344779Sdim  const DIFile *MainSourceFile = CU->getFile();
830344779Sdim  BuildInfoArgs[BuildInfoRecord::CurrentDirectory] =
831344779Sdim      getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory());
832344779Sdim  BuildInfoArgs[BuildInfoRecord::SourceFile] =
833344779Sdim      getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename());
834344779Sdim  // FIXME: Path to compiler and command line. PDB is intentionally blank unless
835344779Sdim  // we implement /Zi type servers.
836344779Sdim  BuildInfoRecord BIR(BuildInfoArgs);
837344779Sdim  TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR);
838344779Sdim
839344779Sdim  // Make a new .debug$S subsection for the S_BUILDINFO record, which points
840344779Sdim  // from the module symbols into the type stream.
841344779Sdim  MCSymbol *BISubsecEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
842344779Sdim  MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO);
843344779Sdim  OS.AddComment("LF_BUILDINFO index");
844344779Sdim  OS.EmitIntValue(BuildInfoIndex.getIndex(), 4);
845344779Sdim  endSymbolRecord(BIEnd);
846344779Sdim  endCVSubsection(BISubsecEnd);
847344779Sdim}
848344779Sdim
849303231Sdimvoid CodeViewDebug::emitInlineeLinesSubsection() {
850303231Sdim  if (InlinedSubprograms.empty())
851303231Sdim    return;
852303231Sdim
853303231Sdim  OS.AddComment("Inlinee lines subsection");
854321369Sdim  MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
855303231Sdim
856327952Sdim  // We emit the checksum info for files.  This is used by debuggers to
857327952Sdim  // determine if a pdb matches the source before loading it.  Visual Studio,
858327952Sdim  // for instance, will display a warning that the breakpoints are not valid if
859327952Sdim  // the pdb does not match the source.
860303231Sdim  OS.AddComment("Inlinee lines signature");
861303231Sdim  OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
862303231Sdim
863303231Sdim  for (const DISubprogram *SP : InlinedSubprograms) {
864303231Sdim    assert(TypeIndices.count({SP, nullptr}));
865303231Sdim    TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
866303231Sdim
867303231Sdim    OS.AddBlankLine();
868303231Sdim    unsigned FileId = maybeRecordFile(SP->getFile());
869321369Sdim    OS.AddComment("Inlined function " + SP->getName() + " starts at " +
870303231Sdim                  SP->getFilename() + Twine(':') + Twine(SP->getLine()));
871303231Sdim    OS.AddBlankLine();
872303231Sdim    OS.AddComment("Type index of inlined function");
873303231Sdim    OS.EmitIntValue(InlineeIdx.getIndex(), 4);
874303231Sdim    OS.AddComment("Offset into filechecksum table");
875327952Sdim    OS.EmitCVFileChecksumOffsetDirective(FileId);
876303231Sdim    OS.AddComment("Starting line number");
877303231Sdim    OS.EmitIntValue(SP->getLine(), 4);
878303231Sdim  }
879303231Sdim
880303231Sdim  endCVSubsection(InlineEnd);
881303231Sdim}
882303231Sdim
883303231Sdimvoid CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
884303231Sdim                                        const DILocation *InlinedAt,
885303231Sdim                                        const InlineSite &Site) {
886303231Sdim  assert(TypeIndices.count({Site.Inlinee, nullptr}));
887303231Sdim  TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
888303231Sdim
889303231Sdim  // SymbolRecord
890344779Sdim  MCSymbol *InlineEnd = beginSymbolRecord(SymbolKind::S_INLINESITE);
891303231Sdim
892303231Sdim  OS.AddComment("PtrParent");
893303231Sdim  OS.EmitIntValue(0, 4);
894303231Sdim  OS.AddComment("PtrEnd");
895303231Sdim  OS.EmitIntValue(0, 4);
896303231Sdim  OS.AddComment("Inlinee type index");
897303231Sdim  OS.EmitIntValue(InlineeIdx.getIndex(), 4);
898303231Sdim
899303231Sdim  unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
900303231Sdim  unsigned StartLineNum = Site.Inlinee->getLine();
901303231Sdim
902303231Sdim  OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
903314564Sdim                                    FI.Begin, FI.End);
904303231Sdim
905344779Sdim  endSymbolRecord(InlineEnd);
906303231Sdim
907344779Sdim  emitLocalVariableList(FI, Site.InlinedLocals);
908303231Sdim
909303231Sdim  // Recurse on child inlined call sites before closing the scope.
910303231Sdim  for (const DILocation *ChildSite : Site.ChildSites) {
911303231Sdim    auto I = FI.InlineSites.find(ChildSite);
912303231Sdim    assert(I != FI.InlineSites.end() &&
913303231Sdim           "child site not in function inline site map");
914303231Sdim    emitInlinedCallSite(FI, ChildSite, I->second);
915303231Sdim  }
916303231Sdim
917303231Sdim  // Close the scope.
918344779Sdim  emitEndSymbolRecord(SymbolKind::S_INLINESITE_END);
919303231Sdim}
920303231Sdim
921303231Sdimvoid CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
922303231Sdim  // If we have a symbol, it may be in a section that is COMDAT. If so, find the
923303231Sdim  // comdat key. A section may be comdat because of -ffunction-sections or
924303231Sdim  // because it is comdat in the IR.
925303231Sdim  MCSectionCOFF *GVSec =
926303231Sdim      GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
927303231Sdim  const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
928303231Sdim
929303231Sdim  MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
930303231Sdim      Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
931303231Sdim  DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
932303231Sdim
933303231Sdim  OS.SwitchSection(DebugSec);
934303231Sdim
935303231Sdim  // Emit the magic version number if this is the first time we've switched to
936303231Sdim  // this section.
937303231Sdim  if (ComdatDebugSections.insert(DebugSec).second)
938303231Sdim    emitCodeViewMagicVersion();
939303231Sdim}
940303231Sdim
941341825Sdim// Emit an S_THUNK32/S_END symbol pair for a thunk routine.
942341825Sdim// The only supported thunk ordinal is currently the standard type.
943341825Sdimvoid CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
944341825Sdim                                          FunctionInfo &FI,
945341825Sdim                                          const MCSymbol *Fn) {
946341825Sdim  std::string FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
947341825Sdim  const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
948341825Sdim
949341825Sdim  OS.AddComment("Symbol subsection for " + Twine(FuncName));
950341825Sdim  MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
951341825Sdim
952341825Sdim  // Emit S_THUNK32
953344779Sdim  MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32);
954341825Sdim  OS.AddComment("PtrParent");
955341825Sdim  OS.EmitIntValue(0, 4);
956341825Sdim  OS.AddComment("PtrEnd");
957341825Sdim  OS.EmitIntValue(0, 4);
958341825Sdim  OS.AddComment("PtrNext");
959341825Sdim  OS.EmitIntValue(0, 4);
960341825Sdim  OS.AddComment("Thunk section relative address");
961341825Sdim  OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
962341825Sdim  OS.AddComment("Thunk section index");
963341825Sdim  OS.EmitCOFFSectionIndex(Fn);
964341825Sdim  OS.AddComment("Code size");
965341825Sdim  OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
966341825Sdim  OS.AddComment("Ordinal");
967341825Sdim  OS.EmitIntValue(unsigned(ordinal), 1);
968341825Sdim  OS.AddComment("Function name");
969341825Sdim  emitNullTerminatedSymbolName(OS, FuncName);
970341825Sdim  // Additional fields specific to the thunk ordinal would go here.
971344779Sdim  endSymbolRecord(ThunkRecordEnd);
972341825Sdim
973341825Sdim  // Local variables/inlined routines are purposely omitted here.  The point of
974341825Sdim  // marking this as a thunk is so Visual Studio will NOT stop in this routine.
975341825Sdim
976341825Sdim  // Emit S_PROC_ID_END
977344779Sdim  emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
978341825Sdim
979341825Sdim  endCVSubsection(SymbolsEnd);
980341825Sdim}
981341825Sdim
982303231Sdimvoid CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
983303231Sdim                                             FunctionInfo &FI) {
984341825Sdim  // For each function there is a separate subsection which holds the PC to
985341825Sdim  // file:line table.
986303231Sdim  const MCSymbol *Fn = Asm->getSymbol(GV);
987303231Sdim  assert(Fn);
988303231Sdim
989303231Sdim  // Switch to the to a comdat section, if appropriate.
990303231Sdim  switchToDebugSectionForSymbol(Fn);
991303231Sdim
992303231Sdim  std::string FuncName;
993303231Sdim  auto *SP = GV->getSubprogram();
994304310Sdim  assert(SP);
995303231Sdim  setCurrentSubprogram(SP);
996303231Sdim
997341825Sdim  if (SP->isThunk()) {
998341825Sdim    emitDebugInfoForThunk(GV, FI, Fn);
999341825Sdim    return;
1000341825Sdim  }
1001341825Sdim
1002303231Sdim  // If we have a display name, build the fully qualified name by walking the
1003303231Sdim  // chain of scopes.
1004321369Sdim  if (!SP->getName().empty())
1005353358Sdim    FuncName = getFullyQualifiedName(SP->getScope(), SP->getName());
1006303231Sdim
1007303231Sdim  // If our DISubprogram name is empty, use the mangled name.
1008303231Sdim  if (FuncName.empty())
1009321369Sdim    FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
1010303231Sdim
1011327952Sdim  // Emit FPO data, but only on 32-bit x86. No other platforms use it.
1012327952Sdim  if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
1013327952Sdim    OS.EmitCVFPOData(Fn);
1014327952Sdim
1015303231Sdim  // Emit a symbol subsection, required by VS2012+ to find function boundaries.
1016303231Sdim  OS.AddComment("Symbol subsection for " + Twine(FuncName));
1017321369Sdim  MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
1018303231Sdim  {
1019344779Sdim    SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID
1020344779Sdim                                                : SymbolKind::S_GPROC32_ID;
1021344779Sdim    MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind);
1022303231Sdim
1023303231Sdim    // These fields are filled in by tools like CVPACK which run after the fact.
1024303231Sdim    OS.AddComment("PtrParent");
1025303231Sdim    OS.EmitIntValue(0, 4);
1026303231Sdim    OS.AddComment("PtrEnd");
1027303231Sdim    OS.EmitIntValue(0, 4);
1028303231Sdim    OS.AddComment("PtrNext");
1029303231Sdim    OS.EmitIntValue(0, 4);
1030303231Sdim    // This is the important bit that tells the debugger where the function
1031303231Sdim    // code is located and what's its size:
1032303231Sdim    OS.AddComment("Code size");
1033303231Sdim    OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
1034303231Sdim    OS.AddComment("Offset after prologue");
1035303231Sdim    OS.EmitIntValue(0, 4);
1036303231Sdim    OS.AddComment("Offset before epilogue");
1037303231Sdim    OS.EmitIntValue(0, 4);
1038303231Sdim    OS.AddComment("Function type index");
1039303231Sdim    OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
1040303231Sdim    OS.AddComment("Function section relative address");
1041314564Sdim    OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
1042303231Sdim    OS.AddComment("Function section index");
1043303231Sdim    OS.EmitCOFFSectionIndex(Fn);
1044303231Sdim    OS.AddComment("Flags");
1045303231Sdim    OS.EmitIntValue(0, 1);
1046303231Sdim    // Emit the function display name as a null-terminated string.
1047303231Sdim    OS.AddComment("Function name");
1048303231Sdim    // Truncate the name so we won't overflow the record length field.
1049303231Sdim    emitNullTerminatedSymbolName(OS, FuncName);
1050344779Sdim    endSymbolRecord(ProcRecordEnd);
1051303231Sdim
1052344779Sdim    MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC);
1053344779Sdim    // Subtract out the CSR size since MSVC excludes that and we include it.
1054344779Sdim    OS.AddComment("FrameSize");
1055344779Sdim    OS.EmitIntValue(FI.FrameSize - FI.CSRSize, 4);
1056344779Sdim    OS.AddComment("Padding");
1057344779Sdim    OS.EmitIntValue(0, 4);
1058344779Sdim    OS.AddComment("Offset of padding");
1059344779Sdim    OS.EmitIntValue(0, 4);
1060344779Sdim    OS.AddComment("Bytes of callee saved registers");
1061344779Sdim    OS.EmitIntValue(FI.CSRSize, 4);
1062344779Sdim    OS.AddComment("Exception handler offset");
1063344779Sdim    OS.EmitIntValue(0, 4);
1064344779Sdim    OS.AddComment("Exception handler section");
1065344779Sdim    OS.EmitIntValue(0, 2);
1066344779Sdim    OS.AddComment("Flags (defines frame register)");
1067344779Sdim    OS.EmitIntValue(uint32_t(FI.FrameProcOpts), 4);
1068344779Sdim    endSymbolRecord(FrameProcEnd);
1069344779Sdim
1070344779Sdim    emitLocalVariableList(FI, FI.Locals);
1071344779Sdim    emitGlobalVariableList(FI.Globals);
1072341825Sdim    emitLexicalBlockList(FI.ChildBlocks, FI);
1073303231Sdim
1074303231Sdim    // Emit inlined call site information. Only emit functions inlined directly
1075303231Sdim    // into the parent function. We'll emit the other sites recursively as part
1076303231Sdim    // of their parent inline site.
1077303231Sdim    for (const DILocation *InlinedAt : FI.ChildSites) {
1078303231Sdim      auto I = FI.InlineSites.find(InlinedAt);
1079303231Sdim      assert(I != FI.InlineSites.end() &&
1080303231Sdim             "child site not in function inline site map");
1081303231Sdim      emitInlinedCallSite(FI, InlinedAt, I->second);
1082303231Sdim    }
1083303231Sdim
1084327952Sdim    for (auto Annot : FI.Annotations) {
1085327952Sdim      MCSymbol *Label = Annot.first;
1086327952Sdim      MDTuple *Strs = cast<MDTuple>(Annot.second);
1087344779Sdim      MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION);
1088327952Sdim      OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
1089327952Sdim      // FIXME: Make sure we don't overflow the max record size.
1090327952Sdim      OS.EmitCOFFSectionIndex(Label);
1091327952Sdim      OS.EmitIntValue(Strs->getNumOperands(), 2);
1092327952Sdim      for (Metadata *MD : Strs->operands()) {
1093327952Sdim        // MDStrings are null terminated, so we can do EmitBytes and get the
1094327952Sdim        // nice .asciz directive.
1095327952Sdim        StringRef Str = cast<MDString>(MD)->getString();
1096327952Sdim        assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
1097327952Sdim        OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
1098327952Sdim      }
1099344779Sdim      endSymbolRecord(AnnotEnd);
1100327952Sdim    }
1101327952Sdim
1102353358Sdim    for (auto HeapAllocSite : FI.HeapAllocSites) {
1103360661Sdim      const MCSymbol *BeginLabel = std::get<0>(HeapAllocSite);
1104360661Sdim      const MCSymbol *EndLabel = std::get<1>(HeapAllocSite);
1105360661Sdim      const DIType *DITy = std::get<2>(HeapAllocSite);
1106353358Sdim      MCSymbol *HeapAllocEnd = beginSymbolRecord(SymbolKind::S_HEAPALLOCSITE);
1107353358Sdim      OS.AddComment("Call site offset");
1108353358Sdim      OS.EmitCOFFSecRel32(BeginLabel, /*Offset=*/0);
1109353358Sdim      OS.AddComment("Call site section index");
1110353358Sdim      OS.EmitCOFFSectionIndex(BeginLabel);
1111353358Sdim      OS.AddComment("Call instruction length");
1112353358Sdim      OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
1113353358Sdim      OS.AddComment("Type index");
1114353358Sdim      OS.EmitIntValue(getCompleteTypeIndex(DITy).getIndex(), 4);
1115353358Sdim      endSymbolRecord(HeapAllocEnd);
1116353358Sdim    }
1117353358Sdim
1118303231Sdim    if (SP != nullptr)
1119303231Sdim      emitDebugInfoForUDTs(LocalUDTs);
1120303231Sdim
1121303231Sdim    // We're done with this function.
1122344779Sdim    emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
1123303231Sdim  }
1124303231Sdim  endCVSubsection(SymbolsEnd);
1125303231Sdim
1126303231Sdim  // We have an assembler directive that takes care of the whole line table.
1127303231Sdim  OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
1128303231Sdim}
1129303231Sdim
1130303231SdimCodeViewDebug::LocalVarDefRange
1131303231SdimCodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
1132303231Sdim  LocalVarDefRange DR;
1133303231Sdim  DR.InMemory = -1;
1134303231Sdim  DR.DataOffset = Offset;
1135303231Sdim  assert(DR.DataOffset == Offset && "truncation");
1136314564Sdim  DR.IsSubfield = 0;
1137303231Sdim  DR.StructOffset = 0;
1138303231Sdim  DR.CVRegister = CVRegister;
1139303231Sdim  return DR;
1140303231Sdim}
1141303231Sdim
1142314564Sdimvoid CodeViewDebug::collectVariableInfoFromMFTable(
1143344779Sdim    DenseSet<InlinedEntity> &Processed) {
1144314564Sdim  const MachineFunction &MF = *Asm->MF;
1145314564Sdim  const TargetSubtargetInfo &TSI = MF.getSubtarget();
1146303231Sdim  const TargetFrameLowering *TFI = TSI.getFrameLowering();
1147303231Sdim  const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1148303231Sdim
1149314564Sdim  for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
1150303231Sdim    if (!VI.Var)
1151303231Sdim      continue;
1152303231Sdim    assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1153303231Sdim           "Expected inlined-at fields to agree");
1154303231Sdim
1155344779Sdim    Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
1156303231Sdim    LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1157303231Sdim
1158303231Sdim    // If variable scope is not found then skip this variable.
1159303231Sdim    if (!Scope)
1160303231Sdim      continue;
1161303231Sdim
1162321369Sdim    // If the variable has an attached offset expression, extract it.
1163321369Sdim    // FIXME: Try to handle DW_OP_deref as well.
1164321369Sdim    int64_t ExprOffset = 0;
1165353358Sdim    bool Deref = false;
1166353358Sdim    if (VI.Expr) {
1167353358Sdim      // If there is one DW_OP_deref element, use offset of 0 and keep going.
1168353358Sdim      if (VI.Expr->getNumElements() == 1 &&
1169353358Sdim          VI.Expr->getElement(0) == llvm::dwarf::DW_OP_deref)
1170353358Sdim        Deref = true;
1171353358Sdim      else if (!VI.Expr->extractIfOffset(ExprOffset))
1172321369Sdim        continue;
1173353358Sdim    }
1174321369Sdim
1175303231Sdim    // Get the frame register used and the offset.
1176303231Sdim    unsigned FrameReg = 0;
1177303231Sdim    int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
1178303231Sdim    uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
1179303231Sdim
1180303231Sdim    // Calculate the label ranges.
1181321369Sdim    LocalVarDefRange DefRange =
1182321369Sdim        createDefRangeMem(CVReg, FrameOffset + ExprOffset);
1183353358Sdim
1184303231Sdim    for (const InsnRange &Range : Scope->getRanges()) {
1185303231Sdim      const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1186303231Sdim      const MCSymbol *End = getLabelAfterInsn(Range.second);
1187303231Sdim      End = End ? End : Asm->getFunctionEnd();
1188303231Sdim      DefRange.Ranges.emplace_back(Begin, End);
1189303231Sdim    }
1190303231Sdim
1191303231Sdim    LocalVariable Var;
1192303231Sdim    Var.DIVar = VI.Var;
1193303231Sdim    Var.DefRanges.emplace_back(std::move(DefRange));
1194353358Sdim    if (Deref)
1195353358Sdim      Var.UseReferenceType = true;
1196353358Sdim
1197341825Sdim    recordLocalVariable(std::move(Var), Scope);
1198303231Sdim  }
1199303231Sdim}
1200303231Sdim
1201327952Sdimstatic bool canUseReferenceType(const DbgVariableLocation &Loc) {
1202327952Sdim  return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
1203327952Sdim}
1204327952Sdim
1205327952Sdimstatic bool needsReferenceType(const DbgVariableLocation &Loc) {
1206327952Sdim  return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
1207327952Sdim}
1208327952Sdim
1209327952Sdimvoid CodeViewDebug::calculateRanges(
1210353358Sdim    LocalVariable &Var, const DbgValueHistoryMap::Entries &Entries) {
1211327952Sdim  const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1212327952Sdim
1213327952Sdim  // Calculate the definition ranges.
1214353358Sdim  for (auto I = Entries.begin(), E = Entries.end(); I != E; ++I) {
1215353358Sdim    const auto &Entry = *I;
1216353358Sdim    if (!Entry.isDbgValue())
1217353358Sdim      continue;
1218353358Sdim    const MachineInstr *DVInst = Entry.getInstr();
1219327952Sdim    assert(DVInst->isDebugValue() && "Invalid History entry");
1220327952Sdim    // FIXME: Find a way to represent constant variables, since they are
1221327952Sdim    // relatively common.
1222327952Sdim    Optional<DbgVariableLocation> Location =
1223327952Sdim        DbgVariableLocation::extractFromMachineInstruction(*DVInst);
1224327952Sdim    if (!Location)
1225327952Sdim      continue;
1226327952Sdim
1227327952Sdim    // CodeView can only express variables in register and variables in memory
1228327952Sdim    // at a constant offset from a register. However, for variables passed
1229327952Sdim    // indirectly by pointer, it is common for that pointer to be spilled to a
1230327952Sdim    // stack location. For the special case of one offseted load followed by a
1231327952Sdim    // zero offset load (a pointer spilled to the stack), we change the type of
1232327952Sdim    // the local variable from a value type to a reference type. This tricks the
1233327952Sdim    // debugger into doing the load for us.
1234327952Sdim    if (Var.UseReferenceType) {
1235327952Sdim      // We're using a reference type. Drop the last zero offset load.
1236327952Sdim      if (canUseReferenceType(*Location))
1237327952Sdim        Location->LoadChain.pop_back();
1238327952Sdim      else
1239327952Sdim        continue;
1240327952Sdim    } else if (needsReferenceType(*Location)) {
1241327952Sdim      // This location can't be expressed without switching to a reference type.
1242327952Sdim      // Start over using that.
1243327952Sdim      Var.UseReferenceType = true;
1244327952Sdim      Var.DefRanges.clear();
1245353358Sdim      calculateRanges(Var, Entries);
1246327952Sdim      return;
1247327952Sdim    }
1248327952Sdim
1249327952Sdim    // We can only handle a register or an offseted load of a register.
1250327952Sdim    if (Location->Register == 0 || Location->LoadChain.size() > 1)
1251327952Sdim      continue;
1252327952Sdim    {
1253327952Sdim      LocalVarDefRange DR;
1254327952Sdim      DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
1255327952Sdim      DR.InMemory = !Location->LoadChain.empty();
1256327952Sdim      DR.DataOffset =
1257327952Sdim          !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
1258327952Sdim      if (Location->FragmentInfo) {
1259327952Sdim        DR.IsSubfield = true;
1260327952Sdim        DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
1261327952Sdim      } else {
1262327952Sdim        DR.IsSubfield = false;
1263327952Sdim        DR.StructOffset = 0;
1264327952Sdim      }
1265327952Sdim
1266327952Sdim      if (Var.DefRanges.empty() ||
1267327952Sdim          Var.DefRanges.back().isDifferentLocation(DR)) {
1268327952Sdim        Var.DefRanges.emplace_back(std::move(DR));
1269327952Sdim      }
1270327952Sdim    }
1271327952Sdim
1272327952Sdim    // Compute the label range.
1273353358Sdim    const MCSymbol *Begin = getLabelBeforeInsn(Entry.getInstr());
1274353358Sdim    const MCSymbol *End;
1275353358Sdim    if (Entry.getEndIndex() != DbgValueHistoryMap::NoEntry) {
1276353358Sdim      auto &EndingEntry = Entries[Entry.getEndIndex()];
1277353358Sdim      End = EndingEntry.isDbgValue()
1278353358Sdim                ? getLabelBeforeInsn(EndingEntry.getInstr())
1279353358Sdim                : getLabelAfterInsn(EndingEntry.getInstr());
1280353358Sdim    } else
1281353358Sdim      End = Asm->getFunctionEnd();
1282327952Sdim
1283327952Sdim    // If the last range end is our begin, just extend the last range.
1284327952Sdim    // Otherwise make a new range.
1285327952Sdim    SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1286327952Sdim        Var.DefRanges.back().Ranges;
1287327952Sdim    if (!R.empty() && R.back().second == Begin)
1288327952Sdim      R.back().second = End;
1289327952Sdim    else
1290327952Sdim      R.emplace_back(Begin, End);
1291327952Sdim
1292327952Sdim    // FIXME: Do more range combining.
1293327952Sdim  }
1294327952Sdim}
1295327952Sdim
1296303231Sdimvoid CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
1297344779Sdim  DenseSet<InlinedEntity> Processed;
1298303231Sdim  // Grab the variable info that was squirreled away in the MMI side-table.
1299314564Sdim  collectVariableInfoFromMFTable(Processed);
1300303231Sdim
1301303231Sdim  for (const auto &I : DbgValues) {
1302344779Sdim    InlinedEntity IV = I.first;
1303303231Sdim    if (Processed.count(IV))
1304303231Sdim      continue;
1305344779Sdim    const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
1306303231Sdim    const DILocation *InlinedAt = IV.second;
1307303231Sdim
1308303231Sdim    // Instruction ranges, specifying where IV is accessible.
1309353358Sdim    const auto &Entries = I.second;
1310303231Sdim
1311303231Sdim    LexicalScope *Scope = nullptr;
1312303231Sdim    if (InlinedAt)
1313303231Sdim      Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1314303231Sdim    else
1315303231Sdim      Scope = LScopes.findLexicalScope(DIVar->getScope());
1316303231Sdim    // If variable scope is not found then skip this variable.
1317303231Sdim    if (!Scope)
1318303231Sdim      continue;
1319303231Sdim
1320303231Sdim    LocalVariable Var;
1321303231Sdim    Var.DIVar = DIVar;
1322303231Sdim
1323353358Sdim    calculateRanges(Var, Entries);
1324341825Sdim    recordLocalVariable(std::move(Var), Scope);
1325303231Sdim  }
1326303231Sdim}
1327303231Sdim
1328321369Sdimvoid CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
1329344779Sdim  const TargetSubtargetInfo &TSI = MF->getSubtarget();
1330344779Sdim  const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1331344779Sdim  const MachineFrameInfo &MFI = MF->getFrameInfo();
1332327952Sdim  const Function &GV = MF->getFunction();
1333360784Sdim  auto Insertion = FnDebugInfo.insert({&GV, std::make_unique<FunctionInfo>()});
1334341825Sdim  assert(Insertion.second && "function already has info");
1335341825Sdim  CurFn = Insertion.first->second.get();
1336303231Sdim  CurFn->FuncId = NextFuncId++;
1337303231Sdim  CurFn->Begin = Asm->getFunctionBegin();
1338303231Sdim
1339344779Sdim  // The S_FRAMEPROC record reports the stack size, and how many bytes of
1340344779Sdim  // callee-saved registers were used. For targets that don't use a PUSH
1341344779Sdim  // instruction (AArch64), this will be zero.
1342344779Sdim  CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
1343344779Sdim  CurFn->FrameSize = MFI.getStackSize();
1344344779Sdim  CurFn->OffsetAdjustment = MFI.getOffsetAdjustment();
1345344779Sdim  CurFn->HasStackRealignment = TRI->needsStackRealignment(*MF);
1346344779Sdim
1347344779Sdim  // For this function S_FRAMEPROC record, figure out which codeview register
1348344779Sdim  // will be the frame pointer.
1349344779Sdim  CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
1350344779Sdim  CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
1351344779Sdim  if (CurFn->FrameSize > 0) {
1352344779Sdim    if (!TSI.getFrameLowering()->hasFP(*MF)) {
1353344779Sdim      CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1354344779Sdim      CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
1355344779Sdim    } else {
1356344779Sdim      // If there is an FP, parameters are always relative to it.
1357344779Sdim      CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
1358344779Sdim      if (CurFn->HasStackRealignment) {
1359344779Sdim        // If the stack needs realignment, locals are relative to SP or VFRAME.
1360344779Sdim        CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1361344779Sdim      } else {
1362344779Sdim        // Otherwise, locals are relative to EBP, and we probably have VLAs or
1363344779Sdim        // other stack adjustments.
1364344779Sdim        CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
1365344779Sdim      }
1366344779Sdim    }
1367344779Sdim  }
1368344779Sdim
1369344779Sdim  // Compute other frame procedure options.
1370344779Sdim  FrameProcedureOptions FPO = FrameProcedureOptions::None;
1371344779Sdim  if (MFI.hasVarSizedObjects())
1372344779Sdim    FPO |= FrameProcedureOptions::HasAlloca;
1373344779Sdim  if (MF->exposesReturnsTwice())
1374344779Sdim    FPO |= FrameProcedureOptions::HasSetJmp;
1375344779Sdim  // FIXME: Set HasLongJmp if we ever track that info.
1376344779Sdim  if (MF->hasInlineAsm())
1377344779Sdim    FPO |= FrameProcedureOptions::HasInlineAssembly;
1378344779Sdim  if (GV.hasPersonalityFn()) {
1379344779Sdim    if (isAsynchronousEHPersonality(
1380344779Sdim            classifyEHPersonality(GV.getPersonalityFn())))
1381344779Sdim      FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
1382344779Sdim    else
1383344779Sdim      FPO |= FrameProcedureOptions::HasExceptionHandling;
1384344779Sdim  }
1385344779Sdim  if (GV.hasFnAttribute(Attribute::InlineHint))
1386344779Sdim    FPO |= FrameProcedureOptions::MarkedInline;
1387344779Sdim  if (GV.hasFnAttribute(Attribute::Naked))
1388344779Sdim    FPO |= FrameProcedureOptions::Naked;
1389344779Sdim  if (MFI.hasStackProtectorIndex())
1390344779Sdim    FPO |= FrameProcedureOptions::SecurityChecks;
1391344779Sdim  FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
1392344779Sdim  FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
1393353358Sdim  if (Asm->TM.getOptLevel() != CodeGenOpt::None &&
1394353358Sdim      !GV.hasOptSize() && !GV.hasOptNone())
1395344779Sdim    FPO |= FrameProcedureOptions::OptimizedForSpeed;
1396344779Sdim  // FIXME: Set GuardCfg when it is implemented.
1397344779Sdim  CurFn->FrameProcOpts = FPO;
1398344779Sdim
1399314564Sdim  OS.EmitCVFuncIdDirective(CurFn->FuncId);
1400314564Sdim
1401303231Sdim  // Find the end of the function prolog.  First known non-DBG_VALUE and
1402303231Sdim  // non-frame setup location marks the beginning of the function body.
1403303231Sdim  // FIXME: is there a simpler a way to do this? Can we just search
1404303231Sdim  // for the first instruction of the function, not the last of the prolog?
1405303231Sdim  DebugLoc PrologEndLoc;
1406303231Sdim  bool EmptyPrologue = true;
1407303231Sdim  for (const auto &MBB : *MF) {
1408303231Sdim    for (const auto &MI : MBB) {
1409321369Sdim      if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1410303231Sdim          MI.getDebugLoc()) {
1411303231Sdim        PrologEndLoc = MI.getDebugLoc();
1412303231Sdim        break;
1413321369Sdim      } else if (!MI.isMetaInstruction()) {
1414303231Sdim        EmptyPrologue = false;
1415303231Sdim      }
1416303231Sdim    }
1417303231Sdim  }
1418303231Sdim
1419303231Sdim  // Record beginning of function if we have a non-empty prologue.
1420303231Sdim  if (PrologEndLoc && !EmptyPrologue) {
1421303231Sdim    DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
1422303231Sdim    maybeRecordLocation(FnStartDL, MF);
1423303231Sdim  }
1424360661Sdim
1425360661Sdim  // Find heap alloc sites and emit labels around them.
1426360661Sdim  for (const auto &MBB : *MF) {
1427360661Sdim    for (const auto &MI : MBB) {
1428360661Sdim      if (MI.getHeapAllocMarker()) {
1429360661Sdim        requestLabelBeforeInsn(&MI);
1430360661Sdim        requestLabelAfterInsn(&MI);
1431360661Sdim      }
1432360661Sdim    }
1433360661Sdim  }
1434303231Sdim}
1435303231Sdim
1436327952Sdimstatic bool shouldEmitUdt(const DIType *T) {
1437327952Sdim  if (!T)
1438327952Sdim    return false;
1439327952Sdim
1440327952Sdim  // MSVC does not emit UDTs for typedefs that are scoped to classes.
1441327952Sdim  if (T->getTag() == dwarf::DW_TAG_typedef) {
1442353358Sdim    if (DIScope *Scope = T->getScope()) {
1443327952Sdim      switch (Scope->getTag()) {
1444327952Sdim      case dwarf::DW_TAG_structure_type:
1445327952Sdim      case dwarf::DW_TAG_class_type:
1446327952Sdim      case dwarf::DW_TAG_union_type:
1447327952Sdim        return false;
1448327952Sdim      }
1449327952Sdim    }
1450327952Sdim  }
1451327952Sdim
1452327952Sdim  while (true) {
1453327952Sdim    if (!T || T->isForwardDecl())
1454327952Sdim      return false;
1455327952Sdim
1456327952Sdim    const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
1457327952Sdim    if (!DT)
1458327952Sdim      return true;
1459353358Sdim    T = DT->getBaseType();
1460327952Sdim  }
1461327952Sdim  return true;
1462327952Sdim}
1463327952Sdim
1464327952Sdimvoid CodeViewDebug::addToUDTs(const DIType *Ty) {
1465303231Sdim  // Don't record empty UDTs.
1466303231Sdim  if (Ty->getName().empty())
1467303231Sdim    return;
1468327952Sdim  if (!shouldEmitUdt(Ty))
1469327952Sdim    return;
1470303231Sdim
1471303231Sdim  SmallVector<StringRef, 5> QualifiedNameComponents;
1472353358Sdim  const DISubprogram *ClosestSubprogram =
1473353358Sdim      getQualifiedNameComponents(Ty->getScope(), QualifiedNameComponents);
1474303231Sdim
1475303231Sdim  std::string FullyQualifiedName =
1476303231Sdim      getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
1477303231Sdim
1478327952Sdim  if (ClosestSubprogram == nullptr) {
1479327952Sdim    GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1480327952Sdim  } else if (ClosestSubprogram == CurrentSubprogram) {
1481327952Sdim    LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1482327952Sdim  }
1483303231Sdim
1484303231Sdim  // TODO: What if the ClosestSubprogram is neither null or the current
1485303231Sdim  // subprogram?  Currently, the UDT just gets dropped on the floor.
1486303231Sdim  //
1487303231Sdim  // The current behavior is not desirable.  To get maximal fidelity, we would
1488303231Sdim  // need to perform all type translation before beginning emission of .debug$S
1489303231Sdim  // and then make LocalUDTs a member of FunctionInfo
1490303231Sdim}
1491303231Sdim
1492303231SdimTypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
1493303231Sdim  // Generic dispatch for lowering an unknown type.
1494303231Sdim  switch (Ty->getTag()) {
1495303231Sdim  case dwarf::DW_TAG_array_type:
1496303231Sdim    return lowerTypeArray(cast<DICompositeType>(Ty));
1497303231Sdim  case dwarf::DW_TAG_typedef:
1498303231Sdim    return lowerTypeAlias(cast<DIDerivedType>(Ty));
1499303231Sdim  case dwarf::DW_TAG_base_type:
1500303231Sdim    return lowerTypeBasic(cast<DIBasicType>(Ty));
1501303231Sdim  case dwarf::DW_TAG_pointer_type:
1502314564Sdim    if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1503314564Sdim      return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1504314564Sdim    LLVM_FALLTHROUGH;
1505303231Sdim  case dwarf::DW_TAG_reference_type:
1506303231Sdim  case dwarf::DW_TAG_rvalue_reference_type:
1507303231Sdim    return lowerTypePointer(cast<DIDerivedType>(Ty));
1508303231Sdim  case dwarf::DW_TAG_ptr_to_member_type:
1509303231Sdim    return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1510341825Sdim  case dwarf::DW_TAG_restrict_type:
1511303231Sdim  case dwarf::DW_TAG_const_type:
1512303231Sdim  case dwarf::DW_TAG_volatile_type:
1513314564Sdim  // TODO: add support for DW_TAG_atomic_type here
1514303231Sdim    return lowerTypeModifier(cast<DIDerivedType>(Ty));
1515303231Sdim  case dwarf::DW_TAG_subroutine_type:
1516303231Sdim    if (ClassTy) {
1517303231Sdim      // The member function type of a member function pointer has no
1518303231Sdim      // ThisAdjustment.
1519303231Sdim      return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1520327952Sdim                                     /*ThisAdjustment=*/0,
1521327952Sdim                                     /*IsStaticMethod=*/false);
1522303231Sdim    }
1523303231Sdim    return lowerTypeFunction(cast<DISubroutineType>(Ty));
1524303231Sdim  case dwarf::DW_TAG_enumeration_type:
1525303231Sdim    return lowerTypeEnum(cast<DICompositeType>(Ty));
1526303231Sdim  case dwarf::DW_TAG_class_type:
1527303231Sdim  case dwarf::DW_TAG_structure_type:
1528303231Sdim    return lowerTypeClass(cast<DICompositeType>(Ty));
1529303231Sdim  case dwarf::DW_TAG_union_type:
1530303231Sdim    return lowerTypeUnion(cast<DICompositeType>(Ty));
1531341825Sdim  case dwarf::DW_TAG_unspecified_type:
1532344779Sdim    if (Ty->getName() == "decltype(nullptr)")
1533344779Sdim      return TypeIndex::NullptrT();
1534341825Sdim    return TypeIndex::None();
1535303231Sdim  default:
1536303231Sdim    // Use the null type index.
1537303231Sdim    return TypeIndex();
1538303231Sdim  }
1539303231Sdim}
1540303231Sdim
1541303231SdimTypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
1542353358Sdim  TypeIndex UnderlyingTypeIndex = getTypeIndex(Ty->getBaseType());
1543303231Sdim  StringRef TypeName = Ty->getName();
1544303231Sdim
1545327952Sdim  addToUDTs(Ty);
1546303231Sdim
1547303231Sdim  if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
1548303231Sdim      TypeName == "HRESULT")
1549303231Sdim    return TypeIndex(SimpleTypeKind::HResult);
1550303231Sdim  if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
1551303231Sdim      TypeName == "wchar_t")
1552303231Sdim    return TypeIndex(SimpleTypeKind::WideCharacter);
1553303231Sdim
1554303231Sdim  return UnderlyingTypeIndex;
1555303231Sdim}
1556303231Sdim
1557303231SdimTypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1558353358Sdim  const DIType *ElementType = Ty->getBaseType();
1559353358Sdim  TypeIndex ElementTypeIndex = getTypeIndex(ElementType);
1560303231Sdim  // IndexType is size_t, which depends on the bitness of the target.
1561341825Sdim  TypeIndex IndexType = getPointerSizeInBytes() == 8
1562303231Sdim                            ? TypeIndex(SimpleTypeKind::UInt64Quad)
1563303231Sdim                            : TypeIndex(SimpleTypeKind::UInt32Long);
1564303231Sdim
1565353358Sdim  uint64_t ElementSize = getBaseTypeSize(ElementType) / 8;
1566303231Sdim
1567303231Sdim  // Add subranges to array type.
1568303231Sdim  DINodeArray Elements = Ty->getElements();
1569303231Sdim  for (int i = Elements.size() - 1; i >= 0; --i) {
1570303231Sdim    const DINode *Element = Elements[i];
1571303231Sdim    assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1572303231Sdim
1573303231Sdim    const DISubrange *Subrange = cast<DISubrange>(Element);
1574303231Sdim    assert(Subrange->getLowerBound() == 0 &&
1575303231Sdim           "codeview doesn't support subranges with lower bounds");
1576341825Sdim    int64_t Count = -1;
1577341825Sdim    if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>())
1578341825Sdim      Count = CI->getSExtValue();
1579303231Sdim
1580327952Sdim    // Forward declarations of arrays without a size and VLAs use a count of -1.
1581327952Sdim    // Emit a count of zero in these cases to match what MSVC does for arrays
1582327952Sdim    // without a size. MSVC doesn't support VLAs, so it's not clear what we
1583327952Sdim    // should do for them even if we could distinguish them.
1584321369Sdim    if (Count == -1)
1585327952Sdim      Count = 0;
1586303231Sdim
1587303231Sdim    // Update the element size and element type index for subsequent subranges.
1588303231Sdim    ElementSize *= Count;
1589314564Sdim
1590314564Sdim    // If this is the outermost array, use the size from the array. It will be
1591321369Sdim    // more accurate if we had a VLA or an incomplete element type size.
1592314564Sdim    uint64_t ArraySize =
1593314564Sdim        (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1594314564Sdim
1595314564Sdim    StringRef Name = (i == 0) ? Ty->getName() : "";
1596314564Sdim    ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1597327952Sdim    ElementTypeIndex = TypeTable.writeLeafType(AR);
1598303231Sdim  }
1599303231Sdim
1600303231Sdim  return ElementTypeIndex;
1601303231Sdim}
1602303231Sdim
1603303231SdimTypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1604303231Sdim  TypeIndex Index;
1605303231Sdim  dwarf::TypeKind Kind;
1606303231Sdim  uint32_t ByteSize;
1607303231Sdim
1608303231Sdim  Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
1609303231Sdim  ByteSize = Ty->getSizeInBits() / 8;
1610303231Sdim
1611303231Sdim  SimpleTypeKind STK = SimpleTypeKind::None;
1612303231Sdim  switch (Kind) {
1613303231Sdim  case dwarf::DW_ATE_address:
1614303231Sdim    // FIXME: Translate
1615303231Sdim    break;
1616303231Sdim  case dwarf::DW_ATE_boolean:
1617303231Sdim    switch (ByteSize) {
1618303231Sdim    case 1:  STK = SimpleTypeKind::Boolean8;   break;
1619303231Sdim    case 2:  STK = SimpleTypeKind::Boolean16;  break;
1620303231Sdim    case 4:  STK = SimpleTypeKind::Boolean32;  break;
1621303231Sdim    case 8:  STK = SimpleTypeKind::Boolean64;  break;
1622303231Sdim    case 16: STK = SimpleTypeKind::Boolean128; break;
1623303231Sdim    }
1624303231Sdim    break;
1625303231Sdim  case dwarf::DW_ATE_complex_float:
1626303231Sdim    switch (ByteSize) {
1627303231Sdim    case 2:  STK = SimpleTypeKind::Complex16;  break;
1628303231Sdim    case 4:  STK = SimpleTypeKind::Complex32;  break;
1629303231Sdim    case 8:  STK = SimpleTypeKind::Complex64;  break;
1630303231Sdim    case 10: STK = SimpleTypeKind::Complex80;  break;
1631303231Sdim    case 16: STK = SimpleTypeKind::Complex128; break;
1632303231Sdim    }
1633303231Sdim    break;
1634303231Sdim  case dwarf::DW_ATE_float:
1635303231Sdim    switch (ByteSize) {
1636303231Sdim    case 2:  STK = SimpleTypeKind::Float16;  break;
1637303231Sdim    case 4:  STK = SimpleTypeKind::Float32;  break;
1638303231Sdim    case 6:  STK = SimpleTypeKind::Float48;  break;
1639303231Sdim    case 8:  STK = SimpleTypeKind::Float64;  break;
1640303231Sdim    case 10: STK = SimpleTypeKind::Float80;  break;
1641303231Sdim    case 16: STK = SimpleTypeKind::Float128; break;
1642303231Sdim    }
1643303231Sdim    break;
1644303231Sdim  case dwarf::DW_ATE_signed:
1645303231Sdim    switch (ByteSize) {
1646314564Sdim    case 1:  STK = SimpleTypeKind::SignedCharacter; break;
1647314564Sdim    case 2:  STK = SimpleTypeKind::Int16Short;      break;
1648314564Sdim    case 4:  STK = SimpleTypeKind::Int32;           break;
1649314564Sdim    case 8:  STK = SimpleTypeKind::Int64Quad;       break;
1650314564Sdim    case 16: STK = SimpleTypeKind::Int128Oct;       break;
1651303231Sdim    }
1652303231Sdim    break;
1653303231Sdim  case dwarf::DW_ATE_unsigned:
1654303231Sdim    switch (ByteSize) {
1655314564Sdim    case 1:  STK = SimpleTypeKind::UnsignedCharacter; break;
1656314564Sdim    case 2:  STK = SimpleTypeKind::UInt16Short;       break;
1657314564Sdim    case 4:  STK = SimpleTypeKind::UInt32;            break;
1658314564Sdim    case 8:  STK = SimpleTypeKind::UInt64Quad;        break;
1659314564Sdim    case 16: STK = SimpleTypeKind::UInt128Oct;        break;
1660303231Sdim    }
1661303231Sdim    break;
1662303231Sdim  case dwarf::DW_ATE_UTF:
1663303231Sdim    switch (ByteSize) {
1664303231Sdim    case 2: STK = SimpleTypeKind::Character16; break;
1665303231Sdim    case 4: STK = SimpleTypeKind::Character32; break;
1666303231Sdim    }
1667303231Sdim    break;
1668303231Sdim  case dwarf::DW_ATE_signed_char:
1669303231Sdim    if (ByteSize == 1)
1670303231Sdim      STK = SimpleTypeKind::SignedCharacter;
1671303231Sdim    break;
1672303231Sdim  case dwarf::DW_ATE_unsigned_char:
1673303231Sdim    if (ByteSize == 1)
1674303231Sdim      STK = SimpleTypeKind::UnsignedCharacter;
1675303231Sdim    break;
1676303231Sdim  default:
1677303231Sdim    break;
1678303231Sdim  }
1679303231Sdim
1680303231Sdim  // Apply some fixups based on the source-level type name.
1681303231Sdim  if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1682303231Sdim    STK = SimpleTypeKind::Int32Long;
1683303231Sdim  if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1684303231Sdim    STK = SimpleTypeKind::UInt32Long;
1685303231Sdim  if (STK == SimpleTypeKind::UInt16Short &&
1686303231Sdim      (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
1687303231Sdim    STK = SimpleTypeKind::WideCharacter;
1688303231Sdim  if ((STK == SimpleTypeKind::SignedCharacter ||
1689303231Sdim       STK == SimpleTypeKind::UnsignedCharacter) &&
1690303231Sdim      Ty->getName() == "char")
1691303231Sdim    STK = SimpleTypeKind::NarrowCharacter;
1692303231Sdim
1693303231Sdim  return TypeIndex(STK);
1694303231Sdim}
1695303231Sdim
1696341825SdimTypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
1697341825Sdim                                          PointerOptions PO) {
1698303231Sdim  TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1699303231Sdim
1700341825Sdim  // Pointers to simple types without any options can use SimpleTypeMode, rather
1701341825Sdim  // than having a dedicated pointer type record.
1702341825Sdim  if (PointeeTI.isSimple() && PO == PointerOptions::None &&
1703303231Sdim      PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1704303231Sdim      Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1705303231Sdim    SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1706303231Sdim                              ? SimpleTypeMode::NearPointer64
1707303231Sdim                              : SimpleTypeMode::NearPointer32;
1708303231Sdim    return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1709303231Sdim  }
1710303231Sdim
1711303231Sdim  PointerKind PK =
1712303231Sdim      Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1713303231Sdim  PointerMode PM = PointerMode::Pointer;
1714303231Sdim  switch (Ty->getTag()) {
1715303231Sdim  default: llvm_unreachable("not a pointer tag type");
1716303231Sdim  case dwarf::DW_TAG_pointer_type:
1717303231Sdim    PM = PointerMode::Pointer;
1718303231Sdim    break;
1719303231Sdim  case dwarf::DW_TAG_reference_type:
1720303231Sdim    PM = PointerMode::LValueReference;
1721303231Sdim    break;
1722303231Sdim  case dwarf::DW_TAG_rvalue_reference_type:
1723303231Sdim    PM = PointerMode::RValueReference;
1724303231Sdim    break;
1725303231Sdim  }
1726341825Sdim
1727344779Sdim  if (Ty->isObjectPointer())
1728344779Sdim    PO |= PointerOptions::Const;
1729344779Sdim
1730303231Sdim  PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1731327952Sdim  return TypeTable.writeLeafType(PR);
1732303231Sdim}
1733303231Sdim
1734303231Sdimstatic PointerToMemberRepresentation
1735303231SdimtranslatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1736303231Sdim  // SizeInBytes being zero generally implies that the member pointer type was
1737303231Sdim  // incomplete, which can happen if it is part of a function prototype. In this
1738303231Sdim  // case, use the unknown model instead of the general model.
1739303231Sdim  if (IsPMF) {
1740303231Sdim    switch (Flags & DINode::FlagPtrToMemberRep) {
1741303231Sdim    case 0:
1742303231Sdim      return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1743303231Sdim                              : PointerToMemberRepresentation::GeneralFunction;
1744303231Sdim    case DINode::FlagSingleInheritance:
1745303231Sdim      return PointerToMemberRepresentation::SingleInheritanceFunction;
1746303231Sdim    case DINode::FlagMultipleInheritance:
1747303231Sdim      return PointerToMemberRepresentation::MultipleInheritanceFunction;
1748303231Sdim    case DINode::FlagVirtualInheritance:
1749303231Sdim      return PointerToMemberRepresentation::VirtualInheritanceFunction;
1750303231Sdim    }
1751303231Sdim  } else {
1752303231Sdim    switch (Flags & DINode::FlagPtrToMemberRep) {
1753303231Sdim    case 0:
1754303231Sdim      return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1755303231Sdim                              : PointerToMemberRepresentation::GeneralData;
1756303231Sdim    case DINode::FlagSingleInheritance:
1757303231Sdim      return PointerToMemberRepresentation::SingleInheritanceData;
1758303231Sdim    case DINode::FlagMultipleInheritance:
1759303231Sdim      return PointerToMemberRepresentation::MultipleInheritanceData;
1760303231Sdim    case DINode::FlagVirtualInheritance:
1761303231Sdim      return PointerToMemberRepresentation::VirtualInheritanceData;
1762303231Sdim    }
1763303231Sdim  }
1764303231Sdim  llvm_unreachable("invalid ptr to member representation");
1765303231Sdim}
1766303231Sdim
1767341825SdimTypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
1768341825Sdim                                                PointerOptions PO) {
1769303231Sdim  assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1770303231Sdim  TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
1771303231Sdim  TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
1772341825Sdim  PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1773341825Sdim                                                : PointerKind::Near32;
1774303231Sdim  bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1775303231Sdim  PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1776303231Sdim                         : PointerMode::PointerToDataMember;
1777341825Sdim
1778303231Sdim  assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1779303231Sdim  uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1780303231Sdim  MemberPointerInfo MPI(
1781303231Sdim      ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
1782303231Sdim  PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
1783327952Sdim  return TypeTable.writeLeafType(PR);
1784303231Sdim}
1785303231Sdim
1786303231Sdim/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1787303231Sdim/// have a translation, use the NearC convention.
1788303231Sdimstatic CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1789303231Sdim  switch (DwarfCC) {
1790303231Sdim  case dwarf::DW_CC_normal:             return CallingConvention::NearC;
1791303231Sdim  case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1792303231Sdim  case dwarf::DW_CC_BORLAND_thiscall:   return CallingConvention::ThisCall;
1793303231Sdim  case dwarf::DW_CC_BORLAND_stdcall:    return CallingConvention::NearStdCall;
1794303231Sdim  case dwarf::DW_CC_BORLAND_pascal:     return CallingConvention::NearPascal;
1795303231Sdim  case dwarf::DW_CC_LLVM_vectorcall:    return CallingConvention::NearVector;
1796303231Sdim  }
1797303231Sdim  return CallingConvention::NearC;
1798303231Sdim}
1799303231Sdim
1800303231SdimTypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1801303231Sdim  ModifierOptions Mods = ModifierOptions::None;
1802341825Sdim  PointerOptions PO = PointerOptions::None;
1803303231Sdim  bool IsModifier = true;
1804303231Sdim  const DIType *BaseTy = Ty;
1805303231Sdim  while (IsModifier && BaseTy) {
1806314564Sdim    // FIXME: Need to add DWARF tags for __unaligned and _Atomic
1807303231Sdim    switch (BaseTy->getTag()) {
1808303231Sdim    case dwarf::DW_TAG_const_type:
1809303231Sdim      Mods |= ModifierOptions::Const;
1810341825Sdim      PO |= PointerOptions::Const;
1811303231Sdim      break;
1812303231Sdim    case dwarf::DW_TAG_volatile_type:
1813303231Sdim      Mods |= ModifierOptions::Volatile;
1814341825Sdim      PO |= PointerOptions::Volatile;
1815303231Sdim      break;
1816341825Sdim    case dwarf::DW_TAG_restrict_type:
1817341825Sdim      // Only pointer types be marked with __restrict. There is no known flag
1818341825Sdim      // for __restrict in LF_MODIFIER records.
1819341825Sdim      PO |= PointerOptions::Restrict;
1820341825Sdim      break;
1821303231Sdim    default:
1822303231Sdim      IsModifier = false;
1823303231Sdim      break;
1824303231Sdim    }
1825303231Sdim    if (IsModifier)
1826353358Sdim      BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType();
1827303231Sdim  }
1828341825Sdim
1829341825Sdim  // Check if the inner type will use an LF_POINTER record. If so, the
1830341825Sdim  // qualifiers will go in the LF_POINTER record. This comes up for types like
1831341825Sdim  // 'int *const' and 'int *__restrict', not the more common cases like 'const
1832341825Sdim  // char *'.
1833341825Sdim  if (BaseTy) {
1834341825Sdim    switch (BaseTy->getTag()) {
1835341825Sdim    case dwarf::DW_TAG_pointer_type:
1836341825Sdim    case dwarf::DW_TAG_reference_type:
1837341825Sdim    case dwarf::DW_TAG_rvalue_reference_type:
1838341825Sdim      return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
1839341825Sdim    case dwarf::DW_TAG_ptr_to_member_type:
1840341825Sdim      return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
1841341825Sdim    default:
1842341825Sdim      break;
1843341825Sdim    }
1844341825Sdim  }
1845341825Sdim
1846303231Sdim  TypeIndex ModifiedTI = getTypeIndex(BaseTy);
1847341825Sdim
1848341825Sdim  // Return the base type index if there aren't any modifiers. For example, the
1849341825Sdim  // metadata could contain restrict wrappers around non-pointer types.
1850341825Sdim  if (Mods == ModifierOptions::None)
1851341825Sdim    return ModifiedTI;
1852341825Sdim
1853303231Sdim  ModifierRecord MR(ModifiedTI, Mods);
1854327952Sdim  return TypeTable.writeLeafType(MR);
1855303231Sdim}
1856303231Sdim
1857303231SdimTypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1858303231Sdim  SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1859353358Sdim  for (const DIType *ArgType : Ty->getTypeArray())
1860353358Sdim    ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgType));
1861303231Sdim
1862341825Sdim  // MSVC uses type none for variadic argument.
1863341825Sdim  if (ReturnAndArgTypeIndices.size() > 1 &&
1864341825Sdim      ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1865341825Sdim    ReturnAndArgTypeIndices.back() = TypeIndex::None();
1866341825Sdim  }
1867303231Sdim  TypeIndex ReturnTypeIndex = TypeIndex::Void();
1868303231Sdim  ArrayRef<TypeIndex> ArgTypeIndices = None;
1869303231Sdim  if (!ReturnAndArgTypeIndices.empty()) {
1870303231Sdim    auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1871303231Sdim    ReturnTypeIndex = ReturnAndArgTypesRef.front();
1872303231Sdim    ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1873303231Sdim  }
1874303231Sdim
1875303231Sdim  ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1876327952Sdim  TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
1877303231Sdim
1878303231Sdim  CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1879303231Sdim
1880344779Sdim  FunctionOptions FO = getFunctionOptions(Ty);
1881344779Sdim  ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
1882344779Sdim                            ArgListIndex);
1883327952Sdim  return TypeTable.writeLeafType(Procedure);
1884303231Sdim}
1885303231Sdim
1886303231SdimTypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
1887303231Sdim                                                 const DIType *ClassTy,
1888327952Sdim                                                 int ThisAdjustment,
1889344779Sdim                                                 bool IsStaticMethod,
1890344779Sdim                                                 FunctionOptions FO) {
1891303231Sdim  // Lower the containing class type.
1892303231Sdim  TypeIndex ClassType = getTypeIndex(ClassTy);
1893303231Sdim
1894344779Sdim  DITypeRefArray ReturnAndArgs = Ty->getTypeArray();
1895303231Sdim
1896344779Sdim  unsigned Index = 0;
1897344779Sdim  SmallVector<TypeIndex, 8> ArgTypeIndices;
1898303231Sdim  TypeIndex ReturnTypeIndex = TypeIndex::Void();
1899344779Sdim  if (ReturnAndArgs.size() > Index) {
1900344779Sdim    ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]);
1901303231Sdim  }
1902344779Sdim
1903344779Sdim  // If the first argument is a pointer type and this isn't a static method,
1904344779Sdim  // treat it as the special 'this' parameter, which is encoded separately from
1905344779Sdim  // the arguments.
1906327952Sdim  TypeIndex ThisTypeIndex;
1907344779Sdim  if (!IsStaticMethod && ReturnAndArgs.size() > Index) {
1908344779Sdim    if (const DIDerivedType *PtrTy =
1909353358Sdim            dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index])) {
1910344779Sdim      if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) {
1911344779Sdim        ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty);
1912344779Sdim        Index++;
1913344779Sdim      }
1914344779Sdim    }
1915303231Sdim  }
1916303231Sdim
1917344779Sdim  while (Index < ReturnAndArgs.size())
1918344779Sdim    ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++]));
1919344779Sdim
1920344779Sdim  // MSVC uses type none for variadic argument.
1921344779Sdim  if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void())
1922344779Sdim    ArgTypeIndices.back() = TypeIndex::None();
1923344779Sdim
1924303231Sdim  ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1925327952Sdim  TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
1926303231Sdim
1927303231Sdim  CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1928303231Sdim
1929344779Sdim  MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
1930344779Sdim                           ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
1931327952Sdim  return TypeTable.writeLeafType(MFR);
1932303231Sdim}
1933303231Sdim
1934314564SdimTypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
1935321369Sdim  unsigned VSlotCount =
1936321369Sdim      Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
1937314564Sdim  SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
1938314564Sdim
1939314564Sdim  VFTableShapeRecord VFTSR(Slots);
1940327952Sdim  return TypeTable.writeLeafType(VFTSR);
1941314564Sdim}
1942314564Sdim
1943303231Sdimstatic MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1944303231Sdim  switch (Flags & DINode::FlagAccessibility) {
1945303231Sdim  case DINode::FlagPrivate:   return MemberAccess::Private;
1946303231Sdim  case DINode::FlagPublic:    return MemberAccess::Public;
1947303231Sdim  case DINode::FlagProtected: return MemberAccess::Protected;
1948303231Sdim  case 0:
1949303231Sdim    // If there was no explicit access control, provide the default for the tag.
1950303231Sdim    return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1951303231Sdim                                                 : MemberAccess::Public;
1952303231Sdim  }
1953303231Sdim  llvm_unreachable("access flags are exclusive");
1954303231Sdim}
1955303231Sdim
1956303231Sdimstatic MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1957303231Sdim  if (SP->isArtificial())
1958303231Sdim    return MethodOptions::CompilerGenerated;
1959303231Sdim
1960303231Sdim  // FIXME: Handle other MethodOptions.
1961303231Sdim
1962303231Sdim  return MethodOptions::None;
1963303231Sdim}
1964303231Sdim
1965303231Sdimstatic MethodKind translateMethodKindFlags(const DISubprogram *SP,
1966303231Sdim                                           bool Introduced) {
1967327952Sdim  if (SP->getFlags() & DINode::FlagStaticMember)
1968327952Sdim    return MethodKind::Static;
1969327952Sdim
1970303231Sdim  switch (SP->getVirtuality()) {
1971303231Sdim  case dwarf::DW_VIRTUALITY_none:
1972303231Sdim    break;
1973303231Sdim  case dwarf::DW_VIRTUALITY_virtual:
1974303231Sdim    return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1975303231Sdim  case dwarf::DW_VIRTUALITY_pure_virtual:
1976303231Sdim    return Introduced ? MethodKind::PureIntroducingVirtual
1977303231Sdim                      : MethodKind::PureVirtual;
1978303231Sdim  default:
1979303231Sdim    llvm_unreachable("unhandled virtuality case");
1980303231Sdim  }
1981303231Sdim
1982303231Sdim  return MethodKind::Vanilla;
1983303231Sdim}
1984303231Sdim
1985303231Sdimstatic TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1986303231Sdim  switch (Ty->getTag()) {
1987303231Sdim  case dwarf::DW_TAG_class_type:     return TypeRecordKind::Class;
1988303231Sdim  case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1989303231Sdim  }
1990303231Sdim  llvm_unreachable("unexpected tag");
1991303231Sdim}
1992303231Sdim
1993303231Sdim/// Return ClassOptions that should be present on both the forward declaration
1994303231Sdim/// and the defintion of a tag type.
1995303231Sdimstatic ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1996303231Sdim  ClassOptions CO = ClassOptions::None;
1997303231Sdim
1998303231Sdim  // MSVC always sets this flag, even for local types. Clang doesn't always
1999303231Sdim  // appear to give every type a linkage name, which may be problematic for us.
2000303231Sdim  // FIXME: Investigate the consequences of not following them here.
2001303231Sdim  if (!Ty->getIdentifier().empty())
2002303231Sdim    CO |= ClassOptions::HasUniqueName;
2003303231Sdim
2004303231Sdim  // Put the Nested flag on a type if it appears immediately inside a tag type.
2005303231Sdim  // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
2006303231Sdim  // here. That flag is only set on definitions, and not forward declarations.
2007353358Sdim  const DIScope *ImmediateScope = Ty->getScope();
2008303231Sdim  if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
2009303231Sdim    CO |= ClassOptions::Nested;
2010303231Sdim
2011344779Sdim  // Put the Scoped flag on function-local types. MSVC puts this flag for enum
2012344779Sdim  // type only when it has an immediate function scope. Clang never puts enums
2013344779Sdim  // inside DILexicalBlock scopes. Enum types, as generated by clang, are
2014344779Sdim  // always in function, class, or file scopes.
2015344779Sdim  if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
2016344779Sdim    if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
2017303231Sdim      CO |= ClassOptions::Scoped;
2018344779Sdim  } else {
2019344779Sdim    for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
2020353358Sdim         Scope = Scope->getScope()) {
2021344779Sdim      if (isa<DISubprogram>(Scope)) {
2022344779Sdim        CO |= ClassOptions::Scoped;
2023344779Sdim        break;
2024344779Sdim      }
2025303231Sdim    }
2026303231Sdim  }
2027303231Sdim
2028303231Sdim  return CO;
2029303231Sdim}
2030303231Sdim
2031341825Sdimvoid CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
2032341825Sdim  switch (Ty->getTag()) {
2033341825Sdim  case dwarf::DW_TAG_class_type:
2034341825Sdim  case dwarf::DW_TAG_structure_type:
2035341825Sdim  case dwarf::DW_TAG_union_type:
2036341825Sdim  case dwarf::DW_TAG_enumeration_type:
2037341825Sdim    break;
2038341825Sdim  default:
2039341825Sdim    return;
2040341825Sdim  }
2041341825Sdim
2042341825Sdim  if (const auto *File = Ty->getFile()) {
2043341825Sdim    StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
2044341825Sdim    TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
2045341825Sdim
2046341825Sdim    UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
2047341825Sdim    TypeTable.writeLeafType(USLR);
2048341825Sdim  }
2049341825Sdim}
2050341825Sdim
2051303231SdimTypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
2052303231Sdim  ClassOptions CO = getCommonClassOptions(Ty);
2053303231Sdim  TypeIndex FTI;
2054303231Sdim  unsigned EnumeratorCount = 0;
2055303231Sdim
2056303231Sdim  if (Ty->isForwardDecl()) {
2057303231Sdim    CO |= ClassOptions::ForwardReference;
2058303231Sdim  } else {
2059327952Sdim    ContinuationRecordBuilder ContinuationBuilder;
2060327952Sdim    ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
2061303231Sdim    for (const DINode *Element : Ty->getElements()) {
2062303231Sdim      // We assume that the frontend provides all members in source declaration
2063303231Sdim      // order, which is what MSVC does.
2064303231Sdim      if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
2065314564Sdim        EnumeratorRecord ER(MemberAccess::Public,
2066314564Sdim                            APSInt::getUnsigned(Enumerator->getValue()),
2067314564Sdim                            Enumerator->getName());
2068327952Sdim        ContinuationBuilder.writeMemberType(ER);
2069303231Sdim        EnumeratorCount++;
2070303231Sdim      }
2071303231Sdim    }
2072327952Sdim    FTI = TypeTable.insertRecord(ContinuationBuilder);
2073303231Sdim  }
2074303231Sdim
2075303231Sdim  std::string FullName = getFullyQualifiedName(Ty);
2076303231Sdim
2077314564Sdim  EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
2078314564Sdim                getTypeIndex(Ty->getBaseType()));
2079341825Sdim  TypeIndex EnumTI = TypeTable.writeLeafType(ER);
2080341825Sdim
2081341825Sdim  addUDTSrcLine(Ty, EnumTI);
2082341825Sdim
2083341825Sdim  return EnumTI;
2084303231Sdim}
2085303231Sdim
2086303231Sdim//===----------------------------------------------------------------------===//
2087303231Sdim// ClassInfo
2088303231Sdim//===----------------------------------------------------------------------===//
2089303231Sdim
2090303231Sdimstruct llvm::ClassInfo {
2091303231Sdim  struct MemberInfo {
2092303231Sdim    const DIDerivedType *MemberTypeNode;
2093303231Sdim    uint64_t BaseOffset;
2094303231Sdim  };
2095303231Sdim  // [MemberInfo]
2096321369Sdim  using MemberList = std::vector<MemberInfo>;
2097303231Sdim
2098321369Sdim  using MethodsList = TinyPtrVector<const DISubprogram *>;
2099303231Sdim  // MethodName -> MethodsList
2100321369Sdim  using MethodsMap = MapVector<MDString *, MethodsList>;
2101303231Sdim
2102303231Sdim  /// Base classes.
2103303231Sdim  std::vector<const DIDerivedType *> Inheritance;
2104303231Sdim
2105303231Sdim  /// Direct members.
2106303231Sdim  MemberList Members;
2107303231Sdim  // Direct overloaded methods gathered by name.
2108303231Sdim  MethodsMap Methods;
2109303231Sdim
2110314564Sdim  TypeIndex VShapeTI;
2111314564Sdim
2112327952Sdim  std::vector<const DIType *> NestedTypes;
2113303231Sdim};
2114303231Sdim
2115303231Sdimvoid CodeViewDebug::clear() {
2116303231Sdim  assert(CurFn == nullptr);
2117303231Sdim  FileIdMap.clear();
2118303231Sdim  FnDebugInfo.clear();
2119303231Sdim  FileToFilepathMap.clear();
2120303231Sdim  LocalUDTs.clear();
2121303231Sdim  GlobalUDTs.clear();
2122303231Sdim  TypeIndices.clear();
2123303231Sdim  CompleteTypeIndices.clear();
2124344779Sdim  ScopeGlobals.clear();
2125303231Sdim}
2126303231Sdim
2127303231Sdimvoid CodeViewDebug::collectMemberInfo(ClassInfo &Info,
2128303231Sdim                                      const DIDerivedType *DDTy) {
2129303231Sdim  if (!DDTy->getName().empty()) {
2130303231Sdim    Info.Members.push_back({DDTy, 0});
2131303231Sdim    return;
2132303231Sdim  }
2133341825Sdim
2134341825Sdim  // An unnamed member may represent a nested struct or union. Attempt to
2135341825Sdim  // interpret the unnamed member as a DICompositeType possibly wrapped in
2136341825Sdim  // qualifier types. Add all the indirect fields to the current record if that
2137341825Sdim  // succeeds, and drop the member if that fails.
2138303231Sdim  assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
2139303231Sdim  uint64_t Offset = DDTy->getOffsetInBits();
2140353358Sdim  const DIType *Ty = DDTy->getBaseType();
2141341825Sdim  bool FullyResolved = false;
2142341825Sdim  while (!FullyResolved) {
2143341825Sdim    switch (Ty->getTag()) {
2144341825Sdim    case dwarf::DW_TAG_const_type:
2145341825Sdim    case dwarf::DW_TAG_volatile_type:
2146341825Sdim      // FIXME: we should apply the qualifier types to the indirect fields
2147341825Sdim      // rather than dropping them.
2148353358Sdim      Ty = cast<DIDerivedType>(Ty)->getBaseType();
2149341825Sdim      break;
2150341825Sdim    default:
2151341825Sdim      FullyResolved = true;
2152341825Sdim      break;
2153341825Sdim    }
2154341825Sdim  }
2155341825Sdim
2156341825Sdim  const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
2157341825Sdim  if (!DCTy)
2158341825Sdim    return;
2159341825Sdim
2160303231Sdim  ClassInfo NestedInfo = collectClassInfo(DCTy);
2161303231Sdim  for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
2162303231Sdim    Info.Members.push_back(
2163303231Sdim        {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
2164303231Sdim}
2165303231Sdim
2166303231SdimClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
2167303231Sdim  ClassInfo Info;
2168303231Sdim  // Add elements to structure type.
2169303231Sdim  DINodeArray Elements = Ty->getElements();
2170303231Sdim  for (auto *Element : Elements) {
2171303231Sdim    // We assume that the frontend provides all members in source declaration
2172303231Sdim    // order, which is what MSVC does.
2173303231Sdim    if (!Element)
2174303231Sdim      continue;
2175303231Sdim    if (auto *SP = dyn_cast<DISubprogram>(Element)) {
2176303231Sdim      Info.Methods[SP->getRawName()].push_back(SP);
2177303231Sdim    } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
2178303231Sdim      if (DDTy->getTag() == dwarf::DW_TAG_member) {
2179303231Sdim        collectMemberInfo(Info, DDTy);
2180303231Sdim      } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
2181303231Sdim        Info.Inheritance.push_back(DDTy);
2182314564Sdim      } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
2183314564Sdim                 DDTy->getName() == "__vtbl_ptr_type") {
2184314564Sdim        Info.VShapeTI = getTypeIndex(DDTy);
2185327952Sdim      } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
2186327952Sdim        Info.NestedTypes.push_back(DDTy);
2187303231Sdim      } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
2188303231Sdim        // Ignore friend members. It appears that MSVC emitted info about
2189303231Sdim        // friends in the past, but modern versions do not.
2190303231Sdim      }
2191303231Sdim    } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
2192327952Sdim      Info.NestedTypes.push_back(Composite);
2193303231Sdim    }
2194303231Sdim    // Skip other unrecognized kinds of elements.
2195303231Sdim  }
2196303231Sdim  return Info;
2197303231Sdim}
2198303231Sdim
2199341825Sdimstatic bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) {
2200341825Sdim  // This routine is used by lowerTypeClass and lowerTypeUnion to determine
2201341825Sdim  // if a complete type should be emitted instead of a forward reference.
2202341825Sdim  return Ty->getName().empty() && Ty->getIdentifier().empty() &&
2203341825Sdim      !Ty->isForwardDecl();
2204341825Sdim}
2205341825Sdim
2206303231SdimTypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
2207341825Sdim  // Emit the complete type for unnamed structs.  C++ classes with methods
2208341825Sdim  // which have a circular reference back to the class type are expected to
2209341825Sdim  // be named by the front-end and should not be "unnamed".  C unnamed
2210341825Sdim  // structs should not have circular references.
2211341825Sdim  if (shouldAlwaysEmitCompleteClassType(Ty)) {
2212341825Sdim    // If this unnamed complete type is already in the process of being defined
2213341825Sdim    // then the description of the type is malformed and cannot be emitted
2214341825Sdim    // into CodeView correctly so report a fatal error.
2215341825Sdim    auto I = CompleteTypeIndices.find(Ty);
2216341825Sdim    if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
2217341825Sdim      report_fatal_error("cannot debug circular reference to unnamed type");
2218341825Sdim    return getCompleteTypeIndex(Ty);
2219341825Sdim  }
2220341825Sdim
2221303231Sdim  // First, construct the forward decl.  Don't look into Ty to compute the
2222303231Sdim  // forward decl options, since it might not be available in all TUs.
2223303231Sdim  TypeRecordKind Kind = getRecordKind(Ty);
2224303231Sdim  ClassOptions CO =
2225303231Sdim      ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2226303231Sdim  std::string FullName = getFullyQualifiedName(Ty);
2227314564Sdim  ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
2228314564Sdim                 FullName, Ty->getIdentifier());
2229327952Sdim  TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
2230303231Sdim  if (!Ty->isForwardDecl())
2231303231Sdim    DeferredCompleteTypes.push_back(Ty);
2232303231Sdim  return FwdDeclTI;
2233303231Sdim}
2234303231Sdim
2235303231SdimTypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
2236303231Sdim  // Construct the field list and complete type record.
2237303231Sdim  TypeRecordKind Kind = getRecordKind(Ty);
2238303231Sdim  ClassOptions CO = getCommonClassOptions(Ty);
2239303231Sdim  TypeIndex FieldTI;
2240303231Sdim  TypeIndex VShapeTI;
2241303231Sdim  unsigned FieldCount;
2242303231Sdim  bool ContainsNestedClass;
2243303231Sdim  std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
2244303231Sdim      lowerRecordFieldList(Ty);
2245303231Sdim
2246303231Sdim  if (ContainsNestedClass)
2247303231Sdim    CO |= ClassOptions::ContainsNestedClass;
2248303231Sdim
2249353358Sdim  // MSVC appears to set this flag by searching any destructor or method with
2250353358Sdim  // FunctionOptions::Constructor among the emitted members. Clang AST has all
2251353358Sdim  // the members, however special member functions are not yet emitted into
2252353358Sdim  // debug information. For now checking a class's non-triviality seems enough.
2253353358Sdim  // FIXME: not true for a nested unnamed struct.
2254353358Sdim  if (isNonTrivial(Ty))
2255353358Sdim    CO |= ClassOptions::HasConstructorOrDestructor;
2256353358Sdim
2257303231Sdim  std::string FullName = getFullyQualifiedName(Ty);
2258303231Sdim
2259303231Sdim  uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2260303231Sdim
2261314564Sdim  ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
2262314564Sdim                 SizeInBytes, FullName, Ty->getIdentifier());
2263327952Sdim  TypeIndex ClassTI = TypeTable.writeLeafType(CR);
2264303231Sdim
2265341825Sdim  addUDTSrcLine(Ty, ClassTI);
2266327952Sdim
2267327952Sdim  addToUDTs(Ty);
2268303231Sdim
2269303231Sdim  return ClassTI;
2270303231Sdim}
2271303231Sdim
2272303231SdimTypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
2273341825Sdim  // Emit the complete type for unnamed unions.
2274341825Sdim  if (shouldAlwaysEmitCompleteClassType(Ty))
2275341825Sdim    return getCompleteTypeIndex(Ty);
2276341825Sdim
2277303231Sdim  ClassOptions CO =
2278303231Sdim      ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2279303231Sdim  std::string FullName = getFullyQualifiedName(Ty);
2280314564Sdim  UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
2281327952Sdim  TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
2282303231Sdim  if (!Ty->isForwardDecl())
2283303231Sdim    DeferredCompleteTypes.push_back(Ty);
2284303231Sdim  return FwdDeclTI;
2285303231Sdim}
2286303231Sdim
2287303231SdimTypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
2288303231Sdim  ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
2289303231Sdim  TypeIndex FieldTI;
2290303231Sdim  unsigned FieldCount;
2291303231Sdim  bool ContainsNestedClass;
2292303231Sdim  std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
2293303231Sdim      lowerRecordFieldList(Ty);
2294303231Sdim
2295303231Sdim  if (ContainsNestedClass)
2296303231Sdim    CO |= ClassOptions::ContainsNestedClass;
2297303231Sdim
2298303231Sdim  uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2299303231Sdim  std::string FullName = getFullyQualifiedName(Ty);
2300303231Sdim
2301314564Sdim  UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
2302314564Sdim                 Ty->getIdentifier());
2303327952Sdim  TypeIndex UnionTI = TypeTable.writeLeafType(UR);
2304303231Sdim
2305341825Sdim  addUDTSrcLine(Ty, UnionTI);
2306327952Sdim
2307327952Sdim  addToUDTs(Ty);
2308303231Sdim
2309303231Sdim  return UnionTI;
2310303231Sdim}
2311303231Sdim
2312303231Sdimstd::tuple<TypeIndex, TypeIndex, unsigned, bool>
2313303231SdimCodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
2314303231Sdim  // Manually count members. MSVC appears to count everything that generates a
2315303231Sdim  // field list record. Each individual overload in a method overload group
2316303231Sdim  // contributes to this count, even though the overload group is a single field
2317303231Sdim  // list record.
2318303231Sdim  unsigned MemberCount = 0;
2319303231Sdim  ClassInfo Info = collectClassInfo(Ty);
2320327952Sdim  ContinuationRecordBuilder ContinuationBuilder;
2321327952Sdim  ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
2322303231Sdim
2323303231Sdim  // Create base classes.
2324303231Sdim  for (const DIDerivedType *I : Info.Inheritance) {
2325303231Sdim    if (I->getFlags() & DINode::FlagVirtual) {
2326303231Sdim      // Virtual base.
2327341825Sdim      unsigned VBPtrOffset = I->getVBPtrOffset();
2328303231Sdim      // FIXME: Despite the accessor name, the offset is really in bytes.
2329303231Sdim      unsigned VBTableIndex = I->getOffsetInBits() / 4;
2330314564Sdim      auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
2331314564Sdim                            ? TypeRecordKind::IndirectVirtualBaseClass
2332314564Sdim                            : TypeRecordKind::VirtualBaseClass;
2333314564Sdim      VirtualBaseClassRecord VBCR(
2334314564Sdim          RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
2335303231Sdim          getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
2336314564Sdim          VBTableIndex);
2337314564Sdim
2338327952Sdim      ContinuationBuilder.writeMemberType(VBCR);
2339341825Sdim      MemberCount++;
2340303231Sdim    } else {
2341303231Sdim      assert(I->getOffsetInBits() % 8 == 0 &&
2342303231Sdim             "bases must be on byte boundaries");
2343314564Sdim      BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
2344314564Sdim                          getTypeIndex(I->getBaseType()),
2345314564Sdim                          I->getOffsetInBits() / 8);
2346327952Sdim      ContinuationBuilder.writeMemberType(BCR);
2347341825Sdim      MemberCount++;
2348303231Sdim    }
2349303231Sdim  }
2350303231Sdim
2351303231Sdim  // Create members.
2352303231Sdim  for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
2353303231Sdim    const DIDerivedType *Member = MemberInfo.MemberTypeNode;
2354303231Sdim    TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
2355303231Sdim    StringRef MemberName = Member->getName();
2356303231Sdim    MemberAccess Access =
2357303231Sdim        translateAccessFlags(Ty->getTag(), Member->getFlags());
2358303231Sdim
2359303231Sdim    if (Member->isStaticMember()) {
2360314564Sdim      StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
2361327952Sdim      ContinuationBuilder.writeMemberType(SDMR);
2362303231Sdim      MemberCount++;
2363303231Sdim      continue;
2364303231Sdim    }
2365303231Sdim
2366314564Sdim    // Virtual function pointer member.
2367314564Sdim    if ((Member->getFlags() & DINode::FlagArtificial) &&
2368314564Sdim        Member->getName().startswith("_vptr$")) {
2369314564Sdim      VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
2370327952Sdim      ContinuationBuilder.writeMemberType(VFPR);
2371314564Sdim      MemberCount++;
2372314564Sdim      continue;
2373314564Sdim    }
2374314564Sdim
2375303231Sdim    // Data member.
2376303231Sdim    uint64_t MemberOffsetInBits =
2377303231Sdim        Member->getOffsetInBits() + MemberInfo.BaseOffset;
2378303231Sdim    if (Member->isBitField()) {
2379303231Sdim      uint64_t StartBitOffset = MemberOffsetInBits;
2380303231Sdim      if (const auto *CI =
2381303231Sdim              dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
2382303231Sdim        MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
2383303231Sdim      }
2384303231Sdim      StartBitOffset -= MemberOffsetInBits;
2385314564Sdim      BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2386314564Sdim                         StartBitOffset);
2387327952Sdim      MemberBaseType = TypeTable.writeLeafType(BFR);
2388303231Sdim    }
2389303231Sdim    uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
2390314564Sdim    DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2391314564Sdim                         MemberName);
2392327952Sdim    ContinuationBuilder.writeMemberType(DMR);
2393303231Sdim    MemberCount++;
2394303231Sdim  }
2395303231Sdim
2396303231Sdim  // Create methods
2397303231Sdim  for (auto &MethodItr : Info.Methods) {
2398303231Sdim    StringRef Name = MethodItr.first->getString();
2399303231Sdim
2400303231Sdim    std::vector<OneMethodRecord> Methods;
2401303231Sdim    for (const DISubprogram *SP : MethodItr.second) {
2402303231Sdim      TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2403303231Sdim      bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
2404303231Sdim
2405303231Sdim      unsigned VFTableOffset = -1;
2406303231Sdim      if (Introduced)
2407303231Sdim        VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2408303231Sdim
2409314564Sdim      Methods.push_back(OneMethodRecord(
2410314564Sdim          MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
2411314564Sdim          translateMethodKindFlags(SP, Introduced),
2412314564Sdim          translateMethodOptionFlags(SP), VFTableOffset, Name));
2413303231Sdim      MemberCount++;
2414303231Sdim    }
2415321369Sdim    assert(!Methods.empty() && "Empty methods map entry");
2416303231Sdim    if (Methods.size() == 1)
2417327952Sdim      ContinuationBuilder.writeMemberType(Methods[0]);
2418303231Sdim    else {
2419327952Sdim      // FIXME: Make this use its own ContinuationBuilder so that
2420327952Sdim      // MethodOverloadList can be split correctly.
2421314564Sdim      MethodOverloadListRecord MOLR(Methods);
2422327952Sdim      TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
2423327952Sdim
2424314564Sdim      OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
2425327952Sdim      ContinuationBuilder.writeMemberType(OMR);
2426303231Sdim    }
2427303231Sdim  }
2428303231Sdim
2429303231Sdim  // Create nested classes.
2430327952Sdim  for (const DIType *Nested : Info.NestedTypes) {
2431353358Sdim    NestedTypeRecord R(getTypeIndex(Nested), Nested->getName());
2432327952Sdim    ContinuationBuilder.writeMemberType(R);
2433303231Sdim    MemberCount++;
2434303231Sdim  }
2435303231Sdim
2436327952Sdim  TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
2437314564Sdim  return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
2438327952Sdim                         !Info.NestedTypes.empty());
2439303231Sdim}
2440303231Sdim
2441303231SdimTypeIndex CodeViewDebug::getVBPTypeIndex() {
2442303231Sdim  if (!VBPType.getIndex()) {
2443303231Sdim    // Make a 'const int *' type.
2444303231Sdim    ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
2445327952Sdim    TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
2446303231Sdim
2447303231Sdim    PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2448303231Sdim                                                  : PointerKind::Near32;
2449303231Sdim    PointerMode PM = PointerMode::Pointer;
2450303231Sdim    PointerOptions PO = PointerOptions::None;
2451303231Sdim    PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
2452327952Sdim    VBPType = TypeTable.writeLeafType(PR);
2453303231Sdim  }
2454303231Sdim
2455303231Sdim  return VBPType;
2456303231Sdim}
2457303231Sdim
2458353358SdimTypeIndex CodeViewDebug::getTypeIndex(const DIType *Ty, const DIType *ClassTy) {
2459303231Sdim  // The null DIType is the void type. Don't try to hash it.
2460303231Sdim  if (!Ty)
2461303231Sdim    return TypeIndex::Void();
2462303231Sdim
2463303231Sdim  // Check if we've already translated this type. Don't try to do a
2464303231Sdim  // get-or-create style insertion that caches the hash lookup across the
2465303231Sdim  // lowerType call. It will update the TypeIndices map.
2466303231Sdim  auto I = TypeIndices.find({Ty, ClassTy});
2467303231Sdim  if (I != TypeIndices.end())
2468303231Sdim    return I->second;
2469303231Sdim
2470303231Sdim  TypeLoweringScope S(*this);
2471303231Sdim  TypeIndex TI = lowerType(Ty, ClassTy);
2472303231Sdim  return recordTypeIndexForDINode(Ty, TI, ClassTy);
2473303231Sdim}
2474303231Sdim
2475344779Sdimcodeview::TypeIndex
2476344779SdimCodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy,
2477344779Sdim                                      const DISubroutineType *SubroutineTy) {
2478344779Sdim  assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type &&
2479344779Sdim         "this type must be a pointer type");
2480344779Sdim
2481344779Sdim  PointerOptions Options = PointerOptions::None;
2482344779Sdim  if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference)
2483344779Sdim    Options = PointerOptions::LValueRefThisPointer;
2484344779Sdim  else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference)
2485344779Sdim    Options = PointerOptions::RValueRefThisPointer;
2486344779Sdim
2487344779Sdim  // Check if we've already translated this type.  If there is no ref qualifier
2488344779Sdim  // on the function then we look up this pointer type with no associated class
2489344779Sdim  // so that the TypeIndex for the this pointer can be shared with the type
2490344779Sdim  // index for other pointers to this class type.  If there is a ref qualifier
2491344779Sdim  // then we lookup the pointer using the subroutine as the parent type.
2492344779Sdim  auto I = TypeIndices.find({PtrTy, SubroutineTy});
2493344779Sdim  if (I != TypeIndices.end())
2494344779Sdim    return I->second;
2495344779Sdim
2496344779Sdim  TypeLoweringScope S(*this);
2497344779Sdim  TypeIndex TI = lowerTypePointer(PtrTy, Options);
2498344779Sdim  return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy);
2499344779Sdim}
2500344779Sdim
2501353358SdimTypeIndex CodeViewDebug::getTypeIndexForReferenceTo(const DIType *Ty) {
2502327952Sdim  PointerRecord PR(getTypeIndex(Ty),
2503327952Sdim                   getPointerSizeInBytes() == 8 ? PointerKind::Near64
2504327952Sdim                                                : PointerKind::Near32,
2505327952Sdim                   PointerMode::LValueReference, PointerOptions::None,
2506327952Sdim                   Ty->getSizeInBits() / 8);
2507327952Sdim  return TypeTable.writeLeafType(PR);
2508327952Sdim}
2509327952Sdim
2510353358SdimTypeIndex CodeViewDebug::getCompleteTypeIndex(const DIType *Ty) {
2511303231Sdim  // The null DIType is the void type. Don't try to hash it.
2512303231Sdim  if (!Ty)
2513303231Sdim    return TypeIndex::Void();
2514303231Sdim
2515344779Sdim  // Look through typedefs when getting the complete type index. Call
2516344779Sdim  // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are
2517344779Sdim  // emitted only once.
2518344779Sdim  if (Ty->getTag() == dwarf::DW_TAG_typedef)
2519344779Sdim    (void)getTypeIndex(Ty);
2520344779Sdim  while (Ty->getTag() == dwarf::DW_TAG_typedef)
2521353358Sdim    Ty = cast<DIDerivedType>(Ty)->getBaseType();
2522344779Sdim
2523303231Sdim  // If this is a non-record type, the complete type index is the same as the
2524303231Sdim  // normal type index. Just call getTypeIndex.
2525303231Sdim  switch (Ty->getTag()) {
2526303231Sdim  case dwarf::DW_TAG_class_type:
2527303231Sdim  case dwarf::DW_TAG_structure_type:
2528303231Sdim  case dwarf::DW_TAG_union_type:
2529303231Sdim    break;
2530303231Sdim  default:
2531303231Sdim    return getTypeIndex(Ty);
2532303231Sdim  }
2533303231Sdim
2534303231Sdim  const auto *CTy = cast<DICompositeType>(Ty);
2535303231Sdim
2536303231Sdim  TypeLoweringScope S(*this);
2537303231Sdim
2538303231Sdim  // Make sure the forward declaration is emitted first. It's unclear if this
2539303231Sdim  // is necessary, but MSVC does it, and we should follow suit until we can show
2540303231Sdim  // otherwise.
2541341825Sdim  // We only emit a forward declaration for named types.
2542341825Sdim  if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
2543341825Sdim    TypeIndex FwdDeclTI = getTypeIndex(CTy);
2544303231Sdim
2545341825Sdim    // Just use the forward decl if we don't have complete type info. This
2546341825Sdim    // might happen if the frontend is using modules and expects the complete
2547341825Sdim    // definition to be emitted elsewhere.
2548341825Sdim    if (CTy->isForwardDecl())
2549341825Sdim      return FwdDeclTI;
2550341825Sdim  }
2551303231Sdim
2552353358Sdim  // Check if we've already translated the complete record type.
2553353358Sdim  // Insert the type with a null TypeIndex to signify that the type is currently
2554353358Sdim  // being lowered.
2555353358Sdim  auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
2556353358Sdim  if (!InsertResult.second)
2557353358Sdim    return InsertResult.first->second;
2558353358Sdim
2559303231Sdim  TypeIndex TI;
2560303231Sdim  switch (CTy->getTag()) {
2561303231Sdim  case dwarf::DW_TAG_class_type:
2562303231Sdim  case dwarf::DW_TAG_structure_type:
2563303231Sdim    TI = lowerCompleteTypeClass(CTy);
2564303231Sdim    break;
2565303231Sdim  case dwarf::DW_TAG_union_type:
2566303231Sdim    TI = lowerCompleteTypeUnion(CTy);
2567303231Sdim    break;
2568303231Sdim  default:
2569303231Sdim    llvm_unreachable("not a record");
2570303231Sdim  }
2571303231Sdim
2572341825Sdim  // Update the type index associated with this CompositeType.  This cannot
2573341825Sdim  // use the 'InsertResult' iterator above because it is potentially
2574341825Sdim  // invalidated by map insertions which can occur while lowering the class
2575341825Sdim  // type above.
2576341825Sdim  CompleteTypeIndices[CTy] = TI;
2577303231Sdim  return TI;
2578303231Sdim}
2579303231Sdim
2580303231Sdim/// Emit all the deferred complete record types. Try to do this in FIFO order,
2581303231Sdim/// and do this until fixpoint, as each complete record type typically
2582303231Sdim/// references
2583303231Sdim/// many other record types.
2584303231Sdimvoid CodeViewDebug::emitDeferredCompleteTypes() {
2585303231Sdim  SmallVector<const DICompositeType *, 4> TypesToEmit;
2586303231Sdim  while (!DeferredCompleteTypes.empty()) {
2587303231Sdim    std::swap(DeferredCompleteTypes, TypesToEmit);
2588303231Sdim    for (const DICompositeType *RecordTy : TypesToEmit)
2589303231Sdim      getCompleteTypeIndex(RecordTy);
2590303231Sdim    TypesToEmit.clear();
2591303231Sdim  }
2592303231Sdim}
2593303231Sdim
2594344779Sdimvoid CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
2595344779Sdim                                          ArrayRef<LocalVariable> Locals) {
2596303231Sdim  // Get the sorted list of parameters and emit them first.
2597303231Sdim  SmallVector<const LocalVariable *, 6> Params;
2598303231Sdim  for (const LocalVariable &L : Locals)
2599303231Sdim    if (L.DIVar->isParameter())
2600303231Sdim      Params.push_back(&L);
2601344779Sdim  llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
2602344779Sdim    return L->DIVar->getArg() < R->DIVar->getArg();
2603344779Sdim  });
2604303231Sdim  for (const LocalVariable *L : Params)
2605344779Sdim    emitLocalVariable(FI, *L);
2606303231Sdim
2607303231Sdim  // Next emit all non-parameters in the order that we found them.
2608303231Sdim  for (const LocalVariable &L : Locals)
2609303231Sdim    if (!L.DIVar->isParameter())
2610344779Sdim      emitLocalVariable(FI, L);
2611303231Sdim}
2612303231Sdim
2613344779Sdimvoid CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
2614344779Sdim                                      const LocalVariable &Var) {
2615303231Sdim  // LocalSym record, see SymbolRecord.h for more info.
2616344779Sdim  MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL);
2617303231Sdim
2618303231Sdim  LocalSymFlags Flags = LocalSymFlags::None;
2619303231Sdim  if (Var.DIVar->isParameter())
2620303231Sdim    Flags |= LocalSymFlags::IsParameter;
2621303231Sdim  if (Var.DefRanges.empty())
2622303231Sdim    Flags |= LocalSymFlags::IsOptimizedOut;
2623303231Sdim
2624303231Sdim  OS.AddComment("TypeIndex");
2625327952Sdim  TypeIndex TI = Var.UseReferenceType
2626327952Sdim                     ? getTypeIndexForReferenceTo(Var.DIVar->getType())
2627327952Sdim                     : getCompleteTypeIndex(Var.DIVar->getType());
2628303231Sdim  OS.EmitIntValue(TI.getIndex(), 4);
2629303231Sdim  OS.AddComment("Flags");
2630303231Sdim  OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
2631303231Sdim  // Truncate the name so we won't overflow the record length field.
2632303231Sdim  emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
2633344779Sdim  endSymbolRecord(LocalEnd);
2634303231Sdim
2635303231Sdim  // Calculate the on disk prefix of the appropriate def range record. The
2636303231Sdim  // records and on disk formats are described in SymbolRecords.h. BytePrefix
2637303231Sdim  // should be big enough to hold all forms without memory allocation.
2638303231Sdim  SmallString<20> BytePrefix;
2639303231Sdim  for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2640303231Sdim    BytePrefix.clear();
2641303231Sdim    if (DefRange.InMemory) {
2642344779Sdim      int Offset = DefRange.DataOffset;
2643344779Sdim      unsigned Reg = DefRange.CVRegister;
2644344779Sdim
2645344779Sdim      // 32-bit x86 call sequences often use PUSH instructions, which disrupt
2646344779Sdim      // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
2647344779Sdim      // instead. In frames without stack realignment, $T0 will be the CFA.
2648344779Sdim      if (RegisterId(Reg) == RegisterId::ESP) {
2649344779Sdim        Reg = unsigned(RegisterId::VFRAME);
2650344779Sdim        Offset += FI.OffsetAdjustment;
2651314564Sdim      }
2652344779Sdim
2653344779Sdim      // If we can use the chosen frame pointer for the frame and this isn't a
2654344779Sdim      // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
2655344779Sdim      // Otherwise, use S_DEFRANGE_REGISTER_REL.
2656344779Sdim      EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU);
2657344779Sdim      if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
2658344779Sdim          (bool(Flags & LocalSymFlags::IsParameter)
2659344779Sdim               ? (EncFP == FI.EncodedParamFramePtrReg)
2660344779Sdim               : (EncFP == FI.EncodedLocalFramePtrReg))) {
2661360784Sdim        DefRangeFramePointerRelHeader DRHdr;
2662360784Sdim        DRHdr.Offset = Offset;
2663360784Sdim        OS.EmitCVDefRangeDirective(DefRange.Ranges, DRHdr);
2664344779Sdim      } else {
2665344779Sdim        uint16_t RegRelFlags = 0;
2666344779Sdim        if (DefRange.IsSubfield) {
2667344779Sdim          RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2668344779Sdim                        (DefRange.StructOffset
2669344779Sdim                         << DefRangeRegisterRelSym::OffsetInParentShift);
2670344779Sdim        }
2671360784Sdim        DefRangeRegisterRelHeader DRHdr;
2672344779Sdim        DRHdr.Register = Reg;
2673344779Sdim        DRHdr.Flags = RegRelFlags;
2674344779Sdim        DRHdr.BasePointerOffset = Offset;
2675360784Sdim        OS.EmitCVDefRangeDirective(DefRange.Ranges, DRHdr);
2676344779Sdim      }
2677303231Sdim    } else {
2678303231Sdim      assert(DefRange.DataOffset == 0 && "unexpected offset into register");
2679314564Sdim      if (DefRange.IsSubfield) {
2680360784Sdim        DefRangeSubfieldRegisterHeader DRHdr;
2681344779Sdim        DRHdr.Register = DefRange.CVRegister;
2682344779Sdim        DRHdr.MayHaveNoName = 0;
2683344779Sdim        DRHdr.OffsetInParent = DefRange.StructOffset;
2684360784Sdim        OS.EmitCVDefRangeDirective(DefRange.Ranges, DRHdr);
2685314564Sdim      } else {
2686360784Sdim        DefRangeRegisterHeader DRHdr;
2687344779Sdim        DRHdr.Register = DefRange.CVRegister;
2688344779Sdim        DRHdr.MayHaveNoName = 0;
2689360784Sdim        OS.EmitCVDefRangeDirective(DefRange.Ranges, DRHdr);
2690314564Sdim      }
2691303231Sdim    }
2692303231Sdim  }
2693303231Sdim}
2694303231Sdim
2695341825Sdimvoid CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
2696341825Sdim                                         const FunctionInfo& FI) {
2697341825Sdim  for (LexicalBlock *Block : Blocks)
2698341825Sdim    emitLexicalBlock(*Block, FI);
2699341825Sdim}
2700341825Sdim
2701341825Sdim/// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
2702341825Sdim/// lexical block scope.
2703341825Sdimvoid CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
2704341825Sdim                                     const FunctionInfo& FI) {
2705344779Sdim  MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32);
2706341825Sdim  OS.AddComment("PtrParent");
2707341825Sdim  OS.EmitIntValue(0, 4);                                  // PtrParent
2708341825Sdim  OS.AddComment("PtrEnd");
2709341825Sdim  OS.EmitIntValue(0, 4);                                  // PtrEnd
2710341825Sdim  OS.AddComment("Code size");
2711341825Sdim  OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4);   // Code Size
2712341825Sdim  OS.AddComment("Function section relative address");
2713341825Sdim  OS.EmitCOFFSecRel32(Block.Begin, /*Offset=*/0);         // Func Offset
2714341825Sdim  OS.AddComment("Function section index");
2715341825Sdim  OS.EmitCOFFSectionIndex(FI.Begin);                      // Func Symbol
2716341825Sdim  OS.AddComment("Lexical block name");
2717341825Sdim  emitNullTerminatedSymbolName(OS, Block.Name);           // Name
2718344779Sdim  endSymbolRecord(RecordEnd);
2719341825Sdim
2720341825Sdim  // Emit variables local to this lexical block.
2721344779Sdim  emitLocalVariableList(FI, Block.Locals);
2722344779Sdim  emitGlobalVariableList(Block.Globals);
2723341825Sdim
2724341825Sdim  // Emit lexical blocks contained within this block.
2725341825Sdim  emitLexicalBlockList(Block.Children, FI);
2726341825Sdim
2727341825Sdim  // Close the lexical block scope.
2728344779Sdim  emitEndSymbolRecord(SymbolKind::S_END);
2729341825Sdim}
2730341825Sdim
2731341825Sdim/// Convenience routine for collecting lexical block information for a list
2732341825Sdim/// of lexical scopes.
2733341825Sdimvoid CodeViewDebug::collectLexicalBlockInfo(
2734341825Sdim        SmallVectorImpl<LexicalScope *> &Scopes,
2735341825Sdim        SmallVectorImpl<LexicalBlock *> &Blocks,
2736344779Sdim        SmallVectorImpl<LocalVariable> &Locals,
2737344779Sdim        SmallVectorImpl<CVGlobalVariable> &Globals) {
2738341825Sdim  for (LexicalScope *Scope : Scopes)
2739344779Sdim    collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals);
2740341825Sdim}
2741341825Sdim
2742341825Sdim/// Populate the lexical blocks and local variable lists of the parent with
2743341825Sdim/// information about the specified lexical scope.
2744341825Sdimvoid CodeViewDebug::collectLexicalBlockInfo(
2745341825Sdim    LexicalScope &Scope,
2746341825Sdim    SmallVectorImpl<LexicalBlock *> &ParentBlocks,
2747344779Sdim    SmallVectorImpl<LocalVariable> &ParentLocals,
2748344779Sdim    SmallVectorImpl<CVGlobalVariable> &ParentGlobals) {
2749341825Sdim  if (Scope.isAbstractScope())
2750341825Sdim    return;
2751341825Sdim
2752344779Sdim  // Gather information about the lexical scope including local variables,
2753344779Sdim  // global variables, and address ranges.
2754344779Sdim  bool IgnoreScope = false;
2755344779Sdim  auto LI = ScopeVariables.find(&Scope);
2756344779Sdim  SmallVectorImpl<LocalVariable> *Locals =
2757344779Sdim      LI != ScopeVariables.end() ? &LI->second : nullptr;
2758344779Sdim  auto GI = ScopeGlobals.find(Scope.getScopeNode());
2759344779Sdim  SmallVectorImpl<CVGlobalVariable> *Globals =
2760344779Sdim      GI != ScopeGlobals.end() ? GI->second.get() : nullptr;
2761341825Sdim  const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
2762344779Sdim  const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
2763341825Sdim
2764344779Sdim  // Ignore lexical scopes which do not contain variables.
2765344779Sdim  if (!Locals && !Globals)
2766344779Sdim    IgnoreScope = true;
2767344779Sdim
2768344779Sdim  // Ignore lexical scopes which are not lexical blocks.
2769344779Sdim  if (!DILB)
2770344779Sdim    IgnoreScope = true;
2771344779Sdim
2772344779Sdim  // Ignore scopes which have too many address ranges to represent in the
2773344779Sdim  // current CodeView format or do not have a valid address range.
2774344779Sdim  //
2775344779Sdim  // For lexical scopes with multiple address ranges you may be tempted to
2776344779Sdim  // construct a single range covering every instruction where the block is
2777344779Sdim  // live and everything in between.  Unfortunately, Visual Studio only
2778344779Sdim  // displays variables from the first matching lexical block scope.  If the
2779344779Sdim  // first lexical block contains exception handling code or cold code which
2780344779Sdim  // is moved to the bottom of the routine creating a single range covering
2781344779Sdim  // nearly the entire routine, then it will hide all other lexical blocks
2782344779Sdim  // and the variables they contain.
2783344779Sdim  if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second))
2784344779Sdim    IgnoreScope = true;
2785344779Sdim
2786344779Sdim  if (IgnoreScope) {
2787344779Sdim    // This scope can be safely ignored and eliminating it will reduce the
2788344779Sdim    // size of the debug information. Be sure to collect any variable and scope
2789344779Sdim    // information from the this scope or any of its children and collapse them
2790344779Sdim    // into the parent scope.
2791344779Sdim    if (Locals)
2792344779Sdim      ParentLocals.append(Locals->begin(), Locals->end());
2793344779Sdim    if (Globals)
2794344779Sdim      ParentGlobals.append(Globals->begin(), Globals->end());
2795344779Sdim    collectLexicalBlockInfo(Scope.getChildren(),
2796344779Sdim                            ParentBlocks,
2797344779Sdim                            ParentLocals,
2798344779Sdim                            ParentGlobals);
2799341825Sdim    return;
2800341825Sdim  }
2801341825Sdim
2802341825Sdim  // Create a new CodeView lexical block for this lexical scope.  If we've
2803341825Sdim  // seen this DILexicalBlock before then the scope tree is malformed and
2804341825Sdim  // we can handle this gracefully by not processing it a second time.
2805341825Sdim  auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
2806341825Sdim  if (!BlockInsertion.second)
2807341825Sdim    return;
2808341825Sdim
2809344779Sdim  // Create a lexical block containing the variables and collect the the
2810344779Sdim  // lexical block information for the children.
2811341825Sdim  const InsnRange &Range = Ranges.front();
2812341825Sdim  assert(Range.first && Range.second);
2813341825Sdim  LexicalBlock &Block = BlockInsertion.first->second;
2814341825Sdim  Block.Begin = getLabelBeforeInsn(Range.first);
2815341825Sdim  Block.End = getLabelAfterInsn(Range.second);
2816341825Sdim  assert(Block.Begin && "missing label for scope begin");
2817341825Sdim  assert(Block.End && "missing label for scope end");
2818341825Sdim  Block.Name = DILB->getName();
2819344779Sdim  if (Locals)
2820344779Sdim    Block.Locals = std::move(*Locals);
2821344779Sdim  if (Globals)
2822344779Sdim    Block.Globals = std::move(*Globals);
2823341825Sdim  ParentBlocks.push_back(&Block);
2824344779Sdim  collectLexicalBlockInfo(Scope.getChildren(),
2825344779Sdim                          Block.Children,
2826344779Sdim                          Block.Locals,
2827344779Sdim                          Block.Globals);
2828341825Sdim}
2829341825Sdim
2830321369Sdimvoid CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
2831327952Sdim  const Function &GV = MF->getFunction();
2832327952Sdim  assert(FnDebugInfo.count(&GV));
2833341825Sdim  assert(CurFn == FnDebugInfo[&GV].get());
2834303231Sdim
2835327952Sdim  collectVariableInfo(GV.getSubprogram());
2836303231Sdim
2837341825Sdim  // Build the lexical block structure to emit for this routine.
2838341825Sdim  if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
2839344779Sdim    collectLexicalBlockInfo(*CFS,
2840344779Sdim                            CurFn->ChildBlocks,
2841344779Sdim                            CurFn->Locals,
2842344779Sdim                            CurFn->Globals);
2843341825Sdim
2844341825Sdim  // Clear the scope and variable information from the map which will not be
2845341825Sdim  // valid after we have finished processing this routine.  This also prepares
2846341825Sdim  // the map for the subsequent routine.
2847341825Sdim  ScopeVariables.clear();
2848341825Sdim
2849303231Sdim  // Don't emit anything if we don't have any line tables.
2850341825Sdim  // Thunks are compiler-generated and probably won't have source correlation.
2851341825Sdim  if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
2852327952Sdim    FnDebugInfo.erase(&GV);
2853303231Sdim    CurFn = nullptr;
2854303231Sdim    return;
2855303231Sdim  }
2856303231Sdim
2857360661Sdim  // Find heap alloc sites and add to list.
2858360661Sdim  for (const auto &MBB : *MF) {
2859360661Sdim    for (const auto &MI : MBB) {
2860360661Sdim      if (MDNode *MD = MI.getHeapAllocMarker()) {
2861360661Sdim        CurFn->HeapAllocSites.push_back(std::make_tuple(getLabelBeforeInsn(&MI),
2862360661Sdim                                                        getLabelAfterInsn(&MI),
2863360661Sdim                                                        dyn_cast<DIType>(MD)));
2864360661Sdim      }
2865360661Sdim    }
2866360661Sdim  }
2867360661Sdim
2868327952Sdim  CurFn->Annotations = MF->getCodeViewAnnotations();
2869327952Sdim
2870303231Sdim  CurFn->End = Asm->getFunctionEnd();
2871303231Sdim
2872303231Sdim  CurFn = nullptr;
2873303231Sdim}
2874303231Sdim
2875360784Sdim// Usable locations are valid with non-zero line numbers. A line number of zero
2876360784Sdim// corresponds to optimized code that doesn't have a distinct source location.
2877360784Sdim// In this case, we try to use the previous or next source location depending on
2878360784Sdim// the context.
2879360784Sdimstatic bool isUsableDebugLoc(DebugLoc DL) {
2880360784Sdim  return DL && DL.getLine() != 0;
2881360784Sdim}
2882360784Sdim
2883303231Sdimvoid CodeViewDebug::beginInstruction(const MachineInstr *MI) {
2884303231Sdim  DebugHandlerBase::beginInstruction(MI);
2885303231Sdim
2886341825Sdim  // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
2887341825Sdim  if (!Asm || !CurFn || MI->isDebugInstr() ||
2888304310Sdim      MI->getFlag(MachineInstr::FrameSetup))
2889303231Sdim    return;
2890321369Sdim
2891321369Sdim  // If the first instruction of a new MBB has no location, find the first
2892321369Sdim  // instruction with a location and use that.
2893303231Sdim  DebugLoc DL = MI->getDebugLoc();
2894360784Sdim  if (!isUsableDebugLoc(DL) && MI->getParent() != PrevInstBB) {
2895321369Sdim    for (const auto &NextMI : *MI->getParent()) {
2896341825Sdim      if (NextMI.isDebugInstr())
2897327952Sdim        continue;
2898321369Sdim      DL = NextMI.getDebugLoc();
2899360784Sdim      if (isUsableDebugLoc(DL))
2900321369Sdim        break;
2901321369Sdim    }
2902360784Sdim    // FIXME: Handle the case where the BB has no valid locations. This would
2903360784Sdim    // probably require doing a real dataflow analysis.
2904321369Sdim  }
2905321369Sdim  PrevInstBB = MI->getParent();
2906321369Sdim
2907321369Sdim  // If we still don't have a debug location, don't record a location.
2908360784Sdim  if (!isUsableDebugLoc(DL))
2909303231Sdim    return;
2910321369Sdim
2911303231Sdim  maybeRecordLocation(DL, Asm->MF);
2912303231Sdim}
2913303231Sdim
2914321369SdimMCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
2915303231Sdim  MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2916303231Sdim           *EndLabel = MMI->getContext().createTempSymbol();
2917303231Sdim  OS.EmitIntValue(unsigned(Kind), 4);
2918303231Sdim  OS.AddComment("Subsection size");
2919303231Sdim  OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2920303231Sdim  OS.EmitLabel(BeginLabel);
2921303231Sdim  return EndLabel;
2922303231Sdim}
2923303231Sdim
2924303231Sdimvoid CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2925303231Sdim  OS.EmitLabel(EndLabel);
2926303231Sdim  // Every subsection must be aligned to a 4-byte boundary.
2927303231Sdim  OS.EmitValueToAlignment(4);
2928303231Sdim}
2929303231Sdim
2930344779Sdimstatic StringRef getSymbolName(SymbolKind SymKind) {
2931344779Sdim  for (const EnumEntry<SymbolKind> &EE : getSymbolTypeNames())
2932344779Sdim    if (EE.Value == SymKind)
2933344779Sdim      return EE.Name;
2934344779Sdim  return "";
2935344779Sdim}
2936344779Sdim
2937344779SdimMCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) {
2938344779Sdim  MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2939344779Sdim           *EndLabel = MMI->getContext().createTempSymbol();
2940344779Sdim  OS.AddComment("Record length");
2941344779Sdim  OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
2942344779Sdim  OS.EmitLabel(BeginLabel);
2943344779Sdim  if (OS.isVerboseAsm())
2944344779Sdim    OS.AddComment("Record kind: " + getSymbolName(SymKind));
2945344779Sdim  OS.EmitIntValue(unsigned(SymKind), 2);
2946344779Sdim  return EndLabel;
2947344779Sdim}
2948344779Sdim
2949344779Sdimvoid CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) {
2950344779Sdim  // MSVC does not pad out symbol records to four bytes, but LLVM does to avoid
2951344779Sdim  // an extra copy of every symbol record in LLD. This increases object file
2952344779Sdim  // size by less than 1% in the clang build, and is compatible with the Visual
2953344779Sdim  // C++ linker.
2954344779Sdim  OS.EmitValueToAlignment(4);
2955344779Sdim  OS.EmitLabel(SymEnd);
2956344779Sdim}
2957344779Sdim
2958344779Sdimvoid CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) {
2959344779Sdim  OS.AddComment("Record length");
2960344779Sdim  OS.EmitIntValue(2, 2);
2961344779Sdim  if (OS.isVerboseAsm())
2962344779Sdim    OS.AddComment("Record kind: " + getSymbolName(EndKind));
2963344779Sdim  OS.EmitIntValue(unsigned(EndKind), 2); // Record Kind
2964344779Sdim}
2965344779Sdim
2966303231Sdimvoid CodeViewDebug::emitDebugInfoForUDTs(
2967327952Sdim    ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
2968327952Sdim  for (const auto &UDT : UDTs) {
2969327952Sdim    const DIType *T = UDT.second;
2970327952Sdim    assert(shouldEmitUdt(T));
2971327952Sdim
2972344779Sdim    MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT);
2973303231Sdim    OS.AddComment("Type");
2974327952Sdim    OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
2975303231Sdim    emitNullTerminatedSymbolName(OS, UDT.first);
2976344779Sdim    endSymbolRecord(UDTRecordEnd);
2977303231Sdim  }
2978303231Sdim}
2979303231Sdim
2980344779Sdimvoid CodeViewDebug::collectGlobalVariableInfo() {
2981314564Sdim  DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2982314564Sdim      GlobalMap;
2983314564Sdim  for (const GlobalVariable &GV : MMI->getModule()->globals()) {
2984314564Sdim    SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2985314564Sdim    GV.getDebugInfo(GVEs);
2986314564Sdim    for (const auto *GVE : GVEs)
2987314564Sdim      GlobalMap[GVE] = &GV;
2988314564Sdim  }
2989314564Sdim
2990303231Sdim  NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2991303231Sdim  for (const MDNode *Node : CUs->operands()) {
2992303231Sdim    const auto *CU = cast<DICompileUnit>(Node);
2993314564Sdim    for (const auto *GVE : CU->getGlobalVariables()) {
2994353358Sdim      const DIGlobalVariable *DIGV = GVE->getVariable();
2995353358Sdim      const DIExpression *DIE = GVE->getExpression();
2996353358Sdim
2997353358Sdim      // Emit constant global variables in a global symbol section.
2998353358Sdim      if (GlobalMap.count(GVE) == 0 && DIE->isConstant()) {
2999353358Sdim        CVGlobalVariable CVGV = {DIGV, DIE};
3000353358Sdim        GlobalVariables.emplace_back(std::move(CVGV));
3001353358Sdim      }
3002353358Sdim
3003344779Sdim      const auto *GV = GlobalMap.lookup(GVE);
3004344779Sdim      if (!GV || GV->isDeclarationForLinker())
3005344779Sdim        continue;
3006353358Sdim
3007344779Sdim      DIScope *Scope = DIGV->getScope();
3008344779Sdim      SmallVector<CVGlobalVariable, 1> *VariableList;
3009344779Sdim      if (Scope && isa<DILocalScope>(Scope)) {
3010344779Sdim        // Locate a global variable list for this scope, creating one if
3011344779Sdim        // necessary.
3012344779Sdim        auto Insertion = ScopeGlobals.insert(
3013344779Sdim            {Scope, std::unique_ptr<GlobalVariableList>()});
3014344779Sdim        if (Insertion.second)
3015360784Sdim          Insertion.first->second = std::make_unique<GlobalVariableList>();
3016344779Sdim        VariableList = Insertion.first->second.get();
3017344779Sdim      } else if (GV->hasComdat())
3018344779Sdim        // Emit this global variable into a COMDAT section.
3019344779Sdim        VariableList = &ComdatVariables;
3020344779Sdim      else
3021353358Sdim        // Emit this global variable in a single global symbol section.
3022344779Sdim        VariableList = &GlobalVariables;
3023344779Sdim      CVGlobalVariable CVGV = {DIGV, GV};
3024344779Sdim      VariableList->emplace_back(std::move(CVGV));
3025303231Sdim    }
3026344779Sdim  }
3027344779Sdim}
3028303231Sdim
3029344779Sdimvoid CodeViewDebug::emitDebugInfoForGlobals() {
3030344779Sdim  // First, emit all globals that are not in a comdat in a single symbol
3031344779Sdim  // substream. MSVC doesn't like it if the substream is empty, so only open
3032344779Sdim  // it if we have at least one global to emit.
3033344779Sdim  switchToDebugSectionForSymbol(nullptr);
3034344779Sdim  if (!GlobalVariables.empty()) {
3035344779Sdim    OS.AddComment("Symbol subsection for globals");
3036344779Sdim    MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
3037344779Sdim    emitGlobalVariableList(GlobalVariables);
3038344779Sdim    endCVSubsection(EndLabel);
3039303231Sdim  }
3040344779Sdim
3041344779Sdim  // Second, emit each global that is in a comdat into its own .debug$S
3042344779Sdim  // section along with its own symbol substream.
3043344779Sdim  for (const CVGlobalVariable &CVGV : ComdatVariables) {
3044353358Sdim    const GlobalVariable *GV = CVGV.GVInfo.get<const GlobalVariable *>();
3045353358Sdim    MCSymbol *GVSym = Asm->getSymbol(GV);
3046344779Sdim    OS.AddComment("Symbol subsection for " +
3047353358Sdim                  Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
3048344779Sdim    switchToDebugSectionForSymbol(GVSym);
3049344779Sdim    MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
3050344779Sdim    // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3051353358Sdim    emitDebugInfoForGlobal(CVGV);
3052344779Sdim    endCVSubsection(EndLabel);
3053344779Sdim  }
3054303231Sdim}
3055303231Sdim
3056303231Sdimvoid CodeViewDebug::emitDebugInfoForRetainedTypes() {
3057303231Sdim  NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
3058303231Sdim  for (const MDNode *Node : CUs->operands()) {
3059303231Sdim    for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
3060303231Sdim      if (DIType *RT = dyn_cast<DIType>(Ty)) {
3061303231Sdim        getTypeIndex(RT);
3062303231Sdim        // FIXME: Add to global/local DTU list.
3063303231Sdim      }
3064303231Sdim    }
3065303231Sdim  }
3066303231Sdim}
3067303231Sdim
3068344779Sdim// Emit each global variable in the specified array.
3069344779Sdimvoid CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) {
3070344779Sdim  for (const CVGlobalVariable &CVGV : Globals) {
3071344779Sdim    // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3072353358Sdim    emitDebugInfoForGlobal(CVGV);
3073344779Sdim  }
3074344779Sdim}
3075344779Sdim
3076353358Sdimvoid CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable &CVGV) {
3077353358Sdim  const DIGlobalVariable *DIGV = CVGV.DIGV;
3078353358Sdim  if (const GlobalVariable *GV =
3079353358Sdim          CVGV.GVInfo.dyn_cast<const GlobalVariable *>()) {
3080353358Sdim    // DataSym record, see SymbolRecord.h for more info. Thread local data
3081353358Sdim    // happens to have the same format as global data.
3082353358Sdim    MCSymbol *GVSym = Asm->getSymbol(GV);
3083353358Sdim    SymbolKind DataSym = GV->isThreadLocal()
3084353358Sdim                             ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32
3085353358Sdim                                                      : SymbolKind::S_GTHREAD32)
3086353358Sdim                             : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32
3087353358Sdim                                                      : SymbolKind::S_GDATA32);
3088353358Sdim    MCSymbol *DataEnd = beginSymbolRecord(DataSym);
3089353358Sdim    OS.AddComment("Type");
3090353358Sdim    OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
3091353358Sdim    OS.AddComment("DataOffset");
3092353358Sdim    OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
3093353358Sdim    OS.AddComment("Segment");
3094353358Sdim    OS.EmitCOFFSectionIndex(GVSym);
3095353358Sdim    OS.AddComment("Name");
3096353358Sdim    const unsigned LengthOfDataRecord = 12;
3097353358Sdim    emitNullTerminatedSymbolName(OS, DIGV->getName(), LengthOfDataRecord);
3098353358Sdim    endSymbolRecord(DataEnd);
3099353358Sdim  } else {
3100353358Sdim    // FIXME: Currently this only emits the global variables in the IR metadata.
3101353358Sdim    // This should also emit enums and static data members.
3102353358Sdim    const DIExpression *DIE = CVGV.GVInfo.get<const DIExpression *>();
3103353358Sdim    assert(DIE->isConstant() &&
3104353358Sdim           "Global constant variables must contain a constant expression.");
3105353358Sdim    uint64_t Val = DIE->getElement(1);
3106353358Sdim
3107353358Sdim    MCSymbol *SConstantEnd = beginSymbolRecord(SymbolKind::S_CONSTANT);
3108353358Sdim    OS.AddComment("Type");
3109353358Sdim    OS.EmitIntValue(getTypeIndex(DIGV->getType()).getIndex(), 4);
3110353358Sdim    OS.AddComment("Value");
3111353358Sdim
3112353358Sdim    // Encoded integers shouldn't need more than 10 bytes.
3113353358Sdim    uint8_t data[10];
3114353358Sdim    BinaryStreamWriter Writer(data, llvm::support::endianness::little);
3115353358Sdim    CodeViewRecordIO IO(Writer);
3116353358Sdim    cantFail(IO.mapEncodedInteger(Val));
3117353358Sdim    StringRef SRef((char *)data, Writer.getOffset());
3118353358Sdim    OS.EmitBinaryData(SRef);
3119353358Sdim
3120353358Sdim    OS.AddComment("Name");
3121353358Sdim    const DIScope *Scope = DIGV->getScope();
3122353358Sdim    // For static data members, get the scope from the declaration.
3123353358Sdim    if (const auto *MemberDecl = dyn_cast_or_null<DIDerivedType>(
3124353358Sdim            DIGV->getRawStaticDataMemberDeclaration()))
3125353358Sdim      Scope = MemberDecl->getScope();
3126353358Sdim    emitNullTerminatedSymbolName(OS,
3127353358Sdim                                 getFullyQualifiedName(Scope, DIGV->getName()));
3128353358Sdim    endSymbolRecord(SConstantEnd);
3129353358Sdim  }
3130303231Sdim}
3131