10b57cec5SDimitry Andric //===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file contains support for writing Microsoft CodeView debug info.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "CodeViewDebug.h"
140b57cec5SDimitry Andric #include "DwarfExpression.h"
150b57cec5SDimitry Andric #include "llvm/ADT/APSInt.h"
160b57cec5SDimitry Andric #include "llvm/ADT/None.h"
170b57cec5SDimitry Andric #include "llvm/ADT/Optional.h"
180b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
190b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
200b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
210b57cec5SDimitry Andric #include "llvm/ADT/TinyPtrVector.h"
220b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
230b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
240b57cec5SDimitry Andric #include "llvm/BinaryFormat/COFF.h"
250b57cec5SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/AsmPrinter.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/LexicalScopes.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
310b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
320b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
350b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
360b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
370b57cec5SDimitry Andric #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
380b57cec5SDimitry Andric #include "llvm/DebugInfo/CodeView/CodeViewRecordIO.h"
390b57cec5SDimitry Andric #include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h"
400b57cec5SDimitry Andric #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
410b57cec5SDimitry Andric #include "llvm/DebugInfo/CodeView/EnumTables.h"
420b57cec5SDimitry Andric #include "llvm/DebugInfo/CodeView/Line.h"
430b57cec5SDimitry Andric #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
440b57cec5SDimitry Andric #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
450b57cec5SDimitry Andric #include "llvm/DebugInfo/CodeView/TypeRecord.h"
460b57cec5SDimitry Andric #include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
470b57cec5SDimitry Andric #include "llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h"
480b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
490b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
500b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
510b57cec5SDimitry Andric #include "llvm/IR/Function.h"
520b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
530b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
540b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
550b57cec5SDimitry Andric #include "llvm/IR/Module.h"
560b57cec5SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
570b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
580b57cec5SDimitry Andric #include "llvm/MC/MCSectionCOFF.h"
590b57cec5SDimitry Andric #include "llvm/MC/MCStreamer.h"
600b57cec5SDimitry Andric #include "llvm/MC/MCSymbol.h"
610b57cec5SDimitry Andric #include "llvm/Support/BinaryByteStream.h"
620b57cec5SDimitry Andric #include "llvm/Support/BinaryStreamReader.h"
630b57cec5SDimitry Andric #include "llvm/Support/BinaryStreamWriter.h"
640b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
650b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
660b57cec5SDimitry Andric #include "llvm/Support/Endian.h"
670b57cec5SDimitry Andric #include "llvm/Support/Error.h"
680b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
690b57cec5SDimitry Andric #include "llvm/Support/FormatVariadic.h"
700b57cec5SDimitry Andric #include "llvm/Support/Path.h"
710b57cec5SDimitry Andric #include "llvm/Support/SMLoc.h"
720b57cec5SDimitry Andric #include "llvm/Support/ScopedPrinter.h"
730b57cec5SDimitry Andric #include "llvm/Target/TargetLoweringObjectFile.h"
740b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
750b57cec5SDimitry Andric #include <algorithm>
760b57cec5SDimitry Andric #include <cassert>
770b57cec5SDimitry Andric #include <cctype>
780b57cec5SDimitry Andric #include <cstddef>
790b57cec5SDimitry Andric #include <iterator>
800b57cec5SDimitry Andric #include <limits>
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric using namespace llvm;
830b57cec5SDimitry Andric using namespace llvm::codeview;
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric namespace {
860b57cec5SDimitry Andric class CVMCAdapter : public CodeViewRecordStreamer {
870b57cec5SDimitry Andric public:
CVMCAdapter(MCStreamer & OS,TypeCollection & TypeTable)888bcb0991SDimitry Andric   CVMCAdapter(MCStreamer &OS, TypeCollection &TypeTable)
898bcb0991SDimitry Andric       : OS(&OS), TypeTable(TypeTable) {}
900b57cec5SDimitry Andric 
emitBytes(StringRef Data)915ffd83dbSDimitry Andric   void emitBytes(StringRef Data) override { OS->emitBytes(Data); }
920b57cec5SDimitry Andric 
emitIntValue(uint64_t Value,unsigned Size)935ffd83dbSDimitry Andric   void emitIntValue(uint64_t Value, unsigned Size) override {
945ffd83dbSDimitry Andric     OS->emitIntValueInHex(Value, Size);
950b57cec5SDimitry Andric   }
960b57cec5SDimitry Andric 
emitBinaryData(StringRef Data)975ffd83dbSDimitry Andric   void emitBinaryData(StringRef Data) override { OS->emitBinaryData(Data); }
980b57cec5SDimitry Andric 
AddComment(const Twine & T)995ffd83dbSDimitry Andric   void AddComment(const Twine &T) override { OS->AddComment(T); }
1000b57cec5SDimitry Andric 
AddRawComment(const Twine & T)1015ffd83dbSDimitry Andric   void AddRawComment(const Twine &T) override { OS->emitRawComment(T); }
1028bcb0991SDimitry Andric 
isVerboseAsm()1035ffd83dbSDimitry Andric   bool isVerboseAsm() override { return OS->isVerboseAsm(); }
1048bcb0991SDimitry Andric 
getTypeName(TypeIndex TI)1055ffd83dbSDimitry Andric   std::string getTypeName(TypeIndex TI) override {
1068bcb0991SDimitry Andric     std::string TypeName;
1078bcb0991SDimitry Andric     if (!TI.isNoneType()) {
1088bcb0991SDimitry Andric       if (TI.isSimple())
1095ffd83dbSDimitry Andric         TypeName = std::string(TypeIndex::simpleTypeName(TI));
1108bcb0991SDimitry Andric       else
1115ffd83dbSDimitry Andric         TypeName = std::string(TypeTable.getTypeName(TI));
1128bcb0991SDimitry Andric     }
1138bcb0991SDimitry Andric     return TypeName;
1148bcb0991SDimitry Andric   }
1158bcb0991SDimitry Andric 
1160b57cec5SDimitry Andric private:
1170b57cec5SDimitry Andric   MCStreamer *OS = nullptr;
1188bcb0991SDimitry Andric   TypeCollection &TypeTable;
1190b57cec5SDimitry Andric };
1200b57cec5SDimitry Andric } // namespace
1210b57cec5SDimitry Andric 
mapArchToCVCPUType(Triple::ArchType Type)1220b57cec5SDimitry Andric static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
1230b57cec5SDimitry Andric   switch (Type) {
1240b57cec5SDimitry Andric   case Triple::ArchType::x86:
1250b57cec5SDimitry Andric     return CPUType::Pentium3;
1260b57cec5SDimitry Andric   case Triple::ArchType::x86_64:
1270b57cec5SDimitry Andric     return CPUType::X64;
1280b57cec5SDimitry Andric   case Triple::ArchType::thumb:
129af732203SDimitry Andric     // LLVM currently doesn't support Windows CE and so thumb
130af732203SDimitry Andric     // here is indiscriminately mapped to ARMNT specifically.
131af732203SDimitry Andric     return CPUType::ARMNT;
1320b57cec5SDimitry Andric   case Triple::ArchType::aarch64:
1330b57cec5SDimitry Andric     return CPUType::ARM64;
1340b57cec5SDimitry Andric   default:
1350b57cec5SDimitry Andric     report_fatal_error("target architecture doesn't map to a CodeView CPUType");
1360b57cec5SDimitry Andric   }
1370b57cec5SDimitry Andric }
1380b57cec5SDimitry Andric 
CodeViewDebug(AsmPrinter * AP)1390b57cec5SDimitry Andric CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
140af732203SDimitry Andric     : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {}
1410b57cec5SDimitry Andric 
getFullFilepath(const DIFile * File)1420b57cec5SDimitry Andric StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
1430b57cec5SDimitry Andric   std::string &Filepath = FileToFilepathMap[File];
1440b57cec5SDimitry Andric   if (!Filepath.empty())
1450b57cec5SDimitry Andric     return Filepath;
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric   StringRef Dir = File->getDirectory(), Filename = File->getFilename();
1480b57cec5SDimitry Andric 
1490b57cec5SDimitry Andric   // If this is a Unix-style path, just use it as is. Don't try to canonicalize
1500b57cec5SDimitry Andric   // it textually because one of the path components could be a symlink.
1510b57cec5SDimitry Andric   if (Dir.startswith("/") || Filename.startswith("/")) {
1520b57cec5SDimitry Andric     if (llvm::sys::path::is_absolute(Filename, llvm::sys::path::Style::posix))
1530b57cec5SDimitry Andric       return Filename;
1545ffd83dbSDimitry Andric     Filepath = std::string(Dir);
1550b57cec5SDimitry Andric     if (Dir.back() != '/')
1560b57cec5SDimitry Andric       Filepath += '/';
1570b57cec5SDimitry Andric     Filepath += Filename;
1580b57cec5SDimitry Andric     return Filepath;
1590b57cec5SDimitry Andric   }
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric   // Clang emits directory and relative filename info into the IR, but CodeView
1620b57cec5SDimitry Andric   // operates on full paths.  We could change Clang to emit full paths too, but
1630b57cec5SDimitry Andric   // that would increase the IR size and probably not needed for other users.
1640b57cec5SDimitry Andric   // For now, just concatenate and canonicalize the path here.
1650b57cec5SDimitry Andric   if (Filename.find(':') == 1)
1665ffd83dbSDimitry Andric     Filepath = std::string(Filename);
1670b57cec5SDimitry Andric   else
1680b57cec5SDimitry Andric     Filepath = (Dir + "\\" + Filename).str();
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric   // Canonicalize the path.  We have to do it textually because we may no longer
1710b57cec5SDimitry Andric   // have access the file in the filesystem.
1720b57cec5SDimitry Andric   // First, replace all slashes with backslashes.
1730b57cec5SDimitry Andric   std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
1740b57cec5SDimitry Andric 
1750b57cec5SDimitry Andric   // Remove all "\.\" with "\".
1760b57cec5SDimitry Andric   size_t Cursor = 0;
1770b57cec5SDimitry Andric   while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
1780b57cec5SDimitry Andric     Filepath.erase(Cursor, 2);
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric   // Replace all "\XXX\..\" with "\".  Don't try too hard though as the original
1810b57cec5SDimitry Andric   // path should be well-formatted, e.g. start with a drive letter, etc.
1820b57cec5SDimitry Andric   Cursor = 0;
1830b57cec5SDimitry Andric   while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
1840b57cec5SDimitry Andric     // Something's wrong if the path starts with "\..\", abort.
1850b57cec5SDimitry Andric     if (Cursor == 0)
1860b57cec5SDimitry Andric       break;
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric     size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
1890b57cec5SDimitry Andric     if (PrevSlash == std::string::npos)
1900b57cec5SDimitry Andric       // Something's wrong, abort.
1910b57cec5SDimitry Andric       break;
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric     Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
1940b57cec5SDimitry Andric     // The next ".." might be following the one we've just erased.
1950b57cec5SDimitry Andric     Cursor = PrevSlash;
1960b57cec5SDimitry Andric   }
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric   // Remove all duplicate backslashes.
1990b57cec5SDimitry Andric   Cursor = 0;
2000b57cec5SDimitry Andric   while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
2010b57cec5SDimitry Andric     Filepath.erase(Cursor, 1);
2020b57cec5SDimitry Andric 
2030b57cec5SDimitry Andric   return Filepath;
2040b57cec5SDimitry Andric }
2050b57cec5SDimitry Andric 
maybeRecordFile(const DIFile * F)2060b57cec5SDimitry Andric unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
2070b57cec5SDimitry Andric   StringRef FullPath = getFullFilepath(F);
2080b57cec5SDimitry Andric   unsigned NextId = FileIdMap.size() + 1;
2090b57cec5SDimitry Andric   auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
2100b57cec5SDimitry Andric   if (Insertion.second) {
2110b57cec5SDimitry Andric     // We have to compute the full filepath and emit a .cv_file directive.
2120b57cec5SDimitry Andric     ArrayRef<uint8_t> ChecksumAsBytes;
2130b57cec5SDimitry Andric     FileChecksumKind CSKind = FileChecksumKind::None;
2140b57cec5SDimitry Andric     if (F->getChecksum()) {
2150b57cec5SDimitry Andric       std::string Checksum = fromHex(F->getChecksum()->Value);
2160b57cec5SDimitry Andric       void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
2170b57cec5SDimitry Andric       memcpy(CKMem, Checksum.data(), Checksum.size());
2180b57cec5SDimitry Andric       ChecksumAsBytes = ArrayRef<uint8_t>(
2190b57cec5SDimitry Andric           reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
2200b57cec5SDimitry Andric       switch (F->getChecksum()->Kind) {
2215ffd83dbSDimitry Andric       case DIFile::CSK_MD5:
2225ffd83dbSDimitry Andric         CSKind = FileChecksumKind::MD5;
2235ffd83dbSDimitry Andric         break;
2245ffd83dbSDimitry Andric       case DIFile::CSK_SHA1:
2255ffd83dbSDimitry Andric         CSKind = FileChecksumKind::SHA1;
2265ffd83dbSDimitry Andric         break;
2275ffd83dbSDimitry Andric       case DIFile::CSK_SHA256:
2285ffd83dbSDimitry Andric         CSKind = FileChecksumKind::SHA256;
2295ffd83dbSDimitry Andric         break;
2300b57cec5SDimitry Andric       }
2310b57cec5SDimitry Andric     }
2320b57cec5SDimitry Andric     bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
2330b57cec5SDimitry Andric                                           static_cast<unsigned>(CSKind));
2340b57cec5SDimitry Andric     (void)Success;
2350b57cec5SDimitry Andric     assert(Success && ".cv_file directive failed");
2360b57cec5SDimitry Andric   }
2370b57cec5SDimitry Andric   return Insertion.first->second;
2380b57cec5SDimitry Andric }
2390b57cec5SDimitry Andric 
2400b57cec5SDimitry Andric CodeViewDebug::InlineSite &
getInlineSite(const DILocation * InlinedAt,const DISubprogram * Inlinee)2410b57cec5SDimitry Andric CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
2420b57cec5SDimitry Andric                              const DISubprogram *Inlinee) {
2430b57cec5SDimitry Andric   auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
2440b57cec5SDimitry Andric   InlineSite *Site = &SiteInsertion.first->second;
2450b57cec5SDimitry Andric   if (SiteInsertion.second) {
2460b57cec5SDimitry Andric     unsigned ParentFuncId = CurFn->FuncId;
2470b57cec5SDimitry Andric     if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
2480b57cec5SDimitry Andric       ParentFuncId =
2490b57cec5SDimitry Andric           getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
2500b57cec5SDimitry Andric               .SiteFuncId;
2510b57cec5SDimitry Andric 
2520b57cec5SDimitry Andric     Site->SiteFuncId = NextFuncId++;
2530b57cec5SDimitry Andric     OS.EmitCVInlineSiteIdDirective(
2540b57cec5SDimitry Andric         Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
2550b57cec5SDimitry Andric         InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
2560b57cec5SDimitry Andric     Site->Inlinee = Inlinee;
2570b57cec5SDimitry Andric     InlinedSubprograms.insert(Inlinee);
2580b57cec5SDimitry Andric     getFuncIdForSubprogram(Inlinee);
2590b57cec5SDimitry Andric   }
2600b57cec5SDimitry Andric   return *Site;
2610b57cec5SDimitry Andric }
2620b57cec5SDimitry Andric 
getPrettyScopeName(const DIScope * Scope)2630b57cec5SDimitry Andric static StringRef getPrettyScopeName(const DIScope *Scope) {
2640b57cec5SDimitry Andric   StringRef ScopeName = Scope->getName();
2650b57cec5SDimitry Andric   if (!ScopeName.empty())
2660b57cec5SDimitry Andric     return ScopeName;
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric   switch (Scope->getTag()) {
2690b57cec5SDimitry Andric   case dwarf::DW_TAG_enumeration_type:
2700b57cec5SDimitry Andric   case dwarf::DW_TAG_class_type:
2710b57cec5SDimitry Andric   case dwarf::DW_TAG_structure_type:
2720b57cec5SDimitry Andric   case dwarf::DW_TAG_union_type:
2730b57cec5SDimitry Andric     return "<unnamed-tag>";
2740b57cec5SDimitry Andric   case dwarf::DW_TAG_namespace:
2750b57cec5SDimitry Andric     return "`anonymous namespace'";
276*5f7ddb14SDimitry Andric   default:
2770b57cec5SDimitry Andric     return StringRef();
2780b57cec5SDimitry Andric   }
279*5f7ddb14SDimitry Andric }
2800b57cec5SDimitry Andric 
collectParentScopeNames(const DIScope * Scope,SmallVectorImpl<StringRef> & QualifiedNameComponents)2815ffd83dbSDimitry Andric const DISubprogram *CodeViewDebug::collectParentScopeNames(
2820b57cec5SDimitry Andric     const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
2830b57cec5SDimitry Andric   const DISubprogram *ClosestSubprogram = nullptr;
2840b57cec5SDimitry Andric   while (Scope != nullptr) {
2850b57cec5SDimitry Andric     if (ClosestSubprogram == nullptr)
2860b57cec5SDimitry Andric       ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
2875ffd83dbSDimitry Andric 
2885ffd83dbSDimitry Andric     // If a type appears in a scope chain, make sure it gets emitted. The
2895ffd83dbSDimitry Andric     // frontend will be responsible for deciding if this should be a forward
2905ffd83dbSDimitry Andric     // declaration or a complete type.
2915ffd83dbSDimitry Andric     if (const auto *Ty = dyn_cast<DICompositeType>(Scope))
2925ffd83dbSDimitry Andric       DeferredCompleteTypes.push_back(Ty);
2935ffd83dbSDimitry Andric 
2940b57cec5SDimitry Andric     StringRef ScopeName = getPrettyScopeName(Scope);
2950b57cec5SDimitry Andric     if (!ScopeName.empty())
2960b57cec5SDimitry Andric       QualifiedNameComponents.push_back(ScopeName);
2970b57cec5SDimitry Andric     Scope = Scope->getScope();
2980b57cec5SDimitry Andric   }
2990b57cec5SDimitry Andric   return ClosestSubprogram;
3000b57cec5SDimitry Andric }
3010b57cec5SDimitry Andric 
formatNestedName(ArrayRef<StringRef> QualifiedNameComponents,StringRef TypeName)3025ffd83dbSDimitry Andric static std::string formatNestedName(ArrayRef<StringRef> QualifiedNameComponents,
3030b57cec5SDimitry Andric                                     StringRef TypeName) {
3040b57cec5SDimitry Andric   std::string FullyQualifiedName;
3050b57cec5SDimitry Andric   for (StringRef QualifiedNameComponent :
3060b57cec5SDimitry Andric        llvm::reverse(QualifiedNameComponents)) {
3075ffd83dbSDimitry Andric     FullyQualifiedName.append(std::string(QualifiedNameComponent));
3080b57cec5SDimitry Andric     FullyQualifiedName.append("::");
3090b57cec5SDimitry Andric   }
3105ffd83dbSDimitry Andric   FullyQualifiedName.append(std::string(TypeName));
3110b57cec5SDimitry Andric   return FullyQualifiedName;
3120b57cec5SDimitry Andric }
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric struct CodeViewDebug::TypeLoweringScope {
TypeLoweringScopeCodeViewDebug::TypeLoweringScope3150b57cec5SDimitry Andric   TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
~TypeLoweringScopeCodeViewDebug::TypeLoweringScope3160b57cec5SDimitry Andric   ~TypeLoweringScope() {
3170b57cec5SDimitry Andric     // Don't decrement TypeEmissionLevel until after emitting deferred types, so
3180b57cec5SDimitry Andric     // inner TypeLoweringScopes don't attempt to emit deferred types.
3190b57cec5SDimitry Andric     if (CVD.TypeEmissionLevel == 1)
3200b57cec5SDimitry Andric       CVD.emitDeferredCompleteTypes();
3210b57cec5SDimitry Andric     --CVD.TypeEmissionLevel;
3220b57cec5SDimitry Andric   }
3230b57cec5SDimitry Andric   CodeViewDebug &CVD;
3240b57cec5SDimitry Andric };
3250b57cec5SDimitry Andric 
getFullyQualifiedName(const DIScope * Scope,StringRef Name)3265ffd83dbSDimitry Andric std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Scope,
3275ffd83dbSDimitry Andric                                                  StringRef Name) {
3285ffd83dbSDimitry Andric   // Ensure types in the scope chain are emitted as soon as possible.
3295ffd83dbSDimitry Andric   // This can create otherwise a situation where S_UDTs are emitted while
3305ffd83dbSDimitry Andric   // looping in emitDebugInfoForUDTs.
3315ffd83dbSDimitry Andric   TypeLoweringScope S(*this);
3325ffd83dbSDimitry Andric   SmallVector<StringRef, 5> QualifiedNameComponents;
3335ffd83dbSDimitry Andric   collectParentScopeNames(Scope, QualifiedNameComponents);
3345ffd83dbSDimitry Andric   return formatNestedName(QualifiedNameComponents, Name);
3355ffd83dbSDimitry Andric }
3365ffd83dbSDimitry Andric 
getFullyQualifiedName(const DIScope * Ty)3375ffd83dbSDimitry Andric std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Ty) {
3380b57cec5SDimitry Andric   const DIScope *Scope = Ty->getScope();
3390b57cec5SDimitry Andric   return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
3400b57cec5SDimitry Andric }
3410b57cec5SDimitry Andric 
getScopeIndex(const DIScope * Scope)3420b57cec5SDimitry Andric TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
3430b57cec5SDimitry Andric   // No scope means global scope and that uses the zero index.
3440b57cec5SDimitry Andric   if (!Scope || isa<DIFile>(Scope))
3450b57cec5SDimitry Andric     return TypeIndex();
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric   assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric   // Check if we've already translated this scope.
3500b57cec5SDimitry Andric   auto I = TypeIndices.find({Scope, nullptr});
3510b57cec5SDimitry Andric   if (I != TypeIndices.end())
3520b57cec5SDimitry Andric     return I->second;
3530b57cec5SDimitry Andric 
3540b57cec5SDimitry Andric   // Build the fully qualified name of the scope.
3550b57cec5SDimitry Andric   std::string ScopeName = getFullyQualifiedName(Scope);
3560b57cec5SDimitry Andric   StringIdRecord SID(TypeIndex(), ScopeName);
3570b57cec5SDimitry Andric   auto TI = TypeTable.writeLeafType(SID);
3580b57cec5SDimitry Andric   return recordTypeIndexForDINode(Scope, TI);
3590b57cec5SDimitry Andric }
3600b57cec5SDimitry Andric 
removeTemplateArgs(StringRef Name)361*5f7ddb14SDimitry Andric static StringRef removeTemplateArgs(StringRef Name) {
362*5f7ddb14SDimitry Andric   // Remove template args from the display name. Assume that the template args
363*5f7ddb14SDimitry Andric   // are the last thing in the name.
364*5f7ddb14SDimitry Andric   if (Name.empty() || Name.back() != '>')
365*5f7ddb14SDimitry Andric     return Name;
366*5f7ddb14SDimitry Andric 
367*5f7ddb14SDimitry Andric   int OpenBrackets = 0;
368*5f7ddb14SDimitry Andric   for (int i = Name.size() - 1; i >= 0; --i) {
369*5f7ddb14SDimitry Andric     if (Name[i] == '>')
370*5f7ddb14SDimitry Andric       ++OpenBrackets;
371*5f7ddb14SDimitry Andric     else if (Name[i] == '<') {
372*5f7ddb14SDimitry Andric       --OpenBrackets;
373*5f7ddb14SDimitry Andric       if (OpenBrackets == 0)
374*5f7ddb14SDimitry Andric         return Name.substr(0, i);
375*5f7ddb14SDimitry Andric     }
376*5f7ddb14SDimitry Andric   }
377*5f7ddb14SDimitry Andric   return Name;
378*5f7ddb14SDimitry Andric }
379*5f7ddb14SDimitry Andric 
getFuncIdForSubprogram(const DISubprogram * SP)3800b57cec5SDimitry Andric TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
3810b57cec5SDimitry Andric   assert(SP);
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric   // Check if we've already translated this subprogram.
3840b57cec5SDimitry Andric   auto I = TypeIndices.find({SP, nullptr});
3850b57cec5SDimitry Andric   if (I != TypeIndices.end())
3860b57cec5SDimitry Andric     return I->second;
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric   // The display name includes function template arguments. Drop them to match
389*5f7ddb14SDimitry Andric   // MSVC. We need to have the template arguments in the DISubprogram name
390*5f7ddb14SDimitry Andric   // because they are used in other symbol records, such as S_GPROC32_IDs.
391*5f7ddb14SDimitry Andric   StringRef DisplayName = removeTemplateArgs(SP->getName());
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric   const DIScope *Scope = SP->getScope();
3940b57cec5SDimitry Andric   TypeIndex TI;
3950b57cec5SDimitry Andric   if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
3960b57cec5SDimitry Andric     // If the scope is a DICompositeType, then this must be a method. Member
3970b57cec5SDimitry Andric     // function types take some special handling, and require access to the
3980b57cec5SDimitry Andric     // subprogram.
3990b57cec5SDimitry Andric     TypeIndex ClassType = getTypeIndex(Class);
4000b57cec5SDimitry Andric     MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
4010b57cec5SDimitry Andric                                DisplayName);
4020b57cec5SDimitry Andric     TI = TypeTable.writeLeafType(MFuncId);
4030b57cec5SDimitry Andric   } else {
4040b57cec5SDimitry Andric     // Otherwise, this must be a free function.
4050b57cec5SDimitry Andric     TypeIndex ParentScope = getScopeIndex(Scope);
4060b57cec5SDimitry Andric     FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
4070b57cec5SDimitry Andric     TI = TypeTable.writeLeafType(FuncId);
4080b57cec5SDimitry Andric   }
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric   return recordTypeIndexForDINode(SP, TI);
4110b57cec5SDimitry Andric }
4120b57cec5SDimitry Andric 
isNonTrivial(const DICompositeType * DCTy)4130b57cec5SDimitry Andric static bool isNonTrivial(const DICompositeType *DCTy) {
4140b57cec5SDimitry Andric   return ((DCTy->getFlags() & DINode::FlagNonTrivial) == DINode::FlagNonTrivial);
4150b57cec5SDimitry Andric }
4160b57cec5SDimitry Andric 
4170b57cec5SDimitry Andric static FunctionOptions
getFunctionOptions(const DISubroutineType * Ty,const DICompositeType * ClassTy=nullptr,StringRef SPName=StringRef (""))4180b57cec5SDimitry Andric getFunctionOptions(const DISubroutineType *Ty,
4190b57cec5SDimitry Andric                    const DICompositeType *ClassTy = nullptr,
4200b57cec5SDimitry Andric                    StringRef SPName = StringRef("")) {
4210b57cec5SDimitry Andric   FunctionOptions FO = FunctionOptions::None;
4220b57cec5SDimitry Andric   const DIType *ReturnTy = nullptr;
4230b57cec5SDimitry Andric   if (auto TypeArray = Ty->getTypeArray()) {
4240b57cec5SDimitry Andric     if (TypeArray.size())
4250b57cec5SDimitry Andric       ReturnTy = TypeArray[0];
4260b57cec5SDimitry Andric   }
4270b57cec5SDimitry Andric 
4285ffd83dbSDimitry Andric   // Add CxxReturnUdt option to functions that return nontrivial record types
4295ffd83dbSDimitry Andric   // or methods that return record types.
4305ffd83dbSDimitry Andric   if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy))
4315ffd83dbSDimitry Andric     if (isNonTrivial(ReturnDCTy) || ClassTy)
4320b57cec5SDimitry Andric       FO |= FunctionOptions::CxxReturnUdt;
4330b57cec5SDimitry Andric 
4340b57cec5SDimitry Andric   // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison.
4350b57cec5SDimitry Andric   if (ClassTy && isNonTrivial(ClassTy) && SPName == ClassTy->getName()) {
4360b57cec5SDimitry Andric     FO |= FunctionOptions::Constructor;
4370b57cec5SDimitry Andric 
4380b57cec5SDimitry Andric   // TODO: put the FunctionOptions::ConstructorWithVirtualBases flag.
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric   }
4410b57cec5SDimitry Andric   return FO;
4420b57cec5SDimitry Andric }
4430b57cec5SDimitry Andric 
getMemberFunctionType(const DISubprogram * SP,const DICompositeType * Class)4440b57cec5SDimitry Andric TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
4450b57cec5SDimitry Andric                                                const DICompositeType *Class) {
4460b57cec5SDimitry Andric   // Always use the method declaration as the key for the function type. The
4470b57cec5SDimitry Andric   // method declaration contains the this adjustment.
4480b57cec5SDimitry Andric   if (SP->getDeclaration())
4490b57cec5SDimitry Andric     SP = SP->getDeclaration();
4500b57cec5SDimitry Andric   assert(!SP->getDeclaration() && "should use declaration as key");
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric   // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
4530b57cec5SDimitry Andric   // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
4540b57cec5SDimitry Andric   auto I = TypeIndices.find({SP, Class});
4550b57cec5SDimitry Andric   if (I != TypeIndices.end())
4560b57cec5SDimitry Andric     return I->second;
4570b57cec5SDimitry Andric 
4580b57cec5SDimitry Andric   // Make sure complete type info for the class is emitted *after* the member
4590b57cec5SDimitry Andric   // function type, as the complete class type is likely to reference this
4600b57cec5SDimitry Andric   // member function type.
4610b57cec5SDimitry Andric   TypeLoweringScope S(*this);
4620b57cec5SDimitry Andric   const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric   FunctionOptions FO = getFunctionOptions(SP->getType(), Class, SP->getName());
4650b57cec5SDimitry Andric   TypeIndex TI = lowerTypeMemberFunction(
4660b57cec5SDimitry Andric       SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO);
4670b57cec5SDimitry Andric   return recordTypeIndexForDINode(SP, TI, Class);
4680b57cec5SDimitry Andric }
4690b57cec5SDimitry Andric 
recordTypeIndexForDINode(const DINode * Node,TypeIndex TI,const DIType * ClassTy)4700b57cec5SDimitry Andric TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
4710b57cec5SDimitry Andric                                                   TypeIndex TI,
4720b57cec5SDimitry Andric                                                   const DIType *ClassTy) {
4730b57cec5SDimitry Andric   auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
4740b57cec5SDimitry Andric   (void)InsertResult;
4750b57cec5SDimitry Andric   assert(InsertResult.second && "DINode was already assigned a type index");
4760b57cec5SDimitry Andric   return TI;
4770b57cec5SDimitry Andric }
4780b57cec5SDimitry Andric 
getPointerSizeInBytes()4790b57cec5SDimitry Andric unsigned CodeViewDebug::getPointerSizeInBytes() {
4800b57cec5SDimitry Andric   return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
4810b57cec5SDimitry Andric }
4820b57cec5SDimitry Andric 
recordLocalVariable(LocalVariable && Var,const LexicalScope * LS)4830b57cec5SDimitry Andric void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
4840b57cec5SDimitry Andric                                         const LexicalScope *LS) {
4850b57cec5SDimitry Andric   if (const DILocation *InlinedAt = LS->getInlinedAt()) {
4860b57cec5SDimitry Andric     // This variable was inlined. Associate it with the InlineSite.
4870b57cec5SDimitry Andric     const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
4880b57cec5SDimitry Andric     InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
4890b57cec5SDimitry Andric     Site.InlinedLocals.emplace_back(Var);
4900b57cec5SDimitry Andric   } else {
4910b57cec5SDimitry Andric     // This variable goes into the corresponding lexical scope.
4920b57cec5SDimitry Andric     ScopeVariables[LS].emplace_back(Var);
4930b57cec5SDimitry Andric   }
4940b57cec5SDimitry Andric }
4950b57cec5SDimitry Andric 
addLocIfNotPresent(SmallVectorImpl<const DILocation * > & Locs,const DILocation * Loc)4960b57cec5SDimitry Andric static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
4970b57cec5SDimitry Andric                                const DILocation *Loc) {
498af732203SDimitry Andric   if (!llvm::is_contained(Locs, Loc))
4990b57cec5SDimitry Andric     Locs.push_back(Loc);
5000b57cec5SDimitry Andric }
5010b57cec5SDimitry Andric 
maybeRecordLocation(const DebugLoc & DL,const MachineFunction * MF)5020b57cec5SDimitry Andric void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
5030b57cec5SDimitry Andric                                         const MachineFunction *MF) {
5040b57cec5SDimitry Andric   // Skip this instruction if it has the same location as the previous one.
5050b57cec5SDimitry Andric   if (!DL || DL == PrevInstLoc)
5060b57cec5SDimitry Andric     return;
5070b57cec5SDimitry Andric 
5080b57cec5SDimitry Andric   const DIScope *Scope = DL.get()->getScope();
5090b57cec5SDimitry Andric   if (!Scope)
5100b57cec5SDimitry Andric     return;
5110b57cec5SDimitry Andric 
5120b57cec5SDimitry Andric   // Skip this line if it is longer than the maximum we can record.
5130b57cec5SDimitry Andric   LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
5140b57cec5SDimitry Andric   if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
5150b57cec5SDimitry Andric       LI.isNeverStepInto())
5160b57cec5SDimitry Andric     return;
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric   ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
5190b57cec5SDimitry Andric   if (CI.getStartColumn() != DL.getCol())
5200b57cec5SDimitry Andric     return;
5210b57cec5SDimitry Andric 
5220b57cec5SDimitry Andric   if (!CurFn->HaveLineInfo)
5230b57cec5SDimitry Andric     CurFn->HaveLineInfo = true;
5240b57cec5SDimitry Andric   unsigned FileId = 0;
5250b57cec5SDimitry Andric   if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
5260b57cec5SDimitry Andric     FileId = CurFn->LastFileId;
5270b57cec5SDimitry Andric   else
5280b57cec5SDimitry Andric     FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
5290b57cec5SDimitry Andric   PrevInstLoc = DL;
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric   unsigned FuncId = CurFn->FuncId;
5320b57cec5SDimitry Andric   if (const DILocation *SiteLoc = DL->getInlinedAt()) {
5330b57cec5SDimitry Andric     const DILocation *Loc = DL.get();
5340b57cec5SDimitry Andric 
5350b57cec5SDimitry Andric     // If this location was actually inlined from somewhere else, give it the ID
5360b57cec5SDimitry Andric     // of the inline call site.
5370b57cec5SDimitry Andric     FuncId =
5380b57cec5SDimitry Andric         getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
5390b57cec5SDimitry Andric 
5400b57cec5SDimitry Andric     // Ensure we have links in the tree of inline call sites.
5410b57cec5SDimitry Andric     bool FirstLoc = true;
5420b57cec5SDimitry Andric     while ((SiteLoc = Loc->getInlinedAt())) {
5430b57cec5SDimitry Andric       InlineSite &Site =
5440b57cec5SDimitry Andric           getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
5450b57cec5SDimitry Andric       if (!FirstLoc)
5460b57cec5SDimitry Andric         addLocIfNotPresent(Site.ChildSites, Loc);
5470b57cec5SDimitry Andric       FirstLoc = false;
5480b57cec5SDimitry Andric       Loc = SiteLoc;
5490b57cec5SDimitry Andric     }
5500b57cec5SDimitry Andric     addLocIfNotPresent(CurFn->ChildSites, Loc);
5510b57cec5SDimitry Andric   }
5520b57cec5SDimitry Andric 
5535ffd83dbSDimitry Andric   OS.emitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
5540b57cec5SDimitry Andric                         /*PrologueEnd=*/false, /*IsStmt=*/false,
5550b57cec5SDimitry Andric                         DL->getFilename(), SMLoc());
5560b57cec5SDimitry Andric }
5570b57cec5SDimitry Andric 
emitCodeViewMagicVersion()5580b57cec5SDimitry Andric void CodeViewDebug::emitCodeViewMagicVersion() {
5595ffd83dbSDimitry Andric   OS.emitValueToAlignment(4);
5600b57cec5SDimitry Andric   OS.AddComment("Debug section magic");
5615ffd83dbSDimitry Andric   OS.emitInt32(COFF::DEBUG_SECTION_MAGIC);
5620b57cec5SDimitry Andric }
5630b57cec5SDimitry Andric 
beginModule(Module * M)564af732203SDimitry Andric void CodeViewDebug::beginModule(Module *M) {
565af732203SDimitry Andric   // If module doesn't have named metadata anchors or COFF debug section
566af732203SDimitry Andric   // is not available, skip any debug info related stuff.
567af732203SDimitry Andric   if (!M->getNamedMetadata("llvm.dbg.cu") ||
568af732203SDimitry Andric       !Asm->getObjFileLowering().getCOFFDebugSymbolsSection()) {
569af732203SDimitry Andric     Asm = nullptr;
570af732203SDimitry Andric     return;
571af732203SDimitry Andric   }
572af732203SDimitry Andric   // Tell MMI that we have and need debug info.
573af732203SDimitry Andric   MMI->setDebugInfoAvailability(true);
574af732203SDimitry Andric 
575af732203SDimitry Andric   TheCPU = mapArchToCVCPUType(Triple(M->getTargetTriple()).getArch());
576af732203SDimitry Andric 
577af732203SDimitry Andric   collectGlobalVariableInfo();
578af732203SDimitry Andric 
579af732203SDimitry Andric   // Check if we should emit type record hashes.
580af732203SDimitry Andric   ConstantInt *GH =
581af732203SDimitry Andric       mdconst::extract_or_null<ConstantInt>(M->getModuleFlag("CodeViewGHash"));
582af732203SDimitry Andric   EmitDebugGlobalHashes = GH && !GH->isZero();
583af732203SDimitry Andric }
584af732203SDimitry Andric 
endModule()5850b57cec5SDimitry Andric void CodeViewDebug::endModule() {
5860b57cec5SDimitry Andric   if (!Asm || !MMI->hasDebugInfo())
5870b57cec5SDimitry Andric     return;
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric   // The COFF .debug$S section consists of several subsections, each starting
5900b57cec5SDimitry Andric   // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
5910b57cec5SDimitry Andric   // of the payload followed by the payload itself.  The subsections are 4-byte
5920b57cec5SDimitry Andric   // aligned.
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric   // Use the generic .debug$S section, and make a subsection for all the inlined
5950b57cec5SDimitry Andric   // subprograms.
5960b57cec5SDimitry Andric   switchToDebugSectionForSymbol(nullptr);
5970b57cec5SDimitry Andric 
5980b57cec5SDimitry Andric   MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
5990b57cec5SDimitry Andric   emitCompilerInformation();
6000b57cec5SDimitry Andric   endCVSubsection(CompilerInfo);
6010b57cec5SDimitry Andric 
6020b57cec5SDimitry Andric   emitInlineeLinesSubsection();
6030b57cec5SDimitry Andric 
6040b57cec5SDimitry Andric   // Emit per-function debug information.
6050b57cec5SDimitry Andric   for (auto &P : FnDebugInfo)
6060b57cec5SDimitry Andric     if (!P.first->isDeclarationForLinker())
6070b57cec5SDimitry Andric       emitDebugInfoForFunction(P.first, *P.second);
6080b57cec5SDimitry Andric 
609af732203SDimitry Andric   // Get types used by globals without emitting anything.
610af732203SDimitry Andric   // This is meant to collect all static const data members so they can be
611af732203SDimitry Andric   // emitted as globals.
612af732203SDimitry Andric   collectDebugInfoForGlobals();
6130b57cec5SDimitry Andric 
6140b57cec5SDimitry Andric   // Emit retained types.
6150b57cec5SDimitry Andric   emitDebugInfoForRetainedTypes();
6160b57cec5SDimitry Andric 
617af732203SDimitry Andric   // Emit global variable debug information.
618af732203SDimitry Andric   setCurrentSubprogram(nullptr);
619af732203SDimitry Andric   emitDebugInfoForGlobals();
620af732203SDimitry Andric 
6210b57cec5SDimitry Andric   // Switch back to the generic .debug$S section after potentially processing
6220b57cec5SDimitry Andric   // comdat symbol sections.
6230b57cec5SDimitry Andric   switchToDebugSectionForSymbol(nullptr);
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric   // Emit UDT records for any types used by global variables.
6260b57cec5SDimitry Andric   if (!GlobalUDTs.empty()) {
6270b57cec5SDimitry Andric     MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
6280b57cec5SDimitry Andric     emitDebugInfoForUDTs(GlobalUDTs);
6290b57cec5SDimitry Andric     endCVSubsection(SymbolsEnd);
6300b57cec5SDimitry Andric   }
6310b57cec5SDimitry Andric 
6320b57cec5SDimitry Andric   // This subsection holds a file index to offset in string table table.
6330b57cec5SDimitry Andric   OS.AddComment("File index to string table offset subsection");
6345ffd83dbSDimitry Andric   OS.emitCVFileChecksumsDirective();
6350b57cec5SDimitry Andric 
6360b57cec5SDimitry Andric   // This subsection holds the string table.
6370b57cec5SDimitry Andric   OS.AddComment("String table");
6385ffd83dbSDimitry Andric   OS.emitCVStringTableDirective();
6390b57cec5SDimitry Andric 
6400b57cec5SDimitry Andric   // Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol
6410b57cec5SDimitry Andric   // subsection in the generic .debug$S section at the end. There is no
6420b57cec5SDimitry Andric   // particular reason for this ordering other than to match MSVC.
6430b57cec5SDimitry Andric   emitBuildInfo();
6440b57cec5SDimitry Andric 
6450b57cec5SDimitry Andric   // Emit type information and hashes last, so that any types we translate while
6460b57cec5SDimitry Andric   // emitting function info are included.
6470b57cec5SDimitry Andric   emitTypeInformation();
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric   if (EmitDebugGlobalHashes)
6500b57cec5SDimitry Andric     emitTypeGlobalHashes();
6510b57cec5SDimitry Andric 
6520b57cec5SDimitry Andric   clear();
6530b57cec5SDimitry Andric }
6540b57cec5SDimitry Andric 
6550b57cec5SDimitry Andric static void
emitNullTerminatedSymbolName(MCStreamer & OS,StringRef S,unsigned MaxFixedRecordLength=0xF00)6560b57cec5SDimitry Andric emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S,
6570b57cec5SDimitry Andric                              unsigned MaxFixedRecordLength = 0xF00) {
6580b57cec5SDimitry Andric   // The maximum CV record length is 0xFF00. Most of the strings we emit appear
6590b57cec5SDimitry Andric   // after a fixed length portion of the record. The fixed length portion should
6600b57cec5SDimitry Andric   // always be less than 0xF00 (3840) bytes, so truncate the string so that the
6610b57cec5SDimitry Andric   // overall record size is less than the maximum allowed.
6620b57cec5SDimitry Andric   SmallString<32> NullTerminatedString(
6630b57cec5SDimitry Andric       S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
6640b57cec5SDimitry Andric   NullTerminatedString.push_back('\0');
6655ffd83dbSDimitry Andric   OS.emitBytes(NullTerminatedString);
6660b57cec5SDimitry Andric }
6670b57cec5SDimitry Andric 
emitTypeInformation()6680b57cec5SDimitry Andric void CodeViewDebug::emitTypeInformation() {
6690b57cec5SDimitry Andric   if (TypeTable.empty())
6700b57cec5SDimitry Andric     return;
6710b57cec5SDimitry Andric 
6720b57cec5SDimitry Andric   // Start the .debug$T or .debug$P section with 0x4.
6730b57cec5SDimitry Andric   OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
6740b57cec5SDimitry Andric   emitCodeViewMagicVersion();
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric   TypeTableCollection Table(TypeTable.records());
6770b57cec5SDimitry Andric   TypeVisitorCallbackPipeline Pipeline;
6780b57cec5SDimitry Andric 
6790b57cec5SDimitry Andric   // To emit type record using Codeview MCStreamer adapter
6808bcb0991SDimitry Andric   CVMCAdapter CVMCOS(OS, Table);
6810b57cec5SDimitry Andric   TypeRecordMapping typeMapping(CVMCOS);
6820b57cec5SDimitry Andric   Pipeline.addCallbackToPipeline(typeMapping);
6830b57cec5SDimitry Andric 
6840b57cec5SDimitry Andric   Optional<TypeIndex> B = Table.getFirst();
6850b57cec5SDimitry Andric   while (B) {
6860b57cec5SDimitry Andric     // This will fail if the record data is invalid.
6870b57cec5SDimitry Andric     CVType Record = Table.getType(*B);
6880b57cec5SDimitry Andric 
6890b57cec5SDimitry Andric     Error E = codeview::visitTypeRecord(Record, *B, Pipeline);
6900b57cec5SDimitry Andric 
6910b57cec5SDimitry Andric     if (E) {
6920b57cec5SDimitry Andric       logAllUnhandledErrors(std::move(E), errs(), "error: ");
6930b57cec5SDimitry Andric       llvm_unreachable("produced malformed type record");
6940b57cec5SDimitry Andric     }
6950b57cec5SDimitry Andric 
6960b57cec5SDimitry Andric     B = Table.getNext(*B);
6970b57cec5SDimitry Andric   }
6980b57cec5SDimitry Andric }
6990b57cec5SDimitry Andric 
emitTypeGlobalHashes()7000b57cec5SDimitry Andric void CodeViewDebug::emitTypeGlobalHashes() {
7010b57cec5SDimitry Andric   if (TypeTable.empty())
7020b57cec5SDimitry Andric     return;
7030b57cec5SDimitry Andric 
7040b57cec5SDimitry Andric   // Start the .debug$H section with the version and hash algorithm, currently
7050b57cec5SDimitry Andric   // hardcoded to version 0, SHA1.
7060b57cec5SDimitry Andric   OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
7070b57cec5SDimitry Andric 
7085ffd83dbSDimitry Andric   OS.emitValueToAlignment(4);
7090b57cec5SDimitry Andric   OS.AddComment("Magic");
7105ffd83dbSDimitry Andric   OS.emitInt32(COFF::DEBUG_HASHES_SECTION_MAGIC);
7110b57cec5SDimitry Andric   OS.AddComment("Section Version");
7125ffd83dbSDimitry Andric   OS.emitInt16(0);
7130b57cec5SDimitry Andric   OS.AddComment("Hash Algorithm");
7145ffd83dbSDimitry Andric   OS.emitInt16(uint16_t(GlobalTypeHashAlg::SHA1_8));
7150b57cec5SDimitry Andric 
7160b57cec5SDimitry Andric   TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
7170b57cec5SDimitry Andric   for (const auto &GHR : TypeTable.hashes()) {
7180b57cec5SDimitry Andric     if (OS.isVerboseAsm()) {
7190b57cec5SDimitry Andric       // Emit an EOL-comment describing which TypeIndex this hash corresponds
7200b57cec5SDimitry Andric       // to, as well as the stringified SHA1 hash.
7210b57cec5SDimitry Andric       SmallString<32> Comment;
7220b57cec5SDimitry Andric       raw_svector_ostream CommentOS(Comment);
7230b57cec5SDimitry Andric       CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
7240b57cec5SDimitry Andric       OS.AddComment(Comment);
7250b57cec5SDimitry Andric       ++TI;
7260b57cec5SDimitry Andric     }
7270b57cec5SDimitry Andric     assert(GHR.Hash.size() == 8);
7280b57cec5SDimitry Andric     StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
7290b57cec5SDimitry Andric                 GHR.Hash.size());
7305ffd83dbSDimitry Andric     OS.emitBinaryData(S);
7310b57cec5SDimitry Andric   }
7320b57cec5SDimitry Andric }
7330b57cec5SDimitry Andric 
MapDWLangToCVLang(unsigned DWLang)7340b57cec5SDimitry Andric static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
7350b57cec5SDimitry Andric   switch (DWLang) {
7360b57cec5SDimitry Andric   case dwarf::DW_LANG_C:
7370b57cec5SDimitry Andric   case dwarf::DW_LANG_C89:
7380b57cec5SDimitry Andric   case dwarf::DW_LANG_C99:
7390b57cec5SDimitry Andric   case dwarf::DW_LANG_C11:
7400b57cec5SDimitry Andric   case dwarf::DW_LANG_ObjC:
7410b57cec5SDimitry Andric     return SourceLanguage::C;
7420b57cec5SDimitry Andric   case dwarf::DW_LANG_C_plus_plus:
7430b57cec5SDimitry Andric   case dwarf::DW_LANG_C_plus_plus_03:
7440b57cec5SDimitry Andric   case dwarf::DW_LANG_C_plus_plus_11:
7450b57cec5SDimitry Andric   case dwarf::DW_LANG_C_plus_plus_14:
7460b57cec5SDimitry Andric     return SourceLanguage::Cpp;
7470b57cec5SDimitry Andric   case dwarf::DW_LANG_Fortran77:
7480b57cec5SDimitry Andric   case dwarf::DW_LANG_Fortran90:
7490b57cec5SDimitry Andric   case dwarf::DW_LANG_Fortran03:
7500b57cec5SDimitry Andric   case dwarf::DW_LANG_Fortran08:
7510b57cec5SDimitry Andric     return SourceLanguage::Fortran;
7520b57cec5SDimitry Andric   case dwarf::DW_LANG_Pascal83:
7530b57cec5SDimitry Andric     return SourceLanguage::Pascal;
7540b57cec5SDimitry Andric   case dwarf::DW_LANG_Cobol74:
7550b57cec5SDimitry Andric   case dwarf::DW_LANG_Cobol85:
7560b57cec5SDimitry Andric     return SourceLanguage::Cobol;
7570b57cec5SDimitry Andric   case dwarf::DW_LANG_Java:
7580b57cec5SDimitry Andric     return SourceLanguage::Java;
7590b57cec5SDimitry Andric   case dwarf::DW_LANG_D:
7600b57cec5SDimitry Andric     return SourceLanguage::D;
7610b57cec5SDimitry Andric   case dwarf::DW_LANG_Swift:
7620b57cec5SDimitry Andric     return SourceLanguage::Swift;
7630b57cec5SDimitry Andric   default:
7640b57cec5SDimitry Andric     // There's no CodeView representation for this language, and CV doesn't
7650b57cec5SDimitry Andric     // have an "unknown" option for the language field, so we'll use MASM,
7660b57cec5SDimitry Andric     // as it's very low level.
7670b57cec5SDimitry Andric     return SourceLanguage::Masm;
7680b57cec5SDimitry Andric   }
7690b57cec5SDimitry Andric }
7700b57cec5SDimitry Andric 
7710b57cec5SDimitry Andric namespace {
7720b57cec5SDimitry Andric struct Version {
7730b57cec5SDimitry Andric   int Part[4];
7740b57cec5SDimitry Andric };
7750b57cec5SDimitry Andric } // end anonymous namespace
7760b57cec5SDimitry Andric 
7770b57cec5SDimitry Andric // Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
7780b57cec5SDimitry Andric // the version number.
parseVersion(StringRef Name)7790b57cec5SDimitry Andric static Version parseVersion(StringRef Name) {
7800b57cec5SDimitry Andric   Version V = {{0}};
7810b57cec5SDimitry Andric   int N = 0;
7820b57cec5SDimitry Andric   for (const char C : Name) {
7830b57cec5SDimitry Andric     if (isdigit(C)) {
7840b57cec5SDimitry Andric       V.Part[N] *= 10;
7850b57cec5SDimitry Andric       V.Part[N] += C - '0';
7860b57cec5SDimitry Andric     } else if (C == '.') {
7870b57cec5SDimitry Andric       ++N;
7880b57cec5SDimitry Andric       if (N >= 4)
7890b57cec5SDimitry Andric         return V;
7900b57cec5SDimitry Andric     } else if (N > 0)
7910b57cec5SDimitry Andric       return V;
7920b57cec5SDimitry Andric   }
7930b57cec5SDimitry Andric   return V;
7940b57cec5SDimitry Andric }
7950b57cec5SDimitry Andric 
emitCompilerInformation()7960b57cec5SDimitry Andric void CodeViewDebug::emitCompilerInformation() {
7970b57cec5SDimitry Andric   MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_COMPILE3);
7980b57cec5SDimitry Andric   uint32_t Flags = 0;
7990b57cec5SDimitry Andric 
8000b57cec5SDimitry Andric   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
8010b57cec5SDimitry Andric   const MDNode *Node = *CUs->operands().begin();
8020b57cec5SDimitry Andric   const auto *CU = cast<DICompileUnit>(Node);
8030b57cec5SDimitry Andric 
8040b57cec5SDimitry Andric   // The low byte of the flags indicates the source language.
8050b57cec5SDimitry Andric   Flags = MapDWLangToCVLang(CU->getSourceLanguage());
8060b57cec5SDimitry Andric   // TODO:  Figure out which other flags need to be set.
807*5f7ddb14SDimitry Andric   if (MMI->getModule()->getProfileSummary(/*IsCS*/ false) != nullptr) {
808*5f7ddb14SDimitry Andric     Flags |= static_cast<uint32_t>(CompileSym3Flags::PGO);
809*5f7ddb14SDimitry Andric   }
8100b57cec5SDimitry Andric 
8110b57cec5SDimitry Andric   OS.AddComment("Flags and language");
8125ffd83dbSDimitry Andric   OS.emitInt32(Flags);
8130b57cec5SDimitry Andric 
8140b57cec5SDimitry Andric   OS.AddComment("CPUType");
8155ffd83dbSDimitry Andric   OS.emitInt16(static_cast<uint64_t>(TheCPU));
8160b57cec5SDimitry Andric 
8170b57cec5SDimitry Andric   StringRef CompilerVersion = CU->getProducer();
8180b57cec5SDimitry Andric   Version FrontVer = parseVersion(CompilerVersion);
8190b57cec5SDimitry Andric   OS.AddComment("Frontend version");
820*5f7ddb14SDimitry Andric   for (int N : FrontVer.Part)
821*5f7ddb14SDimitry Andric     OS.emitInt16(N);
8220b57cec5SDimitry Andric 
8230b57cec5SDimitry Andric   // Some Microsoft tools, like Binscope, expect a backend version number of at
8240b57cec5SDimitry Andric   // least 8.something, so we'll coerce the LLVM version into a form that
8250b57cec5SDimitry Andric   // guarantees it'll be big enough without really lying about the version.
8260b57cec5SDimitry Andric   int Major = 1000 * LLVM_VERSION_MAJOR +
8270b57cec5SDimitry Andric               10 * LLVM_VERSION_MINOR +
8280b57cec5SDimitry Andric               LLVM_VERSION_PATCH;
8290b57cec5SDimitry Andric   // Clamp it for builds that use unusually large version numbers.
8300b57cec5SDimitry Andric   Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
8310b57cec5SDimitry Andric   Version BackVer = {{ Major, 0, 0, 0 }};
8320b57cec5SDimitry Andric   OS.AddComment("Backend version");
833*5f7ddb14SDimitry Andric   for (int N : BackVer.Part)
834*5f7ddb14SDimitry Andric     OS.emitInt16(N);
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric   OS.AddComment("Null-terminated compiler version string");
8370b57cec5SDimitry Andric   emitNullTerminatedSymbolName(OS, CompilerVersion);
8380b57cec5SDimitry Andric 
8390b57cec5SDimitry Andric   endSymbolRecord(CompilerEnd);
8400b57cec5SDimitry Andric }
8410b57cec5SDimitry Andric 
getStringIdTypeIdx(GlobalTypeTableBuilder & TypeTable,StringRef S)8420b57cec5SDimitry Andric static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable,
8430b57cec5SDimitry Andric                                     StringRef S) {
8440b57cec5SDimitry Andric   StringIdRecord SIR(TypeIndex(0x0), S);
8450b57cec5SDimitry Andric   return TypeTable.writeLeafType(SIR);
8460b57cec5SDimitry Andric }
8470b57cec5SDimitry Andric 
emitBuildInfo()8480b57cec5SDimitry Andric void CodeViewDebug::emitBuildInfo() {
8490b57cec5SDimitry Andric   // First, make LF_BUILDINFO. It's a sequence of strings with various bits of
8500b57cec5SDimitry Andric   // build info. The known prefix is:
8510b57cec5SDimitry Andric   // - Absolute path of current directory
8520b57cec5SDimitry Andric   // - Compiler path
8530b57cec5SDimitry Andric   // - Main source file path, relative to CWD or absolute
8540b57cec5SDimitry Andric   // - Type server PDB file
8550b57cec5SDimitry Andric   // - Canonical compiler command line
8560b57cec5SDimitry Andric   // If frontend and backend compilation are separated (think llc or LTO), it's
8570b57cec5SDimitry Andric   // not clear if the compiler path should refer to the executable for the
8580b57cec5SDimitry Andric   // frontend or the backend. Leave it blank for now.
8590b57cec5SDimitry Andric   TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {};
8600b57cec5SDimitry Andric   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
8610b57cec5SDimitry Andric   const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs.
8620b57cec5SDimitry Andric   const auto *CU = cast<DICompileUnit>(Node);
8630b57cec5SDimitry Andric   const DIFile *MainSourceFile = CU->getFile();
8640b57cec5SDimitry Andric   BuildInfoArgs[BuildInfoRecord::CurrentDirectory] =
8650b57cec5SDimitry Andric       getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory());
8660b57cec5SDimitry Andric   BuildInfoArgs[BuildInfoRecord::SourceFile] =
8670b57cec5SDimitry Andric       getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename());
8680b57cec5SDimitry Andric   // FIXME: Path to compiler and command line. PDB is intentionally blank unless
8690b57cec5SDimitry Andric   // we implement /Zi type servers.
8700b57cec5SDimitry Andric   BuildInfoRecord BIR(BuildInfoArgs);
8710b57cec5SDimitry Andric   TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR);
8720b57cec5SDimitry Andric 
8730b57cec5SDimitry Andric   // Make a new .debug$S subsection for the S_BUILDINFO record, which points
8740b57cec5SDimitry Andric   // from the module symbols into the type stream.
8750b57cec5SDimitry Andric   MCSymbol *BISubsecEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
8760b57cec5SDimitry Andric   MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO);
8770b57cec5SDimitry Andric   OS.AddComment("LF_BUILDINFO index");
8785ffd83dbSDimitry Andric   OS.emitInt32(BuildInfoIndex.getIndex());
8790b57cec5SDimitry Andric   endSymbolRecord(BIEnd);
8800b57cec5SDimitry Andric   endCVSubsection(BISubsecEnd);
8810b57cec5SDimitry Andric }
8820b57cec5SDimitry Andric 
emitInlineeLinesSubsection()8830b57cec5SDimitry Andric void CodeViewDebug::emitInlineeLinesSubsection() {
8840b57cec5SDimitry Andric   if (InlinedSubprograms.empty())
8850b57cec5SDimitry Andric     return;
8860b57cec5SDimitry Andric 
8870b57cec5SDimitry Andric   OS.AddComment("Inlinee lines subsection");
8880b57cec5SDimitry Andric   MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
8890b57cec5SDimitry Andric 
8900b57cec5SDimitry Andric   // We emit the checksum info for files.  This is used by debuggers to
8910b57cec5SDimitry Andric   // determine if a pdb matches the source before loading it.  Visual Studio,
8920b57cec5SDimitry Andric   // for instance, will display a warning that the breakpoints are not valid if
8930b57cec5SDimitry Andric   // the pdb does not match the source.
8940b57cec5SDimitry Andric   OS.AddComment("Inlinee lines signature");
8955ffd83dbSDimitry Andric   OS.emitInt32(unsigned(InlineeLinesSignature::Normal));
8960b57cec5SDimitry Andric 
8970b57cec5SDimitry Andric   for (const DISubprogram *SP : InlinedSubprograms) {
8980b57cec5SDimitry Andric     assert(TypeIndices.count({SP, nullptr}));
8990b57cec5SDimitry Andric     TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
9000b57cec5SDimitry Andric 
9010b57cec5SDimitry Andric     OS.AddBlankLine();
9020b57cec5SDimitry Andric     unsigned FileId = maybeRecordFile(SP->getFile());
9030b57cec5SDimitry Andric     OS.AddComment("Inlined function " + SP->getName() + " starts at " +
9040b57cec5SDimitry Andric                   SP->getFilename() + Twine(':') + Twine(SP->getLine()));
9050b57cec5SDimitry Andric     OS.AddBlankLine();
9060b57cec5SDimitry Andric     OS.AddComment("Type index of inlined function");
9075ffd83dbSDimitry Andric     OS.emitInt32(InlineeIdx.getIndex());
9080b57cec5SDimitry Andric     OS.AddComment("Offset into filechecksum table");
9095ffd83dbSDimitry Andric     OS.emitCVFileChecksumOffsetDirective(FileId);
9100b57cec5SDimitry Andric     OS.AddComment("Starting line number");
9115ffd83dbSDimitry Andric     OS.emitInt32(SP->getLine());
9120b57cec5SDimitry Andric   }
9130b57cec5SDimitry Andric 
9140b57cec5SDimitry Andric   endCVSubsection(InlineEnd);
9150b57cec5SDimitry Andric }
9160b57cec5SDimitry Andric 
emitInlinedCallSite(const FunctionInfo & FI,const DILocation * InlinedAt,const InlineSite & Site)9170b57cec5SDimitry Andric void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
9180b57cec5SDimitry Andric                                         const DILocation *InlinedAt,
9190b57cec5SDimitry Andric                                         const InlineSite &Site) {
9200b57cec5SDimitry Andric   assert(TypeIndices.count({Site.Inlinee, nullptr}));
9210b57cec5SDimitry Andric   TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric   // SymbolRecord
9240b57cec5SDimitry Andric   MCSymbol *InlineEnd = beginSymbolRecord(SymbolKind::S_INLINESITE);
9250b57cec5SDimitry Andric 
9260b57cec5SDimitry Andric   OS.AddComment("PtrParent");
9275ffd83dbSDimitry Andric   OS.emitInt32(0);
9280b57cec5SDimitry Andric   OS.AddComment("PtrEnd");
9295ffd83dbSDimitry Andric   OS.emitInt32(0);
9300b57cec5SDimitry Andric   OS.AddComment("Inlinee type index");
9315ffd83dbSDimitry Andric   OS.emitInt32(InlineeIdx.getIndex());
9320b57cec5SDimitry Andric 
9330b57cec5SDimitry Andric   unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
9340b57cec5SDimitry Andric   unsigned StartLineNum = Site.Inlinee->getLine();
9350b57cec5SDimitry Andric 
9365ffd83dbSDimitry Andric   OS.emitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
9370b57cec5SDimitry Andric                                     FI.Begin, FI.End);
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric   endSymbolRecord(InlineEnd);
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric   emitLocalVariableList(FI, Site.InlinedLocals);
9420b57cec5SDimitry Andric 
9430b57cec5SDimitry Andric   // Recurse on child inlined call sites before closing the scope.
9440b57cec5SDimitry Andric   for (const DILocation *ChildSite : Site.ChildSites) {
9450b57cec5SDimitry Andric     auto I = FI.InlineSites.find(ChildSite);
9460b57cec5SDimitry Andric     assert(I != FI.InlineSites.end() &&
9470b57cec5SDimitry Andric            "child site not in function inline site map");
9480b57cec5SDimitry Andric     emitInlinedCallSite(FI, ChildSite, I->second);
9490b57cec5SDimitry Andric   }
9500b57cec5SDimitry Andric 
9510b57cec5SDimitry Andric   // Close the scope.
9520b57cec5SDimitry Andric   emitEndSymbolRecord(SymbolKind::S_INLINESITE_END);
9530b57cec5SDimitry Andric }
9540b57cec5SDimitry Andric 
switchToDebugSectionForSymbol(const MCSymbol * GVSym)9550b57cec5SDimitry Andric void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
9560b57cec5SDimitry Andric   // If we have a symbol, it may be in a section that is COMDAT. If so, find the
9570b57cec5SDimitry Andric   // comdat key. A section may be comdat because of -ffunction-sections or
9580b57cec5SDimitry Andric   // because it is comdat in the IR.
9590b57cec5SDimitry Andric   MCSectionCOFF *GVSec =
9600b57cec5SDimitry Andric       GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
9610b57cec5SDimitry Andric   const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
9620b57cec5SDimitry Andric 
9630b57cec5SDimitry Andric   MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
9640b57cec5SDimitry Andric       Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
9650b57cec5SDimitry Andric   DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
9660b57cec5SDimitry Andric 
9670b57cec5SDimitry Andric   OS.SwitchSection(DebugSec);
9680b57cec5SDimitry Andric 
9690b57cec5SDimitry Andric   // Emit the magic version number if this is the first time we've switched to
9700b57cec5SDimitry Andric   // this section.
9710b57cec5SDimitry Andric   if (ComdatDebugSections.insert(DebugSec).second)
9720b57cec5SDimitry Andric     emitCodeViewMagicVersion();
9730b57cec5SDimitry Andric }
9740b57cec5SDimitry Andric 
9750b57cec5SDimitry Andric // Emit an S_THUNK32/S_END symbol pair for a thunk routine.
9760b57cec5SDimitry Andric // The only supported thunk ordinal is currently the standard type.
emitDebugInfoForThunk(const Function * GV,FunctionInfo & FI,const MCSymbol * Fn)9770b57cec5SDimitry Andric void CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
9780b57cec5SDimitry Andric                                           FunctionInfo &FI,
9790b57cec5SDimitry Andric                                           const MCSymbol *Fn) {
9805ffd83dbSDimitry Andric   std::string FuncName =
9815ffd83dbSDimitry Andric       std::string(GlobalValue::dropLLVMManglingEscape(GV->getName()));
9820b57cec5SDimitry Andric   const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
9830b57cec5SDimitry Andric 
9840b57cec5SDimitry Andric   OS.AddComment("Symbol subsection for " + Twine(FuncName));
9850b57cec5SDimitry Andric   MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
9860b57cec5SDimitry Andric 
9870b57cec5SDimitry Andric   // Emit S_THUNK32
9880b57cec5SDimitry Andric   MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32);
9890b57cec5SDimitry Andric   OS.AddComment("PtrParent");
9905ffd83dbSDimitry Andric   OS.emitInt32(0);
9910b57cec5SDimitry Andric   OS.AddComment("PtrEnd");
9925ffd83dbSDimitry Andric   OS.emitInt32(0);
9930b57cec5SDimitry Andric   OS.AddComment("PtrNext");
9945ffd83dbSDimitry Andric   OS.emitInt32(0);
9950b57cec5SDimitry Andric   OS.AddComment("Thunk section relative address");
9960b57cec5SDimitry Andric   OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
9970b57cec5SDimitry Andric   OS.AddComment("Thunk section index");
9980b57cec5SDimitry Andric   OS.EmitCOFFSectionIndex(Fn);
9990b57cec5SDimitry Andric   OS.AddComment("Code size");
10000b57cec5SDimitry Andric   OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
10010b57cec5SDimitry Andric   OS.AddComment("Ordinal");
10025ffd83dbSDimitry Andric   OS.emitInt8(unsigned(ordinal));
10030b57cec5SDimitry Andric   OS.AddComment("Function name");
10040b57cec5SDimitry Andric   emitNullTerminatedSymbolName(OS, FuncName);
10050b57cec5SDimitry Andric   // Additional fields specific to the thunk ordinal would go here.
10060b57cec5SDimitry Andric   endSymbolRecord(ThunkRecordEnd);
10070b57cec5SDimitry Andric 
10080b57cec5SDimitry Andric   // Local variables/inlined routines are purposely omitted here.  The point of
10090b57cec5SDimitry Andric   // marking this as a thunk is so Visual Studio will NOT stop in this routine.
10100b57cec5SDimitry Andric 
10110b57cec5SDimitry Andric   // Emit S_PROC_ID_END
10120b57cec5SDimitry Andric   emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
10130b57cec5SDimitry Andric 
10140b57cec5SDimitry Andric   endCVSubsection(SymbolsEnd);
10150b57cec5SDimitry Andric }
10160b57cec5SDimitry Andric 
emitDebugInfoForFunction(const Function * GV,FunctionInfo & FI)10170b57cec5SDimitry Andric void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
10180b57cec5SDimitry Andric                                              FunctionInfo &FI) {
10190b57cec5SDimitry Andric   // For each function there is a separate subsection which holds the PC to
10200b57cec5SDimitry Andric   // file:line table.
10210b57cec5SDimitry Andric   const MCSymbol *Fn = Asm->getSymbol(GV);
10220b57cec5SDimitry Andric   assert(Fn);
10230b57cec5SDimitry Andric 
10240b57cec5SDimitry Andric   // Switch to the to a comdat section, if appropriate.
10250b57cec5SDimitry Andric   switchToDebugSectionForSymbol(Fn);
10260b57cec5SDimitry Andric 
10270b57cec5SDimitry Andric   std::string FuncName;
10280b57cec5SDimitry Andric   auto *SP = GV->getSubprogram();
10290b57cec5SDimitry Andric   assert(SP);
10300b57cec5SDimitry Andric   setCurrentSubprogram(SP);
10310b57cec5SDimitry Andric 
10320b57cec5SDimitry Andric   if (SP->isThunk()) {
10330b57cec5SDimitry Andric     emitDebugInfoForThunk(GV, FI, Fn);
10340b57cec5SDimitry Andric     return;
10350b57cec5SDimitry Andric   }
10360b57cec5SDimitry Andric 
10370b57cec5SDimitry Andric   // If we have a display name, build the fully qualified name by walking the
10380b57cec5SDimitry Andric   // chain of scopes.
10390b57cec5SDimitry Andric   if (!SP->getName().empty())
10400b57cec5SDimitry Andric     FuncName = getFullyQualifiedName(SP->getScope(), SP->getName());
10410b57cec5SDimitry Andric 
10420b57cec5SDimitry Andric   // If our DISubprogram name is empty, use the mangled name.
10430b57cec5SDimitry Andric   if (FuncName.empty())
10445ffd83dbSDimitry Andric     FuncName = std::string(GlobalValue::dropLLVMManglingEscape(GV->getName()));
10450b57cec5SDimitry Andric 
10460b57cec5SDimitry Andric   // Emit FPO data, but only on 32-bit x86. No other platforms use it.
10470b57cec5SDimitry Andric   if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
10480b57cec5SDimitry Andric     OS.EmitCVFPOData(Fn);
10490b57cec5SDimitry Andric 
10500b57cec5SDimitry Andric   // Emit a symbol subsection, required by VS2012+ to find function boundaries.
10510b57cec5SDimitry Andric   OS.AddComment("Symbol subsection for " + Twine(FuncName));
10520b57cec5SDimitry Andric   MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
10530b57cec5SDimitry Andric   {
10540b57cec5SDimitry Andric     SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID
10550b57cec5SDimitry Andric                                                 : SymbolKind::S_GPROC32_ID;
10560b57cec5SDimitry Andric     MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind);
10570b57cec5SDimitry Andric 
10580b57cec5SDimitry Andric     // These fields are filled in by tools like CVPACK which run after the fact.
10590b57cec5SDimitry Andric     OS.AddComment("PtrParent");
10605ffd83dbSDimitry Andric     OS.emitInt32(0);
10610b57cec5SDimitry Andric     OS.AddComment("PtrEnd");
10625ffd83dbSDimitry Andric     OS.emitInt32(0);
10630b57cec5SDimitry Andric     OS.AddComment("PtrNext");
10645ffd83dbSDimitry Andric     OS.emitInt32(0);
10650b57cec5SDimitry Andric     // This is the important bit that tells the debugger where the function
10660b57cec5SDimitry Andric     // code is located and what's its size:
10670b57cec5SDimitry Andric     OS.AddComment("Code size");
10680b57cec5SDimitry Andric     OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
10690b57cec5SDimitry Andric     OS.AddComment("Offset after prologue");
10705ffd83dbSDimitry Andric     OS.emitInt32(0);
10710b57cec5SDimitry Andric     OS.AddComment("Offset before epilogue");
10725ffd83dbSDimitry Andric     OS.emitInt32(0);
10730b57cec5SDimitry Andric     OS.AddComment("Function type index");
10745ffd83dbSDimitry Andric     OS.emitInt32(getFuncIdForSubprogram(GV->getSubprogram()).getIndex());
10750b57cec5SDimitry Andric     OS.AddComment("Function section relative address");
10760b57cec5SDimitry Andric     OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
10770b57cec5SDimitry Andric     OS.AddComment("Function section index");
10780b57cec5SDimitry Andric     OS.EmitCOFFSectionIndex(Fn);
10790b57cec5SDimitry Andric     OS.AddComment("Flags");
10805ffd83dbSDimitry Andric     OS.emitInt8(0);
10810b57cec5SDimitry Andric     // Emit the function display name as a null-terminated string.
10820b57cec5SDimitry Andric     OS.AddComment("Function name");
10830b57cec5SDimitry Andric     // Truncate the name so we won't overflow the record length field.
10840b57cec5SDimitry Andric     emitNullTerminatedSymbolName(OS, FuncName);
10850b57cec5SDimitry Andric     endSymbolRecord(ProcRecordEnd);
10860b57cec5SDimitry Andric 
10870b57cec5SDimitry Andric     MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC);
10880b57cec5SDimitry Andric     // Subtract out the CSR size since MSVC excludes that and we include it.
10890b57cec5SDimitry Andric     OS.AddComment("FrameSize");
10905ffd83dbSDimitry Andric     OS.emitInt32(FI.FrameSize - FI.CSRSize);
10910b57cec5SDimitry Andric     OS.AddComment("Padding");
10925ffd83dbSDimitry Andric     OS.emitInt32(0);
10930b57cec5SDimitry Andric     OS.AddComment("Offset of padding");
10945ffd83dbSDimitry Andric     OS.emitInt32(0);
10950b57cec5SDimitry Andric     OS.AddComment("Bytes of callee saved registers");
10965ffd83dbSDimitry Andric     OS.emitInt32(FI.CSRSize);
10970b57cec5SDimitry Andric     OS.AddComment("Exception handler offset");
10985ffd83dbSDimitry Andric     OS.emitInt32(0);
10990b57cec5SDimitry Andric     OS.AddComment("Exception handler section");
11005ffd83dbSDimitry Andric     OS.emitInt16(0);
11010b57cec5SDimitry Andric     OS.AddComment("Flags (defines frame register)");
11025ffd83dbSDimitry Andric     OS.emitInt32(uint32_t(FI.FrameProcOpts));
11030b57cec5SDimitry Andric     endSymbolRecord(FrameProcEnd);
11040b57cec5SDimitry Andric 
11050b57cec5SDimitry Andric     emitLocalVariableList(FI, FI.Locals);
11060b57cec5SDimitry Andric     emitGlobalVariableList(FI.Globals);
11070b57cec5SDimitry Andric     emitLexicalBlockList(FI.ChildBlocks, FI);
11080b57cec5SDimitry Andric 
11090b57cec5SDimitry Andric     // Emit inlined call site information. Only emit functions inlined directly
11100b57cec5SDimitry Andric     // into the parent function. We'll emit the other sites recursively as part
11110b57cec5SDimitry Andric     // of their parent inline site.
11120b57cec5SDimitry Andric     for (const DILocation *InlinedAt : FI.ChildSites) {
11130b57cec5SDimitry Andric       auto I = FI.InlineSites.find(InlinedAt);
11140b57cec5SDimitry Andric       assert(I != FI.InlineSites.end() &&
11150b57cec5SDimitry Andric              "child site not in function inline site map");
11160b57cec5SDimitry Andric       emitInlinedCallSite(FI, InlinedAt, I->second);
11170b57cec5SDimitry Andric     }
11180b57cec5SDimitry Andric 
11190b57cec5SDimitry Andric     for (auto Annot : FI.Annotations) {
11200b57cec5SDimitry Andric       MCSymbol *Label = Annot.first;
11210b57cec5SDimitry Andric       MDTuple *Strs = cast<MDTuple>(Annot.second);
11220b57cec5SDimitry Andric       MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION);
11230b57cec5SDimitry Andric       OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
11240b57cec5SDimitry Andric       // FIXME: Make sure we don't overflow the max record size.
11250b57cec5SDimitry Andric       OS.EmitCOFFSectionIndex(Label);
11265ffd83dbSDimitry Andric       OS.emitInt16(Strs->getNumOperands());
11270b57cec5SDimitry Andric       for (Metadata *MD : Strs->operands()) {
11280b57cec5SDimitry Andric         // MDStrings are null terminated, so we can do EmitBytes and get the
11290b57cec5SDimitry Andric         // nice .asciz directive.
11300b57cec5SDimitry Andric         StringRef Str = cast<MDString>(MD)->getString();
11310b57cec5SDimitry Andric         assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
11325ffd83dbSDimitry Andric         OS.emitBytes(StringRef(Str.data(), Str.size() + 1));
11330b57cec5SDimitry Andric       }
11340b57cec5SDimitry Andric       endSymbolRecord(AnnotEnd);
11350b57cec5SDimitry Andric     }
11360b57cec5SDimitry Andric 
11370b57cec5SDimitry Andric     for (auto HeapAllocSite : FI.HeapAllocSites) {
1138480093f4SDimitry Andric       const MCSymbol *BeginLabel = std::get<0>(HeapAllocSite);
1139480093f4SDimitry Andric       const MCSymbol *EndLabel = std::get<1>(HeapAllocSite);
1140c14a5a88SDimitry Andric       const DIType *DITy = std::get<2>(HeapAllocSite);
11410b57cec5SDimitry Andric       MCSymbol *HeapAllocEnd = beginSymbolRecord(SymbolKind::S_HEAPALLOCSITE);
11420b57cec5SDimitry Andric       OS.AddComment("Call site offset");
11430b57cec5SDimitry Andric       OS.EmitCOFFSecRel32(BeginLabel, /*Offset=*/0);
11440b57cec5SDimitry Andric       OS.AddComment("Call site section index");
11450b57cec5SDimitry Andric       OS.EmitCOFFSectionIndex(BeginLabel);
11460b57cec5SDimitry Andric       OS.AddComment("Call instruction length");
11470b57cec5SDimitry Andric       OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
11480b57cec5SDimitry Andric       OS.AddComment("Type index");
11495ffd83dbSDimitry Andric       OS.emitInt32(getCompleteTypeIndex(DITy).getIndex());
11500b57cec5SDimitry Andric       endSymbolRecord(HeapAllocEnd);
11510b57cec5SDimitry Andric     }
11520b57cec5SDimitry Andric 
11530b57cec5SDimitry Andric     if (SP != nullptr)
11540b57cec5SDimitry Andric       emitDebugInfoForUDTs(LocalUDTs);
11550b57cec5SDimitry Andric 
11560b57cec5SDimitry Andric     // We're done with this function.
11570b57cec5SDimitry Andric     emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
11580b57cec5SDimitry Andric   }
11590b57cec5SDimitry Andric   endCVSubsection(SymbolsEnd);
11600b57cec5SDimitry Andric 
11610b57cec5SDimitry Andric   // We have an assembler directive that takes care of the whole line table.
11625ffd83dbSDimitry Andric   OS.emitCVLinetableDirective(FI.FuncId, Fn, FI.End);
11630b57cec5SDimitry Andric }
11640b57cec5SDimitry Andric 
11650b57cec5SDimitry Andric CodeViewDebug::LocalVarDefRange
createDefRangeMem(uint16_t CVRegister,int Offset)11660b57cec5SDimitry Andric CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
11670b57cec5SDimitry Andric   LocalVarDefRange DR;
11680b57cec5SDimitry Andric   DR.InMemory = -1;
11690b57cec5SDimitry Andric   DR.DataOffset = Offset;
11700b57cec5SDimitry Andric   assert(DR.DataOffset == Offset && "truncation");
11710b57cec5SDimitry Andric   DR.IsSubfield = 0;
11720b57cec5SDimitry Andric   DR.StructOffset = 0;
11730b57cec5SDimitry Andric   DR.CVRegister = CVRegister;
11740b57cec5SDimitry Andric   return DR;
11750b57cec5SDimitry Andric }
11760b57cec5SDimitry Andric 
collectVariableInfoFromMFTable(DenseSet<InlinedEntity> & Processed)11770b57cec5SDimitry Andric void CodeViewDebug::collectVariableInfoFromMFTable(
11780b57cec5SDimitry Andric     DenseSet<InlinedEntity> &Processed) {
11790b57cec5SDimitry Andric   const MachineFunction &MF = *Asm->MF;
11800b57cec5SDimitry Andric   const TargetSubtargetInfo &TSI = MF.getSubtarget();
11810b57cec5SDimitry Andric   const TargetFrameLowering *TFI = TSI.getFrameLowering();
11820b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
11830b57cec5SDimitry Andric 
11840b57cec5SDimitry Andric   for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
11850b57cec5SDimitry Andric     if (!VI.Var)
11860b57cec5SDimitry Andric       continue;
11870b57cec5SDimitry Andric     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
11880b57cec5SDimitry Andric            "Expected inlined-at fields to agree");
11890b57cec5SDimitry Andric 
11900b57cec5SDimitry Andric     Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
11910b57cec5SDimitry Andric     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
11920b57cec5SDimitry Andric 
11930b57cec5SDimitry Andric     // If variable scope is not found then skip this variable.
11940b57cec5SDimitry Andric     if (!Scope)
11950b57cec5SDimitry Andric       continue;
11960b57cec5SDimitry Andric 
11970b57cec5SDimitry Andric     // If the variable has an attached offset expression, extract it.
11980b57cec5SDimitry Andric     // FIXME: Try to handle DW_OP_deref as well.
11990b57cec5SDimitry Andric     int64_t ExprOffset = 0;
12000b57cec5SDimitry Andric     bool Deref = false;
12010b57cec5SDimitry Andric     if (VI.Expr) {
12020b57cec5SDimitry Andric       // If there is one DW_OP_deref element, use offset of 0 and keep going.
12030b57cec5SDimitry Andric       if (VI.Expr->getNumElements() == 1 &&
12040b57cec5SDimitry Andric           VI.Expr->getElement(0) == llvm::dwarf::DW_OP_deref)
12050b57cec5SDimitry Andric         Deref = true;
12060b57cec5SDimitry Andric       else if (!VI.Expr->extractIfOffset(ExprOffset))
12070b57cec5SDimitry Andric         continue;
12080b57cec5SDimitry Andric     }
12090b57cec5SDimitry Andric 
12100b57cec5SDimitry Andric     // Get the frame register used and the offset.
12115ffd83dbSDimitry Andric     Register FrameReg;
1212af732203SDimitry Andric     StackOffset FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
12130b57cec5SDimitry Andric     uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
12140b57cec5SDimitry Andric 
1215af732203SDimitry Andric     assert(!FrameOffset.getScalable() &&
1216af732203SDimitry Andric            "Frame offsets with a scalable component are not supported");
1217af732203SDimitry Andric 
12180b57cec5SDimitry Andric     // Calculate the label ranges.
12190b57cec5SDimitry Andric     LocalVarDefRange DefRange =
1220af732203SDimitry Andric         createDefRangeMem(CVReg, FrameOffset.getFixed() + ExprOffset);
12210b57cec5SDimitry Andric 
12220b57cec5SDimitry Andric     for (const InsnRange &Range : Scope->getRanges()) {
12230b57cec5SDimitry Andric       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
12240b57cec5SDimitry Andric       const MCSymbol *End = getLabelAfterInsn(Range.second);
12250b57cec5SDimitry Andric       End = End ? End : Asm->getFunctionEnd();
12260b57cec5SDimitry Andric       DefRange.Ranges.emplace_back(Begin, End);
12270b57cec5SDimitry Andric     }
12280b57cec5SDimitry Andric 
12290b57cec5SDimitry Andric     LocalVariable Var;
12300b57cec5SDimitry Andric     Var.DIVar = VI.Var;
12310b57cec5SDimitry Andric     Var.DefRanges.emplace_back(std::move(DefRange));
12320b57cec5SDimitry Andric     if (Deref)
12330b57cec5SDimitry Andric       Var.UseReferenceType = true;
12340b57cec5SDimitry Andric 
12350b57cec5SDimitry Andric     recordLocalVariable(std::move(Var), Scope);
12360b57cec5SDimitry Andric   }
12370b57cec5SDimitry Andric }
12380b57cec5SDimitry Andric 
canUseReferenceType(const DbgVariableLocation & Loc)12390b57cec5SDimitry Andric static bool canUseReferenceType(const DbgVariableLocation &Loc) {
12400b57cec5SDimitry Andric   return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
12410b57cec5SDimitry Andric }
12420b57cec5SDimitry Andric 
needsReferenceType(const DbgVariableLocation & Loc)12430b57cec5SDimitry Andric static bool needsReferenceType(const DbgVariableLocation &Loc) {
12440b57cec5SDimitry Andric   return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
12450b57cec5SDimitry Andric }
12460b57cec5SDimitry Andric 
calculateRanges(LocalVariable & Var,const DbgValueHistoryMap::Entries & Entries)12470b57cec5SDimitry Andric void CodeViewDebug::calculateRanges(
12480b57cec5SDimitry Andric     LocalVariable &Var, const DbgValueHistoryMap::Entries &Entries) {
12490b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
12500b57cec5SDimitry Andric 
12510b57cec5SDimitry Andric   // Calculate the definition ranges.
12520b57cec5SDimitry Andric   for (auto I = Entries.begin(), E = Entries.end(); I != E; ++I) {
12530b57cec5SDimitry Andric     const auto &Entry = *I;
12540b57cec5SDimitry Andric     if (!Entry.isDbgValue())
12550b57cec5SDimitry Andric       continue;
12560b57cec5SDimitry Andric     const MachineInstr *DVInst = Entry.getInstr();
12570b57cec5SDimitry Andric     assert(DVInst->isDebugValue() && "Invalid History entry");
12580b57cec5SDimitry Andric     // FIXME: Find a way to represent constant variables, since they are
12590b57cec5SDimitry Andric     // relatively common.
12600b57cec5SDimitry Andric     Optional<DbgVariableLocation> Location =
12610b57cec5SDimitry Andric         DbgVariableLocation::extractFromMachineInstruction(*DVInst);
12620b57cec5SDimitry Andric     if (!Location)
12630b57cec5SDimitry Andric       continue;
12640b57cec5SDimitry Andric 
12650b57cec5SDimitry Andric     // CodeView can only express variables in register and variables in memory
12660b57cec5SDimitry Andric     // at a constant offset from a register. However, for variables passed
12670b57cec5SDimitry Andric     // indirectly by pointer, it is common for that pointer to be spilled to a
12680b57cec5SDimitry Andric     // stack location. For the special case of one offseted load followed by a
12690b57cec5SDimitry Andric     // zero offset load (a pointer spilled to the stack), we change the type of
12700b57cec5SDimitry Andric     // the local variable from a value type to a reference type. This tricks the
12710b57cec5SDimitry Andric     // debugger into doing the load for us.
12720b57cec5SDimitry Andric     if (Var.UseReferenceType) {
12730b57cec5SDimitry Andric       // We're using a reference type. Drop the last zero offset load.
12740b57cec5SDimitry Andric       if (canUseReferenceType(*Location))
12750b57cec5SDimitry Andric         Location->LoadChain.pop_back();
12760b57cec5SDimitry Andric       else
12770b57cec5SDimitry Andric         continue;
12780b57cec5SDimitry Andric     } else if (needsReferenceType(*Location)) {
12790b57cec5SDimitry Andric       // This location can't be expressed without switching to a reference type.
12800b57cec5SDimitry Andric       // Start over using that.
12810b57cec5SDimitry Andric       Var.UseReferenceType = true;
12820b57cec5SDimitry Andric       Var.DefRanges.clear();
12830b57cec5SDimitry Andric       calculateRanges(Var, Entries);
12840b57cec5SDimitry Andric       return;
12850b57cec5SDimitry Andric     }
12860b57cec5SDimitry Andric 
12870b57cec5SDimitry Andric     // We can only handle a register or an offseted load of a register.
12880b57cec5SDimitry Andric     if (Location->Register == 0 || Location->LoadChain.size() > 1)
12890b57cec5SDimitry Andric       continue;
12900b57cec5SDimitry Andric     {
12910b57cec5SDimitry Andric       LocalVarDefRange DR;
12920b57cec5SDimitry Andric       DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
12930b57cec5SDimitry Andric       DR.InMemory = !Location->LoadChain.empty();
12940b57cec5SDimitry Andric       DR.DataOffset =
12950b57cec5SDimitry Andric           !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
12960b57cec5SDimitry Andric       if (Location->FragmentInfo) {
12970b57cec5SDimitry Andric         DR.IsSubfield = true;
12980b57cec5SDimitry Andric         DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
12990b57cec5SDimitry Andric       } else {
13000b57cec5SDimitry Andric         DR.IsSubfield = false;
13010b57cec5SDimitry Andric         DR.StructOffset = 0;
13020b57cec5SDimitry Andric       }
13030b57cec5SDimitry Andric 
13040b57cec5SDimitry Andric       if (Var.DefRanges.empty() ||
13050b57cec5SDimitry Andric           Var.DefRanges.back().isDifferentLocation(DR)) {
13060b57cec5SDimitry Andric         Var.DefRanges.emplace_back(std::move(DR));
13070b57cec5SDimitry Andric       }
13080b57cec5SDimitry Andric     }
13090b57cec5SDimitry Andric 
13100b57cec5SDimitry Andric     // Compute the label range.
13110b57cec5SDimitry Andric     const MCSymbol *Begin = getLabelBeforeInsn(Entry.getInstr());
13120b57cec5SDimitry Andric     const MCSymbol *End;
13130b57cec5SDimitry Andric     if (Entry.getEndIndex() != DbgValueHistoryMap::NoEntry) {
13140b57cec5SDimitry Andric       auto &EndingEntry = Entries[Entry.getEndIndex()];
13150b57cec5SDimitry Andric       End = EndingEntry.isDbgValue()
13160b57cec5SDimitry Andric                 ? getLabelBeforeInsn(EndingEntry.getInstr())
13170b57cec5SDimitry Andric                 : getLabelAfterInsn(EndingEntry.getInstr());
13180b57cec5SDimitry Andric     } else
13190b57cec5SDimitry Andric       End = Asm->getFunctionEnd();
13200b57cec5SDimitry Andric 
13210b57cec5SDimitry Andric     // If the last range end is our begin, just extend the last range.
13220b57cec5SDimitry Andric     // Otherwise make a new range.
13230b57cec5SDimitry Andric     SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
13240b57cec5SDimitry Andric         Var.DefRanges.back().Ranges;
13250b57cec5SDimitry Andric     if (!R.empty() && R.back().second == Begin)
13260b57cec5SDimitry Andric       R.back().second = End;
13270b57cec5SDimitry Andric     else
13280b57cec5SDimitry Andric       R.emplace_back(Begin, End);
13290b57cec5SDimitry Andric 
13300b57cec5SDimitry Andric     // FIXME: Do more range combining.
13310b57cec5SDimitry Andric   }
13320b57cec5SDimitry Andric }
13330b57cec5SDimitry Andric 
collectVariableInfo(const DISubprogram * SP)13340b57cec5SDimitry Andric void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
13350b57cec5SDimitry Andric   DenseSet<InlinedEntity> Processed;
13360b57cec5SDimitry Andric   // Grab the variable info that was squirreled away in the MMI side-table.
13370b57cec5SDimitry Andric   collectVariableInfoFromMFTable(Processed);
13380b57cec5SDimitry Andric 
13390b57cec5SDimitry Andric   for (const auto &I : DbgValues) {
13400b57cec5SDimitry Andric     InlinedEntity IV = I.first;
13410b57cec5SDimitry Andric     if (Processed.count(IV))
13420b57cec5SDimitry Andric       continue;
13430b57cec5SDimitry Andric     const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
13440b57cec5SDimitry Andric     const DILocation *InlinedAt = IV.second;
13450b57cec5SDimitry Andric 
13460b57cec5SDimitry Andric     // Instruction ranges, specifying where IV is accessible.
13470b57cec5SDimitry Andric     const auto &Entries = I.second;
13480b57cec5SDimitry Andric 
13490b57cec5SDimitry Andric     LexicalScope *Scope = nullptr;
13500b57cec5SDimitry Andric     if (InlinedAt)
13510b57cec5SDimitry Andric       Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
13520b57cec5SDimitry Andric     else
13530b57cec5SDimitry Andric       Scope = LScopes.findLexicalScope(DIVar->getScope());
13540b57cec5SDimitry Andric     // If variable scope is not found then skip this variable.
13550b57cec5SDimitry Andric     if (!Scope)
13560b57cec5SDimitry Andric       continue;
13570b57cec5SDimitry Andric 
13580b57cec5SDimitry Andric     LocalVariable Var;
13590b57cec5SDimitry Andric     Var.DIVar = DIVar;
13600b57cec5SDimitry Andric 
13610b57cec5SDimitry Andric     calculateRanges(Var, Entries);
13620b57cec5SDimitry Andric     recordLocalVariable(std::move(Var), Scope);
13630b57cec5SDimitry Andric   }
13640b57cec5SDimitry Andric }
13650b57cec5SDimitry Andric 
beginFunctionImpl(const MachineFunction * MF)13660b57cec5SDimitry Andric void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
13670b57cec5SDimitry Andric   const TargetSubtargetInfo &TSI = MF->getSubtarget();
13680b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
13690b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF->getFrameInfo();
13700b57cec5SDimitry Andric   const Function &GV = MF->getFunction();
13718bcb0991SDimitry Andric   auto Insertion = FnDebugInfo.insert({&GV, std::make_unique<FunctionInfo>()});
13720b57cec5SDimitry Andric   assert(Insertion.second && "function already has info");
13730b57cec5SDimitry Andric   CurFn = Insertion.first->second.get();
13740b57cec5SDimitry Andric   CurFn->FuncId = NextFuncId++;
13750b57cec5SDimitry Andric   CurFn->Begin = Asm->getFunctionBegin();
13760b57cec5SDimitry Andric 
13770b57cec5SDimitry Andric   // The S_FRAMEPROC record reports the stack size, and how many bytes of
13780b57cec5SDimitry Andric   // callee-saved registers were used. For targets that don't use a PUSH
13790b57cec5SDimitry Andric   // instruction (AArch64), this will be zero.
13800b57cec5SDimitry Andric   CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
13810b57cec5SDimitry Andric   CurFn->FrameSize = MFI.getStackSize();
13820b57cec5SDimitry Andric   CurFn->OffsetAdjustment = MFI.getOffsetAdjustment();
1383*5f7ddb14SDimitry Andric   CurFn->HasStackRealignment = TRI->hasStackRealignment(*MF);
13840b57cec5SDimitry Andric 
13850b57cec5SDimitry Andric   // For this function S_FRAMEPROC record, figure out which codeview register
13860b57cec5SDimitry Andric   // will be the frame pointer.
13870b57cec5SDimitry Andric   CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
13880b57cec5SDimitry Andric   CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
13890b57cec5SDimitry Andric   if (CurFn->FrameSize > 0) {
13900b57cec5SDimitry Andric     if (!TSI.getFrameLowering()->hasFP(*MF)) {
13910b57cec5SDimitry Andric       CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
13920b57cec5SDimitry Andric       CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
13930b57cec5SDimitry Andric     } else {
13940b57cec5SDimitry Andric       // If there is an FP, parameters are always relative to it.
13950b57cec5SDimitry Andric       CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
13960b57cec5SDimitry Andric       if (CurFn->HasStackRealignment) {
13970b57cec5SDimitry Andric         // If the stack needs realignment, locals are relative to SP or VFRAME.
13980b57cec5SDimitry Andric         CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
13990b57cec5SDimitry Andric       } else {
14000b57cec5SDimitry Andric         // Otherwise, locals are relative to EBP, and we probably have VLAs or
14010b57cec5SDimitry Andric         // other stack adjustments.
14020b57cec5SDimitry Andric         CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
14030b57cec5SDimitry Andric       }
14040b57cec5SDimitry Andric     }
14050b57cec5SDimitry Andric   }
14060b57cec5SDimitry Andric 
14070b57cec5SDimitry Andric   // Compute other frame procedure options.
14080b57cec5SDimitry Andric   FrameProcedureOptions FPO = FrameProcedureOptions::None;
14090b57cec5SDimitry Andric   if (MFI.hasVarSizedObjects())
14100b57cec5SDimitry Andric     FPO |= FrameProcedureOptions::HasAlloca;
14110b57cec5SDimitry Andric   if (MF->exposesReturnsTwice())
14120b57cec5SDimitry Andric     FPO |= FrameProcedureOptions::HasSetJmp;
14130b57cec5SDimitry Andric   // FIXME: Set HasLongJmp if we ever track that info.
14140b57cec5SDimitry Andric   if (MF->hasInlineAsm())
14150b57cec5SDimitry Andric     FPO |= FrameProcedureOptions::HasInlineAssembly;
14160b57cec5SDimitry Andric   if (GV.hasPersonalityFn()) {
14170b57cec5SDimitry Andric     if (isAsynchronousEHPersonality(
14180b57cec5SDimitry Andric             classifyEHPersonality(GV.getPersonalityFn())))
14190b57cec5SDimitry Andric       FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
14200b57cec5SDimitry Andric     else
14210b57cec5SDimitry Andric       FPO |= FrameProcedureOptions::HasExceptionHandling;
14220b57cec5SDimitry Andric   }
14230b57cec5SDimitry Andric   if (GV.hasFnAttribute(Attribute::InlineHint))
14240b57cec5SDimitry Andric     FPO |= FrameProcedureOptions::MarkedInline;
14250b57cec5SDimitry Andric   if (GV.hasFnAttribute(Attribute::Naked))
14260b57cec5SDimitry Andric     FPO |= FrameProcedureOptions::Naked;
14270b57cec5SDimitry Andric   if (MFI.hasStackProtectorIndex())
14280b57cec5SDimitry Andric     FPO |= FrameProcedureOptions::SecurityChecks;
14290b57cec5SDimitry Andric   FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
14300b57cec5SDimitry Andric   FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
14310b57cec5SDimitry Andric   if (Asm->TM.getOptLevel() != CodeGenOpt::None &&
14320b57cec5SDimitry Andric       !GV.hasOptSize() && !GV.hasOptNone())
14330b57cec5SDimitry Andric     FPO |= FrameProcedureOptions::OptimizedForSpeed;
1434*5f7ddb14SDimitry Andric   if (GV.hasProfileData()) {
1435*5f7ddb14SDimitry Andric     FPO |= FrameProcedureOptions::ValidProfileCounts;
1436*5f7ddb14SDimitry Andric     FPO |= FrameProcedureOptions::ProfileGuidedOptimization;
1437*5f7ddb14SDimitry Andric   }
14380b57cec5SDimitry Andric   // FIXME: Set GuardCfg when it is implemented.
14390b57cec5SDimitry Andric   CurFn->FrameProcOpts = FPO;
14400b57cec5SDimitry Andric 
14410b57cec5SDimitry Andric   OS.EmitCVFuncIdDirective(CurFn->FuncId);
14420b57cec5SDimitry Andric 
14430b57cec5SDimitry Andric   // Find the end of the function prolog.  First known non-DBG_VALUE and
14440b57cec5SDimitry Andric   // non-frame setup location marks the beginning of the function body.
14450b57cec5SDimitry Andric   // FIXME: is there a simpler a way to do this? Can we just search
14460b57cec5SDimitry Andric   // for the first instruction of the function, not the last of the prolog?
14470b57cec5SDimitry Andric   DebugLoc PrologEndLoc;
14480b57cec5SDimitry Andric   bool EmptyPrologue = true;
14490b57cec5SDimitry Andric   for (const auto &MBB : *MF) {
14500b57cec5SDimitry Andric     for (const auto &MI : MBB) {
14510b57cec5SDimitry Andric       if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
14520b57cec5SDimitry Andric           MI.getDebugLoc()) {
14530b57cec5SDimitry Andric         PrologEndLoc = MI.getDebugLoc();
14540b57cec5SDimitry Andric         break;
14550b57cec5SDimitry Andric       } else if (!MI.isMetaInstruction()) {
14560b57cec5SDimitry Andric         EmptyPrologue = false;
14570b57cec5SDimitry Andric       }
14580b57cec5SDimitry Andric     }
14590b57cec5SDimitry Andric   }
14600b57cec5SDimitry Andric 
14610b57cec5SDimitry Andric   // Record beginning of function if we have a non-empty prologue.
14620b57cec5SDimitry Andric   if (PrologEndLoc && !EmptyPrologue) {
14630b57cec5SDimitry Andric     DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
14640b57cec5SDimitry Andric     maybeRecordLocation(FnStartDL, MF);
14650b57cec5SDimitry Andric   }
1466480093f4SDimitry Andric 
1467480093f4SDimitry Andric   // Find heap alloc sites and emit labels around them.
1468480093f4SDimitry Andric   for (const auto &MBB : *MF) {
1469480093f4SDimitry Andric     for (const auto &MI : MBB) {
1470480093f4SDimitry Andric       if (MI.getHeapAllocMarker()) {
1471480093f4SDimitry Andric         requestLabelBeforeInsn(&MI);
1472480093f4SDimitry Andric         requestLabelAfterInsn(&MI);
1473480093f4SDimitry Andric       }
1474480093f4SDimitry Andric     }
1475480093f4SDimitry Andric   }
14760b57cec5SDimitry Andric }
14770b57cec5SDimitry Andric 
shouldEmitUdt(const DIType * T)14780b57cec5SDimitry Andric static bool shouldEmitUdt(const DIType *T) {
14790b57cec5SDimitry Andric   if (!T)
14800b57cec5SDimitry Andric     return false;
14810b57cec5SDimitry Andric 
14820b57cec5SDimitry Andric   // MSVC does not emit UDTs for typedefs that are scoped to classes.
14830b57cec5SDimitry Andric   if (T->getTag() == dwarf::DW_TAG_typedef) {
14840b57cec5SDimitry Andric     if (DIScope *Scope = T->getScope()) {
14850b57cec5SDimitry Andric       switch (Scope->getTag()) {
14860b57cec5SDimitry Andric       case dwarf::DW_TAG_structure_type:
14870b57cec5SDimitry Andric       case dwarf::DW_TAG_class_type:
14880b57cec5SDimitry Andric       case dwarf::DW_TAG_union_type:
14890b57cec5SDimitry Andric         return false;
1490*5f7ddb14SDimitry Andric       default:
1491*5f7ddb14SDimitry Andric           // do nothing.
1492*5f7ddb14SDimitry Andric           ;
14930b57cec5SDimitry Andric       }
14940b57cec5SDimitry Andric     }
14950b57cec5SDimitry Andric   }
14960b57cec5SDimitry Andric 
14970b57cec5SDimitry Andric   while (true) {
14980b57cec5SDimitry Andric     if (!T || T->isForwardDecl())
14990b57cec5SDimitry Andric       return false;
15000b57cec5SDimitry Andric 
15010b57cec5SDimitry Andric     const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
15020b57cec5SDimitry Andric     if (!DT)
15030b57cec5SDimitry Andric       return true;
15040b57cec5SDimitry Andric     T = DT->getBaseType();
15050b57cec5SDimitry Andric   }
15060b57cec5SDimitry Andric   return true;
15070b57cec5SDimitry Andric }
15080b57cec5SDimitry Andric 
addToUDTs(const DIType * Ty)15090b57cec5SDimitry Andric void CodeViewDebug::addToUDTs(const DIType *Ty) {
15100b57cec5SDimitry Andric   // Don't record empty UDTs.
15110b57cec5SDimitry Andric   if (Ty->getName().empty())
15120b57cec5SDimitry Andric     return;
15130b57cec5SDimitry Andric   if (!shouldEmitUdt(Ty))
15140b57cec5SDimitry Andric     return;
15150b57cec5SDimitry Andric 
15165ffd83dbSDimitry Andric   SmallVector<StringRef, 5> ParentScopeNames;
15170b57cec5SDimitry Andric   const DISubprogram *ClosestSubprogram =
15185ffd83dbSDimitry Andric       collectParentScopeNames(Ty->getScope(), ParentScopeNames);
15190b57cec5SDimitry Andric 
15200b57cec5SDimitry Andric   std::string FullyQualifiedName =
15215ffd83dbSDimitry Andric       formatNestedName(ParentScopeNames, getPrettyScopeName(Ty));
15220b57cec5SDimitry Andric 
15230b57cec5SDimitry Andric   if (ClosestSubprogram == nullptr) {
15240b57cec5SDimitry Andric     GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
15250b57cec5SDimitry Andric   } else if (ClosestSubprogram == CurrentSubprogram) {
15260b57cec5SDimitry Andric     LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
15270b57cec5SDimitry Andric   }
15280b57cec5SDimitry Andric 
15290b57cec5SDimitry Andric   // TODO: What if the ClosestSubprogram is neither null or the current
15300b57cec5SDimitry Andric   // subprogram?  Currently, the UDT just gets dropped on the floor.
15310b57cec5SDimitry Andric   //
15320b57cec5SDimitry Andric   // The current behavior is not desirable.  To get maximal fidelity, we would
15330b57cec5SDimitry Andric   // need to perform all type translation before beginning emission of .debug$S
15340b57cec5SDimitry Andric   // and then make LocalUDTs a member of FunctionInfo
15350b57cec5SDimitry Andric }
15360b57cec5SDimitry Andric 
lowerType(const DIType * Ty,const DIType * ClassTy)15370b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
15380b57cec5SDimitry Andric   // Generic dispatch for lowering an unknown type.
15390b57cec5SDimitry Andric   switch (Ty->getTag()) {
15400b57cec5SDimitry Andric   case dwarf::DW_TAG_array_type:
15410b57cec5SDimitry Andric     return lowerTypeArray(cast<DICompositeType>(Ty));
15420b57cec5SDimitry Andric   case dwarf::DW_TAG_typedef:
15430b57cec5SDimitry Andric     return lowerTypeAlias(cast<DIDerivedType>(Ty));
15440b57cec5SDimitry Andric   case dwarf::DW_TAG_base_type:
15450b57cec5SDimitry Andric     return lowerTypeBasic(cast<DIBasicType>(Ty));
15460b57cec5SDimitry Andric   case dwarf::DW_TAG_pointer_type:
15470b57cec5SDimitry Andric     if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
15480b57cec5SDimitry Andric       return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
15490b57cec5SDimitry Andric     LLVM_FALLTHROUGH;
15500b57cec5SDimitry Andric   case dwarf::DW_TAG_reference_type:
15510b57cec5SDimitry Andric   case dwarf::DW_TAG_rvalue_reference_type:
15520b57cec5SDimitry Andric     return lowerTypePointer(cast<DIDerivedType>(Ty));
15530b57cec5SDimitry Andric   case dwarf::DW_TAG_ptr_to_member_type:
15540b57cec5SDimitry Andric     return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
15550b57cec5SDimitry Andric   case dwarf::DW_TAG_restrict_type:
15560b57cec5SDimitry Andric   case dwarf::DW_TAG_const_type:
15570b57cec5SDimitry Andric   case dwarf::DW_TAG_volatile_type:
15580b57cec5SDimitry Andric   // TODO: add support for DW_TAG_atomic_type here
15590b57cec5SDimitry Andric     return lowerTypeModifier(cast<DIDerivedType>(Ty));
15600b57cec5SDimitry Andric   case dwarf::DW_TAG_subroutine_type:
15610b57cec5SDimitry Andric     if (ClassTy) {
15620b57cec5SDimitry Andric       // The member function type of a member function pointer has no
15630b57cec5SDimitry Andric       // ThisAdjustment.
15640b57cec5SDimitry Andric       return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
15650b57cec5SDimitry Andric                                      /*ThisAdjustment=*/0,
15660b57cec5SDimitry Andric                                      /*IsStaticMethod=*/false);
15670b57cec5SDimitry Andric     }
15680b57cec5SDimitry Andric     return lowerTypeFunction(cast<DISubroutineType>(Ty));
15690b57cec5SDimitry Andric   case dwarf::DW_TAG_enumeration_type:
15700b57cec5SDimitry Andric     return lowerTypeEnum(cast<DICompositeType>(Ty));
15710b57cec5SDimitry Andric   case dwarf::DW_TAG_class_type:
15720b57cec5SDimitry Andric   case dwarf::DW_TAG_structure_type:
15730b57cec5SDimitry Andric     return lowerTypeClass(cast<DICompositeType>(Ty));
15740b57cec5SDimitry Andric   case dwarf::DW_TAG_union_type:
15750b57cec5SDimitry Andric     return lowerTypeUnion(cast<DICompositeType>(Ty));
15760b57cec5SDimitry Andric   case dwarf::DW_TAG_unspecified_type:
15770b57cec5SDimitry Andric     if (Ty->getName() == "decltype(nullptr)")
15780b57cec5SDimitry Andric       return TypeIndex::NullptrT();
15790b57cec5SDimitry Andric     return TypeIndex::None();
15800b57cec5SDimitry Andric   default:
15810b57cec5SDimitry Andric     // Use the null type index.
15820b57cec5SDimitry Andric     return TypeIndex();
15830b57cec5SDimitry Andric   }
15840b57cec5SDimitry Andric }
15850b57cec5SDimitry Andric 
lowerTypeAlias(const DIDerivedType * Ty)15860b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
15870b57cec5SDimitry Andric   TypeIndex UnderlyingTypeIndex = getTypeIndex(Ty->getBaseType());
15880b57cec5SDimitry Andric   StringRef TypeName = Ty->getName();
15890b57cec5SDimitry Andric 
15900b57cec5SDimitry Andric   addToUDTs(Ty);
15910b57cec5SDimitry Andric 
15920b57cec5SDimitry Andric   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
15930b57cec5SDimitry Andric       TypeName == "HRESULT")
15940b57cec5SDimitry Andric     return TypeIndex(SimpleTypeKind::HResult);
15950b57cec5SDimitry Andric   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
15960b57cec5SDimitry Andric       TypeName == "wchar_t")
15970b57cec5SDimitry Andric     return TypeIndex(SimpleTypeKind::WideCharacter);
15980b57cec5SDimitry Andric 
15990b57cec5SDimitry Andric   return UnderlyingTypeIndex;
16000b57cec5SDimitry Andric }
16010b57cec5SDimitry Andric 
lowerTypeArray(const DICompositeType * Ty)16020b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
16030b57cec5SDimitry Andric   const DIType *ElementType = Ty->getBaseType();
16040b57cec5SDimitry Andric   TypeIndex ElementTypeIndex = getTypeIndex(ElementType);
16050b57cec5SDimitry Andric   // IndexType is size_t, which depends on the bitness of the target.
16060b57cec5SDimitry Andric   TypeIndex IndexType = getPointerSizeInBytes() == 8
16070b57cec5SDimitry Andric                             ? TypeIndex(SimpleTypeKind::UInt64Quad)
16080b57cec5SDimitry Andric                             : TypeIndex(SimpleTypeKind::UInt32Long);
16090b57cec5SDimitry Andric 
16100b57cec5SDimitry Andric   uint64_t ElementSize = getBaseTypeSize(ElementType) / 8;
16110b57cec5SDimitry Andric 
16120b57cec5SDimitry Andric   // Add subranges to array type.
16130b57cec5SDimitry Andric   DINodeArray Elements = Ty->getElements();
16140b57cec5SDimitry Andric   for (int i = Elements.size() - 1; i >= 0; --i) {
16150b57cec5SDimitry Andric     const DINode *Element = Elements[i];
16160b57cec5SDimitry Andric     assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
16170b57cec5SDimitry Andric 
16180b57cec5SDimitry Andric     const DISubrange *Subrange = cast<DISubrange>(Element);
16190b57cec5SDimitry Andric     int64_t Count = -1;
162016d6b3b3SDimitry Andric     // Calculate the count if either LowerBound is absent or is zero and
162116d6b3b3SDimitry Andric     // either of Count or UpperBound are constant.
162216d6b3b3SDimitry Andric     auto *LI = Subrange->getLowerBound().dyn_cast<ConstantInt *>();
162316d6b3b3SDimitry Andric     if (!Subrange->getRawLowerBound() || (LI && (LI->getSExtValue() == 0))) {
16240b57cec5SDimitry Andric       if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>())
16250b57cec5SDimitry Andric         Count = CI->getSExtValue();
162616d6b3b3SDimitry Andric       else if (auto *UI = Subrange->getUpperBound().dyn_cast<ConstantInt*>())
162716d6b3b3SDimitry Andric         Count = UI->getSExtValue() + 1; // LowerBound is zero
162816d6b3b3SDimitry Andric     }
16290b57cec5SDimitry Andric 
16300b57cec5SDimitry Andric     // Forward declarations of arrays without a size and VLAs use a count of -1.
16310b57cec5SDimitry Andric     // Emit a count of zero in these cases to match what MSVC does for arrays
16320b57cec5SDimitry Andric     // without a size. MSVC doesn't support VLAs, so it's not clear what we
16330b57cec5SDimitry Andric     // should do for them even if we could distinguish them.
16340b57cec5SDimitry Andric     if (Count == -1)
16350b57cec5SDimitry Andric       Count = 0;
16360b57cec5SDimitry Andric 
16370b57cec5SDimitry Andric     // Update the element size and element type index for subsequent subranges.
16380b57cec5SDimitry Andric     ElementSize *= Count;
16390b57cec5SDimitry Andric 
16400b57cec5SDimitry Andric     // If this is the outermost array, use the size from the array. It will be
16410b57cec5SDimitry Andric     // more accurate if we had a VLA or an incomplete element type size.
16420b57cec5SDimitry Andric     uint64_t ArraySize =
16430b57cec5SDimitry Andric         (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
16440b57cec5SDimitry Andric 
16450b57cec5SDimitry Andric     StringRef Name = (i == 0) ? Ty->getName() : "";
16460b57cec5SDimitry Andric     ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
16470b57cec5SDimitry Andric     ElementTypeIndex = TypeTable.writeLeafType(AR);
16480b57cec5SDimitry Andric   }
16490b57cec5SDimitry Andric 
16500b57cec5SDimitry Andric   return ElementTypeIndex;
16510b57cec5SDimitry Andric }
16520b57cec5SDimitry Andric 
lowerTypeBasic(const DIBasicType * Ty)16530b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
16540b57cec5SDimitry Andric   TypeIndex Index;
16550b57cec5SDimitry Andric   dwarf::TypeKind Kind;
16560b57cec5SDimitry Andric   uint32_t ByteSize;
16570b57cec5SDimitry Andric 
16580b57cec5SDimitry Andric   Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
16590b57cec5SDimitry Andric   ByteSize = Ty->getSizeInBits() / 8;
16600b57cec5SDimitry Andric 
16610b57cec5SDimitry Andric   SimpleTypeKind STK = SimpleTypeKind::None;
16620b57cec5SDimitry Andric   switch (Kind) {
16630b57cec5SDimitry Andric   case dwarf::DW_ATE_address:
16640b57cec5SDimitry Andric     // FIXME: Translate
16650b57cec5SDimitry Andric     break;
16660b57cec5SDimitry Andric   case dwarf::DW_ATE_boolean:
16670b57cec5SDimitry Andric     switch (ByteSize) {
16680b57cec5SDimitry Andric     case 1:  STK = SimpleTypeKind::Boolean8;   break;
16690b57cec5SDimitry Andric     case 2:  STK = SimpleTypeKind::Boolean16;  break;
16700b57cec5SDimitry Andric     case 4:  STK = SimpleTypeKind::Boolean32;  break;
16710b57cec5SDimitry Andric     case 8:  STK = SimpleTypeKind::Boolean64;  break;
16720b57cec5SDimitry Andric     case 16: STK = SimpleTypeKind::Boolean128; break;
16730b57cec5SDimitry Andric     }
16740b57cec5SDimitry Andric     break;
16750b57cec5SDimitry Andric   case dwarf::DW_ATE_complex_float:
16760b57cec5SDimitry Andric     switch (ByteSize) {
16770b57cec5SDimitry Andric     case 2:  STK = SimpleTypeKind::Complex16;  break;
16780b57cec5SDimitry Andric     case 4:  STK = SimpleTypeKind::Complex32;  break;
16790b57cec5SDimitry Andric     case 8:  STK = SimpleTypeKind::Complex64;  break;
16800b57cec5SDimitry Andric     case 10: STK = SimpleTypeKind::Complex80;  break;
16810b57cec5SDimitry Andric     case 16: STK = SimpleTypeKind::Complex128; break;
16820b57cec5SDimitry Andric     }
16830b57cec5SDimitry Andric     break;
16840b57cec5SDimitry Andric   case dwarf::DW_ATE_float:
16850b57cec5SDimitry Andric     switch (ByteSize) {
16860b57cec5SDimitry Andric     case 2:  STK = SimpleTypeKind::Float16;  break;
16870b57cec5SDimitry Andric     case 4:  STK = SimpleTypeKind::Float32;  break;
16880b57cec5SDimitry Andric     case 6:  STK = SimpleTypeKind::Float48;  break;
16890b57cec5SDimitry Andric     case 8:  STK = SimpleTypeKind::Float64;  break;
16900b57cec5SDimitry Andric     case 10: STK = SimpleTypeKind::Float80;  break;
16910b57cec5SDimitry Andric     case 16: STK = SimpleTypeKind::Float128; break;
16920b57cec5SDimitry Andric     }
16930b57cec5SDimitry Andric     break;
16940b57cec5SDimitry Andric   case dwarf::DW_ATE_signed:
16950b57cec5SDimitry Andric     switch (ByteSize) {
16960b57cec5SDimitry Andric     case 1:  STK = SimpleTypeKind::SignedCharacter; break;
16970b57cec5SDimitry Andric     case 2:  STK = SimpleTypeKind::Int16Short;      break;
16980b57cec5SDimitry Andric     case 4:  STK = SimpleTypeKind::Int32;           break;
16990b57cec5SDimitry Andric     case 8:  STK = SimpleTypeKind::Int64Quad;       break;
17000b57cec5SDimitry Andric     case 16: STK = SimpleTypeKind::Int128Oct;       break;
17010b57cec5SDimitry Andric     }
17020b57cec5SDimitry Andric     break;
17030b57cec5SDimitry Andric   case dwarf::DW_ATE_unsigned:
17040b57cec5SDimitry Andric     switch (ByteSize) {
17050b57cec5SDimitry Andric     case 1:  STK = SimpleTypeKind::UnsignedCharacter; break;
17060b57cec5SDimitry Andric     case 2:  STK = SimpleTypeKind::UInt16Short;       break;
17070b57cec5SDimitry Andric     case 4:  STK = SimpleTypeKind::UInt32;            break;
17080b57cec5SDimitry Andric     case 8:  STK = SimpleTypeKind::UInt64Quad;        break;
17090b57cec5SDimitry Andric     case 16: STK = SimpleTypeKind::UInt128Oct;        break;
17100b57cec5SDimitry Andric     }
17110b57cec5SDimitry Andric     break;
17120b57cec5SDimitry Andric   case dwarf::DW_ATE_UTF:
17130b57cec5SDimitry Andric     switch (ByteSize) {
17140b57cec5SDimitry Andric     case 2: STK = SimpleTypeKind::Character16; break;
17150b57cec5SDimitry Andric     case 4: STK = SimpleTypeKind::Character32; break;
17160b57cec5SDimitry Andric     }
17170b57cec5SDimitry Andric     break;
17180b57cec5SDimitry Andric   case dwarf::DW_ATE_signed_char:
17190b57cec5SDimitry Andric     if (ByteSize == 1)
17200b57cec5SDimitry Andric       STK = SimpleTypeKind::SignedCharacter;
17210b57cec5SDimitry Andric     break;
17220b57cec5SDimitry Andric   case dwarf::DW_ATE_unsigned_char:
17230b57cec5SDimitry Andric     if (ByteSize == 1)
17240b57cec5SDimitry Andric       STK = SimpleTypeKind::UnsignedCharacter;
17250b57cec5SDimitry Andric     break;
17260b57cec5SDimitry Andric   default:
17270b57cec5SDimitry Andric     break;
17280b57cec5SDimitry Andric   }
17290b57cec5SDimitry Andric 
17300b57cec5SDimitry Andric   // Apply some fixups based on the source-level type name.
17310b57cec5SDimitry Andric   if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
17320b57cec5SDimitry Andric     STK = SimpleTypeKind::Int32Long;
17330b57cec5SDimitry Andric   if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
17340b57cec5SDimitry Andric     STK = SimpleTypeKind::UInt32Long;
17350b57cec5SDimitry Andric   if (STK == SimpleTypeKind::UInt16Short &&
17360b57cec5SDimitry Andric       (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
17370b57cec5SDimitry Andric     STK = SimpleTypeKind::WideCharacter;
17380b57cec5SDimitry Andric   if ((STK == SimpleTypeKind::SignedCharacter ||
17390b57cec5SDimitry Andric        STK == SimpleTypeKind::UnsignedCharacter) &&
17400b57cec5SDimitry Andric       Ty->getName() == "char")
17410b57cec5SDimitry Andric     STK = SimpleTypeKind::NarrowCharacter;
17420b57cec5SDimitry Andric 
17430b57cec5SDimitry Andric   return TypeIndex(STK);
17440b57cec5SDimitry Andric }
17450b57cec5SDimitry Andric 
lowerTypePointer(const DIDerivedType * Ty,PointerOptions PO)17460b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
17470b57cec5SDimitry Andric                                           PointerOptions PO) {
17480b57cec5SDimitry Andric   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
17490b57cec5SDimitry Andric 
17500b57cec5SDimitry Andric   // Pointers to simple types without any options can use SimpleTypeMode, rather
17510b57cec5SDimitry Andric   // than having a dedicated pointer type record.
17520b57cec5SDimitry Andric   if (PointeeTI.isSimple() && PO == PointerOptions::None &&
17530b57cec5SDimitry Andric       PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
17540b57cec5SDimitry Andric       Ty->getTag() == dwarf::DW_TAG_pointer_type) {
17550b57cec5SDimitry Andric     SimpleTypeMode Mode = Ty->getSizeInBits() == 64
17560b57cec5SDimitry Andric                               ? SimpleTypeMode::NearPointer64
17570b57cec5SDimitry Andric                               : SimpleTypeMode::NearPointer32;
17580b57cec5SDimitry Andric     return TypeIndex(PointeeTI.getSimpleKind(), Mode);
17590b57cec5SDimitry Andric   }
17600b57cec5SDimitry Andric 
17610b57cec5SDimitry Andric   PointerKind PK =
17620b57cec5SDimitry Andric       Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
17630b57cec5SDimitry Andric   PointerMode PM = PointerMode::Pointer;
17640b57cec5SDimitry Andric   switch (Ty->getTag()) {
17650b57cec5SDimitry Andric   default: llvm_unreachable("not a pointer tag type");
17660b57cec5SDimitry Andric   case dwarf::DW_TAG_pointer_type:
17670b57cec5SDimitry Andric     PM = PointerMode::Pointer;
17680b57cec5SDimitry Andric     break;
17690b57cec5SDimitry Andric   case dwarf::DW_TAG_reference_type:
17700b57cec5SDimitry Andric     PM = PointerMode::LValueReference;
17710b57cec5SDimitry Andric     break;
17720b57cec5SDimitry Andric   case dwarf::DW_TAG_rvalue_reference_type:
17730b57cec5SDimitry Andric     PM = PointerMode::RValueReference;
17740b57cec5SDimitry Andric     break;
17750b57cec5SDimitry Andric   }
17760b57cec5SDimitry Andric 
17770b57cec5SDimitry Andric   if (Ty->isObjectPointer())
17780b57cec5SDimitry Andric     PO |= PointerOptions::Const;
17790b57cec5SDimitry Andric 
17800b57cec5SDimitry Andric   PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
17810b57cec5SDimitry Andric   return TypeTable.writeLeafType(PR);
17820b57cec5SDimitry Andric }
17830b57cec5SDimitry Andric 
17840b57cec5SDimitry Andric static PointerToMemberRepresentation
translatePtrToMemberRep(unsigned SizeInBytes,bool IsPMF,unsigned Flags)17850b57cec5SDimitry Andric translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
17860b57cec5SDimitry Andric   // SizeInBytes being zero generally implies that the member pointer type was
17870b57cec5SDimitry Andric   // incomplete, which can happen if it is part of a function prototype. In this
17880b57cec5SDimitry Andric   // case, use the unknown model instead of the general model.
17890b57cec5SDimitry Andric   if (IsPMF) {
17900b57cec5SDimitry Andric     switch (Flags & DINode::FlagPtrToMemberRep) {
17910b57cec5SDimitry Andric     case 0:
17920b57cec5SDimitry Andric       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
17930b57cec5SDimitry Andric                               : PointerToMemberRepresentation::GeneralFunction;
17940b57cec5SDimitry Andric     case DINode::FlagSingleInheritance:
17950b57cec5SDimitry Andric       return PointerToMemberRepresentation::SingleInheritanceFunction;
17960b57cec5SDimitry Andric     case DINode::FlagMultipleInheritance:
17970b57cec5SDimitry Andric       return PointerToMemberRepresentation::MultipleInheritanceFunction;
17980b57cec5SDimitry Andric     case DINode::FlagVirtualInheritance:
17990b57cec5SDimitry Andric       return PointerToMemberRepresentation::VirtualInheritanceFunction;
18000b57cec5SDimitry Andric     }
18010b57cec5SDimitry Andric   } else {
18020b57cec5SDimitry Andric     switch (Flags & DINode::FlagPtrToMemberRep) {
18030b57cec5SDimitry Andric     case 0:
18040b57cec5SDimitry Andric       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
18050b57cec5SDimitry Andric                               : PointerToMemberRepresentation::GeneralData;
18060b57cec5SDimitry Andric     case DINode::FlagSingleInheritance:
18070b57cec5SDimitry Andric       return PointerToMemberRepresentation::SingleInheritanceData;
18080b57cec5SDimitry Andric     case DINode::FlagMultipleInheritance:
18090b57cec5SDimitry Andric       return PointerToMemberRepresentation::MultipleInheritanceData;
18100b57cec5SDimitry Andric     case DINode::FlagVirtualInheritance:
18110b57cec5SDimitry Andric       return PointerToMemberRepresentation::VirtualInheritanceData;
18120b57cec5SDimitry Andric     }
18130b57cec5SDimitry Andric   }
18140b57cec5SDimitry Andric   llvm_unreachable("invalid ptr to member representation");
18150b57cec5SDimitry Andric }
18160b57cec5SDimitry Andric 
lowerTypeMemberPointer(const DIDerivedType * Ty,PointerOptions PO)18170b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
18180b57cec5SDimitry Andric                                                 PointerOptions PO) {
18190b57cec5SDimitry Andric   assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
18205ffd83dbSDimitry Andric   bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
18210b57cec5SDimitry Andric   TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
18225ffd83dbSDimitry Andric   TypeIndex PointeeTI =
18235ffd83dbSDimitry Andric       getTypeIndex(Ty->getBaseType(), IsPMF ? Ty->getClassType() : nullptr);
18240b57cec5SDimitry Andric   PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
18250b57cec5SDimitry Andric                                                 : PointerKind::Near32;
18260b57cec5SDimitry Andric   PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
18270b57cec5SDimitry Andric                          : PointerMode::PointerToDataMember;
18280b57cec5SDimitry Andric 
18290b57cec5SDimitry Andric   assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
18300b57cec5SDimitry Andric   uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
18310b57cec5SDimitry Andric   MemberPointerInfo MPI(
18320b57cec5SDimitry Andric       ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
18330b57cec5SDimitry Andric   PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
18340b57cec5SDimitry Andric   return TypeTable.writeLeafType(PR);
18350b57cec5SDimitry Andric }
18360b57cec5SDimitry Andric 
18370b57cec5SDimitry Andric /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
18380b57cec5SDimitry Andric /// have a translation, use the NearC convention.
dwarfCCToCodeView(unsigned DwarfCC)18390b57cec5SDimitry Andric static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
18400b57cec5SDimitry Andric   switch (DwarfCC) {
18410b57cec5SDimitry Andric   case dwarf::DW_CC_normal:             return CallingConvention::NearC;
18420b57cec5SDimitry Andric   case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
18430b57cec5SDimitry Andric   case dwarf::DW_CC_BORLAND_thiscall:   return CallingConvention::ThisCall;
18440b57cec5SDimitry Andric   case dwarf::DW_CC_BORLAND_stdcall:    return CallingConvention::NearStdCall;
18450b57cec5SDimitry Andric   case dwarf::DW_CC_BORLAND_pascal:     return CallingConvention::NearPascal;
18460b57cec5SDimitry Andric   case dwarf::DW_CC_LLVM_vectorcall:    return CallingConvention::NearVector;
18470b57cec5SDimitry Andric   }
18480b57cec5SDimitry Andric   return CallingConvention::NearC;
18490b57cec5SDimitry Andric }
18500b57cec5SDimitry Andric 
lowerTypeModifier(const DIDerivedType * Ty)18510b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
18520b57cec5SDimitry Andric   ModifierOptions Mods = ModifierOptions::None;
18530b57cec5SDimitry Andric   PointerOptions PO = PointerOptions::None;
18540b57cec5SDimitry Andric   bool IsModifier = true;
18550b57cec5SDimitry Andric   const DIType *BaseTy = Ty;
18560b57cec5SDimitry Andric   while (IsModifier && BaseTy) {
18570b57cec5SDimitry Andric     // FIXME: Need to add DWARF tags for __unaligned and _Atomic
18580b57cec5SDimitry Andric     switch (BaseTy->getTag()) {
18590b57cec5SDimitry Andric     case dwarf::DW_TAG_const_type:
18600b57cec5SDimitry Andric       Mods |= ModifierOptions::Const;
18610b57cec5SDimitry Andric       PO |= PointerOptions::Const;
18620b57cec5SDimitry Andric       break;
18630b57cec5SDimitry Andric     case dwarf::DW_TAG_volatile_type:
18640b57cec5SDimitry Andric       Mods |= ModifierOptions::Volatile;
18650b57cec5SDimitry Andric       PO |= PointerOptions::Volatile;
18660b57cec5SDimitry Andric       break;
18670b57cec5SDimitry Andric     case dwarf::DW_TAG_restrict_type:
18680b57cec5SDimitry Andric       // Only pointer types be marked with __restrict. There is no known flag
18690b57cec5SDimitry Andric       // for __restrict in LF_MODIFIER records.
18700b57cec5SDimitry Andric       PO |= PointerOptions::Restrict;
18710b57cec5SDimitry Andric       break;
18720b57cec5SDimitry Andric     default:
18730b57cec5SDimitry Andric       IsModifier = false;
18740b57cec5SDimitry Andric       break;
18750b57cec5SDimitry Andric     }
18760b57cec5SDimitry Andric     if (IsModifier)
18770b57cec5SDimitry Andric       BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType();
18780b57cec5SDimitry Andric   }
18790b57cec5SDimitry Andric 
18800b57cec5SDimitry Andric   // Check if the inner type will use an LF_POINTER record. If so, the
18810b57cec5SDimitry Andric   // qualifiers will go in the LF_POINTER record. This comes up for types like
18820b57cec5SDimitry Andric   // 'int *const' and 'int *__restrict', not the more common cases like 'const
18830b57cec5SDimitry Andric   // char *'.
18840b57cec5SDimitry Andric   if (BaseTy) {
18850b57cec5SDimitry Andric     switch (BaseTy->getTag()) {
18860b57cec5SDimitry Andric     case dwarf::DW_TAG_pointer_type:
18870b57cec5SDimitry Andric     case dwarf::DW_TAG_reference_type:
18880b57cec5SDimitry Andric     case dwarf::DW_TAG_rvalue_reference_type:
18890b57cec5SDimitry Andric       return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
18900b57cec5SDimitry Andric     case dwarf::DW_TAG_ptr_to_member_type:
18910b57cec5SDimitry Andric       return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
18920b57cec5SDimitry Andric     default:
18930b57cec5SDimitry Andric       break;
18940b57cec5SDimitry Andric     }
18950b57cec5SDimitry Andric   }
18960b57cec5SDimitry Andric 
18970b57cec5SDimitry Andric   TypeIndex ModifiedTI = getTypeIndex(BaseTy);
18980b57cec5SDimitry Andric 
18990b57cec5SDimitry Andric   // Return the base type index if there aren't any modifiers. For example, the
19000b57cec5SDimitry Andric   // metadata could contain restrict wrappers around non-pointer types.
19010b57cec5SDimitry Andric   if (Mods == ModifierOptions::None)
19020b57cec5SDimitry Andric     return ModifiedTI;
19030b57cec5SDimitry Andric 
19040b57cec5SDimitry Andric   ModifierRecord MR(ModifiedTI, Mods);
19050b57cec5SDimitry Andric   return TypeTable.writeLeafType(MR);
19060b57cec5SDimitry Andric }
19070b57cec5SDimitry Andric 
lowerTypeFunction(const DISubroutineType * Ty)19080b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
19090b57cec5SDimitry Andric   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
19100b57cec5SDimitry Andric   for (const DIType *ArgType : Ty->getTypeArray())
19110b57cec5SDimitry Andric     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgType));
19120b57cec5SDimitry Andric 
19130b57cec5SDimitry Andric   // MSVC uses type none for variadic argument.
19140b57cec5SDimitry Andric   if (ReturnAndArgTypeIndices.size() > 1 &&
19150b57cec5SDimitry Andric       ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
19160b57cec5SDimitry Andric     ReturnAndArgTypeIndices.back() = TypeIndex::None();
19170b57cec5SDimitry Andric   }
19180b57cec5SDimitry Andric   TypeIndex ReturnTypeIndex = TypeIndex::Void();
19190b57cec5SDimitry Andric   ArrayRef<TypeIndex> ArgTypeIndices = None;
19200b57cec5SDimitry Andric   if (!ReturnAndArgTypeIndices.empty()) {
19210b57cec5SDimitry Andric     auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
19220b57cec5SDimitry Andric     ReturnTypeIndex = ReturnAndArgTypesRef.front();
19230b57cec5SDimitry Andric     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
19240b57cec5SDimitry Andric   }
19250b57cec5SDimitry Andric 
19260b57cec5SDimitry Andric   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
19270b57cec5SDimitry Andric   TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
19280b57cec5SDimitry Andric 
19290b57cec5SDimitry Andric   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
19300b57cec5SDimitry Andric 
19310b57cec5SDimitry Andric   FunctionOptions FO = getFunctionOptions(Ty);
19320b57cec5SDimitry Andric   ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
19330b57cec5SDimitry Andric                             ArgListIndex);
19340b57cec5SDimitry Andric   return TypeTable.writeLeafType(Procedure);
19350b57cec5SDimitry Andric }
19360b57cec5SDimitry Andric 
lowerTypeMemberFunction(const DISubroutineType * Ty,const DIType * ClassTy,int ThisAdjustment,bool IsStaticMethod,FunctionOptions FO)19370b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
19380b57cec5SDimitry Andric                                                  const DIType *ClassTy,
19390b57cec5SDimitry Andric                                                  int ThisAdjustment,
19400b57cec5SDimitry Andric                                                  bool IsStaticMethod,
19410b57cec5SDimitry Andric                                                  FunctionOptions FO) {
19420b57cec5SDimitry Andric   // Lower the containing class type.
19430b57cec5SDimitry Andric   TypeIndex ClassType = getTypeIndex(ClassTy);
19440b57cec5SDimitry Andric 
19450b57cec5SDimitry Andric   DITypeRefArray ReturnAndArgs = Ty->getTypeArray();
19460b57cec5SDimitry Andric 
19470b57cec5SDimitry Andric   unsigned Index = 0;
19480b57cec5SDimitry Andric   SmallVector<TypeIndex, 8> ArgTypeIndices;
19490b57cec5SDimitry Andric   TypeIndex ReturnTypeIndex = TypeIndex::Void();
19500b57cec5SDimitry Andric   if (ReturnAndArgs.size() > Index) {
19510b57cec5SDimitry Andric     ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]);
19520b57cec5SDimitry Andric   }
19530b57cec5SDimitry Andric 
19540b57cec5SDimitry Andric   // If the first argument is a pointer type and this isn't a static method,
19550b57cec5SDimitry Andric   // treat it as the special 'this' parameter, which is encoded separately from
19560b57cec5SDimitry Andric   // the arguments.
19570b57cec5SDimitry Andric   TypeIndex ThisTypeIndex;
19580b57cec5SDimitry Andric   if (!IsStaticMethod && ReturnAndArgs.size() > Index) {
19590b57cec5SDimitry Andric     if (const DIDerivedType *PtrTy =
19600b57cec5SDimitry Andric             dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index])) {
19610b57cec5SDimitry Andric       if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) {
19620b57cec5SDimitry Andric         ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty);
19630b57cec5SDimitry Andric         Index++;
19640b57cec5SDimitry Andric       }
19650b57cec5SDimitry Andric     }
19660b57cec5SDimitry Andric   }
19670b57cec5SDimitry Andric 
19680b57cec5SDimitry Andric   while (Index < ReturnAndArgs.size())
19690b57cec5SDimitry Andric     ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++]));
19700b57cec5SDimitry Andric 
19710b57cec5SDimitry Andric   // MSVC uses type none for variadic argument.
19720b57cec5SDimitry Andric   if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void())
19730b57cec5SDimitry Andric     ArgTypeIndices.back() = TypeIndex::None();
19740b57cec5SDimitry Andric 
19750b57cec5SDimitry Andric   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
19760b57cec5SDimitry Andric   TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
19770b57cec5SDimitry Andric 
19780b57cec5SDimitry Andric   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
19790b57cec5SDimitry Andric 
19800b57cec5SDimitry Andric   MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
19810b57cec5SDimitry Andric                            ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
19820b57cec5SDimitry Andric   return TypeTable.writeLeafType(MFR);
19830b57cec5SDimitry Andric }
19840b57cec5SDimitry Andric 
lowerTypeVFTableShape(const DIDerivedType * Ty)19850b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
19860b57cec5SDimitry Andric   unsigned VSlotCount =
19870b57cec5SDimitry Andric       Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
19880b57cec5SDimitry Andric   SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
19890b57cec5SDimitry Andric 
19900b57cec5SDimitry Andric   VFTableShapeRecord VFTSR(Slots);
19910b57cec5SDimitry Andric   return TypeTable.writeLeafType(VFTSR);
19920b57cec5SDimitry Andric }
19930b57cec5SDimitry Andric 
translateAccessFlags(unsigned RecordTag,unsigned Flags)19940b57cec5SDimitry Andric static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
19950b57cec5SDimitry Andric   switch (Flags & DINode::FlagAccessibility) {
19960b57cec5SDimitry Andric   case DINode::FlagPrivate:   return MemberAccess::Private;
19970b57cec5SDimitry Andric   case DINode::FlagPublic:    return MemberAccess::Public;
19980b57cec5SDimitry Andric   case DINode::FlagProtected: return MemberAccess::Protected;
19990b57cec5SDimitry Andric   case 0:
20000b57cec5SDimitry Andric     // If there was no explicit access control, provide the default for the tag.
20010b57cec5SDimitry Andric     return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
20020b57cec5SDimitry Andric                                                  : MemberAccess::Public;
20030b57cec5SDimitry Andric   }
20040b57cec5SDimitry Andric   llvm_unreachable("access flags are exclusive");
20050b57cec5SDimitry Andric }
20060b57cec5SDimitry Andric 
translateMethodOptionFlags(const DISubprogram * SP)20070b57cec5SDimitry Andric static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
20080b57cec5SDimitry Andric   if (SP->isArtificial())
20090b57cec5SDimitry Andric     return MethodOptions::CompilerGenerated;
20100b57cec5SDimitry Andric 
20110b57cec5SDimitry Andric   // FIXME: Handle other MethodOptions.
20120b57cec5SDimitry Andric 
20130b57cec5SDimitry Andric   return MethodOptions::None;
20140b57cec5SDimitry Andric }
20150b57cec5SDimitry Andric 
translateMethodKindFlags(const DISubprogram * SP,bool Introduced)20160b57cec5SDimitry Andric static MethodKind translateMethodKindFlags(const DISubprogram *SP,
20170b57cec5SDimitry Andric                                            bool Introduced) {
20180b57cec5SDimitry Andric   if (SP->getFlags() & DINode::FlagStaticMember)
20190b57cec5SDimitry Andric     return MethodKind::Static;
20200b57cec5SDimitry Andric 
20210b57cec5SDimitry Andric   switch (SP->getVirtuality()) {
20220b57cec5SDimitry Andric   case dwarf::DW_VIRTUALITY_none:
20230b57cec5SDimitry Andric     break;
20240b57cec5SDimitry Andric   case dwarf::DW_VIRTUALITY_virtual:
20250b57cec5SDimitry Andric     return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
20260b57cec5SDimitry Andric   case dwarf::DW_VIRTUALITY_pure_virtual:
20270b57cec5SDimitry Andric     return Introduced ? MethodKind::PureIntroducingVirtual
20280b57cec5SDimitry Andric                       : MethodKind::PureVirtual;
20290b57cec5SDimitry Andric   default:
20300b57cec5SDimitry Andric     llvm_unreachable("unhandled virtuality case");
20310b57cec5SDimitry Andric   }
20320b57cec5SDimitry Andric 
20330b57cec5SDimitry Andric   return MethodKind::Vanilla;
20340b57cec5SDimitry Andric }
20350b57cec5SDimitry Andric 
getRecordKind(const DICompositeType * Ty)20360b57cec5SDimitry Andric static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
20370b57cec5SDimitry Andric   switch (Ty->getTag()) {
2038*5f7ddb14SDimitry Andric   case dwarf::DW_TAG_class_type:
2039*5f7ddb14SDimitry Andric     return TypeRecordKind::Class;
2040*5f7ddb14SDimitry Andric   case dwarf::DW_TAG_structure_type:
2041*5f7ddb14SDimitry Andric     return TypeRecordKind::Struct;
2042*5f7ddb14SDimitry Andric   default:
20430b57cec5SDimitry Andric     llvm_unreachable("unexpected tag");
20440b57cec5SDimitry Andric   }
2045*5f7ddb14SDimitry Andric }
20460b57cec5SDimitry Andric 
20470b57cec5SDimitry Andric /// Return ClassOptions that should be present on both the forward declaration
20480b57cec5SDimitry Andric /// and the defintion of a tag type.
getCommonClassOptions(const DICompositeType * Ty)20490b57cec5SDimitry Andric static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
20500b57cec5SDimitry Andric   ClassOptions CO = ClassOptions::None;
20510b57cec5SDimitry Andric 
20520b57cec5SDimitry Andric   // MSVC always sets this flag, even for local types. Clang doesn't always
20530b57cec5SDimitry Andric   // appear to give every type a linkage name, which may be problematic for us.
20540b57cec5SDimitry Andric   // FIXME: Investigate the consequences of not following them here.
20550b57cec5SDimitry Andric   if (!Ty->getIdentifier().empty())
20560b57cec5SDimitry Andric     CO |= ClassOptions::HasUniqueName;
20570b57cec5SDimitry Andric 
20580b57cec5SDimitry Andric   // Put the Nested flag on a type if it appears immediately inside a tag type.
20590b57cec5SDimitry Andric   // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
20600b57cec5SDimitry Andric   // here. That flag is only set on definitions, and not forward declarations.
20610b57cec5SDimitry Andric   const DIScope *ImmediateScope = Ty->getScope();
20620b57cec5SDimitry Andric   if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
20630b57cec5SDimitry Andric     CO |= ClassOptions::Nested;
20640b57cec5SDimitry Andric 
20650b57cec5SDimitry Andric   // Put the Scoped flag on function-local types. MSVC puts this flag for enum
20660b57cec5SDimitry Andric   // type only when it has an immediate function scope. Clang never puts enums
20670b57cec5SDimitry Andric   // inside DILexicalBlock scopes. Enum types, as generated by clang, are
20680b57cec5SDimitry Andric   // always in function, class, or file scopes.
20690b57cec5SDimitry Andric   if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
20700b57cec5SDimitry Andric     if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
20710b57cec5SDimitry Andric       CO |= ClassOptions::Scoped;
20720b57cec5SDimitry Andric   } else {
20730b57cec5SDimitry Andric     for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
20740b57cec5SDimitry Andric          Scope = Scope->getScope()) {
20750b57cec5SDimitry Andric       if (isa<DISubprogram>(Scope)) {
20760b57cec5SDimitry Andric         CO |= ClassOptions::Scoped;
20770b57cec5SDimitry Andric         break;
20780b57cec5SDimitry Andric       }
20790b57cec5SDimitry Andric     }
20800b57cec5SDimitry Andric   }
20810b57cec5SDimitry Andric 
20820b57cec5SDimitry Andric   return CO;
20830b57cec5SDimitry Andric }
20840b57cec5SDimitry Andric 
addUDTSrcLine(const DIType * Ty,TypeIndex TI)20850b57cec5SDimitry Andric void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
20860b57cec5SDimitry Andric   switch (Ty->getTag()) {
20870b57cec5SDimitry Andric   case dwarf::DW_TAG_class_type:
20880b57cec5SDimitry Andric   case dwarf::DW_TAG_structure_type:
20890b57cec5SDimitry Andric   case dwarf::DW_TAG_union_type:
20900b57cec5SDimitry Andric   case dwarf::DW_TAG_enumeration_type:
20910b57cec5SDimitry Andric     break;
20920b57cec5SDimitry Andric   default:
20930b57cec5SDimitry Andric     return;
20940b57cec5SDimitry Andric   }
20950b57cec5SDimitry Andric 
20960b57cec5SDimitry Andric   if (const auto *File = Ty->getFile()) {
20970b57cec5SDimitry Andric     StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
20980b57cec5SDimitry Andric     TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
20990b57cec5SDimitry Andric 
21000b57cec5SDimitry Andric     UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
21010b57cec5SDimitry Andric     TypeTable.writeLeafType(USLR);
21020b57cec5SDimitry Andric   }
21030b57cec5SDimitry Andric }
21040b57cec5SDimitry Andric 
lowerTypeEnum(const DICompositeType * Ty)21050b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
21060b57cec5SDimitry Andric   ClassOptions CO = getCommonClassOptions(Ty);
21070b57cec5SDimitry Andric   TypeIndex FTI;
21080b57cec5SDimitry Andric   unsigned EnumeratorCount = 0;
21090b57cec5SDimitry Andric 
21100b57cec5SDimitry Andric   if (Ty->isForwardDecl()) {
21110b57cec5SDimitry Andric     CO |= ClassOptions::ForwardReference;
21120b57cec5SDimitry Andric   } else {
21130b57cec5SDimitry Andric     ContinuationRecordBuilder ContinuationBuilder;
21140b57cec5SDimitry Andric     ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
21150b57cec5SDimitry Andric     for (const DINode *Element : Ty->getElements()) {
21160b57cec5SDimitry Andric       // We assume that the frontend provides all members in source declaration
21170b57cec5SDimitry Andric       // order, which is what MSVC does.
21180b57cec5SDimitry Andric       if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
2119*5f7ddb14SDimitry Andric         // FIXME: Is it correct to always emit these as unsigned here?
21200b57cec5SDimitry Andric         EnumeratorRecord ER(MemberAccess::Public,
21215ffd83dbSDimitry Andric                             APSInt(Enumerator->getValue(), true),
21220b57cec5SDimitry Andric                             Enumerator->getName());
21230b57cec5SDimitry Andric         ContinuationBuilder.writeMemberType(ER);
21240b57cec5SDimitry Andric         EnumeratorCount++;
21250b57cec5SDimitry Andric       }
21260b57cec5SDimitry Andric     }
21270b57cec5SDimitry Andric     FTI = TypeTable.insertRecord(ContinuationBuilder);
21280b57cec5SDimitry Andric   }
21290b57cec5SDimitry Andric 
21300b57cec5SDimitry Andric   std::string FullName = getFullyQualifiedName(Ty);
21310b57cec5SDimitry Andric 
21320b57cec5SDimitry Andric   EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
21330b57cec5SDimitry Andric                 getTypeIndex(Ty->getBaseType()));
21340b57cec5SDimitry Andric   TypeIndex EnumTI = TypeTable.writeLeafType(ER);
21350b57cec5SDimitry Andric 
21360b57cec5SDimitry Andric   addUDTSrcLine(Ty, EnumTI);
21370b57cec5SDimitry Andric 
21380b57cec5SDimitry Andric   return EnumTI;
21390b57cec5SDimitry Andric }
21400b57cec5SDimitry Andric 
21410b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
21420b57cec5SDimitry Andric // ClassInfo
21430b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
21440b57cec5SDimitry Andric 
21450b57cec5SDimitry Andric struct llvm::ClassInfo {
21460b57cec5SDimitry Andric   struct MemberInfo {
21470b57cec5SDimitry Andric     const DIDerivedType *MemberTypeNode;
21480b57cec5SDimitry Andric     uint64_t BaseOffset;
21490b57cec5SDimitry Andric   };
21500b57cec5SDimitry Andric   // [MemberInfo]
21510b57cec5SDimitry Andric   using MemberList = std::vector<MemberInfo>;
21520b57cec5SDimitry Andric 
21530b57cec5SDimitry Andric   using MethodsList = TinyPtrVector<const DISubprogram *>;
21540b57cec5SDimitry Andric   // MethodName -> MethodsList
21550b57cec5SDimitry Andric   using MethodsMap = MapVector<MDString *, MethodsList>;
21560b57cec5SDimitry Andric 
21570b57cec5SDimitry Andric   /// Base classes.
21580b57cec5SDimitry Andric   std::vector<const DIDerivedType *> Inheritance;
21590b57cec5SDimitry Andric 
21600b57cec5SDimitry Andric   /// Direct members.
21610b57cec5SDimitry Andric   MemberList Members;
21620b57cec5SDimitry Andric   // Direct overloaded methods gathered by name.
21630b57cec5SDimitry Andric   MethodsMap Methods;
21640b57cec5SDimitry Andric 
21650b57cec5SDimitry Andric   TypeIndex VShapeTI;
21660b57cec5SDimitry Andric 
21670b57cec5SDimitry Andric   std::vector<const DIType *> NestedTypes;
21680b57cec5SDimitry Andric };
21690b57cec5SDimitry Andric 
clear()21700b57cec5SDimitry Andric void CodeViewDebug::clear() {
21710b57cec5SDimitry Andric   assert(CurFn == nullptr);
21720b57cec5SDimitry Andric   FileIdMap.clear();
21730b57cec5SDimitry Andric   FnDebugInfo.clear();
21740b57cec5SDimitry Andric   FileToFilepathMap.clear();
21750b57cec5SDimitry Andric   LocalUDTs.clear();
21760b57cec5SDimitry Andric   GlobalUDTs.clear();
21770b57cec5SDimitry Andric   TypeIndices.clear();
21780b57cec5SDimitry Andric   CompleteTypeIndices.clear();
21790b57cec5SDimitry Andric   ScopeGlobals.clear();
21800b57cec5SDimitry Andric }
21810b57cec5SDimitry Andric 
collectMemberInfo(ClassInfo & Info,const DIDerivedType * DDTy)21820b57cec5SDimitry Andric void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
21830b57cec5SDimitry Andric                                       const DIDerivedType *DDTy) {
21840b57cec5SDimitry Andric   if (!DDTy->getName().empty()) {
21850b57cec5SDimitry Andric     Info.Members.push_back({DDTy, 0});
2186af732203SDimitry Andric 
2187af732203SDimitry Andric     // Collect static const data members with values.
2188af732203SDimitry Andric     if ((DDTy->getFlags() & DINode::FlagStaticMember) ==
2189af732203SDimitry Andric         DINode::FlagStaticMember) {
2190af732203SDimitry Andric       if (DDTy->getConstant() && (isa<ConstantInt>(DDTy->getConstant()) ||
2191af732203SDimitry Andric                                   isa<ConstantFP>(DDTy->getConstant())))
2192af732203SDimitry Andric         StaticConstMembers.push_back(DDTy);
2193af732203SDimitry Andric     }
2194af732203SDimitry Andric 
21950b57cec5SDimitry Andric     return;
21960b57cec5SDimitry Andric   }
21970b57cec5SDimitry Andric 
21980b57cec5SDimitry Andric   // An unnamed member may represent a nested struct or union. Attempt to
21990b57cec5SDimitry Andric   // interpret the unnamed member as a DICompositeType possibly wrapped in
22000b57cec5SDimitry Andric   // qualifier types. Add all the indirect fields to the current record if that
22010b57cec5SDimitry Andric   // succeeds, and drop the member if that fails.
22020b57cec5SDimitry Andric   assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
22030b57cec5SDimitry Andric   uint64_t Offset = DDTy->getOffsetInBits();
22040b57cec5SDimitry Andric   const DIType *Ty = DDTy->getBaseType();
22050b57cec5SDimitry Andric   bool FullyResolved = false;
22060b57cec5SDimitry Andric   while (!FullyResolved) {
22070b57cec5SDimitry Andric     switch (Ty->getTag()) {
22080b57cec5SDimitry Andric     case dwarf::DW_TAG_const_type:
22090b57cec5SDimitry Andric     case dwarf::DW_TAG_volatile_type:
22100b57cec5SDimitry Andric       // FIXME: we should apply the qualifier types to the indirect fields
22110b57cec5SDimitry Andric       // rather than dropping them.
22120b57cec5SDimitry Andric       Ty = cast<DIDerivedType>(Ty)->getBaseType();
22130b57cec5SDimitry Andric       break;
22140b57cec5SDimitry Andric     default:
22150b57cec5SDimitry Andric       FullyResolved = true;
22160b57cec5SDimitry Andric       break;
22170b57cec5SDimitry Andric     }
22180b57cec5SDimitry Andric   }
22190b57cec5SDimitry Andric 
22200b57cec5SDimitry Andric   const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
22210b57cec5SDimitry Andric   if (!DCTy)
22220b57cec5SDimitry Andric     return;
22230b57cec5SDimitry Andric 
22240b57cec5SDimitry Andric   ClassInfo NestedInfo = collectClassInfo(DCTy);
22250b57cec5SDimitry Andric   for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
22260b57cec5SDimitry Andric     Info.Members.push_back(
22270b57cec5SDimitry Andric         {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
22280b57cec5SDimitry Andric }
22290b57cec5SDimitry Andric 
collectClassInfo(const DICompositeType * Ty)22300b57cec5SDimitry Andric ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
22310b57cec5SDimitry Andric   ClassInfo Info;
22320b57cec5SDimitry Andric   // Add elements to structure type.
22330b57cec5SDimitry Andric   DINodeArray Elements = Ty->getElements();
22340b57cec5SDimitry Andric   for (auto *Element : Elements) {
22350b57cec5SDimitry Andric     // We assume that the frontend provides all members in source declaration
22360b57cec5SDimitry Andric     // order, which is what MSVC does.
22370b57cec5SDimitry Andric     if (!Element)
22380b57cec5SDimitry Andric       continue;
22390b57cec5SDimitry Andric     if (auto *SP = dyn_cast<DISubprogram>(Element)) {
22400b57cec5SDimitry Andric       Info.Methods[SP->getRawName()].push_back(SP);
22410b57cec5SDimitry Andric     } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
22420b57cec5SDimitry Andric       if (DDTy->getTag() == dwarf::DW_TAG_member) {
22430b57cec5SDimitry Andric         collectMemberInfo(Info, DDTy);
22440b57cec5SDimitry Andric       } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
22450b57cec5SDimitry Andric         Info.Inheritance.push_back(DDTy);
22460b57cec5SDimitry Andric       } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
22470b57cec5SDimitry Andric                  DDTy->getName() == "__vtbl_ptr_type") {
22480b57cec5SDimitry Andric         Info.VShapeTI = getTypeIndex(DDTy);
22490b57cec5SDimitry Andric       } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
22500b57cec5SDimitry Andric         Info.NestedTypes.push_back(DDTy);
22510b57cec5SDimitry Andric       } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
22520b57cec5SDimitry Andric         // Ignore friend members. It appears that MSVC emitted info about
22530b57cec5SDimitry Andric         // friends in the past, but modern versions do not.
22540b57cec5SDimitry Andric       }
22550b57cec5SDimitry Andric     } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
22560b57cec5SDimitry Andric       Info.NestedTypes.push_back(Composite);
22570b57cec5SDimitry Andric     }
22580b57cec5SDimitry Andric     // Skip other unrecognized kinds of elements.
22590b57cec5SDimitry Andric   }
22600b57cec5SDimitry Andric   return Info;
22610b57cec5SDimitry Andric }
22620b57cec5SDimitry Andric 
shouldAlwaysEmitCompleteClassType(const DICompositeType * Ty)22630b57cec5SDimitry Andric static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) {
22640b57cec5SDimitry Andric   // This routine is used by lowerTypeClass and lowerTypeUnion to determine
22650b57cec5SDimitry Andric   // if a complete type should be emitted instead of a forward reference.
22660b57cec5SDimitry Andric   return Ty->getName().empty() && Ty->getIdentifier().empty() &&
22670b57cec5SDimitry Andric       !Ty->isForwardDecl();
22680b57cec5SDimitry Andric }
22690b57cec5SDimitry Andric 
lowerTypeClass(const DICompositeType * Ty)22700b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
22710b57cec5SDimitry Andric   // Emit the complete type for unnamed structs.  C++ classes with methods
22720b57cec5SDimitry Andric   // which have a circular reference back to the class type are expected to
22730b57cec5SDimitry Andric   // be named by the front-end and should not be "unnamed".  C unnamed
22740b57cec5SDimitry Andric   // structs should not have circular references.
22750b57cec5SDimitry Andric   if (shouldAlwaysEmitCompleteClassType(Ty)) {
22760b57cec5SDimitry Andric     // If this unnamed complete type is already in the process of being defined
22770b57cec5SDimitry Andric     // then the description of the type is malformed and cannot be emitted
22780b57cec5SDimitry Andric     // into CodeView correctly so report a fatal error.
22790b57cec5SDimitry Andric     auto I = CompleteTypeIndices.find(Ty);
22800b57cec5SDimitry Andric     if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
22810b57cec5SDimitry Andric       report_fatal_error("cannot debug circular reference to unnamed type");
22820b57cec5SDimitry Andric     return getCompleteTypeIndex(Ty);
22830b57cec5SDimitry Andric   }
22840b57cec5SDimitry Andric 
22850b57cec5SDimitry Andric   // First, construct the forward decl.  Don't look into Ty to compute the
22860b57cec5SDimitry Andric   // forward decl options, since it might not be available in all TUs.
22870b57cec5SDimitry Andric   TypeRecordKind Kind = getRecordKind(Ty);
22880b57cec5SDimitry Andric   ClassOptions CO =
22890b57cec5SDimitry Andric       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
22900b57cec5SDimitry Andric   std::string FullName = getFullyQualifiedName(Ty);
22910b57cec5SDimitry Andric   ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
22920b57cec5SDimitry Andric                  FullName, Ty->getIdentifier());
22930b57cec5SDimitry Andric   TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
22940b57cec5SDimitry Andric   if (!Ty->isForwardDecl())
22950b57cec5SDimitry Andric     DeferredCompleteTypes.push_back(Ty);
22960b57cec5SDimitry Andric   return FwdDeclTI;
22970b57cec5SDimitry Andric }
22980b57cec5SDimitry Andric 
lowerCompleteTypeClass(const DICompositeType * Ty)22990b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
23000b57cec5SDimitry Andric   // Construct the field list and complete type record.
23010b57cec5SDimitry Andric   TypeRecordKind Kind = getRecordKind(Ty);
23020b57cec5SDimitry Andric   ClassOptions CO = getCommonClassOptions(Ty);
23030b57cec5SDimitry Andric   TypeIndex FieldTI;
23040b57cec5SDimitry Andric   TypeIndex VShapeTI;
23050b57cec5SDimitry Andric   unsigned FieldCount;
23060b57cec5SDimitry Andric   bool ContainsNestedClass;
23070b57cec5SDimitry Andric   std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
23080b57cec5SDimitry Andric       lowerRecordFieldList(Ty);
23090b57cec5SDimitry Andric 
23100b57cec5SDimitry Andric   if (ContainsNestedClass)
23110b57cec5SDimitry Andric     CO |= ClassOptions::ContainsNestedClass;
23120b57cec5SDimitry Andric 
23130b57cec5SDimitry Andric   // MSVC appears to set this flag by searching any destructor or method with
23140b57cec5SDimitry Andric   // FunctionOptions::Constructor among the emitted members. Clang AST has all
23150b57cec5SDimitry Andric   // the members, however special member functions are not yet emitted into
23160b57cec5SDimitry Andric   // debug information. For now checking a class's non-triviality seems enough.
23170b57cec5SDimitry Andric   // FIXME: not true for a nested unnamed struct.
23180b57cec5SDimitry Andric   if (isNonTrivial(Ty))
23190b57cec5SDimitry Andric     CO |= ClassOptions::HasConstructorOrDestructor;
23200b57cec5SDimitry Andric 
23210b57cec5SDimitry Andric   std::string FullName = getFullyQualifiedName(Ty);
23220b57cec5SDimitry Andric 
23230b57cec5SDimitry Andric   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
23240b57cec5SDimitry Andric 
23250b57cec5SDimitry Andric   ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
23260b57cec5SDimitry Andric                  SizeInBytes, FullName, Ty->getIdentifier());
23270b57cec5SDimitry Andric   TypeIndex ClassTI = TypeTable.writeLeafType(CR);
23280b57cec5SDimitry Andric 
23290b57cec5SDimitry Andric   addUDTSrcLine(Ty, ClassTI);
23300b57cec5SDimitry Andric 
23310b57cec5SDimitry Andric   addToUDTs(Ty);
23320b57cec5SDimitry Andric 
23330b57cec5SDimitry Andric   return ClassTI;
23340b57cec5SDimitry Andric }
23350b57cec5SDimitry Andric 
lowerTypeUnion(const DICompositeType * Ty)23360b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
23370b57cec5SDimitry Andric   // Emit the complete type for unnamed unions.
23380b57cec5SDimitry Andric   if (shouldAlwaysEmitCompleteClassType(Ty))
23390b57cec5SDimitry Andric     return getCompleteTypeIndex(Ty);
23400b57cec5SDimitry Andric 
23410b57cec5SDimitry Andric   ClassOptions CO =
23420b57cec5SDimitry Andric       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
23430b57cec5SDimitry Andric   std::string FullName = getFullyQualifiedName(Ty);
23440b57cec5SDimitry Andric   UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
23450b57cec5SDimitry Andric   TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
23460b57cec5SDimitry Andric   if (!Ty->isForwardDecl())
23470b57cec5SDimitry Andric     DeferredCompleteTypes.push_back(Ty);
23480b57cec5SDimitry Andric   return FwdDeclTI;
23490b57cec5SDimitry Andric }
23500b57cec5SDimitry Andric 
lowerCompleteTypeUnion(const DICompositeType * Ty)23510b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
23520b57cec5SDimitry Andric   ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
23530b57cec5SDimitry Andric   TypeIndex FieldTI;
23540b57cec5SDimitry Andric   unsigned FieldCount;
23550b57cec5SDimitry Andric   bool ContainsNestedClass;
23560b57cec5SDimitry Andric   std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
23570b57cec5SDimitry Andric       lowerRecordFieldList(Ty);
23580b57cec5SDimitry Andric 
23590b57cec5SDimitry Andric   if (ContainsNestedClass)
23600b57cec5SDimitry Andric     CO |= ClassOptions::ContainsNestedClass;
23610b57cec5SDimitry Andric 
23620b57cec5SDimitry Andric   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
23630b57cec5SDimitry Andric   std::string FullName = getFullyQualifiedName(Ty);
23640b57cec5SDimitry Andric 
23650b57cec5SDimitry Andric   UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
23660b57cec5SDimitry Andric                  Ty->getIdentifier());
23670b57cec5SDimitry Andric   TypeIndex UnionTI = TypeTable.writeLeafType(UR);
23680b57cec5SDimitry Andric 
23690b57cec5SDimitry Andric   addUDTSrcLine(Ty, UnionTI);
23700b57cec5SDimitry Andric 
23710b57cec5SDimitry Andric   addToUDTs(Ty);
23720b57cec5SDimitry Andric 
23730b57cec5SDimitry Andric   return UnionTI;
23740b57cec5SDimitry Andric }
23750b57cec5SDimitry Andric 
23760b57cec5SDimitry Andric std::tuple<TypeIndex, TypeIndex, unsigned, bool>
lowerRecordFieldList(const DICompositeType * Ty)23770b57cec5SDimitry Andric CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
23780b57cec5SDimitry Andric   // Manually count members. MSVC appears to count everything that generates a
23790b57cec5SDimitry Andric   // field list record. Each individual overload in a method overload group
23800b57cec5SDimitry Andric   // contributes to this count, even though the overload group is a single field
23810b57cec5SDimitry Andric   // list record.
23820b57cec5SDimitry Andric   unsigned MemberCount = 0;
23830b57cec5SDimitry Andric   ClassInfo Info = collectClassInfo(Ty);
23840b57cec5SDimitry Andric   ContinuationRecordBuilder ContinuationBuilder;
23850b57cec5SDimitry Andric   ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
23860b57cec5SDimitry Andric 
23870b57cec5SDimitry Andric   // Create base classes.
23880b57cec5SDimitry Andric   for (const DIDerivedType *I : Info.Inheritance) {
23890b57cec5SDimitry Andric     if (I->getFlags() & DINode::FlagVirtual) {
23900b57cec5SDimitry Andric       // Virtual base.
23910b57cec5SDimitry Andric       unsigned VBPtrOffset = I->getVBPtrOffset();
23920b57cec5SDimitry Andric       // FIXME: Despite the accessor name, the offset is really in bytes.
23930b57cec5SDimitry Andric       unsigned VBTableIndex = I->getOffsetInBits() / 4;
23940b57cec5SDimitry Andric       auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
23950b57cec5SDimitry Andric                             ? TypeRecordKind::IndirectVirtualBaseClass
23960b57cec5SDimitry Andric                             : TypeRecordKind::VirtualBaseClass;
23970b57cec5SDimitry Andric       VirtualBaseClassRecord VBCR(
23980b57cec5SDimitry Andric           RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
23990b57cec5SDimitry Andric           getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
24000b57cec5SDimitry Andric           VBTableIndex);
24010b57cec5SDimitry Andric 
24020b57cec5SDimitry Andric       ContinuationBuilder.writeMemberType(VBCR);
24030b57cec5SDimitry Andric       MemberCount++;
24040b57cec5SDimitry Andric     } else {
24050b57cec5SDimitry Andric       assert(I->getOffsetInBits() % 8 == 0 &&
24060b57cec5SDimitry Andric              "bases must be on byte boundaries");
24070b57cec5SDimitry Andric       BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
24080b57cec5SDimitry Andric                           getTypeIndex(I->getBaseType()),
24090b57cec5SDimitry Andric                           I->getOffsetInBits() / 8);
24100b57cec5SDimitry Andric       ContinuationBuilder.writeMemberType(BCR);
24110b57cec5SDimitry Andric       MemberCount++;
24120b57cec5SDimitry Andric     }
24130b57cec5SDimitry Andric   }
24140b57cec5SDimitry Andric 
24150b57cec5SDimitry Andric   // Create members.
24160b57cec5SDimitry Andric   for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
24170b57cec5SDimitry Andric     const DIDerivedType *Member = MemberInfo.MemberTypeNode;
24180b57cec5SDimitry Andric     TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
24190b57cec5SDimitry Andric     StringRef MemberName = Member->getName();
24200b57cec5SDimitry Andric     MemberAccess Access =
24210b57cec5SDimitry Andric         translateAccessFlags(Ty->getTag(), Member->getFlags());
24220b57cec5SDimitry Andric 
24230b57cec5SDimitry Andric     if (Member->isStaticMember()) {
24240b57cec5SDimitry Andric       StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
24250b57cec5SDimitry Andric       ContinuationBuilder.writeMemberType(SDMR);
24260b57cec5SDimitry Andric       MemberCount++;
24270b57cec5SDimitry Andric       continue;
24280b57cec5SDimitry Andric     }
24290b57cec5SDimitry Andric 
24300b57cec5SDimitry Andric     // Virtual function pointer member.
24310b57cec5SDimitry Andric     if ((Member->getFlags() & DINode::FlagArtificial) &&
24320b57cec5SDimitry Andric         Member->getName().startswith("_vptr$")) {
24330b57cec5SDimitry Andric       VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
24340b57cec5SDimitry Andric       ContinuationBuilder.writeMemberType(VFPR);
24350b57cec5SDimitry Andric       MemberCount++;
24360b57cec5SDimitry Andric       continue;
24370b57cec5SDimitry Andric     }
24380b57cec5SDimitry Andric 
24390b57cec5SDimitry Andric     // Data member.
24400b57cec5SDimitry Andric     uint64_t MemberOffsetInBits =
24410b57cec5SDimitry Andric         Member->getOffsetInBits() + MemberInfo.BaseOffset;
24420b57cec5SDimitry Andric     if (Member->isBitField()) {
24430b57cec5SDimitry Andric       uint64_t StartBitOffset = MemberOffsetInBits;
24440b57cec5SDimitry Andric       if (const auto *CI =
24450b57cec5SDimitry Andric               dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
24460b57cec5SDimitry Andric         MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
24470b57cec5SDimitry Andric       }
24480b57cec5SDimitry Andric       StartBitOffset -= MemberOffsetInBits;
24490b57cec5SDimitry Andric       BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
24500b57cec5SDimitry Andric                          StartBitOffset);
24510b57cec5SDimitry Andric       MemberBaseType = TypeTable.writeLeafType(BFR);
24520b57cec5SDimitry Andric     }
24530b57cec5SDimitry Andric     uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
24540b57cec5SDimitry Andric     DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
24550b57cec5SDimitry Andric                          MemberName);
24560b57cec5SDimitry Andric     ContinuationBuilder.writeMemberType(DMR);
24570b57cec5SDimitry Andric     MemberCount++;
24580b57cec5SDimitry Andric   }
24590b57cec5SDimitry Andric 
24600b57cec5SDimitry Andric   // Create methods
24610b57cec5SDimitry Andric   for (auto &MethodItr : Info.Methods) {
24620b57cec5SDimitry Andric     StringRef Name = MethodItr.first->getString();
24630b57cec5SDimitry Andric 
24640b57cec5SDimitry Andric     std::vector<OneMethodRecord> Methods;
24650b57cec5SDimitry Andric     for (const DISubprogram *SP : MethodItr.second) {
24660b57cec5SDimitry Andric       TypeIndex MethodType = getMemberFunctionType(SP, Ty);
24670b57cec5SDimitry Andric       bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
24680b57cec5SDimitry Andric 
24690b57cec5SDimitry Andric       unsigned VFTableOffset = -1;
24700b57cec5SDimitry Andric       if (Introduced)
24710b57cec5SDimitry Andric         VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
24720b57cec5SDimitry Andric 
24730b57cec5SDimitry Andric       Methods.push_back(OneMethodRecord(
24740b57cec5SDimitry Andric           MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
24750b57cec5SDimitry Andric           translateMethodKindFlags(SP, Introduced),
24760b57cec5SDimitry Andric           translateMethodOptionFlags(SP), VFTableOffset, Name));
24770b57cec5SDimitry Andric       MemberCount++;
24780b57cec5SDimitry Andric     }
24790b57cec5SDimitry Andric     assert(!Methods.empty() && "Empty methods map entry");
24800b57cec5SDimitry Andric     if (Methods.size() == 1)
24810b57cec5SDimitry Andric       ContinuationBuilder.writeMemberType(Methods[0]);
24820b57cec5SDimitry Andric     else {
24830b57cec5SDimitry Andric       // FIXME: Make this use its own ContinuationBuilder so that
24840b57cec5SDimitry Andric       // MethodOverloadList can be split correctly.
24850b57cec5SDimitry Andric       MethodOverloadListRecord MOLR(Methods);
24860b57cec5SDimitry Andric       TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
24870b57cec5SDimitry Andric 
24880b57cec5SDimitry Andric       OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
24890b57cec5SDimitry Andric       ContinuationBuilder.writeMemberType(OMR);
24900b57cec5SDimitry Andric     }
24910b57cec5SDimitry Andric   }
24920b57cec5SDimitry Andric 
24930b57cec5SDimitry Andric   // Create nested classes.
24940b57cec5SDimitry Andric   for (const DIType *Nested : Info.NestedTypes) {
24950b57cec5SDimitry Andric     NestedTypeRecord R(getTypeIndex(Nested), Nested->getName());
24960b57cec5SDimitry Andric     ContinuationBuilder.writeMemberType(R);
24970b57cec5SDimitry Andric     MemberCount++;
24980b57cec5SDimitry Andric   }
24990b57cec5SDimitry Andric 
25000b57cec5SDimitry Andric   TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
25010b57cec5SDimitry Andric   return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
25020b57cec5SDimitry Andric                          !Info.NestedTypes.empty());
25030b57cec5SDimitry Andric }
25040b57cec5SDimitry Andric 
getVBPTypeIndex()25050b57cec5SDimitry Andric TypeIndex CodeViewDebug::getVBPTypeIndex() {
25060b57cec5SDimitry Andric   if (!VBPType.getIndex()) {
25070b57cec5SDimitry Andric     // Make a 'const int *' type.
25080b57cec5SDimitry Andric     ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
25090b57cec5SDimitry Andric     TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
25100b57cec5SDimitry Andric 
25110b57cec5SDimitry Andric     PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
25120b57cec5SDimitry Andric                                                   : PointerKind::Near32;
25130b57cec5SDimitry Andric     PointerMode PM = PointerMode::Pointer;
25140b57cec5SDimitry Andric     PointerOptions PO = PointerOptions::None;
25150b57cec5SDimitry Andric     PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
25160b57cec5SDimitry Andric     VBPType = TypeTable.writeLeafType(PR);
25170b57cec5SDimitry Andric   }
25180b57cec5SDimitry Andric 
25190b57cec5SDimitry Andric   return VBPType;
25200b57cec5SDimitry Andric }
25210b57cec5SDimitry Andric 
getTypeIndex(const DIType * Ty,const DIType * ClassTy)25220b57cec5SDimitry Andric TypeIndex CodeViewDebug::getTypeIndex(const DIType *Ty, const DIType *ClassTy) {
25230b57cec5SDimitry Andric   // The null DIType is the void type. Don't try to hash it.
25240b57cec5SDimitry Andric   if (!Ty)
25250b57cec5SDimitry Andric     return TypeIndex::Void();
25260b57cec5SDimitry Andric 
25270b57cec5SDimitry Andric   // Check if we've already translated this type. Don't try to do a
25280b57cec5SDimitry Andric   // get-or-create style insertion that caches the hash lookup across the
25290b57cec5SDimitry Andric   // lowerType call. It will update the TypeIndices map.
25300b57cec5SDimitry Andric   auto I = TypeIndices.find({Ty, ClassTy});
25310b57cec5SDimitry Andric   if (I != TypeIndices.end())
25320b57cec5SDimitry Andric     return I->second;
25330b57cec5SDimitry Andric 
25340b57cec5SDimitry Andric   TypeLoweringScope S(*this);
25350b57cec5SDimitry Andric   TypeIndex TI = lowerType(Ty, ClassTy);
25360b57cec5SDimitry Andric   return recordTypeIndexForDINode(Ty, TI, ClassTy);
25370b57cec5SDimitry Andric }
25380b57cec5SDimitry Andric 
25390b57cec5SDimitry Andric codeview::TypeIndex
getTypeIndexForThisPtr(const DIDerivedType * PtrTy,const DISubroutineType * SubroutineTy)25400b57cec5SDimitry Andric CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy,
25410b57cec5SDimitry Andric                                       const DISubroutineType *SubroutineTy) {
25420b57cec5SDimitry Andric   assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type &&
25430b57cec5SDimitry Andric          "this type must be a pointer type");
25440b57cec5SDimitry Andric 
25450b57cec5SDimitry Andric   PointerOptions Options = PointerOptions::None;
25460b57cec5SDimitry Andric   if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference)
25470b57cec5SDimitry Andric     Options = PointerOptions::LValueRefThisPointer;
25480b57cec5SDimitry Andric   else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference)
25490b57cec5SDimitry Andric     Options = PointerOptions::RValueRefThisPointer;
25500b57cec5SDimitry Andric 
25510b57cec5SDimitry Andric   // Check if we've already translated this type.  If there is no ref qualifier
25520b57cec5SDimitry Andric   // on the function then we look up this pointer type with no associated class
25530b57cec5SDimitry Andric   // so that the TypeIndex for the this pointer can be shared with the type
25540b57cec5SDimitry Andric   // index for other pointers to this class type.  If there is a ref qualifier
25550b57cec5SDimitry Andric   // then we lookup the pointer using the subroutine as the parent type.
25560b57cec5SDimitry Andric   auto I = TypeIndices.find({PtrTy, SubroutineTy});
25570b57cec5SDimitry Andric   if (I != TypeIndices.end())
25580b57cec5SDimitry Andric     return I->second;
25590b57cec5SDimitry Andric 
25600b57cec5SDimitry Andric   TypeLoweringScope S(*this);
25610b57cec5SDimitry Andric   TypeIndex TI = lowerTypePointer(PtrTy, Options);
25620b57cec5SDimitry Andric   return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy);
25630b57cec5SDimitry Andric }
25640b57cec5SDimitry Andric 
getTypeIndexForReferenceTo(const DIType * Ty)25650b57cec5SDimitry Andric TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(const DIType *Ty) {
25660b57cec5SDimitry Andric   PointerRecord PR(getTypeIndex(Ty),
25670b57cec5SDimitry Andric                    getPointerSizeInBytes() == 8 ? PointerKind::Near64
25680b57cec5SDimitry Andric                                                 : PointerKind::Near32,
25690b57cec5SDimitry Andric                    PointerMode::LValueReference, PointerOptions::None,
25700b57cec5SDimitry Andric                    Ty->getSizeInBits() / 8);
25710b57cec5SDimitry Andric   return TypeTable.writeLeafType(PR);
25720b57cec5SDimitry Andric }
25730b57cec5SDimitry Andric 
getCompleteTypeIndex(const DIType * Ty)25740b57cec5SDimitry Andric TypeIndex CodeViewDebug::getCompleteTypeIndex(const DIType *Ty) {
25750b57cec5SDimitry Andric   // The null DIType is the void type. Don't try to hash it.
25760b57cec5SDimitry Andric   if (!Ty)
25770b57cec5SDimitry Andric     return TypeIndex::Void();
25780b57cec5SDimitry Andric 
25790b57cec5SDimitry Andric   // Look through typedefs when getting the complete type index. Call
25800b57cec5SDimitry Andric   // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are
25810b57cec5SDimitry Andric   // emitted only once.
25820b57cec5SDimitry Andric   if (Ty->getTag() == dwarf::DW_TAG_typedef)
25830b57cec5SDimitry Andric     (void)getTypeIndex(Ty);
25840b57cec5SDimitry Andric   while (Ty->getTag() == dwarf::DW_TAG_typedef)
25850b57cec5SDimitry Andric     Ty = cast<DIDerivedType>(Ty)->getBaseType();
25860b57cec5SDimitry Andric 
25870b57cec5SDimitry Andric   // If this is a non-record type, the complete type index is the same as the
25880b57cec5SDimitry Andric   // normal type index. Just call getTypeIndex.
25890b57cec5SDimitry Andric   switch (Ty->getTag()) {
25900b57cec5SDimitry Andric   case dwarf::DW_TAG_class_type:
25910b57cec5SDimitry Andric   case dwarf::DW_TAG_structure_type:
25920b57cec5SDimitry Andric   case dwarf::DW_TAG_union_type:
25930b57cec5SDimitry Andric     break;
25940b57cec5SDimitry Andric   default:
25950b57cec5SDimitry Andric     return getTypeIndex(Ty);
25960b57cec5SDimitry Andric   }
25970b57cec5SDimitry Andric 
25980b57cec5SDimitry Andric   const auto *CTy = cast<DICompositeType>(Ty);
25990b57cec5SDimitry Andric 
26000b57cec5SDimitry Andric   TypeLoweringScope S(*this);
26010b57cec5SDimitry Andric 
26020b57cec5SDimitry Andric   // Make sure the forward declaration is emitted first. It's unclear if this
26030b57cec5SDimitry Andric   // is necessary, but MSVC does it, and we should follow suit until we can show
26040b57cec5SDimitry Andric   // otherwise.
26050b57cec5SDimitry Andric   // We only emit a forward declaration for named types.
26060b57cec5SDimitry Andric   if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
26070b57cec5SDimitry Andric     TypeIndex FwdDeclTI = getTypeIndex(CTy);
26080b57cec5SDimitry Andric 
26090b57cec5SDimitry Andric     // Just use the forward decl if we don't have complete type info. This
26100b57cec5SDimitry Andric     // might happen if the frontend is using modules and expects the complete
26110b57cec5SDimitry Andric     // definition to be emitted elsewhere.
26120b57cec5SDimitry Andric     if (CTy->isForwardDecl())
26130b57cec5SDimitry Andric       return FwdDeclTI;
26140b57cec5SDimitry Andric   }
26150b57cec5SDimitry Andric 
26160b57cec5SDimitry Andric   // Check if we've already translated the complete record type.
26170b57cec5SDimitry Andric   // Insert the type with a null TypeIndex to signify that the type is currently
26180b57cec5SDimitry Andric   // being lowered.
26190b57cec5SDimitry Andric   auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
26200b57cec5SDimitry Andric   if (!InsertResult.second)
26210b57cec5SDimitry Andric     return InsertResult.first->second;
26220b57cec5SDimitry Andric 
26230b57cec5SDimitry Andric   TypeIndex TI;
26240b57cec5SDimitry Andric   switch (CTy->getTag()) {
26250b57cec5SDimitry Andric   case dwarf::DW_TAG_class_type:
26260b57cec5SDimitry Andric   case dwarf::DW_TAG_structure_type:
26270b57cec5SDimitry Andric     TI = lowerCompleteTypeClass(CTy);
26280b57cec5SDimitry Andric     break;
26290b57cec5SDimitry Andric   case dwarf::DW_TAG_union_type:
26300b57cec5SDimitry Andric     TI = lowerCompleteTypeUnion(CTy);
26310b57cec5SDimitry Andric     break;
26320b57cec5SDimitry Andric   default:
26330b57cec5SDimitry Andric     llvm_unreachable("not a record");
26340b57cec5SDimitry Andric   }
26350b57cec5SDimitry Andric 
26360b57cec5SDimitry Andric   // Update the type index associated with this CompositeType.  This cannot
26370b57cec5SDimitry Andric   // use the 'InsertResult' iterator above because it is potentially
26380b57cec5SDimitry Andric   // invalidated by map insertions which can occur while lowering the class
26390b57cec5SDimitry Andric   // type above.
26400b57cec5SDimitry Andric   CompleteTypeIndices[CTy] = TI;
26410b57cec5SDimitry Andric   return TI;
26420b57cec5SDimitry Andric }
26430b57cec5SDimitry Andric 
26440b57cec5SDimitry Andric /// Emit all the deferred complete record types. Try to do this in FIFO order,
26450b57cec5SDimitry Andric /// and do this until fixpoint, as each complete record type typically
26460b57cec5SDimitry Andric /// references
26470b57cec5SDimitry Andric /// many other record types.
emitDeferredCompleteTypes()26480b57cec5SDimitry Andric void CodeViewDebug::emitDeferredCompleteTypes() {
26490b57cec5SDimitry Andric   SmallVector<const DICompositeType *, 4> TypesToEmit;
26500b57cec5SDimitry Andric   while (!DeferredCompleteTypes.empty()) {
26510b57cec5SDimitry Andric     std::swap(DeferredCompleteTypes, TypesToEmit);
26520b57cec5SDimitry Andric     for (const DICompositeType *RecordTy : TypesToEmit)
26530b57cec5SDimitry Andric       getCompleteTypeIndex(RecordTy);
26540b57cec5SDimitry Andric     TypesToEmit.clear();
26550b57cec5SDimitry Andric   }
26560b57cec5SDimitry Andric }
26570b57cec5SDimitry Andric 
emitLocalVariableList(const FunctionInfo & FI,ArrayRef<LocalVariable> Locals)26580b57cec5SDimitry Andric void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
26590b57cec5SDimitry Andric                                           ArrayRef<LocalVariable> Locals) {
26600b57cec5SDimitry Andric   // Get the sorted list of parameters and emit them first.
26610b57cec5SDimitry Andric   SmallVector<const LocalVariable *, 6> Params;
26620b57cec5SDimitry Andric   for (const LocalVariable &L : Locals)
26630b57cec5SDimitry Andric     if (L.DIVar->isParameter())
26640b57cec5SDimitry Andric       Params.push_back(&L);
26650b57cec5SDimitry Andric   llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
26660b57cec5SDimitry Andric     return L->DIVar->getArg() < R->DIVar->getArg();
26670b57cec5SDimitry Andric   });
26680b57cec5SDimitry Andric   for (const LocalVariable *L : Params)
26690b57cec5SDimitry Andric     emitLocalVariable(FI, *L);
26700b57cec5SDimitry Andric 
26710b57cec5SDimitry Andric   // Next emit all non-parameters in the order that we found them.
26720b57cec5SDimitry Andric   for (const LocalVariable &L : Locals)
26730b57cec5SDimitry Andric     if (!L.DIVar->isParameter())
26740b57cec5SDimitry Andric       emitLocalVariable(FI, L);
26750b57cec5SDimitry Andric }
26760b57cec5SDimitry Andric 
emitLocalVariable(const FunctionInfo & FI,const LocalVariable & Var)26770b57cec5SDimitry Andric void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
26780b57cec5SDimitry Andric                                       const LocalVariable &Var) {
26790b57cec5SDimitry Andric   // LocalSym record, see SymbolRecord.h for more info.
26800b57cec5SDimitry Andric   MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL);
26810b57cec5SDimitry Andric 
26820b57cec5SDimitry Andric   LocalSymFlags Flags = LocalSymFlags::None;
26830b57cec5SDimitry Andric   if (Var.DIVar->isParameter())
26840b57cec5SDimitry Andric     Flags |= LocalSymFlags::IsParameter;
26850b57cec5SDimitry Andric   if (Var.DefRanges.empty())
26860b57cec5SDimitry Andric     Flags |= LocalSymFlags::IsOptimizedOut;
26870b57cec5SDimitry Andric 
26880b57cec5SDimitry Andric   OS.AddComment("TypeIndex");
26890b57cec5SDimitry Andric   TypeIndex TI = Var.UseReferenceType
26900b57cec5SDimitry Andric                      ? getTypeIndexForReferenceTo(Var.DIVar->getType())
26910b57cec5SDimitry Andric                      : getCompleteTypeIndex(Var.DIVar->getType());
26925ffd83dbSDimitry Andric   OS.emitInt32(TI.getIndex());
26930b57cec5SDimitry Andric   OS.AddComment("Flags");
26945ffd83dbSDimitry Andric   OS.emitInt16(static_cast<uint16_t>(Flags));
26950b57cec5SDimitry Andric   // Truncate the name so we won't overflow the record length field.
26960b57cec5SDimitry Andric   emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
26970b57cec5SDimitry Andric   endSymbolRecord(LocalEnd);
26980b57cec5SDimitry Andric 
26990b57cec5SDimitry Andric   // Calculate the on disk prefix of the appropriate def range record. The
27000b57cec5SDimitry Andric   // records and on disk formats are described in SymbolRecords.h. BytePrefix
27010b57cec5SDimitry Andric   // should be big enough to hold all forms without memory allocation.
27020b57cec5SDimitry Andric   SmallString<20> BytePrefix;
27030b57cec5SDimitry Andric   for (const LocalVarDefRange &DefRange : Var.DefRanges) {
27040b57cec5SDimitry Andric     BytePrefix.clear();
27050b57cec5SDimitry Andric     if (DefRange.InMemory) {
27060b57cec5SDimitry Andric       int Offset = DefRange.DataOffset;
27070b57cec5SDimitry Andric       unsigned Reg = DefRange.CVRegister;
27080b57cec5SDimitry Andric 
27090b57cec5SDimitry Andric       // 32-bit x86 call sequences often use PUSH instructions, which disrupt
27100b57cec5SDimitry Andric       // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
27110b57cec5SDimitry Andric       // instead. In frames without stack realignment, $T0 will be the CFA.
27120b57cec5SDimitry Andric       if (RegisterId(Reg) == RegisterId::ESP) {
27130b57cec5SDimitry Andric         Reg = unsigned(RegisterId::VFRAME);
27140b57cec5SDimitry Andric         Offset += FI.OffsetAdjustment;
27150b57cec5SDimitry Andric       }
27160b57cec5SDimitry Andric 
27170b57cec5SDimitry Andric       // If we can use the chosen frame pointer for the frame and this isn't a
27180b57cec5SDimitry Andric       // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
27190b57cec5SDimitry Andric       // Otherwise, use S_DEFRANGE_REGISTER_REL.
27200b57cec5SDimitry Andric       EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU);
27210b57cec5SDimitry Andric       if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
27220b57cec5SDimitry Andric           (bool(Flags & LocalSymFlags::IsParameter)
27230b57cec5SDimitry Andric                ? (EncFP == FI.EncodedParamFramePtrReg)
27240b57cec5SDimitry Andric                : (EncFP == FI.EncodedLocalFramePtrReg))) {
27258bcb0991SDimitry Andric         DefRangeFramePointerRelHeader DRHdr;
27268bcb0991SDimitry Andric         DRHdr.Offset = Offset;
27275ffd83dbSDimitry Andric         OS.emitCVDefRangeDirective(DefRange.Ranges, DRHdr);
27280b57cec5SDimitry Andric       } else {
27290b57cec5SDimitry Andric         uint16_t RegRelFlags = 0;
27300b57cec5SDimitry Andric         if (DefRange.IsSubfield) {
27310b57cec5SDimitry Andric           RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
27320b57cec5SDimitry Andric                         (DefRange.StructOffset
27330b57cec5SDimitry Andric                          << DefRangeRegisterRelSym::OffsetInParentShift);
27340b57cec5SDimitry Andric         }
27358bcb0991SDimitry Andric         DefRangeRegisterRelHeader DRHdr;
27360b57cec5SDimitry Andric         DRHdr.Register = Reg;
27370b57cec5SDimitry Andric         DRHdr.Flags = RegRelFlags;
27380b57cec5SDimitry Andric         DRHdr.BasePointerOffset = Offset;
27395ffd83dbSDimitry Andric         OS.emitCVDefRangeDirective(DefRange.Ranges, DRHdr);
27400b57cec5SDimitry Andric       }
27410b57cec5SDimitry Andric     } else {
27420b57cec5SDimitry Andric       assert(DefRange.DataOffset == 0 && "unexpected offset into register");
27430b57cec5SDimitry Andric       if (DefRange.IsSubfield) {
27448bcb0991SDimitry Andric         DefRangeSubfieldRegisterHeader DRHdr;
27450b57cec5SDimitry Andric         DRHdr.Register = DefRange.CVRegister;
27460b57cec5SDimitry Andric         DRHdr.MayHaveNoName = 0;
27470b57cec5SDimitry Andric         DRHdr.OffsetInParent = DefRange.StructOffset;
27485ffd83dbSDimitry Andric         OS.emitCVDefRangeDirective(DefRange.Ranges, DRHdr);
27490b57cec5SDimitry Andric       } else {
27508bcb0991SDimitry Andric         DefRangeRegisterHeader DRHdr;
27510b57cec5SDimitry Andric         DRHdr.Register = DefRange.CVRegister;
27520b57cec5SDimitry Andric         DRHdr.MayHaveNoName = 0;
27535ffd83dbSDimitry Andric         OS.emitCVDefRangeDirective(DefRange.Ranges, DRHdr);
27540b57cec5SDimitry Andric       }
27550b57cec5SDimitry Andric     }
27560b57cec5SDimitry Andric   }
27570b57cec5SDimitry Andric }
27580b57cec5SDimitry Andric 
emitLexicalBlockList(ArrayRef<LexicalBlock * > Blocks,const FunctionInfo & FI)27590b57cec5SDimitry Andric void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
27600b57cec5SDimitry Andric                                          const FunctionInfo& FI) {
27610b57cec5SDimitry Andric   for (LexicalBlock *Block : Blocks)
27620b57cec5SDimitry Andric     emitLexicalBlock(*Block, FI);
27630b57cec5SDimitry Andric }
27640b57cec5SDimitry Andric 
27650b57cec5SDimitry Andric /// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
27660b57cec5SDimitry Andric /// lexical block scope.
emitLexicalBlock(const LexicalBlock & Block,const FunctionInfo & FI)27670b57cec5SDimitry Andric void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
27680b57cec5SDimitry Andric                                      const FunctionInfo& FI) {
27690b57cec5SDimitry Andric   MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32);
27700b57cec5SDimitry Andric   OS.AddComment("PtrParent");
27715ffd83dbSDimitry Andric   OS.emitInt32(0); // PtrParent
27720b57cec5SDimitry Andric   OS.AddComment("PtrEnd");
27735ffd83dbSDimitry Andric   OS.emitInt32(0); // PtrEnd
27740b57cec5SDimitry Andric   OS.AddComment("Code size");
27750b57cec5SDimitry Andric   OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4);   // Code Size
27760b57cec5SDimitry Andric   OS.AddComment("Function section relative address");
27770b57cec5SDimitry Andric   OS.EmitCOFFSecRel32(Block.Begin, /*Offset=*/0);         // Func Offset
27780b57cec5SDimitry Andric   OS.AddComment("Function section index");
27790b57cec5SDimitry Andric   OS.EmitCOFFSectionIndex(FI.Begin);                      // Func Symbol
27800b57cec5SDimitry Andric   OS.AddComment("Lexical block name");
27810b57cec5SDimitry Andric   emitNullTerminatedSymbolName(OS, Block.Name);           // Name
27820b57cec5SDimitry Andric   endSymbolRecord(RecordEnd);
27830b57cec5SDimitry Andric 
27840b57cec5SDimitry Andric   // Emit variables local to this lexical block.
27850b57cec5SDimitry Andric   emitLocalVariableList(FI, Block.Locals);
27860b57cec5SDimitry Andric   emitGlobalVariableList(Block.Globals);
27870b57cec5SDimitry Andric 
27880b57cec5SDimitry Andric   // Emit lexical blocks contained within this block.
27890b57cec5SDimitry Andric   emitLexicalBlockList(Block.Children, FI);
27900b57cec5SDimitry Andric 
27910b57cec5SDimitry Andric   // Close the lexical block scope.
27920b57cec5SDimitry Andric   emitEndSymbolRecord(SymbolKind::S_END);
27930b57cec5SDimitry Andric }
27940b57cec5SDimitry Andric 
27950b57cec5SDimitry Andric /// Convenience routine for collecting lexical block information for a list
27960b57cec5SDimitry Andric /// of lexical scopes.
collectLexicalBlockInfo(SmallVectorImpl<LexicalScope * > & Scopes,SmallVectorImpl<LexicalBlock * > & Blocks,SmallVectorImpl<LocalVariable> & Locals,SmallVectorImpl<CVGlobalVariable> & Globals)27970b57cec5SDimitry Andric void CodeViewDebug::collectLexicalBlockInfo(
27980b57cec5SDimitry Andric         SmallVectorImpl<LexicalScope *> &Scopes,
27990b57cec5SDimitry Andric         SmallVectorImpl<LexicalBlock *> &Blocks,
28000b57cec5SDimitry Andric         SmallVectorImpl<LocalVariable> &Locals,
28010b57cec5SDimitry Andric         SmallVectorImpl<CVGlobalVariable> &Globals) {
28020b57cec5SDimitry Andric   for (LexicalScope *Scope : Scopes)
28030b57cec5SDimitry Andric     collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals);
28040b57cec5SDimitry Andric }
28050b57cec5SDimitry Andric 
28060b57cec5SDimitry Andric /// Populate the lexical blocks and local variable lists of the parent with
28070b57cec5SDimitry Andric /// information about the specified lexical scope.
collectLexicalBlockInfo(LexicalScope & Scope,SmallVectorImpl<LexicalBlock * > & ParentBlocks,SmallVectorImpl<LocalVariable> & ParentLocals,SmallVectorImpl<CVGlobalVariable> & ParentGlobals)28080b57cec5SDimitry Andric void CodeViewDebug::collectLexicalBlockInfo(
28090b57cec5SDimitry Andric     LexicalScope &Scope,
28100b57cec5SDimitry Andric     SmallVectorImpl<LexicalBlock *> &ParentBlocks,
28110b57cec5SDimitry Andric     SmallVectorImpl<LocalVariable> &ParentLocals,
28120b57cec5SDimitry Andric     SmallVectorImpl<CVGlobalVariable> &ParentGlobals) {
28130b57cec5SDimitry Andric   if (Scope.isAbstractScope())
28140b57cec5SDimitry Andric     return;
28150b57cec5SDimitry Andric 
28160b57cec5SDimitry Andric   // Gather information about the lexical scope including local variables,
28170b57cec5SDimitry Andric   // global variables, and address ranges.
28180b57cec5SDimitry Andric   bool IgnoreScope = false;
28190b57cec5SDimitry Andric   auto LI = ScopeVariables.find(&Scope);
28200b57cec5SDimitry Andric   SmallVectorImpl<LocalVariable> *Locals =
28210b57cec5SDimitry Andric       LI != ScopeVariables.end() ? &LI->second : nullptr;
28220b57cec5SDimitry Andric   auto GI = ScopeGlobals.find(Scope.getScopeNode());
28230b57cec5SDimitry Andric   SmallVectorImpl<CVGlobalVariable> *Globals =
28240b57cec5SDimitry Andric       GI != ScopeGlobals.end() ? GI->second.get() : nullptr;
28250b57cec5SDimitry Andric   const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
28260b57cec5SDimitry Andric   const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
28270b57cec5SDimitry Andric 
28280b57cec5SDimitry Andric   // Ignore lexical scopes which do not contain variables.
28290b57cec5SDimitry Andric   if (!Locals && !Globals)
28300b57cec5SDimitry Andric     IgnoreScope = true;
28310b57cec5SDimitry Andric 
28320b57cec5SDimitry Andric   // Ignore lexical scopes which are not lexical blocks.
28330b57cec5SDimitry Andric   if (!DILB)
28340b57cec5SDimitry Andric     IgnoreScope = true;
28350b57cec5SDimitry Andric 
28360b57cec5SDimitry Andric   // Ignore scopes which have too many address ranges to represent in the
28370b57cec5SDimitry Andric   // current CodeView format or do not have a valid address range.
28380b57cec5SDimitry Andric   //
28390b57cec5SDimitry Andric   // For lexical scopes with multiple address ranges you may be tempted to
28400b57cec5SDimitry Andric   // construct a single range covering every instruction where the block is
28410b57cec5SDimitry Andric   // live and everything in between.  Unfortunately, Visual Studio only
28420b57cec5SDimitry Andric   // displays variables from the first matching lexical block scope.  If the
28430b57cec5SDimitry Andric   // first lexical block contains exception handling code or cold code which
28440b57cec5SDimitry Andric   // is moved to the bottom of the routine creating a single range covering
28450b57cec5SDimitry Andric   // nearly the entire routine, then it will hide all other lexical blocks
28460b57cec5SDimitry Andric   // and the variables they contain.
28470b57cec5SDimitry Andric   if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second))
28480b57cec5SDimitry Andric     IgnoreScope = true;
28490b57cec5SDimitry Andric 
28500b57cec5SDimitry Andric   if (IgnoreScope) {
28510b57cec5SDimitry Andric     // This scope can be safely ignored and eliminating it will reduce the
28520b57cec5SDimitry Andric     // size of the debug information. Be sure to collect any variable and scope
28530b57cec5SDimitry Andric     // information from the this scope or any of its children and collapse them
28540b57cec5SDimitry Andric     // into the parent scope.
28550b57cec5SDimitry Andric     if (Locals)
28560b57cec5SDimitry Andric       ParentLocals.append(Locals->begin(), Locals->end());
28570b57cec5SDimitry Andric     if (Globals)
28580b57cec5SDimitry Andric       ParentGlobals.append(Globals->begin(), Globals->end());
28590b57cec5SDimitry Andric     collectLexicalBlockInfo(Scope.getChildren(),
28600b57cec5SDimitry Andric                             ParentBlocks,
28610b57cec5SDimitry Andric                             ParentLocals,
28620b57cec5SDimitry Andric                             ParentGlobals);
28630b57cec5SDimitry Andric     return;
28640b57cec5SDimitry Andric   }
28650b57cec5SDimitry Andric 
28660b57cec5SDimitry Andric   // Create a new CodeView lexical block for this lexical scope.  If we've
28670b57cec5SDimitry Andric   // seen this DILexicalBlock before then the scope tree is malformed and
28680b57cec5SDimitry Andric   // we can handle this gracefully by not processing it a second time.
28690b57cec5SDimitry Andric   auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
28700b57cec5SDimitry Andric   if (!BlockInsertion.second)
28710b57cec5SDimitry Andric     return;
28720b57cec5SDimitry Andric 
28730b57cec5SDimitry Andric   // Create a lexical block containing the variables and collect the the
28740b57cec5SDimitry Andric   // lexical block information for the children.
28750b57cec5SDimitry Andric   const InsnRange &Range = Ranges.front();
28760b57cec5SDimitry Andric   assert(Range.first && Range.second);
28770b57cec5SDimitry Andric   LexicalBlock &Block = BlockInsertion.first->second;
28780b57cec5SDimitry Andric   Block.Begin = getLabelBeforeInsn(Range.first);
28790b57cec5SDimitry Andric   Block.End = getLabelAfterInsn(Range.second);
28800b57cec5SDimitry Andric   assert(Block.Begin && "missing label for scope begin");
28810b57cec5SDimitry Andric   assert(Block.End && "missing label for scope end");
28820b57cec5SDimitry Andric   Block.Name = DILB->getName();
28830b57cec5SDimitry Andric   if (Locals)
28840b57cec5SDimitry Andric     Block.Locals = std::move(*Locals);
28850b57cec5SDimitry Andric   if (Globals)
28860b57cec5SDimitry Andric     Block.Globals = std::move(*Globals);
28870b57cec5SDimitry Andric   ParentBlocks.push_back(&Block);
28880b57cec5SDimitry Andric   collectLexicalBlockInfo(Scope.getChildren(),
28890b57cec5SDimitry Andric                           Block.Children,
28900b57cec5SDimitry Andric                           Block.Locals,
28910b57cec5SDimitry Andric                           Block.Globals);
28920b57cec5SDimitry Andric }
28930b57cec5SDimitry Andric 
endFunctionImpl(const MachineFunction * MF)28940b57cec5SDimitry Andric void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
28950b57cec5SDimitry Andric   const Function &GV = MF->getFunction();
28960b57cec5SDimitry Andric   assert(FnDebugInfo.count(&GV));
28970b57cec5SDimitry Andric   assert(CurFn == FnDebugInfo[&GV].get());
28980b57cec5SDimitry Andric 
28990b57cec5SDimitry Andric   collectVariableInfo(GV.getSubprogram());
29000b57cec5SDimitry Andric 
29010b57cec5SDimitry Andric   // Build the lexical block structure to emit for this routine.
29020b57cec5SDimitry Andric   if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
29030b57cec5SDimitry Andric     collectLexicalBlockInfo(*CFS,
29040b57cec5SDimitry Andric                             CurFn->ChildBlocks,
29050b57cec5SDimitry Andric                             CurFn->Locals,
29060b57cec5SDimitry Andric                             CurFn->Globals);
29070b57cec5SDimitry Andric 
29080b57cec5SDimitry Andric   // Clear the scope and variable information from the map which will not be
29090b57cec5SDimitry Andric   // valid after we have finished processing this routine.  This also prepares
29100b57cec5SDimitry Andric   // the map for the subsequent routine.
29110b57cec5SDimitry Andric   ScopeVariables.clear();
29120b57cec5SDimitry Andric 
29130b57cec5SDimitry Andric   // Don't emit anything if we don't have any line tables.
29140b57cec5SDimitry Andric   // Thunks are compiler-generated and probably won't have source correlation.
29150b57cec5SDimitry Andric   if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
29160b57cec5SDimitry Andric     FnDebugInfo.erase(&GV);
29170b57cec5SDimitry Andric     CurFn = nullptr;
29180b57cec5SDimitry Andric     return;
29190b57cec5SDimitry Andric   }
29200b57cec5SDimitry Andric 
2921480093f4SDimitry Andric   // Find heap alloc sites and add to list.
2922480093f4SDimitry Andric   for (const auto &MBB : *MF) {
2923480093f4SDimitry Andric     for (const auto &MI : MBB) {
2924480093f4SDimitry Andric       if (MDNode *MD = MI.getHeapAllocMarker()) {
2925480093f4SDimitry Andric         CurFn->HeapAllocSites.push_back(std::make_tuple(getLabelBeforeInsn(&MI),
2926480093f4SDimitry Andric                                                         getLabelAfterInsn(&MI),
2927480093f4SDimitry Andric                                                         dyn_cast<DIType>(MD)));
2928480093f4SDimitry Andric       }
2929480093f4SDimitry Andric     }
2930480093f4SDimitry Andric   }
2931480093f4SDimitry Andric 
29320b57cec5SDimitry Andric   CurFn->Annotations = MF->getCodeViewAnnotations();
29330b57cec5SDimitry Andric 
29340b57cec5SDimitry Andric   CurFn->End = Asm->getFunctionEnd();
29350b57cec5SDimitry Andric 
29360b57cec5SDimitry Andric   CurFn = nullptr;
29370b57cec5SDimitry Andric }
29380b57cec5SDimitry Andric 
29398bcb0991SDimitry Andric // Usable locations are valid with non-zero line numbers. A line number of zero
29408bcb0991SDimitry Andric // corresponds to optimized code that doesn't have a distinct source location.
29418bcb0991SDimitry Andric // In this case, we try to use the previous or next source location depending on
29428bcb0991SDimitry Andric // the context.
isUsableDebugLoc(DebugLoc DL)29438bcb0991SDimitry Andric static bool isUsableDebugLoc(DebugLoc DL) {
29448bcb0991SDimitry Andric   return DL && DL.getLine() != 0;
29458bcb0991SDimitry Andric }
29468bcb0991SDimitry Andric 
beginInstruction(const MachineInstr * MI)29470b57cec5SDimitry Andric void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
29480b57cec5SDimitry Andric   DebugHandlerBase::beginInstruction(MI);
29490b57cec5SDimitry Andric 
29500b57cec5SDimitry Andric   // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
29510b57cec5SDimitry Andric   if (!Asm || !CurFn || MI->isDebugInstr() ||
29520b57cec5SDimitry Andric       MI->getFlag(MachineInstr::FrameSetup))
29530b57cec5SDimitry Andric     return;
29540b57cec5SDimitry Andric 
29550b57cec5SDimitry Andric   // If the first instruction of a new MBB has no location, find the first
29560b57cec5SDimitry Andric   // instruction with a location and use that.
29570b57cec5SDimitry Andric   DebugLoc DL = MI->getDebugLoc();
29588bcb0991SDimitry Andric   if (!isUsableDebugLoc(DL) && MI->getParent() != PrevInstBB) {
29590b57cec5SDimitry Andric     for (const auto &NextMI : *MI->getParent()) {
29600b57cec5SDimitry Andric       if (NextMI.isDebugInstr())
29610b57cec5SDimitry Andric         continue;
29620b57cec5SDimitry Andric       DL = NextMI.getDebugLoc();
29638bcb0991SDimitry Andric       if (isUsableDebugLoc(DL))
29640b57cec5SDimitry Andric         break;
29650b57cec5SDimitry Andric     }
29668bcb0991SDimitry Andric     // FIXME: Handle the case where the BB has no valid locations. This would
29678bcb0991SDimitry Andric     // probably require doing a real dataflow analysis.
29680b57cec5SDimitry Andric   }
29690b57cec5SDimitry Andric   PrevInstBB = MI->getParent();
29700b57cec5SDimitry Andric 
29710b57cec5SDimitry Andric   // If we still don't have a debug location, don't record a location.
29728bcb0991SDimitry Andric   if (!isUsableDebugLoc(DL))
29730b57cec5SDimitry Andric     return;
29740b57cec5SDimitry Andric 
29750b57cec5SDimitry Andric   maybeRecordLocation(DL, Asm->MF);
29760b57cec5SDimitry Andric }
29770b57cec5SDimitry Andric 
beginCVSubsection(DebugSubsectionKind Kind)29780b57cec5SDimitry Andric MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
29790b57cec5SDimitry Andric   MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
29800b57cec5SDimitry Andric            *EndLabel = MMI->getContext().createTempSymbol();
29815ffd83dbSDimitry Andric   OS.emitInt32(unsigned(Kind));
29820b57cec5SDimitry Andric   OS.AddComment("Subsection size");
29830b57cec5SDimitry Andric   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
29845ffd83dbSDimitry Andric   OS.emitLabel(BeginLabel);
29850b57cec5SDimitry Andric   return EndLabel;
29860b57cec5SDimitry Andric }
29870b57cec5SDimitry Andric 
endCVSubsection(MCSymbol * EndLabel)29880b57cec5SDimitry Andric void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
29895ffd83dbSDimitry Andric   OS.emitLabel(EndLabel);
29900b57cec5SDimitry Andric   // Every subsection must be aligned to a 4-byte boundary.
29915ffd83dbSDimitry Andric   OS.emitValueToAlignment(4);
29920b57cec5SDimitry Andric }
29930b57cec5SDimitry Andric 
getSymbolName(SymbolKind SymKind)29940b57cec5SDimitry Andric static StringRef getSymbolName(SymbolKind SymKind) {
29950b57cec5SDimitry Andric   for (const EnumEntry<SymbolKind> &EE : getSymbolTypeNames())
29960b57cec5SDimitry Andric     if (EE.Value == SymKind)
29970b57cec5SDimitry Andric       return EE.Name;
29980b57cec5SDimitry Andric   return "";
29990b57cec5SDimitry Andric }
30000b57cec5SDimitry Andric 
beginSymbolRecord(SymbolKind SymKind)30010b57cec5SDimitry Andric MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) {
30020b57cec5SDimitry Andric   MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
30030b57cec5SDimitry Andric            *EndLabel = MMI->getContext().createTempSymbol();
30040b57cec5SDimitry Andric   OS.AddComment("Record length");
30050b57cec5SDimitry Andric   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
30065ffd83dbSDimitry Andric   OS.emitLabel(BeginLabel);
30070b57cec5SDimitry Andric   if (OS.isVerboseAsm())
30080b57cec5SDimitry Andric     OS.AddComment("Record kind: " + getSymbolName(SymKind));
30095ffd83dbSDimitry Andric   OS.emitInt16(unsigned(SymKind));
30100b57cec5SDimitry Andric   return EndLabel;
30110b57cec5SDimitry Andric }
30120b57cec5SDimitry Andric 
endSymbolRecord(MCSymbol * SymEnd)30130b57cec5SDimitry Andric void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) {
30140b57cec5SDimitry Andric   // MSVC does not pad out symbol records to four bytes, but LLVM does to avoid
30150b57cec5SDimitry Andric   // an extra copy of every symbol record in LLD. This increases object file
30160b57cec5SDimitry Andric   // size by less than 1% in the clang build, and is compatible with the Visual
30170b57cec5SDimitry Andric   // C++ linker.
30185ffd83dbSDimitry Andric   OS.emitValueToAlignment(4);
30195ffd83dbSDimitry Andric   OS.emitLabel(SymEnd);
30200b57cec5SDimitry Andric }
30210b57cec5SDimitry Andric 
emitEndSymbolRecord(SymbolKind EndKind)30220b57cec5SDimitry Andric void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) {
30230b57cec5SDimitry Andric   OS.AddComment("Record length");
30245ffd83dbSDimitry Andric   OS.emitInt16(2);
30250b57cec5SDimitry Andric   if (OS.isVerboseAsm())
30260b57cec5SDimitry Andric     OS.AddComment("Record kind: " + getSymbolName(EndKind));
30275ffd83dbSDimitry Andric   OS.emitInt16(uint16_t(EndKind)); // Record Kind
30280b57cec5SDimitry Andric }
30290b57cec5SDimitry Andric 
emitDebugInfoForUDTs(const std::vector<std::pair<std::string,const DIType * >> & UDTs)30300b57cec5SDimitry Andric void CodeViewDebug::emitDebugInfoForUDTs(
30315ffd83dbSDimitry Andric     const std::vector<std::pair<std::string, const DIType *>> &UDTs) {
30325ffd83dbSDimitry Andric #ifndef NDEBUG
30335ffd83dbSDimitry Andric   size_t OriginalSize = UDTs.size();
30345ffd83dbSDimitry Andric #endif
30350b57cec5SDimitry Andric   for (const auto &UDT : UDTs) {
30360b57cec5SDimitry Andric     const DIType *T = UDT.second;
30370b57cec5SDimitry Andric     assert(shouldEmitUdt(T));
30380b57cec5SDimitry Andric     MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT);
30390b57cec5SDimitry Andric     OS.AddComment("Type");
30405ffd83dbSDimitry Andric     OS.emitInt32(getCompleteTypeIndex(T).getIndex());
30415ffd83dbSDimitry Andric     assert(OriginalSize == UDTs.size() &&
30425ffd83dbSDimitry Andric            "getCompleteTypeIndex found new UDTs!");
30430b57cec5SDimitry Andric     emitNullTerminatedSymbolName(OS, UDT.first);
30440b57cec5SDimitry Andric     endSymbolRecord(UDTRecordEnd);
30450b57cec5SDimitry Andric   }
30460b57cec5SDimitry Andric }
30470b57cec5SDimitry Andric 
collectGlobalVariableInfo()30480b57cec5SDimitry Andric void CodeViewDebug::collectGlobalVariableInfo() {
30490b57cec5SDimitry Andric   DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
30500b57cec5SDimitry Andric       GlobalMap;
30510b57cec5SDimitry Andric   for (const GlobalVariable &GV : MMI->getModule()->globals()) {
30520b57cec5SDimitry Andric     SmallVector<DIGlobalVariableExpression *, 1> GVEs;
30530b57cec5SDimitry Andric     GV.getDebugInfo(GVEs);
30540b57cec5SDimitry Andric     for (const auto *GVE : GVEs)
30550b57cec5SDimitry Andric       GlobalMap[GVE] = &GV;
30560b57cec5SDimitry Andric   }
30570b57cec5SDimitry Andric 
30580b57cec5SDimitry Andric   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
30590b57cec5SDimitry Andric   for (const MDNode *Node : CUs->operands()) {
30600b57cec5SDimitry Andric     const auto *CU = cast<DICompileUnit>(Node);
30610b57cec5SDimitry Andric     for (const auto *GVE : CU->getGlobalVariables()) {
30620b57cec5SDimitry Andric       const DIGlobalVariable *DIGV = GVE->getVariable();
30630b57cec5SDimitry Andric       const DIExpression *DIE = GVE->getExpression();
30640b57cec5SDimitry Andric 
30650b57cec5SDimitry Andric       // Emit constant global variables in a global symbol section.
30660b57cec5SDimitry Andric       if (GlobalMap.count(GVE) == 0 && DIE->isConstant()) {
30670b57cec5SDimitry Andric         CVGlobalVariable CVGV = {DIGV, DIE};
30680b57cec5SDimitry Andric         GlobalVariables.emplace_back(std::move(CVGV));
30690b57cec5SDimitry Andric       }
30700b57cec5SDimitry Andric 
30710b57cec5SDimitry Andric       const auto *GV = GlobalMap.lookup(GVE);
30720b57cec5SDimitry Andric       if (!GV || GV->isDeclarationForLinker())
30730b57cec5SDimitry Andric         continue;
30740b57cec5SDimitry Andric 
30750b57cec5SDimitry Andric       DIScope *Scope = DIGV->getScope();
30760b57cec5SDimitry Andric       SmallVector<CVGlobalVariable, 1> *VariableList;
30770b57cec5SDimitry Andric       if (Scope && isa<DILocalScope>(Scope)) {
30780b57cec5SDimitry Andric         // Locate a global variable list for this scope, creating one if
30790b57cec5SDimitry Andric         // necessary.
30800b57cec5SDimitry Andric         auto Insertion = ScopeGlobals.insert(
30810b57cec5SDimitry Andric             {Scope, std::unique_ptr<GlobalVariableList>()});
30820b57cec5SDimitry Andric         if (Insertion.second)
30838bcb0991SDimitry Andric           Insertion.first->second = std::make_unique<GlobalVariableList>();
30840b57cec5SDimitry Andric         VariableList = Insertion.first->second.get();
30850b57cec5SDimitry Andric       } else if (GV->hasComdat())
30860b57cec5SDimitry Andric         // Emit this global variable into a COMDAT section.
30870b57cec5SDimitry Andric         VariableList = &ComdatVariables;
30880b57cec5SDimitry Andric       else
30890b57cec5SDimitry Andric         // Emit this global variable in a single global symbol section.
30900b57cec5SDimitry Andric         VariableList = &GlobalVariables;
30910b57cec5SDimitry Andric       CVGlobalVariable CVGV = {DIGV, GV};
30920b57cec5SDimitry Andric       VariableList->emplace_back(std::move(CVGV));
30930b57cec5SDimitry Andric     }
30940b57cec5SDimitry Andric   }
30950b57cec5SDimitry Andric }
30960b57cec5SDimitry Andric 
collectDebugInfoForGlobals()3097af732203SDimitry Andric void CodeViewDebug::collectDebugInfoForGlobals() {
3098af732203SDimitry Andric   for (const CVGlobalVariable &CVGV : GlobalVariables) {
3099af732203SDimitry Andric     const DIGlobalVariable *DIGV = CVGV.DIGV;
3100af732203SDimitry Andric     const DIScope *Scope = DIGV->getScope();
3101af732203SDimitry Andric     getCompleteTypeIndex(DIGV->getType());
3102af732203SDimitry Andric     getFullyQualifiedName(Scope, DIGV->getName());
3103af732203SDimitry Andric   }
3104af732203SDimitry Andric 
3105af732203SDimitry Andric   for (const CVGlobalVariable &CVGV : ComdatVariables) {
3106af732203SDimitry Andric     const DIGlobalVariable *DIGV = CVGV.DIGV;
3107af732203SDimitry Andric     const DIScope *Scope = DIGV->getScope();
3108af732203SDimitry Andric     getCompleteTypeIndex(DIGV->getType());
3109af732203SDimitry Andric     getFullyQualifiedName(Scope, DIGV->getName());
3110af732203SDimitry Andric   }
3111af732203SDimitry Andric }
3112af732203SDimitry Andric 
emitDebugInfoForGlobals()31130b57cec5SDimitry Andric void CodeViewDebug::emitDebugInfoForGlobals() {
31140b57cec5SDimitry Andric   // First, emit all globals that are not in a comdat in a single symbol
31150b57cec5SDimitry Andric   // substream. MSVC doesn't like it if the substream is empty, so only open
31160b57cec5SDimitry Andric   // it if we have at least one global to emit.
31170b57cec5SDimitry Andric   switchToDebugSectionForSymbol(nullptr);
3118af732203SDimitry Andric   if (!GlobalVariables.empty() || !StaticConstMembers.empty()) {
31190b57cec5SDimitry Andric     OS.AddComment("Symbol subsection for globals");
31200b57cec5SDimitry Andric     MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
31210b57cec5SDimitry Andric     emitGlobalVariableList(GlobalVariables);
3122af732203SDimitry Andric     emitStaticConstMemberList();
31230b57cec5SDimitry Andric     endCVSubsection(EndLabel);
31240b57cec5SDimitry Andric   }
31250b57cec5SDimitry Andric 
31260b57cec5SDimitry Andric   // Second, emit each global that is in a comdat into its own .debug$S
31270b57cec5SDimitry Andric   // section along with its own symbol substream.
31280b57cec5SDimitry Andric   for (const CVGlobalVariable &CVGV : ComdatVariables) {
31290b57cec5SDimitry Andric     const GlobalVariable *GV = CVGV.GVInfo.get<const GlobalVariable *>();
31300b57cec5SDimitry Andric     MCSymbol *GVSym = Asm->getSymbol(GV);
31310b57cec5SDimitry Andric     OS.AddComment("Symbol subsection for " +
31320b57cec5SDimitry Andric                   Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
31330b57cec5SDimitry Andric     switchToDebugSectionForSymbol(GVSym);
31340b57cec5SDimitry Andric     MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
31350b57cec5SDimitry Andric     // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
31360b57cec5SDimitry Andric     emitDebugInfoForGlobal(CVGV);
31370b57cec5SDimitry Andric     endCVSubsection(EndLabel);
31380b57cec5SDimitry Andric   }
31390b57cec5SDimitry Andric }
31400b57cec5SDimitry Andric 
emitDebugInfoForRetainedTypes()31410b57cec5SDimitry Andric void CodeViewDebug::emitDebugInfoForRetainedTypes() {
31420b57cec5SDimitry Andric   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
31430b57cec5SDimitry Andric   for (const MDNode *Node : CUs->operands()) {
31440b57cec5SDimitry Andric     for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
31450b57cec5SDimitry Andric       if (DIType *RT = dyn_cast<DIType>(Ty)) {
31460b57cec5SDimitry Andric         getTypeIndex(RT);
31470b57cec5SDimitry Andric         // FIXME: Add to global/local DTU list.
31480b57cec5SDimitry Andric       }
31490b57cec5SDimitry Andric     }
31500b57cec5SDimitry Andric   }
31510b57cec5SDimitry Andric }
31520b57cec5SDimitry Andric 
31530b57cec5SDimitry Andric // Emit each global variable in the specified array.
emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals)31540b57cec5SDimitry Andric void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) {
31550b57cec5SDimitry Andric   for (const CVGlobalVariable &CVGV : Globals) {
31560b57cec5SDimitry Andric     // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
31570b57cec5SDimitry Andric     emitDebugInfoForGlobal(CVGV);
31580b57cec5SDimitry Andric   }
31590b57cec5SDimitry Andric }
31600b57cec5SDimitry Andric 
emitConstantSymbolRecord(const DIType * DTy,APSInt & Value,const std::string & QualifiedName)3161*5f7ddb14SDimitry Andric void CodeViewDebug::emitConstantSymbolRecord(const DIType *DTy, APSInt &Value,
3162*5f7ddb14SDimitry Andric                                              const std::string &QualifiedName) {
3163*5f7ddb14SDimitry Andric   MCSymbol *SConstantEnd = beginSymbolRecord(SymbolKind::S_CONSTANT);
3164*5f7ddb14SDimitry Andric   OS.AddComment("Type");
3165*5f7ddb14SDimitry Andric   OS.emitInt32(getTypeIndex(DTy).getIndex());
3166*5f7ddb14SDimitry Andric 
3167*5f7ddb14SDimitry Andric   OS.AddComment("Value");
3168*5f7ddb14SDimitry Andric 
3169*5f7ddb14SDimitry Andric   // Encoded integers shouldn't need more than 10 bytes.
3170*5f7ddb14SDimitry Andric   uint8_t Data[10];
3171*5f7ddb14SDimitry Andric   BinaryStreamWriter Writer(Data, llvm::support::endianness::little);
3172*5f7ddb14SDimitry Andric   CodeViewRecordIO IO(Writer);
3173*5f7ddb14SDimitry Andric   cantFail(IO.mapEncodedInteger(Value));
3174*5f7ddb14SDimitry Andric   StringRef SRef((char *)Data, Writer.getOffset());
3175*5f7ddb14SDimitry Andric   OS.emitBinaryData(SRef);
3176*5f7ddb14SDimitry Andric 
3177*5f7ddb14SDimitry Andric   OS.AddComment("Name");
3178*5f7ddb14SDimitry Andric   emitNullTerminatedSymbolName(OS, QualifiedName);
3179*5f7ddb14SDimitry Andric   endSymbolRecord(SConstantEnd);
3180*5f7ddb14SDimitry Andric }
3181*5f7ddb14SDimitry Andric 
emitStaticConstMemberList()3182af732203SDimitry Andric void CodeViewDebug::emitStaticConstMemberList() {
3183af732203SDimitry Andric   for (const DIDerivedType *DTy : StaticConstMembers) {
3184af732203SDimitry Andric     const DIScope *Scope = DTy->getScope();
3185af732203SDimitry Andric 
3186af732203SDimitry Andric     APSInt Value;
3187af732203SDimitry Andric     if (const ConstantInt *CI =
3188af732203SDimitry Andric             dyn_cast_or_null<ConstantInt>(DTy->getConstant()))
3189af732203SDimitry Andric       Value = APSInt(CI->getValue(),
3190af732203SDimitry Andric                      DebugHandlerBase::isUnsignedDIType(DTy->getBaseType()));
3191af732203SDimitry Andric     else if (const ConstantFP *CFP =
3192af732203SDimitry Andric                  dyn_cast_or_null<ConstantFP>(DTy->getConstant()))
3193af732203SDimitry Andric       Value = APSInt(CFP->getValueAPF().bitcastToAPInt(), true);
3194af732203SDimitry Andric     else
3195af732203SDimitry Andric       llvm_unreachable("cannot emit a constant without a value");
3196af732203SDimitry Andric 
3197*5f7ddb14SDimitry Andric     emitConstantSymbolRecord(DTy->getBaseType(), Value,
3198*5f7ddb14SDimitry Andric                              getFullyQualifiedName(Scope, DTy->getName()));
3199af732203SDimitry Andric   }
3200af732203SDimitry Andric }
3201af732203SDimitry Andric 
isFloatDIType(const DIType * Ty)3202af732203SDimitry Andric static bool isFloatDIType(const DIType *Ty) {
3203af732203SDimitry Andric   if (isa<DICompositeType>(Ty))
3204af732203SDimitry Andric     return false;
3205af732203SDimitry Andric 
3206af732203SDimitry Andric   if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
3207af732203SDimitry Andric     dwarf::Tag T = (dwarf::Tag)Ty->getTag();
3208af732203SDimitry Andric     if (T == dwarf::DW_TAG_pointer_type ||
3209af732203SDimitry Andric         T == dwarf::DW_TAG_ptr_to_member_type ||
3210af732203SDimitry Andric         T == dwarf::DW_TAG_reference_type ||
3211af732203SDimitry Andric         T == dwarf::DW_TAG_rvalue_reference_type)
3212af732203SDimitry Andric       return false;
3213af732203SDimitry Andric     assert(DTy->getBaseType() && "Expected valid base type");
3214af732203SDimitry Andric     return isFloatDIType(DTy->getBaseType());
3215af732203SDimitry Andric   }
3216af732203SDimitry Andric 
3217af732203SDimitry Andric   auto *BTy = cast<DIBasicType>(Ty);
3218af732203SDimitry Andric   return (BTy->getEncoding() == dwarf::DW_ATE_float);
3219af732203SDimitry Andric }
3220af732203SDimitry Andric 
emitDebugInfoForGlobal(const CVGlobalVariable & CVGV)32210b57cec5SDimitry Andric void CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable &CVGV) {
32220b57cec5SDimitry Andric   const DIGlobalVariable *DIGV = CVGV.DIGV;
32235ffd83dbSDimitry Andric 
32245ffd83dbSDimitry Andric   const DIScope *Scope = DIGV->getScope();
32255ffd83dbSDimitry Andric   // For static data members, get the scope from the declaration.
32265ffd83dbSDimitry Andric   if (const auto *MemberDecl = dyn_cast_or_null<DIDerivedType>(
32275ffd83dbSDimitry Andric           DIGV->getRawStaticDataMemberDeclaration()))
32285ffd83dbSDimitry Andric     Scope = MemberDecl->getScope();
32295ffd83dbSDimitry Andric   std::string QualifiedName = getFullyQualifiedName(Scope, DIGV->getName());
32305ffd83dbSDimitry Andric 
32310b57cec5SDimitry Andric   if (const GlobalVariable *GV =
32320b57cec5SDimitry Andric           CVGV.GVInfo.dyn_cast<const GlobalVariable *>()) {
32330b57cec5SDimitry Andric     // DataSym record, see SymbolRecord.h for more info. Thread local data
32340b57cec5SDimitry Andric     // happens to have the same format as global data.
32350b57cec5SDimitry Andric     MCSymbol *GVSym = Asm->getSymbol(GV);
32360b57cec5SDimitry Andric     SymbolKind DataSym = GV->isThreadLocal()
32370b57cec5SDimitry Andric                              ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32
32380b57cec5SDimitry Andric                                                       : SymbolKind::S_GTHREAD32)
32390b57cec5SDimitry Andric                              : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32
32400b57cec5SDimitry Andric                                                       : SymbolKind::S_GDATA32);
32410b57cec5SDimitry Andric     MCSymbol *DataEnd = beginSymbolRecord(DataSym);
32420b57cec5SDimitry Andric     OS.AddComment("Type");
32435ffd83dbSDimitry Andric     OS.emitInt32(getCompleteTypeIndex(DIGV->getType()).getIndex());
32440b57cec5SDimitry Andric     OS.AddComment("DataOffset");
32450b57cec5SDimitry Andric     OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
32460b57cec5SDimitry Andric     OS.AddComment("Segment");
32470b57cec5SDimitry Andric     OS.EmitCOFFSectionIndex(GVSym);
32480b57cec5SDimitry Andric     OS.AddComment("Name");
32490b57cec5SDimitry Andric     const unsigned LengthOfDataRecord = 12;
32505ffd83dbSDimitry Andric     emitNullTerminatedSymbolName(OS, QualifiedName, LengthOfDataRecord);
32510b57cec5SDimitry Andric     endSymbolRecord(DataEnd);
32520b57cec5SDimitry Andric   } else {
32530b57cec5SDimitry Andric     const DIExpression *DIE = CVGV.GVInfo.get<const DIExpression *>();
32540b57cec5SDimitry Andric     assert(DIE->isConstant() &&
32550b57cec5SDimitry Andric            "Global constant variables must contain a constant expression.");
3256af732203SDimitry Andric 
3257af732203SDimitry Andric     // Use unsigned for floats.
3258af732203SDimitry Andric     bool isUnsigned = isFloatDIType(DIGV->getType())
3259af732203SDimitry Andric                           ? true
3260af732203SDimitry Andric                           : DebugHandlerBase::isUnsignedDIType(DIGV->getType());
3261af732203SDimitry Andric     APSInt Value(APInt(/*BitWidth=*/64, DIE->getElement(1)), isUnsigned);
3262*5f7ddb14SDimitry Andric     emitConstantSymbolRecord(DIGV->getType(), Value, QualifiedName);
32630b57cec5SDimitry Andric   }
32640b57cec5SDimitry Andric }
3265