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 "llvm/ADT/APSInt.h"
150b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
165f757f3fSDimitry Andric #include "llvm/ADT/SmallBitVector.h"
170b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
180b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
190b57cec5SDimitry Andric #include "llvm/ADT/TinyPtrVector.h"
200b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
210b57cec5SDimitry Andric #include "llvm/BinaryFormat/COFF.h"
220b57cec5SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/AsmPrinter.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/LexicalScopes.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
305f757f3fSDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
310b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
320b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
330b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
340b57cec5SDimitry Andric #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
350b57cec5SDimitry Andric #include "llvm/DebugInfo/CodeView/CodeViewRecordIO.h"
360b57cec5SDimitry Andric #include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h"
370b57cec5SDimitry Andric #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
380b57cec5SDimitry Andric #include "llvm/DebugInfo/CodeView/EnumTables.h"
390b57cec5SDimitry Andric #include "llvm/DebugInfo/CodeView/Line.h"
400b57cec5SDimitry Andric #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
410b57cec5SDimitry Andric #include "llvm/DebugInfo/CodeView/TypeRecord.h"
420b57cec5SDimitry Andric #include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
430b57cec5SDimitry Andric #include "llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h"
440b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
450b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
460b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
470b57cec5SDimitry Andric #include "llvm/IR/Function.h"
480b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
490b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
500b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
510b57cec5SDimitry Andric #include "llvm/IR/Module.h"
520b57cec5SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
530b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
540b57cec5SDimitry Andric #include "llvm/MC/MCSectionCOFF.h"
550b57cec5SDimitry Andric #include "llvm/MC/MCStreamer.h"
560b57cec5SDimitry Andric #include "llvm/MC/MCSymbol.h"
570b57cec5SDimitry Andric #include "llvm/Support/BinaryStreamWriter.h"
580b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
590b57cec5SDimitry Andric #include "llvm/Support/Error.h"
600b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
610b57cec5SDimitry Andric #include "llvm/Support/FormatVariadic.h"
620b57cec5SDimitry Andric #include "llvm/Support/Path.h"
6304eeddc0SDimitry Andric #include "llvm/Support/Program.h"
640b57cec5SDimitry Andric #include "llvm/Support/SMLoc.h"
650b57cec5SDimitry Andric #include "llvm/Support/ScopedPrinter.h"
660b57cec5SDimitry Andric #include "llvm/Target/TargetLoweringObjectFile.h"
670b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
6806c3fb27SDimitry Andric #include "llvm/TargetParser/Triple.h"
690b57cec5SDimitry Andric #include <algorithm>
700b57cec5SDimitry Andric #include <cassert>
710b57cec5SDimitry Andric #include <cctype>
720b57cec5SDimitry Andric #include <cstddef>
730b57cec5SDimitry Andric #include <iterator>
740b57cec5SDimitry Andric #include <limits>
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric using namespace llvm;
770b57cec5SDimitry Andric using namespace llvm::codeview;
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric namespace {
800b57cec5SDimitry Andric class CVMCAdapter : public CodeViewRecordStreamer {
810b57cec5SDimitry Andric public:
CVMCAdapter(MCStreamer & OS,TypeCollection & TypeTable)828bcb0991SDimitry Andric   CVMCAdapter(MCStreamer &OS, TypeCollection &TypeTable)
838bcb0991SDimitry Andric       : OS(&OS), TypeTable(TypeTable) {}
840b57cec5SDimitry Andric 
emitBytes(StringRef Data)855ffd83dbSDimitry Andric   void emitBytes(StringRef Data) override { OS->emitBytes(Data); }
860b57cec5SDimitry Andric 
emitIntValue(uint64_t Value,unsigned Size)875ffd83dbSDimitry Andric   void emitIntValue(uint64_t Value, unsigned Size) override {
885ffd83dbSDimitry Andric     OS->emitIntValueInHex(Value, Size);
890b57cec5SDimitry Andric   }
900b57cec5SDimitry Andric 
emitBinaryData(StringRef Data)915ffd83dbSDimitry Andric   void emitBinaryData(StringRef Data) override { OS->emitBinaryData(Data); }
920b57cec5SDimitry Andric 
AddComment(const Twine & T)935ffd83dbSDimitry Andric   void AddComment(const Twine &T) override { OS->AddComment(T); }
940b57cec5SDimitry Andric 
AddRawComment(const Twine & T)955ffd83dbSDimitry Andric   void AddRawComment(const Twine &T) override { OS->emitRawComment(T); }
968bcb0991SDimitry Andric 
isVerboseAsm()975ffd83dbSDimitry Andric   bool isVerboseAsm() override { return OS->isVerboseAsm(); }
988bcb0991SDimitry Andric 
getTypeName(TypeIndex TI)995ffd83dbSDimitry Andric   std::string getTypeName(TypeIndex TI) override {
1008bcb0991SDimitry Andric     std::string TypeName;
1018bcb0991SDimitry Andric     if (!TI.isNoneType()) {
1028bcb0991SDimitry Andric       if (TI.isSimple())
1035ffd83dbSDimitry Andric         TypeName = std::string(TypeIndex::simpleTypeName(TI));
1048bcb0991SDimitry Andric       else
1055ffd83dbSDimitry Andric         TypeName = std::string(TypeTable.getTypeName(TI));
1068bcb0991SDimitry Andric     }
1078bcb0991SDimitry Andric     return TypeName;
1088bcb0991SDimitry Andric   }
1098bcb0991SDimitry Andric 
1100b57cec5SDimitry Andric private:
1110b57cec5SDimitry Andric   MCStreamer *OS = nullptr;
1128bcb0991SDimitry Andric   TypeCollection &TypeTable;
1130b57cec5SDimitry Andric };
1140b57cec5SDimitry Andric } // namespace
1150b57cec5SDimitry Andric 
mapArchToCVCPUType(Triple::ArchType Type)1160b57cec5SDimitry Andric static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
1170b57cec5SDimitry Andric   switch (Type) {
1180b57cec5SDimitry Andric   case Triple::ArchType::x86:
1190b57cec5SDimitry Andric     return CPUType::Pentium3;
1200b57cec5SDimitry Andric   case Triple::ArchType::x86_64:
1210b57cec5SDimitry Andric     return CPUType::X64;
1220b57cec5SDimitry Andric   case Triple::ArchType::thumb:
123e8d8bef9SDimitry Andric     // LLVM currently doesn't support Windows CE and so thumb
124e8d8bef9SDimitry Andric     // here is indiscriminately mapped to ARMNT specifically.
125e8d8bef9SDimitry Andric     return CPUType::ARMNT;
1260b57cec5SDimitry Andric   case Triple::ArchType::aarch64:
1270b57cec5SDimitry Andric     return CPUType::ARM64;
1280b57cec5SDimitry Andric   default:
1290b57cec5SDimitry Andric     report_fatal_error("target architecture doesn't map to a CodeView CPUType");
1300b57cec5SDimitry Andric   }
1310b57cec5SDimitry Andric }
1320b57cec5SDimitry Andric 
CodeViewDebug(AsmPrinter * AP)1330b57cec5SDimitry Andric CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
134e8d8bef9SDimitry Andric     : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {}
1350b57cec5SDimitry Andric 
getFullFilepath(const DIFile * File)1360b57cec5SDimitry Andric StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
1370b57cec5SDimitry Andric   std::string &Filepath = FileToFilepathMap[File];
1380b57cec5SDimitry Andric   if (!Filepath.empty())
1390b57cec5SDimitry Andric     return Filepath;
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric   StringRef Dir = File->getDirectory(), Filename = File->getFilename();
1420b57cec5SDimitry Andric 
1430b57cec5SDimitry Andric   // If this is a Unix-style path, just use it as is. Don't try to canonicalize
1440b57cec5SDimitry Andric   // it textually because one of the path components could be a symlink.
1455f757f3fSDimitry Andric   if (Dir.starts_with("/") || Filename.starts_with("/")) {
1460b57cec5SDimitry Andric     if (llvm::sys::path::is_absolute(Filename, llvm::sys::path::Style::posix))
1470b57cec5SDimitry Andric       return Filename;
1485ffd83dbSDimitry Andric     Filepath = std::string(Dir);
1490b57cec5SDimitry Andric     if (Dir.back() != '/')
1500b57cec5SDimitry Andric       Filepath += '/';
1510b57cec5SDimitry Andric     Filepath += Filename;
1520b57cec5SDimitry Andric     return Filepath;
1530b57cec5SDimitry Andric   }
1540b57cec5SDimitry Andric 
1550b57cec5SDimitry Andric   // Clang emits directory and relative filename info into the IR, but CodeView
1560b57cec5SDimitry Andric   // operates on full paths.  We could change Clang to emit full paths too, but
1570b57cec5SDimitry Andric   // that would increase the IR size and probably not needed for other users.
1580b57cec5SDimitry Andric   // For now, just concatenate and canonicalize the path here.
1590b57cec5SDimitry Andric   if (Filename.find(':') == 1)
1605ffd83dbSDimitry Andric     Filepath = std::string(Filename);
1610b57cec5SDimitry Andric   else
1620b57cec5SDimitry Andric     Filepath = (Dir + "\\" + Filename).str();
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric   // Canonicalize the path.  We have to do it textually because we may no longer
1650b57cec5SDimitry Andric   // have access the file in the filesystem.
1660b57cec5SDimitry Andric   // First, replace all slashes with backslashes.
1670b57cec5SDimitry Andric   std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric   // Remove all "\.\" with "\".
1700b57cec5SDimitry Andric   size_t Cursor = 0;
1710b57cec5SDimitry Andric   while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
1720b57cec5SDimitry Andric     Filepath.erase(Cursor, 2);
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric   // Replace all "\XXX\..\" with "\".  Don't try too hard though as the original
1750b57cec5SDimitry Andric   // path should be well-formatted, e.g. start with a drive letter, etc.
1760b57cec5SDimitry Andric   Cursor = 0;
1770b57cec5SDimitry Andric   while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
1780b57cec5SDimitry Andric     // Something's wrong if the path starts with "\..\", abort.
1790b57cec5SDimitry Andric     if (Cursor == 0)
1800b57cec5SDimitry Andric       break;
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric     size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
1830b57cec5SDimitry Andric     if (PrevSlash == std::string::npos)
1840b57cec5SDimitry Andric       // Something's wrong, abort.
1850b57cec5SDimitry Andric       break;
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric     Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
1880b57cec5SDimitry Andric     // The next ".." might be following the one we've just erased.
1890b57cec5SDimitry Andric     Cursor = PrevSlash;
1900b57cec5SDimitry Andric   }
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   // Remove all duplicate backslashes.
1930b57cec5SDimitry Andric   Cursor = 0;
1940b57cec5SDimitry Andric   while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
1950b57cec5SDimitry Andric     Filepath.erase(Cursor, 1);
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric   return Filepath;
1980b57cec5SDimitry Andric }
1990b57cec5SDimitry Andric 
maybeRecordFile(const DIFile * F)2000b57cec5SDimitry Andric unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
2010b57cec5SDimitry Andric   StringRef FullPath = getFullFilepath(F);
2020b57cec5SDimitry Andric   unsigned NextId = FileIdMap.size() + 1;
2030b57cec5SDimitry Andric   auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
2040b57cec5SDimitry Andric   if (Insertion.second) {
2050b57cec5SDimitry Andric     // We have to compute the full filepath and emit a .cv_file directive.
2060b57cec5SDimitry Andric     ArrayRef<uint8_t> ChecksumAsBytes;
2070b57cec5SDimitry Andric     FileChecksumKind CSKind = FileChecksumKind::None;
2080b57cec5SDimitry Andric     if (F->getChecksum()) {
2090b57cec5SDimitry Andric       std::string Checksum = fromHex(F->getChecksum()->Value);
2100b57cec5SDimitry Andric       void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
2110b57cec5SDimitry Andric       memcpy(CKMem, Checksum.data(), Checksum.size());
2120b57cec5SDimitry Andric       ChecksumAsBytes = ArrayRef<uint8_t>(
2130b57cec5SDimitry Andric           reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
2140b57cec5SDimitry Andric       switch (F->getChecksum()->Kind) {
2155ffd83dbSDimitry Andric       case DIFile::CSK_MD5:
2165ffd83dbSDimitry Andric         CSKind = FileChecksumKind::MD5;
2175ffd83dbSDimitry Andric         break;
2185ffd83dbSDimitry Andric       case DIFile::CSK_SHA1:
2195ffd83dbSDimitry Andric         CSKind = FileChecksumKind::SHA1;
2205ffd83dbSDimitry Andric         break;
2215ffd83dbSDimitry Andric       case DIFile::CSK_SHA256:
2225ffd83dbSDimitry Andric         CSKind = FileChecksumKind::SHA256;
2235ffd83dbSDimitry Andric         break;
2240b57cec5SDimitry Andric       }
2250b57cec5SDimitry Andric     }
22681ad6265SDimitry Andric     bool Success = OS.emitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
2270b57cec5SDimitry Andric                                           static_cast<unsigned>(CSKind));
2280b57cec5SDimitry Andric     (void)Success;
2290b57cec5SDimitry Andric     assert(Success && ".cv_file directive failed");
2300b57cec5SDimitry Andric   }
2310b57cec5SDimitry Andric   return Insertion.first->second;
2320b57cec5SDimitry Andric }
2330b57cec5SDimitry Andric 
2340b57cec5SDimitry Andric CodeViewDebug::InlineSite &
getInlineSite(const DILocation * InlinedAt,const DISubprogram * Inlinee)2350b57cec5SDimitry Andric CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
2360b57cec5SDimitry Andric                              const DISubprogram *Inlinee) {
2370b57cec5SDimitry Andric   auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
2380b57cec5SDimitry Andric   InlineSite *Site = &SiteInsertion.first->second;
2390b57cec5SDimitry Andric   if (SiteInsertion.second) {
2400b57cec5SDimitry Andric     unsigned ParentFuncId = CurFn->FuncId;
2410b57cec5SDimitry Andric     if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
2420b57cec5SDimitry Andric       ParentFuncId =
2430b57cec5SDimitry Andric           getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
2440b57cec5SDimitry Andric               .SiteFuncId;
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric     Site->SiteFuncId = NextFuncId++;
24781ad6265SDimitry Andric     OS.emitCVInlineSiteIdDirective(
2480b57cec5SDimitry Andric         Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
2490b57cec5SDimitry Andric         InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
2500b57cec5SDimitry Andric     Site->Inlinee = Inlinee;
2510b57cec5SDimitry Andric     InlinedSubprograms.insert(Inlinee);
2525f757f3fSDimitry Andric     auto InlineeIdx = getFuncIdForSubprogram(Inlinee);
2535f757f3fSDimitry Andric 
2545f757f3fSDimitry Andric     if (InlinedAt->getInlinedAt() == nullptr)
2555f757f3fSDimitry Andric       CurFn->Inlinees.insert(InlineeIdx);
2560b57cec5SDimitry Andric   }
2570b57cec5SDimitry Andric   return *Site;
2580b57cec5SDimitry Andric }
2590b57cec5SDimitry Andric 
getPrettyScopeName(const DIScope * Scope)2600b57cec5SDimitry Andric static StringRef getPrettyScopeName(const DIScope *Scope) {
2610b57cec5SDimitry Andric   StringRef ScopeName = Scope->getName();
2620b57cec5SDimitry Andric   if (!ScopeName.empty())
2630b57cec5SDimitry Andric     return ScopeName;
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric   switch (Scope->getTag()) {
2660b57cec5SDimitry Andric   case dwarf::DW_TAG_enumeration_type:
2670b57cec5SDimitry Andric   case dwarf::DW_TAG_class_type:
2680b57cec5SDimitry Andric   case dwarf::DW_TAG_structure_type:
2690b57cec5SDimitry Andric   case dwarf::DW_TAG_union_type:
2700b57cec5SDimitry Andric     return "<unnamed-tag>";
2710b57cec5SDimitry Andric   case dwarf::DW_TAG_namespace:
2720b57cec5SDimitry Andric     return "`anonymous namespace'";
273fe6060f1SDimitry Andric   default:
2740b57cec5SDimitry Andric     return StringRef();
2750b57cec5SDimitry Andric   }
276fe6060f1SDimitry Andric }
2770b57cec5SDimitry Andric 
collectParentScopeNames(const DIScope * Scope,SmallVectorImpl<StringRef> & QualifiedNameComponents)2785ffd83dbSDimitry Andric const DISubprogram *CodeViewDebug::collectParentScopeNames(
2790b57cec5SDimitry Andric     const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
2800b57cec5SDimitry Andric   const DISubprogram *ClosestSubprogram = nullptr;
2810b57cec5SDimitry Andric   while (Scope != nullptr) {
2820b57cec5SDimitry Andric     if (ClosestSubprogram == nullptr)
2830b57cec5SDimitry Andric       ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
2845ffd83dbSDimitry Andric 
2855ffd83dbSDimitry Andric     // If a type appears in a scope chain, make sure it gets emitted. The
2865ffd83dbSDimitry Andric     // frontend will be responsible for deciding if this should be a forward
2875ffd83dbSDimitry Andric     // declaration or a complete type.
2885ffd83dbSDimitry Andric     if (const auto *Ty = dyn_cast<DICompositeType>(Scope))
2895ffd83dbSDimitry Andric       DeferredCompleteTypes.push_back(Ty);
2905ffd83dbSDimitry Andric 
2910b57cec5SDimitry Andric     StringRef ScopeName = getPrettyScopeName(Scope);
2920b57cec5SDimitry Andric     if (!ScopeName.empty())
2930b57cec5SDimitry Andric       QualifiedNameComponents.push_back(ScopeName);
2940b57cec5SDimitry Andric     Scope = Scope->getScope();
2950b57cec5SDimitry Andric   }
2960b57cec5SDimitry Andric   return ClosestSubprogram;
2970b57cec5SDimitry Andric }
2980b57cec5SDimitry Andric 
formatNestedName(ArrayRef<StringRef> QualifiedNameComponents,StringRef TypeName)2995ffd83dbSDimitry Andric static std::string formatNestedName(ArrayRef<StringRef> QualifiedNameComponents,
3000b57cec5SDimitry Andric                                     StringRef TypeName) {
3010b57cec5SDimitry Andric   std::string FullyQualifiedName;
3020b57cec5SDimitry Andric   for (StringRef QualifiedNameComponent :
3030b57cec5SDimitry Andric        llvm::reverse(QualifiedNameComponents)) {
3045ffd83dbSDimitry Andric     FullyQualifiedName.append(std::string(QualifiedNameComponent));
3050b57cec5SDimitry Andric     FullyQualifiedName.append("::");
3060b57cec5SDimitry Andric   }
3075ffd83dbSDimitry Andric   FullyQualifiedName.append(std::string(TypeName));
3080b57cec5SDimitry Andric   return FullyQualifiedName;
3090b57cec5SDimitry Andric }
3100b57cec5SDimitry Andric 
3110b57cec5SDimitry Andric struct CodeViewDebug::TypeLoweringScope {
TypeLoweringScopeCodeViewDebug::TypeLoweringScope3120b57cec5SDimitry Andric   TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
~TypeLoweringScopeCodeViewDebug::TypeLoweringScope3130b57cec5SDimitry Andric   ~TypeLoweringScope() {
3140b57cec5SDimitry Andric     // Don't decrement TypeEmissionLevel until after emitting deferred types, so
3150b57cec5SDimitry Andric     // inner TypeLoweringScopes don't attempt to emit deferred types.
3160b57cec5SDimitry Andric     if (CVD.TypeEmissionLevel == 1)
3170b57cec5SDimitry Andric       CVD.emitDeferredCompleteTypes();
3180b57cec5SDimitry Andric     --CVD.TypeEmissionLevel;
3190b57cec5SDimitry Andric   }
3200b57cec5SDimitry Andric   CodeViewDebug &CVD;
3210b57cec5SDimitry Andric };
3220b57cec5SDimitry Andric 
getFullyQualifiedName(const DIScope * Scope,StringRef Name)3235ffd83dbSDimitry Andric std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Scope,
3245ffd83dbSDimitry Andric                                                  StringRef Name) {
3255ffd83dbSDimitry Andric   // Ensure types in the scope chain are emitted as soon as possible.
3265ffd83dbSDimitry Andric   // This can create otherwise a situation where S_UDTs are emitted while
3275ffd83dbSDimitry Andric   // looping in emitDebugInfoForUDTs.
3285ffd83dbSDimitry Andric   TypeLoweringScope S(*this);
3295ffd83dbSDimitry Andric   SmallVector<StringRef, 5> QualifiedNameComponents;
3305ffd83dbSDimitry Andric   collectParentScopeNames(Scope, QualifiedNameComponents);
3315ffd83dbSDimitry Andric   return formatNestedName(QualifiedNameComponents, Name);
3325ffd83dbSDimitry Andric }
3335ffd83dbSDimitry Andric 
getFullyQualifiedName(const DIScope * Ty)3345ffd83dbSDimitry Andric std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Ty) {
3350b57cec5SDimitry Andric   const DIScope *Scope = Ty->getScope();
3360b57cec5SDimitry Andric   return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
3370b57cec5SDimitry Andric }
3380b57cec5SDimitry Andric 
getScopeIndex(const DIScope * Scope)3390b57cec5SDimitry Andric TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
3400b57cec5SDimitry Andric   // No scope means global scope and that uses the zero index.
341349cc55cSDimitry Andric   //
342349cc55cSDimitry Andric   // We also use zero index when the scope is a DISubprogram
343349cc55cSDimitry Andric   // to suppress the emission of LF_STRING_ID for the function,
344349cc55cSDimitry Andric   // which can trigger a link-time error with the linker in
345349cc55cSDimitry Andric   // VS2019 version 16.11.2 or newer.
346349cc55cSDimitry Andric   // Note, however, skipping the debug info emission for the DISubprogram
347349cc55cSDimitry Andric   // is a temporary fix. The root issue here is that we need to figure out
348349cc55cSDimitry Andric   // the proper way to encode a function nested in another function
349349cc55cSDimitry Andric   // (as introduced by the Fortran 'contains' keyword) in CodeView.
350349cc55cSDimitry Andric   if (!Scope || isa<DIFile>(Scope) || isa<DISubprogram>(Scope))
3510b57cec5SDimitry Andric     return TypeIndex();
3520b57cec5SDimitry Andric 
3530b57cec5SDimitry Andric   assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
3540b57cec5SDimitry Andric 
3550b57cec5SDimitry Andric   // Check if we've already translated this scope.
3560b57cec5SDimitry Andric   auto I = TypeIndices.find({Scope, nullptr});
3570b57cec5SDimitry Andric   if (I != TypeIndices.end())
3580b57cec5SDimitry Andric     return I->second;
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric   // Build the fully qualified name of the scope.
3610b57cec5SDimitry Andric   std::string ScopeName = getFullyQualifiedName(Scope);
3620b57cec5SDimitry Andric   StringIdRecord SID(TypeIndex(), ScopeName);
3630b57cec5SDimitry Andric   auto TI = TypeTable.writeLeafType(SID);
3640b57cec5SDimitry Andric   return recordTypeIndexForDINode(Scope, TI);
3650b57cec5SDimitry Andric }
3660b57cec5SDimitry Andric 
removeTemplateArgs(StringRef Name)367fe6060f1SDimitry Andric static StringRef removeTemplateArgs(StringRef Name) {
368fe6060f1SDimitry Andric   // Remove template args from the display name. Assume that the template args
369fe6060f1SDimitry Andric   // are the last thing in the name.
370fe6060f1SDimitry Andric   if (Name.empty() || Name.back() != '>')
371fe6060f1SDimitry Andric     return Name;
372fe6060f1SDimitry Andric 
373fe6060f1SDimitry Andric   int OpenBrackets = 0;
374fe6060f1SDimitry Andric   for (int i = Name.size() - 1; i >= 0; --i) {
375fe6060f1SDimitry Andric     if (Name[i] == '>')
376fe6060f1SDimitry Andric       ++OpenBrackets;
377fe6060f1SDimitry Andric     else if (Name[i] == '<') {
378fe6060f1SDimitry Andric       --OpenBrackets;
379fe6060f1SDimitry Andric       if (OpenBrackets == 0)
380fe6060f1SDimitry Andric         return Name.substr(0, i);
381fe6060f1SDimitry Andric     }
382fe6060f1SDimitry Andric   }
383fe6060f1SDimitry Andric   return Name;
384fe6060f1SDimitry Andric }
385fe6060f1SDimitry Andric 
getFuncIdForSubprogram(const DISubprogram * SP)3860b57cec5SDimitry Andric TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
3870b57cec5SDimitry Andric   assert(SP);
3880b57cec5SDimitry Andric 
3890b57cec5SDimitry Andric   // Check if we've already translated this subprogram.
3900b57cec5SDimitry Andric   auto I = TypeIndices.find({SP, nullptr});
3910b57cec5SDimitry Andric   if (I != TypeIndices.end())
3920b57cec5SDimitry Andric     return I->second;
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric   // The display name includes function template arguments. Drop them to match
395fe6060f1SDimitry Andric   // MSVC. We need to have the template arguments in the DISubprogram name
396fe6060f1SDimitry Andric   // because they are used in other symbol records, such as S_GPROC32_IDs.
397fe6060f1SDimitry Andric   StringRef DisplayName = removeTemplateArgs(SP->getName());
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric   const DIScope *Scope = SP->getScope();
4000b57cec5SDimitry Andric   TypeIndex TI;
4010b57cec5SDimitry Andric   if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
4020b57cec5SDimitry Andric     // If the scope is a DICompositeType, then this must be a method. Member
4030b57cec5SDimitry Andric     // function types take some special handling, and require access to the
4040b57cec5SDimitry Andric     // subprogram.
4050b57cec5SDimitry Andric     TypeIndex ClassType = getTypeIndex(Class);
4060b57cec5SDimitry Andric     MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
4070b57cec5SDimitry Andric                                DisplayName);
4080b57cec5SDimitry Andric     TI = TypeTable.writeLeafType(MFuncId);
4090b57cec5SDimitry Andric   } else {
4100b57cec5SDimitry Andric     // Otherwise, this must be a free function.
4110b57cec5SDimitry Andric     TypeIndex ParentScope = getScopeIndex(Scope);
4120b57cec5SDimitry Andric     FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
4130b57cec5SDimitry Andric     TI = TypeTable.writeLeafType(FuncId);
4140b57cec5SDimitry Andric   }
4150b57cec5SDimitry Andric 
4160b57cec5SDimitry Andric   return recordTypeIndexForDINode(SP, TI);
4170b57cec5SDimitry Andric }
4180b57cec5SDimitry Andric 
isNonTrivial(const DICompositeType * DCTy)4190b57cec5SDimitry Andric static bool isNonTrivial(const DICompositeType *DCTy) {
4200b57cec5SDimitry Andric   return ((DCTy->getFlags() & DINode::FlagNonTrivial) == DINode::FlagNonTrivial);
4210b57cec5SDimitry Andric }
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric static FunctionOptions
getFunctionOptions(const DISubroutineType * Ty,const DICompositeType * ClassTy=nullptr,StringRef SPName=StringRef (""))4240b57cec5SDimitry Andric getFunctionOptions(const DISubroutineType *Ty,
4250b57cec5SDimitry Andric                    const DICompositeType *ClassTy = nullptr,
4260b57cec5SDimitry Andric                    StringRef SPName = StringRef("")) {
4270b57cec5SDimitry Andric   FunctionOptions FO = FunctionOptions::None;
4280b57cec5SDimitry Andric   const DIType *ReturnTy = nullptr;
4290b57cec5SDimitry Andric   if (auto TypeArray = Ty->getTypeArray()) {
4300b57cec5SDimitry Andric     if (TypeArray.size())
4310b57cec5SDimitry Andric       ReturnTy = TypeArray[0];
4320b57cec5SDimitry Andric   }
4330b57cec5SDimitry Andric 
4345ffd83dbSDimitry Andric   // Add CxxReturnUdt option to functions that return nontrivial record types
4355ffd83dbSDimitry Andric   // or methods that return record types.
4365ffd83dbSDimitry Andric   if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy))
4375ffd83dbSDimitry Andric     if (isNonTrivial(ReturnDCTy) || ClassTy)
4380b57cec5SDimitry Andric       FO |= FunctionOptions::CxxReturnUdt;
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric   // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison.
4410b57cec5SDimitry Andric   if (ClassTy && isNonTrivial(ClassTy) && SPName == ClassTy->getName()) {
4420b57cec5SDimitry Andric     FO |= FunctionOptions::Constructor;
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric   // TODO: put the FunctionOptions::ConstructorWithVirtualBases flag.
4450b57cec5SDimitry Andric 
4460b57cec5SDimitry Andric   }
4470b57cec5SDimitry Andric   return FO;
4480b57cec5SDimitry Andric }
4490b57cec5SDimitry Andric 
getMemberFunctionType(const DISubprogram * SP,const DICompositeType * Class)4500b57cec5SDimitry Andric TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
4510b57cec5SDimitry Andric                                                const DICompositeType *Class) {
4520b57cec5SDimitry Andric   // Always use the method declaration as the key for the function type. The
4530b57cec5SDimitry Andric   // method declaration contains the this adjustment.
4540b57cec5SDimitry Andric   if (SP->getDeclaration())
4550b57cec5SDimitry Andric     SP = SP->getDeclaration();
4560b57cec5SDimitry Andric   assert(!SP->getDeclaration() && "should use declaration as key");
4570b57cec5SDimitry Andric 
4580b57cec5SDimitry Andric   // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
4590b57cec5SDimitry Andric   // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
4600b57cec5SDimitry Andric   auto I = TypeIndices.find({SP, Class});
4610b57cec5SDimitry Andric   if (I != TypeIndices.end())
4620b57cec5SDimitry Andric     return I->second;
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric   // Make sure complete type info for the class is emitted *after* the member
4650b57cec5SDimitry Andric   // function type, as the complete class type is likely to reference this
4660b57cec5SDimitry Andric   // member function type.
4670b57cec5SDimitry Andric   TypeLoweringScope S(*this);
4680b57cec5SDimitry Andric   const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
4690b57cec5SDimitry Andric 
4700b57cec5SDimitry Andric   FunctionOptions FO = getFunctionOptions(SP->getType(), Class, SP->getName());
4710b57cec5SDimitry Andric   TypeIndex TI = lowerTypeMemberFunction(
4720b57cec5SDimitry Andric       SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO);
4730b57cec5SDimitry Andric   return recordTypeIndexForDINode(SP, TI, Class);
4740b57cec5SDimitry Andric }
4750b57cec5SDimitry Andric 
recordTypeIndexForDINode(const DINode * Node,TypeIndex TI,const DIType * ClassTy)4760b57cec5SDimitry Andric TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
4770b57cec5SDimitry Andric                                                   TypeIndex TI,
4780b57cec5SDimitry Andric                                                   const DIType *ClassTy) {
4790b57cec5SDimitry Andric   auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
4800b57cec5SDimitry Andric   (void)InsertResult;
4810b57cec5SDimitry Andric   assert(InsertResult.second && "DINode was already assigned a type index");
4820b57cec5SDimitry Andric   return TI;
4830b57cec5SDimitry Andric }
4840b57cec5SDimitry Andric 
getPointerSizeInBytes()4850b57cec5SDimitry Andric unsigned CodeViewDebug::getPointerSizeInBytes() {
4860b57cec5SDimitry Andric   return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
4870b57cec5SDimitry Andric }
4880b57cec5SDimitry Andric 
recordLocalVariable(LocalVariable && Var,const LexicalScope * LS)4890b57cec5SDimitry Andric void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
4900b57cec5SDimitry Andric                                         const LexicalScope *LS) {
4910b57cec5SDimitry Andric   if (const DILocation *InlinedAt = LS->getInlinedAt()) {
4920b57cec5SDimitry Andric     // This variable was inlined. Associate it with the InlineSite.
4930b57cec5SDimitry Andric     const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
4940b57cec5SDimitry Andric     InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
49506c3fb27SDimitry Andric     Site.InlinedLocals.emplace_back(std::move(Var));
4960b57cec5SDimitry Andric   } else {
4970b57cec5SDimitry Andric     // This variable goes into the corresponding lexical scope.
49806c3fb27SDimitry Andric     ScopeVariables[LS].emplace_back(std::move(Var));
4990b57cec5SDimitry Andric   }
5000b57cec5SDimitry Andric }
5010b57cec5SDimitry Andric 
addLocIfNotPresent(SmallVectorImpl<const DILocation * > & Locs,const DILocation * Loc)5020b57cec5SDimitry Andric static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
5030b57cec5SDimitry Andric                                const DILocation *Loc) {
504e8d8bef9SDimitry Andric   if (!llvm::is_contained(Locs, Loc))
5050b57cec5SDimitry Andric     Locs.push_back(Loc);
5060b57cec5SDimitry Andric }
5070b57cec5SDimitry Andric 
maybeRecordLocation(const DebugLoc & DL,const MachineFunction * MF)5080b57cec5SDimitry Andric void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
5090b57cec5SDimitry Andric                                         const MachineFunction *MF) {
5100b57cec5SDimitry Andric   // Skip this instruction if it has the same location as the previous one.
5110b57cec5SDimitry Andric   if (!DL || DL == PrevInstLoc)
5120b57cec5SDimitry Andric     return;
5130b57cec5SDimitry Andric 
51481ad6265SDimitry Andric   const DIScope *Scope = DL->getScope();
5150b57cec5SDimitry Andric   if (!Scope)
5160b57cec5SDimitry Andric     return;
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric   // Skip this line if it is longer than the maximum we can record.
5190b57cec5SDimitry Andric   LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
5200b57cec5SDimitry Andric   if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
5210b57cec5SDimitry Andric       LI.isNeverStepInto())
5220b57cec5SDimitry Andric     return;
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric   ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
5250b57cec5SDimitry Andric   if (CI.getStartColumn() != DL.getCol())
5260b57cec5SDimitry Andric     return;
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric   if (!CurFn->HaveLineInfo)
5290b57cec5SDimitry Andric     CurFn->HaveLineInfo = true;
5300b57cec5SDimitry Andric   unsigned FileId = 0;
5310b57cec5SDimitry Andric   if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
5320b57cec5SDimitry Andric     FileId = CurFn->LastFileId;
5330b57cec5SDimitry Andric   else
5340b57cec5SDimitry Andric     FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
5350b57cec5SDimitry Andric   PrevInstLoc = DL;
5360b57cec5SDimitry Andric 
5370b57cec5SDimitry Andric   unsigned FuncId = CurFn->FuncId;
5380b57cec5SDimitry Andric   if (const DILocation *SiteLoc = DL->getInlinedAt()) {
5390b57cec5SDimitry Andric     const DILocation *Loc = DL.get();
5400b57cec5SDimitry Andric 
5410b57cec5SDimitry Andric     // If this location was actually inlined from somewhere else, give it the ID
5420b57cec5SDimitry Andric     // of the inline call site.
5430b57cec5SDimitry Andric     FuncId =
5440b57cec5SDimitry Andric         getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
5450b57cec5SDimitry Andric 
5460b57cec5SDimitry Andric     // Ensure we have links in the tree of inline call sites.
5470b57cec5SDimitry Andric     bool FirstLoc = true;
5480b57cec5SDimitry Andric     while ((SiteLoc = Loc->getInlinedAt())) {
5490b57cec5SDimitry Andric       InlineSite &Site =
5500b57cec5SDimitry Andric           getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
5510b57cec5SDimitry Andric       if (!FirstLoc)
5520b57cec5SDimitry Andric         addLocIfNotPresent(Site.ChildSites, Loc);
5530b57cec5SDimitry Andric       FirstLoc = false;
5540b57cec5SDimitry Andric       Loc = SiteLoc;
5550b57cec5SDimitry Andric     }
5560b57cec5SDimitry Andric     addLocIfNotPresent(CurFn->ChildSites, Loc);
5570b57cec5SDimitry Andric   }
5580b57cec5SDimitry Andric 
5595ffd83dbSDimitry Andric   OS.emitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
5600b57cec5SDimitry Andric                         /*PrologueEnd=*/false, /*IsStmt=*/false,
5610b57cec5SDimitry Andric                         DL->getFilename(), SMLoc());
5620b57cec5SDimitry Andric }
5630b57cec5SDimitry Andric 
emitCodeViewMagicVersion()5640b57cec5SDimitry Andric void CodeViewDebug::emitCodeViewMagicVersion() {
565bdd1243dSDimitry Andric   OS.emitValueToAlignment(Align(4));
5660b57cec5SDimitry Andric   OS.AddComment("Debug section magic");
5675ffd83dbSDimitry Andric   OS.emitInt32(COFF::DEBUG_SECTION_MAGIC);
5680b57cec5SDimitry Andric }
5690b57cec5SDimitry Andric 
MapDWLangToCVLang(unsigned DWLang)570349cc55cSDimitry Andric static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
571349cc55cSDimitry Andric   switch (DWLang) {
572349cc55cSDimitry Andric   case dwarf::DW_LANG_C:
573349cc55cSDimitry Andric   case dwarf::DW_LANG_C89:
574349cc55cSDimitry Andric   case dwarf::DW_LANG_C99:
575349cc55cSDimitry Andric   case dwarf::DW_LANG_C11:
576349cc55cSDimitry Andric     return SourceLanguage::C;
577349cc55cSDimitry Andric   case dwarf::DW_LANG_C_plus_plus:
578349cc55cSDimitry Andric   case dwarf::DW_LANG_C_plus_plus_03:
579349cc55cSDimitry Andric   case dwarf::DW_LANG_C_plus_plus_11:
580349cc55cSDimitry Andric   case dwarf::DW_LANG_C_plus_plus_14:
581349cc55cSDimitry Andric     return SourceLanguage::Cpp;
582349cc55cSDimitry Andric   case dwarf::DW_LANG_Fortran77:
583349cc55cSDimitry Andric   case dwarf::DW_LANG_Fortran90:
584349cc55cSDimitry Andric   case dwarf::DW_LANG_Fortran95:
585349cc55cSDimitry Andric   case dwarf::DW_LANG_Fortran03:
586349cc55cSDimitry Andric   case dwarf::DW_LANG_Fortran08:
587349cc55cSDimitry Andric     return SourceLanguage::Fortran;
588349cc55cSDimitry Andric   case dwarf::DW_LANG_Pascal83:
589349cc55cSDimitry Andric     return SourceLanguage::Pascal;
590349cc55cSDimitry Andric   case dwarf::DW_LANG_Cobol74:
591349cc55cSDimitry Andric   case dwarf::DW_LANG_Cobol85:
592349cc55cSDimitry Andric     return SourceLanguage::Cobol;
593349cc55cSDimitry Andric   case dwarf::DW_LANG_Java:
594349cc55cSDimitry Andric     return SourceLanguage::Java;
595349cc55cSDimitry Andric   case dwarf::DW_LANG_D:
596349cc55cSDimitry Andric     return SourceLanguage::D;
597349cc55cSDimitry Andric   case dwarf::DW_LANG_Swift:
598349cc55cSDimitry Andric     return SourceLanguage::Swift;
59904eeddc0SDimitry Andric   case dwarf::DW_LANG_Rust:
60004eeddc0SDimitry Andric     return SourceLanguage::Rust;
60106c3fb27SDimitry Andric   case dwarf::DW_LANG_ObjC:
60206c3fb27SDimitry Andric     return SourceLanguage::ObjC;
60306c3fb27SDimitry Andric   case dwarf::DW_LANG_ObjC_plus_plus:
60406c3fb27SDimitry Andric     return SourceLanguage::ObjCpp;
605349cc55cSDimitry Andric   default:
606349cc55cSDimitry Andric     // There's no CodeView representation for this language, and CV doesn't
607349cc55cSDimitry Andric     // have an "unknown" option for the language field, so we'll use MASM,
608349cc55cSDimitry Andric     // as it's very low level.
609349cc55cSDimitry Andric     return SourceLanguage::Masm;
610349cc55cSDimitry Andric   }
611349cc55cSDimitry Andric }
612349cc55cSDimitry Andric 
beginModule(Module * M)613e8d8bef9SDimitry Andric void CodeViewDebug::beginModule(Module *M) {
614e8d8bef9SDimitry Andric   // If module doesn't have named metadata anchors or COFF debug section
615e8d8bef9SDimitry Andric   // is not available, skip any debug info related stuff.
61681ad6265SDimitry Andric   if (!MMI->hasDebugInfo() ||
61781ad6265SDimitry Andric       !Asm->getObjFileLowering().getCOFFDebugSymbolsSection()) {
618e8d8bef9SDimitry Andric     Asm = nullptr;
619e8d8bef9SDimitry Andric     return;
620e8d8bef9SDimitry Andric   }
621e8d8bef9SDimitry Andric 
622e8d8bef9SDimitry Andric   TheCPU = mapArchToCVCPUType(Triple(M->getTargetTriple()).getArch());
623e8d8bef9SDimitry Andric 
624349cc55cSDimitry Andric   // Get the current source language.
62581ad6265SDimitry Andric   const MDNode *Node = *M->debug_compile_units_begin();
626349cc55cSDimitry Andric   const auto *CU = cast<DICompileUnit>(Node);
627349cc55cSDimitry Andric 
628349cc55cSDimitry Andric   CurrentSourceLanguage = MapDWLangToCVLang(CU->getSourceLanguage());
629349cc55cSDimitry Andric 
630e8d8bef9SDimitry Andric   collectGlobalVariableInfo();
631e8d8bef9SDimitry Andric 
632e8d8bef9SDimitry Andric   // Check if we should emit type record hashes.
633e8d8bef9SDimitry Andric   ConstantInt *GH =
634e8d8bef9SDimitry Andric       mdconst::extract_or_null<ConstantInt>(M->getModuleFlag("CodeViewGHash"));
635e8d8bef9SDimitry Andric   EmitDebugGlobalHashes = GH && !GH->isZero();
636e8d8bef9SDimitry Andric }
637e8d8bef9SDimitry Andric 
endModule()6380b57cec5SDimitry Andric void CodeViewDebug::endModule() {
6390b57cec5SDimitry Andric   if (!Asm || !MMI->hasDebugInfo())
6400b57cec5SDimitry Andric     return;
6410b57cec5SDimitry Andric 
6420b57cec5SDimitry Andric   // The COFF .debug$S section consists of several subsections, each starting
6430b57cec5SDimitry Andric   // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
6440b57cec5SDimitry Andric   // of the payload followed by the payload itself.  The subsections are 4-byte
6450b57cec5SDimitry Andric   // aligned.
6460b57cec5SDimitry Andric 
6470b57cec5SDimitry Andric   // Use the generic .debug$S section, and make a subsection for all the inlined
6480b57cec5SDimitry Andric   // subprograms.
6490b57cec5SDimitry Andric   switchToDebugSectionForSymbol(nullptr);
6500b57cec5SDimitry Andric 
6510b57cec5SDimitry Andric   MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
6520eae32dcSDimitry Andric   emitObjName();
6530b57cec5SDimitry Andric   emitCompilerInformation();
6540b57cec5SDimitry Andric   endCVSubsection(CompilerInfo);
6550b57cec5SDimitry Andric 
6560b57cec5SDimitry Andric   emitInlineeLinesSubsection();
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric   // Emit per-function debug information.
6590b57cec5SDimitry Andric   for (auto &P : FnDebugInfo)
6600b57cec5SDimitry Andric     if (!P.first->isDeclarationForLinker())
6610b57cec5SDimitry Andric       emitDebugInfoForFunction(P.first, *P.second);
6620b57cec5SDimitry Andric 
663e8d8bef9SDimitry Andric   // Get types used by globals without emitting anything.
664e8d8bef9SDimitry Andric   // This is meant to collect all static const data members so they can be
665e8d8bef9SDimitry Andric   // emitted as globals.
666e8d8bef9SDimitry Andric   collectDebugInfoForGlobals();
6670b57cec5SDimitry Andric 
6680b57cec5SDimitry Andric   // Emit retained types.
6690b57cec5SDimitry Andric   emitDebugInfoForRetainedTypes();
6700b57cec5SDimitry Andric 
671e8d8bef9SDimitry Andric   // Emit global variable debug information.
672e8d8bef9SDimitry Andric   setCurrentSubprogram(nullptr);
673e8d8bef9SDimitry Andric   emitDebugInfoForGlobals();
674e8d8bef9SDimitry Andric 
6750b57cec5SDimitry Andric   // Switch back to the generic .debug$S section after potentially processing
6760b57cec5SDimitry Andric   // comdat symbol sections.
6770b57cec5SDimitry Andric   switchToDebugSectionForSymbol(nullptr);
6780b57cec5SDimitry Andric 
6790b57cec5SDimitry Andric   // Emit UDT records for any types used by global variables.
6800b57cec5SDimitry Andric   if (!GlobalUDTs.empty()) {
6810b57cec5SDimitry Andric     MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
6820b57cec5SDimitry Andric     emitDebugInfoForUDTs(GlobalUDTs);
6830b57cec5SDimitry Andric     endCVSubsection(SymbolsEnd);
6840b57cec5SDimitry Andric   }
6850b57cec5SDimitry Andric 
6860b57cec5SDimitry Andric   // This subsection holds a file index to offset in string table table.
6870b57cec5SDimitry Andric   OS.AddComment("File index to string table offset subsection");
6885ffd83dbSDimitry Andric   OS.emitCVFileChecksumsDirective();
6890b57cec5SDimitry Andric 
6900b57cec5SDimitry Andric   // This subsection holds the string table.
6910b57cec5SDimitry Andric   OS.AddComment("String table");
6925ffd83dbSDimitry Andric   OS.emitCVStringTableDirective();
6930b57cec5SDimitry Andric 
6940b57cec5SDimitry Andric   // Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol
6950b57cec5SDimitry Andric   // subsection in the generic .debug$S section at the end. There is no
6960b57cec5SDimitry Andric   // particular reason for this ordering other than to match MSVC.
6970b57cec5SDimitry Andric   emitBuildInfo();
6980b57cec5SDimitry Andric 
6990b57cec5SDimitry Andric   // Emit type information and hashes last, so that any types we translate while
7000b57cec5SDimitry Andric   // emitting function info are included.
7010b57cec5SDimitry Andric   emitTypeInformation();
7020b57cec5SDimitry Andric 
7030b57cec5SDimitry Andric   if (EmitDebugGlobalHashes)
7040b57cec5SDimitry Andric     emitTypeGlobalHashes();
7050b57cec5SDimitry Andric 
7060b57cec5SDimitry Andric   clear();
7070b57cec5SDimitry Andric }
7080b57cec5SDimitry Andric 
7090b57cec5SDimitry Andric static void
emitNullTerminatedSymbolName(MCStreamer & OS,StringRef S,unsigned MaxFixedRecordLength=0xF00)7100b57cec5SDimitry Andric emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S,
7110b57cec5SDimitry Andric                              unsigned MaxFixedRecordLength = 0xF00) {
7120b57cec5SDimitry Andric   // The maximum CV record length is 0xFF00. Most of the strings we emit appear
7130b57cec5SDimitry Andric   // after a fixed length portion of the record. The fixed length portion should
7140b57cec5SDimitry Andric   // always be less than 0xF00 (3840) bytes, so truncate the string so that the
7150b57cec5SDimitry Andric   // overall record size is less than the maximum allowed.
7160b57cec5SDimitry Andric   SmallString<32> NullTerminatedString(
7170b57cec5SDimitry Andric       S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
7180b57cec5SDimitry Andric   NullTerminatedString.push_back('\0');
7195ffd83dbSDimitry Andric   OS.emitBytes(NullTerminatedString);
7200b57cec5SDimitry Andric }
7210b57cec5SDimitry Andric 
emitTypeInformation()7220b57cec5SDimitry Andric void CodeViewDebug::emitTypeInformation() {
7230b57cec5SDimitry Andric   if (TypeTable.empty())
7240b57cec5SDimitry Andric     return;
7250b57cec5SDimitry Andric 
7260b57cec5SDimitry Andric   // Start the .debug$T or .debug$P section with 0x4.
72781ad6265SDimitry Andric   OS.switchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
7280b57cec5SDimitry Andric   emitCodeViewMagicVersion();
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric   TypeTableCollection Table(TypeTable.records());
7310b57cec5SDimitry Andric   TypeVisitorCallbackPipeline Pipeline;
7320b57cec5SDimitry Andric 
7330b57cec5SDimitry Andric   // To emit type record using Codeview MCStreamer adapter
7348bcb0991SDimitry Andric   CVMCAdapter CVMCOS(OS, Table);
7350b57cec5SDimitry Andric   TypeRecordMapping typeMapping(CVMCOS);
7360b57cec5SDimitry Andric   Pipeline.addCallbackToPipeline(typeMapping);
7370b57cec5SDimitry Andric 
738bdd1243dSDimitry Andric   std::optional<TypeIndex> B = Table.getFirst();
7390b57cec5SDimitry Andric   while (B) {
7400b57cec5SDimitry Andric     // This will fail if the record data is invalid.
7410b57cec5SDimitry Andric     CVType Record = Table.getType(*B);
7420b57cec5SDimitry Andric 
7430b57cec5SDimitry Andric     Error E = codeview::visitTypeRecord(Record, *B, Pipeline);
7440b57cec5SDimitry Andric 
7450b57cec5SDimitry Andric     if (E) {
7460b57cec5SDimitry Andric       logAllUnhandledErrors(std::move(E), errs(), "error: ");
7470b57cec5SDimitry Andric       llvm_unreachable("produced malformed type record");
7480b57cec5SDimitry Andric     }
7490b57cec5SDimitry Andric 
7500b57cec5SDimitry Andric     B = Table.getNext(*B);
7510b57cec5SDimitry Andric   }
7520b57cec5SDimitry Andric }
7530b57cec5SDimitry Andric 
emitTypeGlobalHashes()7540b57cec5SDimitry Andric void CodeViewDebug::emitTypeGlobalHashes() {
7550b57cec5SDimitry Andric   if (TypeTable.empty())
7560b57cec5SDimitry Andric     return;
7570b57cec5SDimitry Andric 
7580b57cec5SDimitry Andric   // Start the .debug$H section with the version and hash algorithm, currently
7590b57cec5SDimitry Andric   // hardcoded to version 0, SHA1.
76081ad6265SDimitry Andric   OS.switchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
7610b57cec5SDimitry Andric 
762bdd1243dSDimitry Andric   OS.emitValueToAlignment(Align(4));
7630b57cec5SDimitry Andric   OS.AddComment("Magic");
7645ffd83dbSDimitry Andric   OS.emitInt32(COFF::DEBUG_HASHES_SECTION_MAGIC);
7650b57cec5SDimitry Andric   OS.AddComment("Section Version");
7665ffd83dbSDimitry Andric   OS.emitInt16(0);
7670b57cec5SDimitry Andric   OS.AddComment("Hash Algorithm");
768bdd1243dSDimitry Andric   OS.emitInt16(uint16_t(GlobalTypeHashAlg::BLAKE3));
7690b57cec5SDimitry Andric 
7700b57cec5SDimitry Andric   TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
7710b57cec5SDimitry Andric   for (const auto &GHR : TypeTable.hashes()) {
7720b57cec5SDimitry Andric     if (OS.isVerboseAsm()) {
7730b57cec5SDimitry Andric       // Emit an EOL-comment describing which TypeIndex this hash corresponds
7740b57cec5SDimitry Andric       // to, as well as the stringified SHA1 hash.
7750b57cec5SDimitry Andric       SmallString<32> Comment;
7760b57cec5SDimitry Andric       raw_svector_ostream CommentOS(Comment);
7770b57cec5SDimitry Andric       CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
7780b57cec5SDimitry Andric       OS.AddComment(Comment);
7790b57cec5SDimitry Andric       ++TI;
7800b57cec5SDimitry Andric     }
7810b57cec5SDimitry Andric     assert(GHR.Hash.size() == 8);
7820b57cec5SDimitry Andric     StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
7830b57cec5SDimitry Andric                 GHR.Hash.size());
7845ffd83dbSDimitry Andric     OS.emitBinaryData(S);
7850b57cec5SDimitry Andric   }
7860b57cec5SDimitry Andric }
7870b57cec5SDimitry Andric 
emitObjName()7880eae32dcSDimitry Andric void CodeViewDebug::emitObjName() {
7890eae32dcSDimitry Andric   MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_OBJNAME);
7900eae32dcSDimitry Andric 
7910eae32dcSDimitry Andric   StringRef PathRef(Asm->TM.Options.ObjectFilenameForDebug);
7920eae32dcSDimitry Andric   llvm::SmallString<256> PathStore(PathRef);
7930eae32dcSDimitry Andric 
7940eae32dcSDimitry Andric   if (PathRef.empty() || PathRef == "-") {
7950eae32dcSDimitry Andric     // Don't emit the filename if we're writing to stdout or to /dev/null.
7960eae32dcSDimitry Andric     PathRef = {};
7970eae32dcSDimitry Andric   } else {
7980eae32dcSDimitry Andric     PathRef = PathStore;
7990eae32dcSDimitry Andric   }
8000eae32dcSDimitry Andric 
8010eae32dcSDimitry Andric   OS.AddComment("Signature");
8020eae32dcSDimitry Andric   OS.emitIntValue(0, 4);
8030eae32dcSDimitry Andric 
8040eae32dcSDimitry Andric   OS.AddComment("Object name");
8050eae32dcSDimitry Andric   emitNullTerminatedSymbolName(OS, PathRef);
8060eae32dcSDimitry Andric 
8070eae32dcSDimitry Andric   endSymbolRecord(CompilerEnd);
8080eae32dcSDimitry Andric }
8090eae32dcSDimitry Andric 
8100b57cec5SDimitry Andric namespace {
8110b57cec5SDimitry Andric struct Version {
8120b57cec5SDimitry Andric   int Part[4];
8130b57cec5SDimitry Andric };
8140b57cec5SDimitry Andric } // end anonymous namespace
8150b57cec5SDimitry Andric 
8160b57cec5SDimitry Andric // Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
8170b57cec5SDimitry Andric // the version number.
parseVersion(StringRef Name)8180b57cec5SDimitry Andric static Version parseVersion(StringRef Name) {
8190b57cec5SDimitry Andric   Version V = {{0}};
8200b57cec5SDimitry Andric   int N = 0;
8210b57cec5SDimitry Andric   for (const char C : Name) {
8220b57cec5SDimitry Andric     if (isdigit(C)) {
8230b57cec5SDimitry Andric       V.Part[N] *= 10;
8240b57cec5SDimitry Andric       V.Part[N] += C - '0';
82581ad6265SDimitry Andric       V.Part[N] =
82681ad6265SDimitry Andric           std::min<int>(V.Part[N], std::numeric_limits<uint16_t>::max());
8270b57cec5SDimitry Andric     } else if (C == '.') {
8280b57cec5SDimitry Andric       ++N;
8290b57cec5SDimitry Andric       if (N >= 4)
8300b57cec5SDimitry Andric         return V;
8310b57cec5SDimitry Andric     } else if (N > 0)
8320b57cec5SDimitry Andric       return V;
8330b57cec5SDimitry Andric   }
8340b57cec5SDimitry Andric   return V;
8350b57cec5SDimitry Andric }
8360b57cec5SDimitry Andric 
emitCompilerInformation()8370b57cec5SDimitry Andric void CodeViewDebug::emitCompilerInformation() {
8380b57cec5SDimitry Andric   MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_COMPILE3);
8390b57cec5SDimitry Andric   uint32_t Flags = 0;
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric   // The low byte of the flags indicates the source language.
842349cc55cSDimitry Andric   Flags = CurrentSourceLanguage;
8430b57cec5SDimitry Andric   // TODO:  Figure out which other flags need to be set.
844fe6060f1SDimitry Andric   if (MMI->getModule()->getProfileSummary(/*IsCS*/ false) != nullptr) {
845fe6060f1SDimitry Andric     Flags |= static_cast<uint32_t>(CompileSym3Flags::PGO);
846fe6060f1SDimitry Andric   }
84704eeddc0SDimitry Andric   using ArchType = llvm::Triple::ArchType;
84804eeddc0SDimitry Andric   ArchType Arch = Triple(MMI->getModule()->getTargetTriple()).getArch();
84904eeddc0SDimitry Andric   if (Asm->TM.Options.Hotpatch || Arch == ArchType::thumb ||
85004eeddc0SDimitry Andric       Arch == ArchType::aarch64) {
85104eeddc0SDimitry Andric     Flags |= static_cast<uint32_t>(CompileSym3Flags::HotPatch);
85204eeddc0SDimitry Andric   }
8530b57cec5SDimitry Andric 
8540b57cec5SDimitry Andric   OS.AddComment("Flags and language");
8555ffd83dbSDimitry Andric   OS.emitInt32(Flags);
8560b57cec5SDimitry Andric 
8570b57cec5SDimitry Andric   OS.AddComment("CPUType");
8585ffd83dbSDimitry Andric   OS.emitInt16(static_cast<uint64_t>(TheCPU));
8590b57cec5SDimitry Andric 
860349cc55cSDimitry Andric   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
861349cc55cSDimitry Andric   const MDNode *Node = *CUs->operands().begin();
862349cc55cSDimitry Andric   const auto *CU = cast<DICompileUnit>(Node);
863349cc55cSDimitry Andric 
8640b57cec5SDimitry Andric   StringRef CompilerVersion = CU->getProducer();
8650b57cec5SDimitry Andric   Version FrontVer = parseVersion(CompilerVersion);
8660b57cec5SDimitry Andric   OS.AddComment("Frontend version");
86704eeddc0SDimitry Andric   for (int N : FrontVer.Part) {
868fe6060f1SDimitry Andric     OS.emitInt16(N);
86904eeddc0SDimitry Andric   }
8700b57cec5SDimitry Andric 
8710b57cec5SDimitry Andric   // Some Microsoft tools, like Binscope, expect a backend version number of at
8720b57cec5SDimitry Andric   // least 8.something, so we'll coerce the LLVM version into a form that
8730b57cec5SDimitry Andric   // guarantees it'll be big enough without really lying about the version.
8740b57cec5SDimitry Andric   int Major = 1000 * LLVM_VERSION_MAJOR +
8750b57cec5SDimitry Andric               10 * LLVM_VERSION_MINOR +
8760b57cec5SDimitry Andric               LLVM_VERSION_PATCH;
8770b57cec5SDimitry Andric   // Clamp it for builds that use unusually large version numbers.
8780b57cec5SDimitry Andric   Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
8790b57cec5SDimitry Andric   Version BackVer = {{ Major, 0, 0, 0 }};
8800b57cec5SDimitry Andric   OS.AddComment("Backend version");
881fe6060f1SDimitry Andric   for (int N : BackVer.Part)
882fe6060f1SDimitry Andric     OS.emitInt16(N);
8830b57cec5SDimitry Andric 
8840b57cec5SDimitry Andric   OS.AddComment("Null-terminated compiler version string");
8850b57cec5SDimitry Andric   emitNullTerminatedSymbolName(OS, CompilerVersion);
8860b57cec5SDimitry Andric 
8870b57cec5SDimitry Andric   endSymbolRecord(CompilerEnd);
8880b57cec5SDimitry Andric }
8890b57cec5SDimitry Andric 
getStringIdTypeIdx(GlobalTypeTableBuilder & TypeTable,StringRef S)8900b57cec5SDimitry Andric static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable,
8910b57cec5SDimitry Andric                                     StringRef S) {
8920b57cec5SDimitry Andric   StringIdRecord SIR(TypeIndex(0x0), S);
8930b57cec5SDimitry Andric   return TypeTable.writeLeafType(SIR);
8940b57cec5SDimitry Andric }
8950b57cec5SDimitry Andric 
flattenCommandLine(ArrayRef<std::string> Args,StringRef MainFilename)89604eeddc0SDimitry Andric static std::string flattenCommandLine(ArrayRef<std::string> Args,
89704eeddc0SDimitry Andric                                       StringRef MainFilename) {
89804eeddc0SDimitry Andric   std::string FlatCmdLine;
89904eeddc0SDimitry Andric   raw_string_ostream OS(FlatCmdLine);
90004eeddc0SDimitry Andric   bool PrintedOneArg = false;
90104eeddc0SDimitry Andric   if (!StringRef(Args[0]).contains("-cc1")) {
90204eeddc0SDimitry Andric     llvm::sys::printArg(OS, "-cc1", /*Quote=*/true);
90304eeddc0SDimitry Andric     PrintedOneArg = true;
90404eeddc0SDimitry Andric   }
90504eeddc0SDimitry Andric   for (unsigned i = 0; i < Args.size(); i++) {
90604eeddc0SDimitry Andric     StringRef Arg = Args[i];
90704eeddc0SDimitry Andric     if (Arg.empty())
90804eeddc0SDimitry Andric       continue;
90904eeddc0SDimitry Andric     if (Arg == "-main-file-name" || Arg == "-o") {
91004eeddc0SDimitry Andric       i++; // Skip this argument and next one.
91104eeddc0SDimitry Andric       continue;
91204eeddc0SDimitry Andric     }
9135f757f3fSDimitry Andric     if (Arg.starts_with("-object-file-name") || Arg == MainFilename)
91404eeddc0SDimitry Andric       continue;
915bdd1243dSDimitry Andric     // Skip fmessage-length for reproduciability.
9165f757f3fSDimitry Andric     if (Arg.starts_with("-fmessage-length"))
917bdd1243dSDimitry Andric       continue;
91804eeddc0SDimitry Andric     if (PrintedOneArg)
91904eeddc0SDimitry Andric       OS << " ";
92004eeddc0SDimitry Andric     llvm::sys::printArg(OS, Arg, /*Quote=*/true);
92104eeddc0SDimitry Andric     PrintedOneArg = true;
92204eeddc0SDimitry Andric   }
92304eeddc0SDimitry Andric   OS.flush();
92404eeddc0SDimitry Andric   return FlatCmdLine;
92504eeddc0SDimitry Andric }
92604eeddc0SDimitry Andric 
emitBuildInfo()9270b57cec5SDimitry Andric void CodeViewDebug::emitBuildInfo() {
9280b57cec5SDimitry Andric   // First, make LF_BUILDINFO. It's a sequence of strings with various bits of
9290b57cec5SDimitry Andric   // build info. The known prefix is:
9300b57cec5SDimitry Andric   // - Absolute path of current directory
9310b57cec5SDimitry Andric   // - Compiler path
9320b57cec5SDimitry Andric   // - Main source file path, relative to CWD or absolute
9330b57cec5SDimitry Andric   // - Type server PDB file
9340b57cec5SDimitry Andric   // - Canonical compiler command line
9350b57cec5SDimitry Andric   // If frontend and backend compilation are separated (think llc or LTO), it's
9360b57cec5SDimitry Andric   // not clear if the compiler path should refer to the executable for the
9370b57cec5SDimitry Andric   // frontend or the backend. Leave it blank for now.
9380b57cec5SDimitry Andric   TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {};
9390b57cec5SDimitry Andric   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
9400b57cec5SDimitry Andric   const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs.
9410b57cec5SDimitry Andric   const auto *CU = cast<DICompileUnit>(Node);
9420b57cec5SDimitry Andric   const DIFile *MainSourceFile = CU->getFile();
9430b57cec5SDimitry Andric   BuildInfoArgs[BuildInfoRecord::CurrentDirectory] =
9440b57cec5SDimitry Andric       getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory());
9450b57cec5SDimitry Andric   BuildInfoArgs[BuildInfoRecord::SourceFile] =
9460b57cec5SDimitry Andric       getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename());
94704eeddc0SDimitry Andric   // FIXME: PDB is intentionally blank unless we implement /Zi type servers.
94804eeddc0SDimitry Andric   BuildInfoArgs[BuildInfoRecord::TypeServerPDB] =
94904eeddc0SDimitry Andric       getStringIdTypeIdx(TypeTable, "");
95004eeddc0SDimitry Andric   if (Asm->TM.Options.MCOptions.Argv0 != nullptr) {
95104eeddc0SDimitry Andric     BuildInfoArgs[BuildInfoRecord::BuildTool] =
95204eeddc0SDimitry Andric         getStringIdTypeIdx(TypeTable, Asm->TM.Options.MCOptions.Argv0);
95304eeddc0SDimitry Andric     BuildInfoArgs[BuildInfoRecord::CommandLine] = getStringIdTypeIdx(
95404eeddc0SDimitry Andric         TypeTable, flattenCommandLine(Asm->TM.Options.MCOptions.CommandLineArgs,
95504eeddc0SDimitry Andric                                       MainSourceFile->getFilename()));
95604eeddc0SDimitry Andric   }
9570b57cec5SDimitry Andric   BuildInfoRecord BIR(BuildInfoArgs);
9580b57cec5SDimitry Andric   TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR);
9590b57cec5SDimitry Andric 
9600b57cec5SDimitry Andric   // Make a new .debug$S subsection for the S_BUILDINFO record, which points
9610b57cec5SDimitry Andric   // from the module symbols into the type stream.
9620b57cec5SDimitry Andric   MCSymbol *BISubsecEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
9630b57cec5SDimitry Andric   MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO);
9640b57cec5SDimitry Andric   OS.AddComment("LF_BUILDINFO index");
9655ffd83dbSDimitry Andric   OS.emitInt32(BuildInfoIndex.getIndex());
9660b57cec5SDimitry Andric   endSymbolRecord(BIEnd);
9670b57cec5SDimitry Andric   endCVSubsection(BISubsecEnd);
9680b57cec5SDimitry Andric }
9690b57cec5SDimitry Andric 
emitInlineeLinesSubsection()9700b57cec5SDimitry Andric void CodeViewDebug::emitInlineeLinesSubsection() {
9710b57cec5SDimitry Andric   if (InlinedSubprograms.empty())
9720b57cec5SDimitry Andric     return;
9730b57cec5SDimitry Andric 
9740b57cec5SDimitry Andric   OS.AddComment("Inlinee lines subsection");
9750b57cec5SDimitry Andric   MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
9760b57cec5SDimitry Andric 
9770b57cec5SDimitry Andric   // We emit the checksum info for files.  This is used by debuggers to
9780b57cec5SDimitry Andric   // determine if a pdb matches the source before loading it.  Visual Studio,
9790b57cec5SDimitry Andric   // for instance, will display a warning that the breakpoints are not valid if
9800b57cec5SDimitry Andric   // the pdb does not match the source.
9810b57cec5SDimitry Andric   OS.AddComment("Inlinee lines signature");
9825ffd83dbSDimitry Andric   OS.emitInt32(unsigned(InlineeLinesSignature::Normal));
9830b57cec5SDimitry Andric 
9840b57cec5SDimitry Andric   for (const DISubprogram *SP : InlinedSubprograms) {
9850b57cec5SDimitry Andric     assert(TypeIndices.count({SP, nullptr}));
9860b57cec5SDimitry Andric     TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
9870b57cec5SDimitry Andric 
98881ad6265SDimitry Andric     OS.addBlankLine();
9890b57cec5SDimitry Andric     unsigned FileId = maybeRecordFile(SP->getFile());
9900b57cec5SDimitry Andric     OS.AddComment("Inlined function " + SP->getName() + " starts at " +
9910b57cec5SDimitry Andric                   SP->getFilename() + Twine(':') + Twine(SP->getLine()));
99281ad6265SDimitry Andric     OS.addBlankLine();
9930b57cec5SDimitry Andric     OS.AddComment("Type index of inlined function");
9945ffd83dbSDimitry Andric     OS.emitInt32(InlineeIdx.getIndex());
9950b57cec5SDimitry Andric     OS.AddComment("Offset into filechecksum table");
9965ffd83dbSDimitry Andric     OS.emitCVFileChecksumOffsetDirective(FileId);
9970b57cec5SDimitry Andric     OS.AddComment("Starting line number");
9985ffd83dbSDimitry Andric     OS.emitInt32(SP->getLine());
9990b57cec5SDimitry Andric   }
10000b57cec5SDimitry Andric 
10010b57cec5SDimitry Andric   endCVSubsection(InlineEnd);
10020b57cec5SDimitry Andric }
10030b57cec5SDimitry Andric 
emitInlinedCallSite(const FunctionInfo & FI,const DILocation * InlinedAt,const InlineSite & Site)10040b57cec5SDimitry Andric void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
10050b57cec5SDimitry Andric                                         const DILocation *InlinedAt,
10060b57cec5SDimitry Andric                                         const InlineSite &Site) {
10070b57cec5SDimitry Andric   assert(TypeIndices.count({Site.Inlinee, nullptr}));
10080b57cec5SDimitry Andric   TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
10090b57cec5SDimitry Andric 
10100b57cec5SDimitry Andric   // SymbolRecord
10110b57cec5SDimitry Andric   MCSymbol *InlineEnd = beginSymbolRecord(SymbolKind::S_INLINESITE);
10120b57cec5SDimitry Andric 
10130b57cec5SDimitry Andric   OS.AddComment("PtrParent");
10145ffd83dbSDimitry Andric   OS.emitInt32(0);
10150b57cec5SDimitry Andric   OS.AddComment("PtrEnd");
10165ffd83dbSDimitry Andric   OS.emitInt32(0);
10170b57cec5SDimitry Andric   OS.AddComment("Inlinee type index");
10185ffd83dbSDimitry Andric   OS.emitInt32(InlineeIdx.getIndex());
10190b57cec5SDimitry Andric 
10200b57cec5SDimitry Andric   unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
10210b57cec5SDimitry Andric   unsigned StartLineNum = Site.Inlinee->getLine();
10220b57cec5SDimitry Andric 
10235ffd83dbSDimitry Andric   OS.emitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
10240b57cec5SDimitry Andric                                     FI.Begin, FI.End);
10250b57cec5SDimitry Andric 
10260b57cec5SDimitry Andric   endSymbolRecord(InlineEnd);
10270b57cec5SDimitry Andric 
10280b57cec5SDimitry Andric   emitLocalVariableList(FI, Site.InlinedLocals);
10290b57cec5SDimitry Andric 
10300b57cec5SDimitry Andric   // Recurse on child inlined call sites before closing the scope.
10310b57cec5SDimitry Andric   for (const DILocation *ChildSite : Site.ChildSites) {
10320b57cec5SDimitry Andric     auto I = FI.InlineSites.find(ChildSite);
10330b57cec5SDimitry Andric     assert(I != FI.InlineSites.end() &&
10340b57cec5SDimitry Andric            "child site not in function inline site map");
10350b57cec5SDimitry Andric     emitInlinedCallSite(FI, ChildSite, I->second);
10360b57cec5SDimitry Andric   }
10370b57cec5SDimitry Andric 
10380b57cec5SDimitry Andric   // Close the scope.
10390b57cec5SDimitry Andric   emitEndSymbolRecord(SymbolKind::S_INLINESITE_END);
10400b57cec5SDimitry Andric }
10410b57cec5SDimitry Andric 
switchToDebugSectionForSymbol(const MCSymbol * GVSym)10420b57cec5SDimitry Andric void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
10430b57cec5SDimitry Andric   // If we have a symbol, it may be in a section that is COMDAT. If so, find the
10440b57cec5SDimitry Andric   // comdat key. A section may be comdat because of -ffunction-sections or
10450b57cec5SDimitry Andric   // because it is comdat in the IR.
10460b57cec5SDimitry Andric   MCSectionCOFF *GVSec =
10470b57cec5SDimitry Andric       GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
10480b57cec5SDimitry Andric   const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
10490b57cec5SDimitry Andric 
10500b57cec5SDimitry Andric   MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
10510b57cec5SDimitry Andric       Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
10520b57cec5SDimitry Andric   DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
10530b57cec5SDimitry Andric 
105481ad6265SDimitry Andric   OS.switchSection(DebugSec);
10550b57cec5SDimitry Andric 
10560b57cec5SDimitry Andric   // Emit the magic version number if this is the first time we've switched to
10570b57cec5SDimitry Andric   // this section.
10580b57cec5SDimitry Andric   if (ComdatDebugSections.insert(DebugSec).second)
10590b57cec5SDimitry Andric     emitCodeViewMagicVersion();
10600b57cec5SDimitry Andric }
10610b57cec5SDimitry Andric 
10620b57cec5SDimitry Andric // Emit an S_THUNK32/S_END symbol pair for a thunk routine.
10630b57cec5SDimitry Andric // The only supported thunk ordinal is currently the standard type.
emitDebugInfoForThunk(const Function * GV,FunctionInfo & FI,const MCSymbol * Fn)10640b57cec5SDimitry Andric void CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
10650b57cec5SDimitry Andric                                           FunctionInfo &FI,
10660b57cec5SDimitry Andric                                           const MCSymbol *Fn) {
10675ffd83dbSDimitry Andric   std::string FuncName =
10685ffd83dbSDimitry Andric       std::string(GlobalValue::dropLLVMManglingEscape(GV->getName()));
10690b57cec5SDimitry Andric   const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
10700b57cec5SDimitry Andric 
10710b57cec5SDimitry Andric   OS.AddComment("Symbol subsection for " + Twine(FuncName));
10720b57cec5SDimitry Andric   MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
10730b57cec5SDimitry Andric 
10740b57cec5SDimitry Andric   // Emit S_THUNK32
10750b57cec5SDimitry Andric   MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32);
10760b57cec5SDimitry Andric   OS.AddComment("PtrParent");
10775ffd83dbSDimitry Andric   OS.emitInt32(0);
10780b57cec5SDimitry Andric   OS.AddComment("PtrEnd");
10795ffd83dbSDimitry Andric   OS.emitInt32(0);
10800b57cec5SDimitry Andric   OS.AddComment("PtrNext");
10815ffd83dbSDimitry Andric   OS.emitInt32(0);
10820b57cec5SDimitry Andric   OS.AddComment("Thunk section relative address");
108381ad6265SDimitry Andric   OS.emitCOFFSecRel32(Fn, /*Offset=*/0);
10840b57cec5SDimitry Andric   OS.AddComment("Thunk section index");
108581ad6265SDimitry Andric   OS.emitCOFFSectionIndex(Fn);
10860b57cec5SDimitry Andric   OS.AddComment("Code size");
10870b57cec5SDimitry Andric   OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
10880b57cec5SDimitry Andric   OS.AddComment("Ordinal");
10895ffd83dbSDimitry Andric   OS.emitInt8(unsigned(ordinal));
10900b57cec5SDimitry Andric   OS.AddComment("Function name");
10910b57cec5SDimitry Andric   emitNullTerminatedSymbolName(OS, FuncName);
10920b57cec5SDimitry Andric   // Additional fields specific to the thunk ordinal would go here.
10930b57cec5SDimitry Andric   endSymbolRecord(ThunkRecordEnd);
10940b57cec5SDimitry Andric 
10950b57cec5SDimitry Andric   // Local variables/inlined routines are purposely omitted here.  The point of
10960b57cec5SDimitry Andric   // marking this as a thunk is so Visual Studio will NOT stop in this routine.
10970b57cec5SDimitry Andric 
10980b57cec5SDimitry Andric   // Emit S_PROC_ID_END
10990b57cec5SDimitry Andric   emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
11000b57cec5SDimitry Andric 
11010b57cec5SDimitry Andric   endCVSubsection(SymbolsEnd);
11020b57cec5SDimitry Andric }
11030b57cec5SDimitry Andric 
emitDebugInfoForFunction(const Function * GV,FunctionInfo & FI)11040b57cec5SDimitry Andric void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
11050b57cec5SDimitry Andric                                              FunctionInfo &FI) {
11060b57cec5SDimitry Andric   // For each function there is a separate subsection which holds the PC to
11070b57cec5SDimitry Andric   // file:line table.
11080b57cec5SDimitry Andric   const MCSymbol *Fn = Asm->getSymbol(GV);
11090b57cec5SDimitry Andric   assert(Fn);
11100b57cec5SDimitry Andric 
11110b57cec5SDimitry Andric   // Switch to the to a comdat section, if appropriate.
11120b57cec5SDimitry Andric   switchToDebugSectionForSymbol(Fn);
11130b57cec5SDimitry Andric 
11140b57cec5SDimitry Andric   std::string FuncName;
11150b57cec5SDimitry Andric   auto *SP = GV->getSubprogram();
11160b57cec5SDimitry Andric   assert(SP);
11170b57cec5SDimitry Andric   setCurrentSubprogram(SP);
11180b57cec5SDimitry Andric 
11190b57cec5SDimitry Andric   if (SP->isThunk()) {
11200b57cec5SDimitry Andric     emitDebugInfoForThunk(GV, FI, Fn);
11210b57cec5SDimitry Andric     return;
11220b57cec5SDimitry Andric   }
11230b57cec5SDimitry Andric 
11240b57cec5SDimitry Andric   // If we have a display name, build the fully qualified name by walking the
11250b57cec5SDimitry Andric   // chain of scopes.
11260b57cec5SDimitry Andric   if (!SP->getName().empty())
11270b57cec5SDimitry Andric     FuncName = getFullyQualifiedName(SP->getScope(), SP->getName());
11280b57cec5SDimitry Andric 
11290b57cec5SDimitry Andric   // If our DISubprogram name is empty, use the mangled name.
11300b57cec5SDimitry Andric   if (FuncName.empty())
11315ffd83dbSDimitry Andric     FuncName = std::string(GlobalValue::dropLLVMManglingEscape(GV->getName()));
11320b57cec5SDimitry Andric 
11330b57cec5SDimitry Andric   // Emit FPO data, but only on 32-bit x86. No other platforms use it.
11340b57cec5SDimitry Andric   if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
113581ad6265SDimitry Andric     OS.emitCVFPOData(Fn);
11360b57cec5SDimitry Andric 
11370b57cec5SDimitry Andric   // Emit a symbol subsection, required by VS2012+ to find function boundaries.
11380b57cec5SDimitry Andric   OS.AddComment("Symbol subsection for " + Twine(FuncName));
11390b57cec5SDimitry Andric   MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
11400b57cec5SDimitry Andric   {
11410b57cec5SDimitry Andric     SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID
11420b57cec5SDimitry Andric                                                 : SymbolKind::S_GPROC32_ID;
11430b57cec5SDimitry Andric     MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind);
11440b57cec5SDimitry Andric 
11450b57cec5SDimitry Andric     // These fields are filled in by tools like CVPACK which run after the fact.
11460b57cec5SDimitry Andric     OS.AddComment("PtrParent");
11475ffd83dbSDimitry Andric     OS.emitInt32(0);
11480b57cec5SDimitry Andric     OS.AddComment("PtrEnd");
11495ffd83dbSDimitry Andric     OS.emitInt32(0);
11500b57cec5SDimitry Andric     OS.AddComment("PtrNext");
11515ffd83dbSDimitry Andric     OS.emitInt32(0);
11520b57cec5SDimitry Andric     // This is the important bit that tells the debugger where the function
11530b57cec5SDimitry Andric     // code is located and what's its size:
11540b57cec5SDimitry Andric     OS.AddComment("Code size");
11550b57cec5SDimitry Andric     OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
11560b57cec5SDimitry Andric     OS.AddComment("Offset after prologue");
11575ffd83dbSDimitry Andric     OS.emitInt32(0);
11580b57cec5SDimitry Andric     OS.AddComment("Offset before epilogue");
11595ffd83dbSDimitry Andric     OS.emitInt32(0);
11600b57cec5SDimitry Andric     OS.AddComment("Function type index");
11615ffd83dbSDimitry Andric     OS.emitInt32(getFuncIdForSubprogram(GV->getSubprogram()).getIndex());
11620b57cec5SDimitry Andric     OS.AddComment("Function section relative address");
116381ad6265SDimitry Andric     OS.emitCOFFSecRel32(Fn, /*Offset=*/0);
11640b57cec5SDimitry Andric     OS.AddComment("Function section index");
116581ad6265SDimitry Andric     OS.emitCOFFSectionIndex(Fn);
11660b57cec5SDimitry Andric     OS.AddComment("Flags");
116706c3fb27SDimitry Andric     ProcSymFlags ProcFlags = ProcSymFlags::HasOptimizedDebugInfo;
116806c3fb27SDimitry Andric     if (FI.HasFramePointer)
116906c3fb27SDimitry Andric       ProcFlags |= ProcSymFlags::HasFP;
117006c3fb27SDimitry Andric     if (GV->hasFnAttribute(Attribute::NoReturn))
117106c3fb27SDimitry Andric       ProcFlags |= ProcSymFlags::IsNoReturn;
117206c3fb27SDimitry Andric     if (GV->hasFnAttribute(Attribute::NoInline))
117306c3fb27SDimitry Andric       ProcFlags |= ProcSymFlags::IsNoInline;
117406c3fb27SDimitry Andric     OS.emitInt8(static_cast<uint8_t>(ProcFlags));
11750b57cec5SDimitry Andric     // Emit the function display name as a null-terminated string.
11760b57cec5SDimitry Andric     OS.AddComment("Function name");
11770b57cec5SDimitry Andric     // Truncate the name so we won't overflow the record length field.
11780b57cec5SDimitry Andric     emitNullTerminatedSymbolName(OS, FuncName);
11790b57cec5SDimitry Andric     endSymbolRecord(ProcRecordEnd);
11800b57cec5SDimitry Andric 
11810b57cec5SDimitry Andric     MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC);
11820b57cec5SDimitry Andric     // Subtract out the CSR size since MSVC excludes that and we include it.
11830b57cec5SDimitry Andric     OS.AddComment("FrameSize");
11845ffd83dbSDimitry Andric     OS.emitInt32(FI.FrameSize - FI.CSRSize);
11850b57cec5SDimitry Andric     OS.AddComment("Padding");
11865ffd83dbSDimitry Andric     OS.emitInt32(0);
11870b57cec5SDimitry Andric     OS.AddComment("Offset of padding");
11885ffd83dbSDimitry Andric     OS.emitInt32(0);
11890b57cec5SDimitry Andric     OS.AddComment("Bytes of callee saved registers");
11905ffd83dbSDimitry Andric     OS.emitInt32(FI.CSRSize);
11910b57cec5SDimitry Andric     OS.AddComment("Exception handler offset");
11925ffd83dbSDimitry Andric     OS.emitInt32(0);
11930b57cec5SDimitry Andric     OS.AddComment("Exception handler section");
11945ffd83dbSDimitry Andric     OS.emitInt16(0);
11950b57cec5SDimitry Andric     OS.AddComment("Flags (defines frame register)");
11965ffd83dbSDimitry Andric     OS.emitInt32(uint32_t(FI.FrameProcOpts));
11970b57cec5SDimitry Andric     endSymbolRecord(FrameProcEnd);
11980b57cec5SDimitry Andric 
11995f757f3fSDimitry Andric     emitInlinees(FI.Inlinees);
12000b57cec5SDimitry Andric     emitLocalVariableList(FI, FI.Locals);
12010b57cec5SDimitry Andric     emitGlobalVariableList(FI.Globals);
12020b57cec5SDimitry Andric     emitLexicalBlockList(FI.ChildBlocks, FI);
12030b57cec5SDimitry Andric 
12040b57cec5SDimitry Andric     // Emit inlined call site information. Only emit functions inlined directly
12050b57cec5SDimitry Andric     // into the parent function. We'll emit the other sites recursively as part
12060b57cec5SDimitry Andric     // of their parent inline site.
12070b57cec5SDimitry Andric     for (const DILocation *InlinedAt : FI.ChildSites) {
12080b57cec5SDimitry Andric       auto I = FI.InlineSites.find(InlinedAt);
12090b57cec5SDimitry Andric       assert(I != FI.InlineSites.end() &&
12100b57cec5SDimitry Andric              "child site not in function inline site map");
12110b57cec5SDimitry Andric       emitInlinedCallSite(FI, InlinedAt, I->second);
12120b57cec5SDimitry Andric     }
12130b57cec5SDimitry Andric 
12140b57cec5SDimitry Andric     for (auto Annot : FI.Annotations) {
12150b57cec5SDimitry Andric       MCSymbol *Label = Annot.first;
12160b57cec5SDimitry Andric       MDTuple *Strs = cast<MDTuple>(Annot.second);
12170b57cec5SDimitry Andric       MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION);
121881ad6265SDimitry Andric       OS.emitCOFFSecRel32(Label, /*Offset=*/0);
12190b57cec5SDimitry Andric       // FIXME: Make sure we don't overflow the max record size.
122081ad6265SDimitry Andric       OS.emitCOFFSectionIndex(Label);
12215ffd83dbSDimitry Andric       OS.emitInt16(Strs->getNumOperands());
12220b57cec5SDimitry Andric       for (Metadata *MD : Strs->operands()) {
12230b57cec5SDimitry Andric         // MDStrings are null terminated, so we can do EmitBytes and get the
12240b57cec5SDimitry Andric         // nice .asciz directive.
12250b57cec5SDimitry Andric         StringRef Str = cast<MDString>(MD)->getString();
12260b57cec5SDimitry Andric         assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
12275ffd83dbSDimitry Andric         OS.emitBytes(StringRef(Str.data(), Str.size() + 1));
12280b57cec5SDimitry Andric       }
12290b57cec5SDimitry Andric       endSymbolRecord(AnnotEnd);
12300b57cec5SDimitry Andric     }
12310b57cec5SDimitry Andric 
12320b57cec5SDimitry Andric     for (auto HeapAllocSite : FI.HeapAllocSites) {
1233480093f4SDimitry Andric       const MCSymbol *BeginLabel = std::get<0>(HeapAllocSite);
1234480093f4SDimitry Andric       const MCSymbol *EndLabel = std::get<1>(HeapAllocSite);
1235c14a5a88SDimitry Andric       const DIType *DITy = std::get<2>(HeapAllocSite);
12360b57cec5SDimitry Andric       MCSymbol *HeapAllocEnd = beginSymbolRecord(SymbolKind::S_HEAPALLOCSITE);
12370b57cec5SDimitry Andric       OS.AddComment("Call site offset");
123881ad6265SDimitry Andric       OS.emitCOFFSecRel32(BeginLabel, /*Offset=*/0);
12390b57cec5SDimitry Andric       OS.AddComment("Call site section index");
124081ad6265SDimitry Andric       OS.emitCOFFSectionIndex(BeginLabel);
12410b57cec5SDimitry Andric       OS.AddComment("Call instruction length");
12420b57cec5SDimitry Andric       OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
12430b57cec5SDimitry Andric       OS.AddComment("Type index");
12445ffd83dbSDimitry Andric       OS.emitInt32(getCompleteTypeIndex(DITy).getIndex());
12450b57cec5SDimitry Andric       endSymbolRecord(HeapAllocEnd);
12460b57cec5SDimitry Andric     }
12470b57cec5SDimitry Andric 
12480b57cec5SDimitry Andric     if (SP != nullptr)
12490b57cec5SDimitry Andric       emitDebugInfoForUDTs(LocalUDTs);
12500b57cec5SDimitry Andric 
12515f757f3fSDimitry Andric     emitDebugInfoForJumpTables(FI);
12525f757f3fSDimitry Andric 
12530b57cec5SDimitry Andric     // We're done with this function.
12540b57cec5SDimitry Andric     emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
12550b57cec5SDimitry Andric   }
12560b57cec5SDimitry Andric   endCVSubsection(SymbolsEnd);
12570b57cec5SDimitry Andric 
12580b57cec5SDimitry Andric   // We have an assembler directive that takes care of the whole line table.
12595ffd83dbSDimitry Andric   OS.emitCVLinetableDirective(FI.FuncId, Fn, FI.End);
12600b57cec5SDimitry Andric }
12610b57cec5SDimitry Andric 
126281ad6265SDimitry Andric CodeViewDebug::LocalVarDef
createDefRangeMem(uint16_t CVRegister,int Offset)12630b57cec5SDimitry Andric CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
126481ad6265SDimitry Andric   LocalVarDef DR;
12650b57cec5SDimitry Andric   DR.InMemory = -1;
12660b57cec5SDimitry Andric   DR.DataOffset = Offset;
12670b57cec5SDimitry Andric   assert(DR.DataOffset == Offset && "truncation");
12680b57cec5SDimitry Andric   DR.IsSubfield = 0;
12690b57cec5SDimitry Andric   DR.StructOffset = 0;
12700b57cec5SDimitry Andric   DR.CVRegister = CVRegister;
12710b57cec5SDimitry Andric   return DR;
12720b57cec5SDimitry Andric }
12730b57cec5SDimitry Andric 
collectVariableInfoFromMFTable(DenseSet<InlinedEntity> & Processed)12740b57cec5SDimitry Andric void CodeViewDebug::collectVariableInfoFromMFTable(
12750b57cec5SDimitry Andric     DenseSet<InlinedEntity> &Processed) {
12760b57cec5SDimitry Andric   const MachineFunction &MF = *Asm->MF;
12770b57cec5SDimitry Andric   const TargetSubtargetInfo &TSI = MF.getSubtarget();
12780b57cec5SDimitry Andric   const TargetFrameLowering *TFI = TSI.getFrameLowering();
12790b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
12800b57cec5SDimitry Andric 
128106c3fb27SDimitry Andric   for (const MachineFunction::VariableDbgInfo &VI :
128206c3fb27SDimitry Andric        MF.getInStackSlotVariableDbgInfo()) {
12830b57cec5SDimitry Andric     if (!VI.Var)
12840b57cec5SDimitry Andric       continue;
12850b57cec5SDimitry Andric     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
12860b57cec5SDimitry Andric            "Expected inlined-at fields to agree");
12870b57cec5SDimitry Andric 
12880b57cec5SDimitry Andric     Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
12890b57cec5SDimitry Andric     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
12900b57cec5SDimitry Andric 
12910b57cec5SDimitry Andric     // If variable scope is not found then skip this variable.
12920b57cec5SDimitry Andric     if (!Scope)
12930b57cec5SDimitry Andric       continue;
12940b57cec5SDimitry Andric 
12950b57cec5SDimitry Andric     // If the variable has an attached offset expression, extract it.
12960b57cec5SDimitry Andric     // FIXME: Try to handle DW_OP_deref as well.
12970b57cec5SDimitry Andric     int64_t ExprOffset = 0;
12980b57cec5SDimitry Andric     bool Deref = false;
12990b57cec5SDimitry Andric     if (VI.Expr) {
13000b57cec5SDimitry Andric       // If there is one DW_OP_deref element, use offset of 0 and keep going.
13010b57cec5SDimitry Andric       if (VI.Expr->getNumElements() == 1 &&
13020b57cec5SDimitry Andric           VI.Expr->getElement(0) == llvm::dwarf::DW_OP_deref)
13030b57cec5SDimitry Andric         Deref = true;
13040b57cec5SDimitry Andric       else if (!VI.Expr->extractIfOffset(ExprOffset))
13050b57cec5SDimitry Andric         continue;
13060b57cec5SDimitry Andric     }
13070b57cec5SDimitry Andric 
13080b57cec5SDimitry Andric     // Get the frame register used and the offset.
13095ffd83dbSDimitry Andric     Register FrameReg;
131006c3fb27SDimitry Andric     StackOffset FrameOffset =
131106c3fb27SDimitry Andric         TFI->getFrameIndexReference(*Asm->MF, VI.getStackSlot(), FrameReg);
13120b57cec5SDimitry Andric     uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
13130b57cec5SDimitry Andric 
1314e8d8bef9SDimitry Andric     assert(!FrameOffset.getScalable() &&
1315e8d8bef9SDimitry Andric            "Frame offsets with a scalable component are not supported");
1316e8d8bef9SDimitry Andric 
13170b57cec5SDimitry Andric     // Calculate the label ranges.
131881ad6265SDimitry Andric     LocalVarDef DefRange =
1319e8d8bef9SDimitry Andric         createDefRangeMem(CVReg, FrameOffset.getFixed() + ExprOffset);
13200b57cec5SDimitry Andric 
132181ad6265SDimitry Andric     LocalVariable Var;
132281ad6265SDimitry Andric     Var.DIVar = VI.Var;
132381ad6265SDimitry Andric 
13240b57cec5SDimitry Andric     for (const InsnRange &Range : Scope->getRanges()) {
13250b57cec5SDimitry Andric       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
13260b57cec5SDimitry Andric       const MCSymbol *End = getLabelAfterInsn(Range.second);
13270b57cec5SDimitry Andric       End = End ? End : Asm->getFunctionEnd();
132881ad6265SDimitry Andric       Var.DefRanges[DefRange].emplace_back(Begin, End);
13290b57cec5SDimitry Andric     }
13300b57cec5SDimitry Andric 
13310b57cec5SDimitry Andric     if (Deref)
13320b57cec5SDimitry Andric       Var.UseReferenceType = true;
13330b57cec5SDimitry Andric 
13340b57cec5SDimitry Andric     recordLocalVariable(std::move(Var), Scope);
13350b57cec5SDimitry Andric   }
13360b57cec5SDimitry Andric }
13370b57cec5SDimitry Andric 
canUseReferenceType(const DbgVariableLocation & Loc)13380b57cec5SDimitry Andric static bool canUseReferenceType(const DbgVariableLocation &Loc) {
13390b57cec5SDimitry Andric   return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
13400b57cec5SDimitry Andric }
13410b57cec5SDimitry Andric 
needsReferenceType(const DbgVariableLocation & Loc)13420b57cec5SDimitry Andric static bool needsReferenceType(const DbgVariableLocation &Loc) {
13430b57cec5SDimitry Andric   return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
13440b57cec5SDimitry Andric }
13450b57cec5SDimitry Andric 
calculateRanges(LocalVariable & Var,const DbgValueHistoryMap::Entries & Entries)13460b57cec5SDimitry Andric void CodeViewDebug::calculateRanges(
13470b57cec5SDimitry Andric     LocalVariable &Var, const DbgValueHistoryMap::Entries &Entries) {
13480b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
13490b57cec5SDimitry Andric 
13500b57cec5SDimitry Andric   // Calculate the definition ranges.
13510b57cec5SDimitry Andric   for (auto I = Entries.begin(), E = Entries.end(); I != E; ++I) {
13520b57cec5SDimitry Andric     const auto &Entry = *I;
13530b57cec5SDimitry Andric     if (!Entry.isDbgValue())
13540b57cec5SDimitry Andric       continue;
13550b57cec5SDimitry Andric     const MachineInstr *DVInst = Entry.getInstr();
13560b57cec5SDimitry Andric     assert(DVInst->isDebugValue() && "Invalid History entry");
13570b57cec5SDimitry Andric     // FIXME: Find a way to represent constant variables, since they are
13580b57cec5SDimitry Andric     // relatively common.
1359bdd1243dSDimitry Andric     std::optional<DbgVariableLocation> Location =
13600b57cec5SDimitry Andric         DbgVariableLocation::extractFromMachineInstruction(*DVInst);
13610b57cec5SDimitry Andric     if (!Location)
1362bdd1243dSDimitry Andric     {
1363bdd1243dSDimitry Andric       // When we don't have a location this is usually because LLVM has
1364bdd1243dSDimitry Andric       // transformed it into a constant and we only have an llvm.dbg.value. We
1365bdd1243dSDimitry Andric       // can't represent these well in CodeView since S_LOCAL only works on
1366bdd1243dSDimitry Andric       // registers and memory locations. Instead, we will pretend this to be a
1367bdd1243dSDimitry Andric       // constant value to at least have it show up in the debugger.
1368bdd1243dSDimitry Andric       auto Op = DVInst->getDebugOperand(0);
1369bdd1243dSDimitry Andric       if (Op.isImm())
1370bdd1243dSDimitry Andric         Var.ConstantValue = APSInt(APInt(64, Op.getImm()), false);
13710b57cec5SDimitry Andric       continue;
1372bdd1243dSDimitry Andric     }
13730b57cec5SDimitry Andric 
13740b57cec5SDimitry Andric     // CodeView can only express variables in register and variables in memory
13750b57cec5SDimitry Andric     // at a constant offset from a register. However, for variables passed
13760b57cec5SDimitry Andric     // indirectly by pointer, it is common for that pointer to be spilled to a
13770b57cec5SDimitry Andric     // stack location. For the special case of one offseted load followed by a
13780b57cec5SDimitry Andric     // zero offset load (a pointer spilled to the stack), we change the type of
13790b57cec5SDimitry Andric     // the local variable from a value type to a reference type. This tricks the
13800b57cec5SDimitry Andric     // debugger into doing the load for us.
13810b57cec5SDimitry Andric     if (Var.UseReferenceType) {
13820b57cec5SDimitry Andric       // We're using a reference type. Drop the last zero offset load.
13830b57cec5SDimitry Andric       if (canUseReferenceType(*Location))
13840b57cec5SDimitry Andric         Location->LoadChain.pop_back();
13850b57cec5SDimitry Andric       else
13860b57cec5SDimitry Andric         continue;
13870b57cec5SDimitry Andric     } else if (needsReferenceType(*Location)) {
13880b57cec5SDimitry Andric       // This location can't be expressed without switching to a reference type.
13890b57cec5SDimitry Andric       // Start over using that.
13900b57cec5SDimitry Andric       Var.UseReferenceType = true;
13910b57cec5SDimitry Andric       Var.DefRanges.clear();
13920b57cec5SDimitry Andric       calculateRanges(Var, Entries);
13930b57cec5SDimitry Andric       return;
13940b57cec5SDimitry Andric     }
13950b57cec5SDimitry Andric 
13960b57cec5SDimitry Andric     // We can only handle a register or an offseted load of a register.
13970b57cec5SDimitry Andric     if (Location->Register == 0 || Location->LoadChain.size() > 1)
13980b57cec5SDimitry Andric       continue;
139981ad6265SDimitry Andric 
14005f757f3fSDimitry Andric     // Codeview can only express byte-aligned offsets, ensure that we have a
14015f757f3fSDimitry Andric     // byte-boundaried location.
14025f757f3fSDimitry Andric     if (Location->FragmentInfo)
14035f757f3fSDimitry Andric       if (Location->FragmentInfo->OffsetInBits % 8)
14045f757f3fSDimitry Andric         continue;
14055f757f3fSDimitry Andric 
140681ad6265SDimitry Andric     LocalVarDef DR;
14070b57cec5SDimitry Andric     DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
14080b57cec5SDimitry Andric     DR.InMemory = !Location->LoadChain.empty();
14090b57cec5SDimitry Andric     DR.DataOffset =
14100b57cec5SDimitry Andric         !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
14110b57cec5SDimitry Andric     if (Location->FragmentInfo) {
14120b57cec5SDimitry Andric       DR.IsSubfield = true;
14130b57cec5SDimitry Andric       DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
14140b57cec5SDimitry Andric     } else {
14150b57cec5SDimitry Andric       DR.IsSubfield = false;
14160b57cec5SDimitry Andric       DR.StructOffset = 0;
14170b57cec5SDimitry Andric     }
14180b57cec5SDimitry Andric 
14190b57cec5SDimitry Andric     // Compute the label range.
14200b57cec5SDimitry Andric     const MCSymbol *Begin = getLabelBeforeInsn(Entry.getInstr());
14210b57cec5SDimitry Andric     const MCSymbol *End;
14220b57cec5SDimitry Andric     if (Entry.getEndIndex() != DbgValueHistoryMap::NoEntry) {
14230b57cec5SDimitry Andric       auto &EndingEntry = Entries[Entry.getEndIndex()];
14240b57cec5SDimitry Andric       End = EndingEntry.isDbgValue()
14250b57cec5SDimitry Andric                 ? getLabelBeforeInsn(EndingEntry.getInstr())
14260b57cec5SDimitry Andric                 : getLabelAfterInsn(EndingEntry.getInstr());
14270b57cec5SDimitry Andric     } else
14280b57cec5SDimitry Andric       End = Asm->getFunctionEnd();
14290b57cec5SDimitry Andric 
14300b57cec5SDimitry Andric     // If the last range end is our begin, just extend the last range.
14310b57cec5SDimitry Andric     // Otherwise make a new range.
14320b57cec5SDimitry Andric     SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
143381ad6265SDimitry Andric         Var.DefRanges[DR];
14340b57cec5SDimitry Andric     if (!R.empty() && R.back().second == Begin)
14350b57cec5SDimitry Andric       R.back().second = End;
14360b57cec5SDimitry Andric     else
14370b57cec5SDimitry Andric       R.emplace_back(Begin, End);
14380b57cec5SDimitry Andric 
14390b57cec5SDimitry Andric     // FIXME: Do more range combining.
14400b57cec5SDimitry Andric   }
14410b57cec5SDimitry Andric }
14420b57cec5SDimitry Andric 
collectVariableInfo(const DISubprogram * SP)14430b57cec5SDimitry Andric void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
14440b57cec5SDimitry Andric   DenseSet<InlinedEntity> Processed;
14450b57cec5SDimitry Andric   // Grab the variable info that was squirreled away in the MMI side-table.
14460b57cec5SDimitry Andric   collectVariableInfoFromMFTable(Processed);
14470b57cec5SDimitry Andric 
14480b57cec5SDimitry Andric   for (const auto &I : DbgValues) {
14490b57cec5SDimitry Andric     InlinedEntity IV = I.first;
14500b57cec5SDimitry Andric     if (Processed.count(IV))
14510b57cec5SDimitry Andric       continue;
14520b57cec5SDimitry Andric     const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
14530b57cec5SDimitry Andric     const DILocation *InlinedAt = IV.second;
14540b57cec5SDimitry Andric 
14550b57cec5SDimitry Andric     // Instruction ranges, specifying where IV is accessible.
14560b57cec5SDimitry Andric     const auto &Entries = I.second;
14570b57cec5SDimitry Andric 
14580b57cec5SDimitry Andric     LexicalScope *Scope = nullptr;
14590b57cec5SDimitry Andric     if (InlinedAt)
14600b57cec5SDimitry Andric       Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
14610b57cec5SDimitry Andric     else
14620b57cec5SDimitry Andric       Scope = LScopes.findLexicalScope(DIVar->getScope());
14630b57cec5SDimitry Andric     // If variable scope is not found then skip this variable.
14640b57cec5SDimitry Andric     if (!Scope)
14650b57cec5SDimitry Andric       continue;
14660b57cec5SDimitry Andric 
14670b57cec5SDimitry Andric     LocalVariable Var;
14680b57cec5SDimitry Andric     Var.DIVar = DIVar;
14690b57cec5SDimitry Andric 
14700b57cec5SDimitry Andric     calculateRanges(Var, Entries);
14710b57cec5SDimitry Andric     recordLocalVariable(std::move(Var), Scope);
14720b57cec5SDimitry Andric   }
14730b57cec5SDimitry Andric }
14740b57cec5SDimitry Andric 
beginFunctionImpl(const MachineFunction * MF)14750b57cec5SDimitry Andric void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
14760b57cec5SDimitry Andric   const TargetSubtargetInfo &TSI = MF->getSubtarget();
14770b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
14780b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF->getFrameInfo();
14790b57cec5SDimitry Andric   const Function &GV = MF->getFunction();
14808bcb0991SDimitry Andric   auto Insertion = FnDebugInfo.insert({&GV, std::make_unique<FunctionInfo>()});
14810b57cec5SDimitry Andric   assert(Insertion.second && "function already has info");
14820b57cec5SDimitry Andric   CurFn = Insertion.first->second.get();
14830b57cec5SDimitry Andric   CurFn->FuncId = NextFuncId++;
14840b57cec5SDimitry Andric   CurFn->Begin = Asm->getFunctionBegin();
14850b57cec5SDimitry Andric 
14860b57cec5SDimitry Andric   // The S_FRAMEPROC record reports the stack size, and how many bytes of
14870b57cec5SDimitry Andric   // callee-saved registers were used. For targets that don't use a PUSH
14880b57cec5SDimitry Andric   // instruction (AArch64), this will be zero.
14890b57cec5SDimitry Andric   CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
14900b57cec5SDimitry Andric   CurFn->FrameSize = MFI.getStackSize();
14910b57cec5SDimitry Andric   CurFn->OffsetAdjustment = MFI.getOffsetAdjustment();
1492fe6060f1SDimitry Andric   CurFn->HasStackRealignment = TRI->hasStackRealignment(*MF);
14930b57cec5SDimitry Andric 
14940b57cec5SDimitry Andric   // For this function S_FRAMEPROC record, figure out which codeview register
14950b57cec5SDimitry Andric   // will be the frame pointer.
14960b57cec5SDimitry Andric   CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
14970b57cec5SDimitry Andric   CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
14980b57cec5SDimitry Andric   if (CurFn->FrameSize > 0) {
14990b57cec5SDimitry Andric     if (!TSI.getFrameLowering()->hasFP(*MF)) {
15000b57cec5SDimitry Andric       CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
15010b57cec5SDimitry Andric       CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
15020b57cec5SDimitry Andric     } else {
150306c3fb27SDimitry Andric       CurFn->HasFramePointer = true;
15040b57cec5SDimitry Andric       // If there is an FP, parameters are always relative to it.
15050b57cec5SDimitry Andric       CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
15060b57cec5SDimitry Andric       if (CurFn->HasStackRealignment) {
15070b57cec5SDimitry Andric         // If the stack needs realignment, locals are relative to SP or VFRAME.
15080b57cec5SDimitry Andric         CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
15090b57cec5SDimitry Andric       } else {
15100b57cec5SDimitry Andric         // Otherwise, locals are relative to EBP, and we probably have VLAs or
15110b57cec5SDimitry Andric         // other stack adjustments.
15120b57cec5SDimitry Andric         CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
15130b57cec5SDimitry Andric       }
15140b57cec5SDimitry Andric     }
15150b57cec5SDimitry Andric   }
15160b57cec5SDimitry Andric 
15170b57cec5SDimitry Andric   // Compute other frame procedure options.
15180b57cec5SDimitry Andric   FrameProcedureOptions FPO = FrameProcedureOptions::None;
15190b57cec5SDimitry Andric   if (MFI.hasVarSizedObjects())
15200b57cec5SDimitry Andric     FPO |= FrameProcedureOptions::HasAlloca;
15210b57cec5SDimitry Andric   if (MF->exposesReturnsTwice())
15220b57cec5SDimitry Andric     FPO |= FrameProcedureOptions::HasSetJmp;
15230b57cec5SDimitry Andric   // FIXME: Set HasLongJmp if we ever track that info.
15240b57cec5SDimitry Andric   if (MF->hasInlineAsm())
15250b57cec5SDimitry Andric     FPO |= FrameProcedureOptions::HasInlineAssembly;
15260b57cec5SDimitry Andric   if (GV.hasPersonalityFn()) {
15270b57cec5SDimitry Andric     if (isAsynchronousEHPersonality(
15280b57cec5SDimitry Andric             classifyEHPersonality(GV.getPersonalityFn())))
15290b57cec5SDimitry Andric       FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
15300b57cec5SDimitry Andric     else
15310b57cec5SDimitry Andric       FPO |= FrameProcedureOptions::HasExceptionHandling;
15320b57cec5SDimitry Andric   }
15330b57cec5SDimitry Andric   if (GV.hasFnAttribute(Attribute::InlineHint))
15340b57cec5SDimitry Andric     FPO |= FrameProcedureOptions::MarkedInline;
15350b57cec5SDimitry Andric   if (GV.hasFnAttribute(Attribute::Naked))
15360b57cec5SDimitry Andric     FPO |= FrameProcedureOptions::Naked;
1537bdd1243dSDimitry Andric   if (MFI.hasStackProtectorIndex()) {
15380b57cec5SDimitry Andric     FPO |= FrameProcedureOptions::SecurityChecks;
1539bdd1243dSDimitry Andric     if (GV.hasFnAttribute(Attribute::StackProtectStrong) ||
1540bdd1243dSDimitry Andric         GV.hasFnAttribute(Attribute::StackProtectReq)) {
1541bdd1243dSDimitry Andric       FPO |= FrameProcedureOptions::StrictSecurityChecks;
1542bdd1243dSDimitry Andric     }
1543bdd1243dSDimitry Andric   } else if (!GV.hasStackProtectorFnAttr()) {
1544bdd1243dSDimitry Andric     // __declspec(safebuffers) disables stack guards.
1545bdd1243dSDimitry Andric     FPO |= FrameProcedureOptions::SafeBuffers;
1546bdd1243dSDimitry Andric   }
15470b57cec5SDimitry Andric   FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
15480b57cec5SDimitry Andric   FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
15495f757f3fSDimitry Andric   if (Asm->TM.getOptLevel() != CodeGenOptLevel::None && !GV.hasOptSize() &&
15505f757f3fSDimitry Andric       !GV.hasOptNone())
15510b57cec5SDimitry Andric     FPO |= FrameProcedureOptions::OptimizedForSpeed;
1552fe6060f1SDimitry Andric   if (GV.hasProfileData()) {
1553fe6060f1SDimitry Andric     FPO |= FrameProcedureOptions::ValidProfileCounts;
1554fe6060f1SDimitry Andric     FPO |= FrameProcedureOptions::ProfileGuidedOptimization;
1555fe6060f1SDimitry Andric   }
15560b57cec5SDimitry Andric   // FIXME: Set GuardCfg when it is implemented.
15570b57cec5SDimitry Andric   CurFn->FrameProcOpts = FPO;
15580b57cec5SDimitry Andric 
155981ad6265SDimitry Andric   OS.emitCVFuncIdDirective(CurFn->FuncId);
15600b57cec5SDimitry Andric 
15610b57cec5SDimitry Andric   // Find the end of the function prolog.  First known non-DBG_VALUE and
15620b57cec5SDimitry Andric   // non-frame setup location marks the beginning of the function body.
15630b57cec5SDimitry Andric   // FIXME: is there a simpler a way to do this? Can we just search
15640b57cec5SDimitry Andric   // for the first instruction of the function, not the last of the prolog?
15650b57cec5SDimitry Andric   DebugLoc PrologEndLoc;
15660b57cec5SDimitry Andric   bool EmptyPrologue = true;
15670b57cec5SDimitry Andric   for (const auto &MBB : *MF) {
15680b57cec5SDimitry Andric     for (const auto &MI : MBB) {
15690b57cec5SDimitry Andric       if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
15700b57cec5SDimitry Andric           MI.getDebugLoc()) {
15710b57cec5SDimitry Andric         PrologEndLoc = MI.getDebugLoc();
15720b57cec5SDimitry Andric         break;
15730b57cec5SDimitry Andric       } else if (!MI.isMetaInstruction()) {
15740b57cec5SDimitry Andric         EmptyPrologue = false;
15750b57cec5SDimitry Andric       }
15760b57cec5SDimitry Andric     }
15770b57cec5SDimitry Andric   }
15780b57cec5SDimitry Andric 
15790b57cec5SDimitry Andric   // Record beginning of function if we have a non-empty prologue.
15800b57cec5SDimitry Andric   if (PrologEndLoc && !EmptyPrologue) {
15810b57cec5SDimitry Andric     DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
15820b57cec5SDimitry Andric     maybeRecordLocation(FnStartDL, MF);
15830b57cec5SDimitry Andric   }
1584480093f4SDimitry Andric 
1585480093f4SDimitry Andric   // Find heap alloc sites and emit labels around them.
1586480093f4SDimitry Andric   for (const auto &MBB : *MF) {
1587480093f4SDimitry Andric     for (const auto &MI : MBB) {
1588480093f4SDimitry Andric       if (MI.getHeapAllocMarker()) {
1589480093f4SDimitry Andric         requestLabelBeforeInsn(&MI);
1590480093f4SDimitry Andric         requestLabelAfterInsn(&MI);
1591480093f4SDimitry Andric       }
1592480093f4SDimitry Andric     }
1593480093f4SDimitry Andric   }
15945f757f3fSDimitry Andric 
15955f757f3fSDimitry Andric   // Mark branches that may potentially be using jump tables with labels.
15965f757f3fSDimitry Andric   bool isThumb = Triple(MMI->getModule()->getTargetTriple()).getArch() ==
15975f757f3fSDimitry Andric                  llvm::Triple::ArchType::thumb;
15985f757f3fSDimitry Andric   discoverJumpTableBranches(MF, isThumb);
15990b57cec5SDimitry Andric }
16000b57cec5SDimitry Andric 
shouldEmitUdt(const DIType * T)16010b57cec5SDimitry Andric static bool shouldEmitUdt(const DIType *T) {
16020b57cec5SDimitry Andric   if (!T)
16030b57cec5SDimitry Andric     return false;
16040b57cec5SDimitry Andric 
16050b57cec5SDimitry Andric   // MSVC does not emit UDTs for typedefs that are scoped to classes.
16060b57cec5SDimitry Andric   if (T->getTag() == dwarf::DW_TAG_typedef) {
16070b57cec5SDimitry Andric     if (DIScope *Scope = T->getScope()) {
16080b57cec5SDimitry Andric       switch (Scope->getTag()) {
16090b57cec5SDimitry Andric       case dwarf::DW_TAG_structure_type:
16100b57cec5SDimitry Andric       case dwarf::DW_TAG_class_type:
16110b57cec5SDimitry Andric       case dwarf::DW_TAG_union_type:
16120b57cec5SDimitry Andric         return false;
1613fe6060f1SDimitry Andric       default:
1614fe6060f1SDimitry Andric           // do nothing.
1615fe6060f1SDimitry Andric           ;
16160b57cec5SDimitry Andric       }
16170b57cec5SDimitry Andric     }
16180b57cec5SDimitry Andric   }
16190b57cec5SDimitry Andric 
16200b57cec5SDimitry Andric   while (true) {
16210b57cec5SDimitry Andric     if (!T || T->isForwardDecl())
16220b57cec5SDimitry Andric       return false;
16230b57cec5SDimitry Andric 
16240b57cec5SDimitry Andric     const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
16250b57cec5SDimitry Andric     if (!DT)
16260b57cec5SDimitry Andric       return true;
16270b57cec5SDimitry Andric     T = DT->getBaseType();
16280b57cec5SDimitry Andric   }
16290b57cec5SDimitry Andric   return true;
16300b57cec5SDimitry Andric }
16310b57cec5SDimitry Andric 
addToUDTs(const DIType * Ty)16320b57cec5SDimitry Andric void CodeViewDebug::addToUDTs(const DIType *Ty) {
16330b57cec5SDimitry Andric   // Don't record empty UDTs.
16340b57cec5SDimitry Andric   if (Ty->getName().empty())
16350b57cec5SDimitry Andric     return;
16360b57cec5SDimitry Andric   if (!shouldEmitUdt(Ty))
16370b57cec5SDimitry Andric     return;
16380b57cec5SDimitry Andric 
16395ffd83dbSDimitry Andric   SmallVector<StringRef, 5> ParentScopeNames;
16400b57cec5SDimitry Andric   const DISubprogram *ClosestSubprogram =
16415ffd83dbSDimitry Andric       collectParentScopeNames(Ty->getScope(), ParentScopeNames);
16420b57cec5SDimitry Andric 
16430b57cec5SDimitry Andric   std::string FullyQualifiedName =
16445ffd83dbSDimitry Andric       formatNestedName(ParentScopeNames, getPrettyScopeName(Ty));
16450b57cec5SDimitry Andric 
16460b57cec5SDimitry Andric   if (ClosestSubprogram == nullptr) {
16470b57cec5SDimitry Andric     GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
16480b57cec5SDimitry Andric   } else if (ClosestSubprogram == CurrentSubprogram) {
16490b57cec5SDimitry Andric     LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
16500b57cec5SDimitry Andric   }
16510b57cec5SDimitry Andric 
16520b57cec5SDimitry Andric   // TODO: What if the ClosestSubprogram is neither null or the current
16530b57cec5SDimitry Andric   // subprogram?  Currently, the UDT just gets dropped on the floor.
16540b57cec5SDimitry Andric   //
16550b57cec5SDimitry Andric   // The current behavior is not desirable.  To get maximal fidelity, we would
16560b57cec5SDimitry Andric   // need to perform all type translation before beginning emission of .debug$S
16570b57cec5SDimitry Andric   // and then make LocalUDTs a member of FunctionInfo
16580b57cec5SDimitry Andric }
16590b57cec5SDimitry Andric 
lowerType(const DIType * Ty,const DIType * ClassTy)16600b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
16610b57cec5SDimitry Andric   // Generic dispatch for lowering an unknown type.
16620b57cec5SDimitry Andric   switch (Ty->getTag()) {
16630b57cec5SDimitry Andric   case dwarf::DW_TAG_array_type:
16640b57cec5SDimitry Andric     return lowerTypeArray(cast<DICompositeType>(Ty));
16650b57cec5SDimitry Andric   case dwarf::DW_TAG_typedef:
16660b57cec5SDimitry Andric     return lowerTypeAlias(cast<DIDerivedType>(Ty));
16670b57cec5SDimitry Andric   case dwarf::DW_TAG_base_type:
16680b57cec5SDimitry Andric     return lowerTypeBasic(cast<DIBasicType>(Ty));
16690b57cec5SDimitry Andric   case dwarf::DW_TAG_pointer_type:
16700b57cec5SDimitry Andric     if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
16710b57cec5SDimitry Andric       return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1672bdd1243dSDimitry Andric     [[fallthrough]];
16730b57cec5SDimitry Andric   case dwarf::DW_TAG_reference_type:
16740b57cec5SDimitry Andric   case dwarf::DW_TAG_rvalue_reference_type:
16750b57cec5SDimitry Andric     return lowerTypePointer(cast<DIDerivedType>(Ty));
16760b57cec5SDimitry Andric   case dwarf::DW_TAG_ptr_to_member_type:
16770b57cec5SDimitry Andric     return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
16780b57cec5SDimitry Andric   case dwarf::DW_TAG_restrict_type:
16790b57cec5SDimitry Andric   case dwarf::DW_TAG_const_type:
16800b57cec5SDimitry Andric   case dwarf::DW_TAG_volatile_type:
16810b57cec5SDimitry Andric   // TODO: add support for DW_TAG_atomic_type here
16820b57cec5SDimitry Andric     return lowerTypeModifier(cast<DIDerivedType>(Ty));
16830b57cec5SDimitry Andric   case dwarf::DW_TAG_subroutine_type:
16840b57cec5SDimitry Andric     if (ClassTy) {
16850b57cec5SDimitry Andric       // The member function type of a member function pointer has no
16860b57cec5SDimitry Andric       // ThisAdjustment.
16870b57cec5SDimitry Andric       return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
16880b57cec5SDimitry Andric                                      /*ThisAdjustment=*/0,
16890b57cec5SDimitry Andric                                      /*IsStaticMethod=*/false);
16900b57cec5SDimitry Andric     }
16910b57cec5SDimitry Andric     return lowerTypeFunction(cast<DISubroutineType>(Ty));
16920b57cec5SDimitry Andric   case dwarf::DW_TAG_enumeration_type:
16930b57cec5SDimitry Andric     return lowerTypeEnum(cast<DICompositeType>(Ty));
16940b57cec5SDimitry Andric   case dwarf::DW_TAG_class_type:
16950b57cec5SDimitry Andric   case dwarf::DW_TAG_structure_type:
16960b57cec5SDimitry Andric     return lowerTypeClass(cast<DICompositeType>(Ty));
16970b57cec5SDimitry Andric   case dwarf::DW_TAG_union_type:
16980b57cec5SDimitry Andric     return lowerTypeUnion(cast<DICompositeType>(Ty));
1699349cc55cSDimitry Andric   case dwarf::DW_TAG_string_type:
1700349cc55cSDimitry Andric     return lowerTypeString(cast<DIStringType>(Ty));
17010b57cec5SDimitry Andric   case dwarf::DW_TAG_unspecified_type:
17020b57cec5SDimitry Andric     if (Ty->getName() == "decltype(nullptr)")
17030b57cec5SDimitry Andric       return TypeIndex::NullptrT();
17040b57cec5SDimitry Andric     return TypeIndex::None();
17050b57cec5SDimitry Andric   default:
17060b57cec5SDimitry Andric     // Use the null type index.
17070b57cec5SDimitry Andric     return TypeIndex();
17080b57cec5SDimitry Andric   }
17090b57cec5SDimitry Andric }
17100b57cec5SDimitry Andric 
lowerTypeAlias(const DIDerivedType * Ty)17110b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
17120b57cec5SDimitry Andric   TypeIndex UnderlyingTypeIndex = getTypeIndex(Ty->getBaseType());
17130b57cec5SDimitry Andric   StringRef TypeName = Ty->getName();
17140b57cec5SDimitry Andric 
17150b57cec5SDimitry Andric   addToUDTs(Ty);
17160b57cec5SDimitry Andric 
17170b57cec5SDimitry Andric   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
17180b57cec5SDimitry Andric       TypeName == "HRESULT")
17190b57cec5SDimitry Andric     return TypeIndex(SimpleTypeKind::HResult);
17200b57cec5SDimitry Andric   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
17210b57cec5SDimitry Andric       TypeName == "wchar_t")
17220b57cec5SDimitry Andric     return TypeIndex(SimpleTypeKind::WideCharacter);
17230b57cec5SDimitry Andric 
17240b57cec5SDimitry Andric   return UnderlyingTypeIndex;
17250b57cec5SDimitry Andric }
17260b57cec5SDimitry Andric 
lowerTypeArray(const DICompositeType * Ty)17270b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
17280b57cec5SDimitry Andric   const DIType *ElementType = Ty->getBaseType();
17290b57cec5SDimitry Andric   TypeIndex ElementTypeIndex = getTypeIndex(ElementType);
17300b57cec5SDimitry Andric   // IndexType is size_t, which depends on the bitness of the target.
17310b57cec5SDimitry Andric   TypeIndex IndexType = getPointerSizeInBytes() == 8
17320b57cec5SDimitry Andric                             ? TypeIndex(SimpleTypeKind::UInt64Quad)
17330b57cec5SDimitry Andric                             : TypeIndex(SimpleTypeKind::UInt32Long);
17340b57cec5SDimitry Andric 
17350b57cec5SDimitry Andric   uint64_t ElementSize = getBaseTypeSize(ElementType) / 8;
17360b57cec5SDimitry Andric 
17370b57cec5SDimitry Andric   // Add subranges to array type.
17380b57cec5SDimitry Andric   DINodeArray Elements = Ty->getElements();
17390b57cec5SDimitry Andric   for (int i = Elements.size() - 1; i >= 0; --i) {
17400b57cec5SDimitry Andric     const DINode *Element = Elements[i];
17410b57cec5SDimitry Andric     assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
17420b57cec5SDimitry Andric 
17430b57cec5SDimitry Andric     const DISubrange *Subrange = cast<DISubrange>(Element);
17440b57cec5SDimitry Andric     int64_t Count = -1;
1745349cc55cSDimitry Andric 
1746349cc55cSDimitry Andric     // If Subrange has a Count field, use it.
1747349cc55cSDimitry Andric     // Otherwise, if it has an upperboud, use (upperbound - lowerbound + 1),
1748349cc55cSDimitry Andric     // where lowerbound is from the LowerBound field of the Subrange,
1749349cc55cSDimitry Andric     // or the language default lowerbound if that field is unspecified.
175006c3fb27SDimitry Andric     if (auto *CI = dyn_cast_if_present<ConstantInt *>(Subrange->getCount()))
17510b57cec5SDimitry Andric       Count = CI->getSExtValue();
175206c3fb27SDimitry Andric     else if (auto *UI = dyn_cast_if_present<ConstantInt *>(
175306c3fb27SDimitry Andric                  Subrange->getUpperBound())) {
1754349cc55cSDimitry Andric       // Fortran uses 1 as the default lowerbound; other languages use 0.
1755349cc55cSDimitry Andric       int64_t Lowerbound = (moduleIsInFortran()) ? 1 : 0;
175606c3fb27SDimitry Andric       auto *LI = dyn_cast_if_present<ConstantInt *>(Subrange->getLowerBound());
1757349cc55cSDimitry Andric       Lowerbound = (LI) ? LI->getSExtValue() : Lowerbound;
1758349cc55cSDimitry Andric       Count = UI->getSExtValue() - Lowerbound + 1;
175916d6b3b3SDimitry Andric     }
17600b57cec5SDimitry Andric 
17610b57cec5SDimitry Andric     // Forward declarations of arrays without a size and VLAs use a count of -1.
17620b57cec5SDimitry Andric     // Emit a count of zero in these cases to match what MSVC does for arrays
17630b57cec5SDimitry Andric     // without a size. MSVC doesn't support VLAs, so it's not clear what we
17640b57cec5SDimitry Andric     // should do for them even if we could distinguish them.
17650b57cec5SDimitry Andric     if (Count == -1)
17660b57cec5SDimitry Andric       Count = 0;
17670b57cec5SDimitry Andric 
17680b57cec5SDimitry Andric     // Update the element size and element type index for subsequent subranges.
17690b57cec5SDimitry Andric     ElementSize *= Count;
17700b57cec5SDimitry Andric 
17710b57cec5SDimitry Andric     // If this is the outermost array, use the size from the array. It will be
17720b57cec5SDimitry Andric     // more accurate if we had a VLA or an incomplete element type size.
17730b57cec5SDimitry Andric     uint64_t ArraySize =
17740b57cec5SDimitry Andric         (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
17750b57cec5SDimitry Andric 
17760b57cec5SDimitry Andric     StringRef Name = (i == 0) ? Ty->getName() : "";
17770b57cec5SDimitry Andric     ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
17780b57cec5SDimitry Andric     ElementTypeIndex = TypeTable.writeLeafType(AR);
17790b57cec5SDimitry Andric   }
17800b57cec5SDimitry Andric 
17810b57cec5SDimitry Andric   return ElementTypeIndex;
17820b57cec5SDimitry Andric }
17830b57cec5SDimitry Andric 
1784349cc55cSDimitry Andric // This function lowers a Fortran character type (DIStringType).
1785349cc55cSDimitry Andric // Note that it handles only the character*n variant (using SizeInBits
1786349cc55cSDimitry Andric // field in DIString to describe the type size) at the moment.
1787349cc55cSDimitry Andric // Other variants (leveraging the StringLength and StringLengthExp
1788349cc55cSDimitry Andric // fields in DIStringType) remain TBD.
lowerTypeString(const DIStringType * Ty)1789349cc55cSDimitry Andric TypeIndex CodeViewDebug::lowerTypeString(const DIStringType *Ty) {
1790349cc55cSDimitry Andric   TypeIndex CharType = TypeIndex(SimpleTypeKind::NarrowCharacter);
1791349cc55cSDimitry Andric   uint64_t ArraySize = Ty->getSizeInBits() >> 3;
1792349cc55cSDimitry Andric   StringRef Name = Ty->getName();
1793349cc55cSDimitry Andric   // IndexType is size_t, which depends on the bitness of the target.
1794349cc55cSDimitry Andric   TypeIndex IndexType = getPointerSizeInBytes() == 8
1795349cc55cSDimitry Andric                             ? TypeIndex(SimpleTypeKind::UInt64Quad)
1796349cc55cSDimitry Andric                             : TypeIndex(SimpleTypeKind::UInt32Long);
1797349cc55cSDimitry Andric 
1798349cc55cSDimitry Andric   // Create a type of character array of ArraySize.
1799349cc55cSDimitry Andric   ArrayRecord AR(CharType, IndexType, ArraySize, Name);
1800349cc55cSDimitry Andric 
1801349cc55cSDimitry Andric   return TypeTable.writeLeafType(AR);
1802349cc55cSDimitry Andric }
1803349cc55cSDimitry Andric 
lowerTypeBasic(const DIBasicType * Ty)18040b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
18050b57cec5SDimitry Andric   TypeIndex Index;
18060b57cec5SDimitry Andric   dwarf::TypeKind Kind;
18070b57cec5SDimitry Andric   uint32_t ByteSize;
18080b57cec5SDimitry Andric 
18090b57cec5SDimitry Andric   Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
18100b57cec5SDimitry Andric   ByteSize = Ty->getSizeInBits() / 8;
18110b57cec5SDimitry Andric 
18120b57cec5SDimitry Andric   SimpleTypeKind STK = SimpleTypeKind::None;
18130b57cec5SDimitry Andric   switch (Kind) {
18140b57cec5SDimitry Andric   case dwarf::DW_ATE_address:
18150b57cec5SDimitry Andric     // FIXME: Translate
18160b57cec5SDimitry Andric     break;
18170b57cec5SDimitry Andric   case dwarf::DW_ATE_boolean:
18180b57cec5SDimitry Andric     switch (ByteSize) {
18190b57cec5SDimitry Andric     case 1:  STK = SimpleTypeKind::Boolean8;   break;
18200b57cec5SDimitry Andric     case 2:  STK = SimpleTypeKind::Boolean16;  break;
18210b57cec5SDimitry Andric     case 4:  STK = SimpleTypeKind::Boolean32;  break;
18220b57cec5SDimitry Andric     case 8:  STK = SimpleTypeKind::Boolean64;  break;
18230b57cec5SDimitry Andric     case 16: STK = SimpleTypeKind::Boolean128; break;
18240b57cec5SDimitry Andric     }
18250b57cec5SDimitry Andric     break;
18260b57cec5SDimitry Andric   case dwarf::DW_ATE_complex_float:
182706c3fb27SDimitry Andric     // The CodeView size for a complex represents the size of
182806c3fb27SDimitry Andric     // an individual component.
18290b57cec5SDimitry Andric     switch (ByteSize) {
183006c3fb27SDimitry Andric     case 4:  STK = SimpleTypeKind::Complex16;  break;
183106c3fb27SDimitry Andric     case 8:  STK = SimpleTypeKind::Complex32;  break;
183206c3fb27SDimitry Andric     case 16: STK = SimpleTypeKind::Complex64;  break;
183306c3fb27SDimitry Andric     case 20: STK = SimpleTypeKind::Complex80;  break;
183406c3fb27SDimitry Andric     case 32: STK = SimpleTypeKind::Complex128; break;
18350b57cec5SDimitry Andric     }
18360b57cec5SDimitry Andric     break;
18370b57cec5SDimitry Andric   case dwarf::DW_ATE_float:
18380b57cec5SDimitry Andric     switch (ByteSize) {
18390b57cec5SDimitry Andric     case 2:  STK = SimpleTypeKind::Float16;  break;
18400b57cec5SDimitry Andric     case 4:  STK = SimpleTypeKind::Float32;  break;
18410b57cec5SDimitry Andric     case 6:  STK = SimpleTypeKind::Float48;  break;
18420b57cec5SDimitry Andric     case 8:  STK = SimpleTypeKind::Float64;  break;
18430b57cec5SDimitry Andric     case 10: STK = SimpleTypeKind::Float80;  break;
18440b57cec5SDimitry Andric     case 16: STK = SimpleTypeKind::Float128; break;
18450b57cec5SDimitry Andric     }
18460b57cec5SDimitry Andric     break;
18470b57cec5SDimitry Andric   case dwarf::DW_ATE_signed:
18480b57cec5SDimitry Andric     switch (ByteSize) {
18490b57cec5SDimitry Andric     case 1:  STK = SimpleTypeKind::SignedCharacter; break;
18500b57cec5SDimitry Andric     case 2:  STK = SimpleTypeKind::Int16Short;      break;
18510b57cec5SDimitry Andric     case 4:  STK = SimpleTypeKind::Int32;           break;
18520b57cec5SDimitry Andric     case 8:  STK = SimpleTypeKind::Int64Quad;       break;
18530b57cec5SDimitry Andric     case 16: STK = SimpleTypeKind::Int128Oct;       break;
18540b57cec5SDimitry Andric     }
18550b57cec5SDimitry Andric     break;
18560b57cec5SDimitry Andric   case dwarf::DW_ATE_unsigned:
18570b57cec5SDimitry Andric     switch (ByteSize) {
18580b57cec5SDimitry Andric     case 1:  STK = SimpleTypeKind::UnsignedCharacter; break;
18590b57cec5SDimitry Andric     case 2:  STK = SimpleTypeKind::UInt16Short;       break;
18600b57cec5SDimitry Andric     case 4:  STK = SimpleTypeKind::UInt32;            break;
18610b57cec5SDimitry Andric     case 8:  STK = SimpleTypeKind::UInt64Quad;        break;
18620b57cec5SDimitry Andric     case 16: STK = SimpleTypeKind::UInt128Oct;        break;
18630b57cec5SDimitry Andric     }
18640b57cec5SDimitry Andric     break;
18650b57cec5SDimitry Andric   case dwarf::DW_ATE_UTF:
18660b57cec5SDimitry Andric     switch (ByteSize) {
186781ad6265SDimitry Andric     case 1: STK = SimpleTypeKind::Character8; break;
18680b57cec5SDimitry Andric     case 2: STK = SimpleTypeKind::Character16; break;
18690b57cec5SDimitry Andric     case 4: STK = SimpleTypeKind::Character32; break;
18700b57cec5SDimitry Andric     }
18710b57cec5SDimitry Andric     break;
18720b57cec5SDimitry Andric   case dwarf::DW_ATE_signed_char:
18730b57cec5SDimitry Andric     if (ByteSize == 1)
18740b57cec5SDimitry Andric       STK = SimpleTypeKind::SignedCharacter;
18750b57cec5SDimitry Andric     break;
18760b57cec5SDimitry Andric   case dwarf::DW_ATE_unsigned_char:
18770b57cec5SDimitry Andric     if (ByteSize == 1)
18780b57cec5SDimitry Andric       STK = SimpleTypeKind::UnsignedCharacter;
18790b57cec5SDimitry Andric     break;
18800b57cec5SDimitry Andric   default:
18810b57cec5SDimitry Andric     break;
18820b57cec5SDimitry Andric   }
18830b57cec5SDimitry Andric 
18840b57cec5SDimitry Andric   // Apply some fixups based on the source-level type name.
1885349cc55cSDimitry Andric   // Include some amount of canonicalization from an old naming scheme Clang
1886349cc55cSDimitry Andric   // used to use for integer types (in an outdated effort to be compatible with
1887349cc55cSDimitry Andric   // GCC's debug info/GDB's behavior, which has since been addressed).
1888349cc55cSDimitry Andric   if (STK == SimpleTypeKind::Int32 &&
1889349cc55cSDimitry Andric       (Ty->getName() == "long int" || Ty->getName() == "long"))
18900b57cec5SDimitry Andric     STK = SimpleTypeKind::Int32Long;
1891349cc55cSDimitry Andric   if (STK == SimpleTypeKind::UInt32 && (Ty->getName() == "long unsigned int" ||
1892349cc55cSDimitry Andric                                         Ty->getName() == "unsigned long"))
18930b57cec5SDimitry Andric     STK = SimpleTypeKind::UInt32Long;
18940b57cec5SDimitry Andric   if (STK == SimpleTypeKind::UInt16Short &&
18950b57cec5SDimitry Andric       (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
18960b57cec5SDimitry Andric     STK = SimpleTypeKind::WideCharacter;
18970b57cec5SDimitry Andric   if ((STK == SimpleTypeKind::SignedCharacter ||
18980b57cec5SDimitry Andric        STK == SimpleTypeKind::UnsignedCharacter) &&
18990b57cec5SDimitry Andric       Ty->getName() == "char")
19000b57cec5SDimitry Andric     STK = SimpleTypeKind::NarrowCharacter;
19010b57cec5SDimitry Andric 
19020b57cec5SDimitry Andric   return TypeIndex(STK);
19030b57cec5SDimitry Andric }
19040b57cec5SDimitry Andric 
lowerTypePointer(const DIDerivedType * Ty,PointerOptions PO)19050b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
19060b57cec5SDimitry Andric                                           PointerOptions PO) {
19070b57cec5SDimitry Andric   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
19080b57cec5SDimitry Andric 
19090b57cec5SDimitry Andric   // Pointers to simple types without any options can use SimpleTypeMode, rather
19100b57cec5SDimitry Andric   // than having a dedicated pointer type record.
19110b57cec5SDimitry Andric   if (PointeeTI.isSimple() && PO == PointerOptions::None &&
19120b57cec5SDimitry Andric       PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
19130b57cec5SDimitry Andric       Ty->getTag() == dwarf::DW_TAG_pointer_type) {
19140b57cec5SDimitry Andric     SimpleTypeMode Mode = Ty->getSizeInBits() == 64
19150b57cec5SDimitry Andric                               ? SimpleTypeMode::NearPointer64
19160b57cec5SDimitry Andric                               : SimpleTypeMode::NearPointer32;
19170b57cec5SDimitry Andric     return TypeIndex(PointeeTI.getSimpleKind(), Mode);
19180b57cec5SDimitry Andric   }
19190b57cec5SDimitry Andric 
19200b57cec5SDimitry Andric   PointerKind PK =
19210b57cec5SDimitry Andric       Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
19220b57cec5SDimitry Andric   PointerMode PM = PointerMode::Pointer;
19230b57cec5SDimitry Andric   switch (Ty->getTag()) {
19240b57cec5SDimitry Andric   default: llvm_unreachable("not a pointer tag type");
19250b57cec5SDimitry Andric   case dwarf::DW_TAG_pointer_type:
19260b57cec5SDimitry Andric     PM = PointerMode::Pointer;
19270b57cec5SDimitry Andric     break;
19280b57cec5SDimitry Andric   case dwarf::DW_TAG_reference_type:
19290b57cec5SDimitry Andric     PM = PointerMode::LValueReference;
19300b57cec5SDimitry Andric     break;
19310b57cec5SDimitry Andric   case dwarf::DW_TAG_rvalue_reference_type:
19320b57cec5SDimitry Andric     PM = PointerMode::RValueReference;
19330b57cec5SDimitry Andric     break;
19340b57cec5SDimitry Andric   }
19350b57cec5SDimitry Andric 
19360b57cec5SDimitry Andric   if (Ty->isObjectPointer())
19370b57cec5SDimitry Andric     PO |= PointerOptions::Const;
19380b57cec5SDimitry Andric 
19390b57cec5SDimitry Andric   PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
19400b57cec5SDimitry Andric   return TypeTable.writeLeafType(PR);
19410b57cec5SDimitry Andric }
19420b57cec5SDimitry Andric 
19430b57cec5SDimitry Andric static PointerToMemberRepresentation
translatePtrToMemberRep(unsigned SizeInBytes,bool IsPMF,unsigned Flags)19440b57cec5SDimitry Andric translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
19450b57cec5SDimitry Andric   // SizeInBytes being zero generally implies that the member pointer type was
19460b57cec5SDimitry Andric   // incomplete, which can happen if it is part of a function prototype. In this
19470b57cec5SDimitry Andric   // case, use the unknown model instead of the general model.
19480b57cec5SDimitry Andric   if (IsPMF) {
19490b57cec5SDimitry Andric     switch (Flags & DINode::FlagPtrToMemberRep) {
19500b57cec5SDimitry Andric     case 0:
19510b57cec5SDimitry Andric       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
19520b57cec5SDimitry Andric                               : PointerToMemberRepresentation::GeneralFunction;
19530b57cec5SDimitry Andric     case DINode::FlagSingleInheritance:
19540b57cec5SDimitry Andric       return PointerToMemberRepresentation::SingleInheritanceFunction;
19550b57cec5SDimitry Andric     case DINode::FlagMultipleInheritance:
19560b57cec5SDimitry Andric       return PointerToMemberRepresentation::MultipleInheritanceFunction;
19570b57cec5SDimitry Andric     case DINode::FlagVirtualInheritance:
19580b57cec5SDimitry Andric       return PointerToMemberRepresentation::VirtualInheritanceFunction;
19590b57cec5SDimitry Andric     }
19600b57cec5SDimitry Andric   } else {
19610b57cec5SDimitry Andric     switch (Flags & DINode::FlagPtrToMemberRep) {
19620b57cec5SDimitry Andric     case 0:
19630b57cec5SDimitry Andric       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
19640b57cec5SDimitry Andric                               : PointerToMemberRepresentation::GeneralData;
19650b57cec5SDimitry Andric     case DINode::FlagSingleInheritance:
19660b57cec5SDimitry Andric       return PointerToMemberRepresentation::SingleInheritanceData;
19670b57cec5SDimitry Andric     case DINode::FlagMultipleInheritance:
19680b57cec5SDimitry Andric       return PointerToMemberRepresentation::MultipleInheritanceData;
19690b57cec5SDimitry Andric     case DINode::FlagVirtualInheritance:
19700b57cec5SDimitry Andric       return PointerToMemberRepresentation::VirtualInheritanceData;
19710b57cec5SDimitry Andric     }
19720b57cec5SDimitry Andric   }
19730b57cec5SDimitry Andric   llvm_unreachable("invalid ptr to member representation");
19740b57cec5SDimitry Andric }
19750b57cec5SDimitry Andric 
lowerTypeMemberPointer(const DIDerivedType * Ty,PointerOptions PO)19760b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
19770b57cec5SDimitry Andric                                                 PointerOptions PO) {
19780b57cec5SDimitry Andric   assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
19795ffd83dbSDimitry Andric   bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
19800b57cec5SDimitry Andric   TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
19815ffd83dbSDimitry Andric   TypeIndex PointeeTI =
19825ffd83dbSDimitry Andric       getTypeIndex(Ty->getBaseType(), IsPMF ? Ty->getClassType() : nullptr);
19830b57cec5SDimitry Andric   PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
19840b57cec5SDimitry Andric                                                 : PointerKind::Near32;
19850b57cec5SDimitry Andric   PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
19860b57cec5SDimitry Andric                          : PointerMode::PointerToDataMember;
19870b57cec5SDimitry Andric 
19880b57cec5SDimitry Andric   assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
19890b57cec5SDimitry Andric   uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
19900b57cec5SDimitry Andric   MemberPointerInfo MPI(
19910b57cec5SDimitry Andric       ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
19920b57cec5SDimitry Andric   PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
19930b57cec5SDimitry Andric   return TypeTable.writeLeafType(PR);
19940b57cec5SDimitry Andric }
19950b57cec5SDimitry Andric 
19960b57cec5SDimitry Andric /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
19970b57cec5SDimitry Andric /// have a translation, use the NearC convention.
dwarfCCToCodeView(unsigned DwarfCC)19980b57cec5SDimitry Andric static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
19990b57cec5SDimitry Andric   switch (DwarfCC) {
20000b57cec5SDimitry Andric   case dwarf::DW_CC_normal:             return CallingConvention::NearC;
20010b57cec5SDimitry Andric   case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
20020b57cec5SDimitry Andric   case dwarf::DW_CC_BORLAND_thiscall:   return CallingConvention::ThisCall;
20030b57cec5SDimitry Andric   case dwarf::DW_CC_BORLAND_stdcall:    return CallingConvention::NearStdCall;
20040b57cec5SDimitry Andric   case dwarf::DW_CC_BORLAND_pascal:     return CallingConvention::NearPascal;
20050b57cec5SDimitry Andric   case dwarf::DW_CC_LLVM_vectorcall:    return CallingConvention::NearVector;
20060b57cec5SDimitry Andric   }
20070b57cec5SDimitry Andric   return CallingConvention::NearC;
20080b57cec5SDimitry Andric }
20090b57cec5SDimitry Andric 
lowerTypeModifier(const DIDerivedType * Ty)20100b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
20110b57cec5SDimitry Andric   ModifierOptions Mods = ModifierOptions::None;
20120b57cec5SDimitry Andric   PointerOptions PO = PointerOptions::None;
20130b57cec5SDimitry Andric   bool IsModifier = true;
20140b57cec5SDimitry Andric   const DIType *BaseTy = Ty;
20150b57cec5SDimitry Andric   while (IsModifier && BaseTy) {
20160b57cec5SDimitry Andric     // FIXME: Need to add DWARF tags for __unaligned and _Atomic
20170b57cec5SDimitry Andric     switch (BaseTy->getTag()) {
20180b57cec5SDimitry Andric     case dwarf::DW_TAG_const_type:
20190b57cec5SDimitry Andric       Mods |= ModifierOptions::Const;
20200b57cec5SDimitry Andric       PO |= PointerOptions::Const;
20210b57cec5SDimitry Andric       break;
20220b57cec5SDimitry Andric     case dwarf::DW_TAG_volatile_type:
20230b57cec5SDimitry Andric       Mods |= ModifierOptions::Volatile;
20240b57cec5SDimitry Andric       PO |= PointerOptions::Volatile;
20250b57cec5SDimitry Andric       break;
20260b57cec5SDimitry Andric     case dwarf::DW_TAG_restrict_type:
20270b57cec5SDimitry Andric       // Only pointer types be marked with __restrict. There is no known flag
20280b57cec5SDimitry Andric       // for __restrict in LF_MODIFIER records.
20290b57cec5SDimitry Andric       PO |= PointerOptions::Restrict;
20300b57cec5SDimitry Andric       break;
20310b57cec5SDimitry Andric     default:
20320b57cec5SDimitry Andric       IsModifier = false;
20330b57cec5SDimitry Andric       break;
20340b57cec5SDimitry Andric     }
20350b57cec5SDimitry Andric     if (IsModifier)
20360b57cec5SDimitry Andric       BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType();
20370b57cec5SDimitry Andric   }
20380b57cec5SDimitry Andric 
20390b57cec5SDimitry Andric   // Check if the inner type will use an LF_POINTER record. If so, the
20400b57cec5SDimitry Andric   // qualifiers will go in the LF_POINTER record. This comes up for types like
20410b57cec5SDimitry Andric   // 'int *const' and 'int *__restrict', not the more common cases like 'const
20420b57cec5SDimitry Andric   // char *'.
20430b57cec5SDimitry Andric   if (BaseTy) {
20440b57cec5SDimitry Andric     switch (BaseTy->getTag()) {
20450b57cec5SDimitry Andric     case dwarf::DW_TAG_pointer_type:
20460b57cec5SDimitry Andric     case dwarf::DW_TAG_reference_type:
20470b57cec5SDimitry Andric     case dwarf::DW_TAG_rvalue_reference_type:
20480b57cec5SDimitry Andric       return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
20490b57cec5SDimitry Andric     case dwarf::DW_TAG_ptr_to_member_type:
20500b57cec5SDimitry Andric       return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
20510b57cec5SDimitry Andric     default:
20520b57cec5SDimitry Andric       break;
20530b57cec5SDimitry Andric     }
20540b57cec5SDimitry Andric   }
20550b57cec5SDimitry Andric 
20560b57cec5SDimitry Andric   TypeIndex ModifiedTI = getTypeIndex(BaseTy);
20570b57cec5SDimitry Andric 
20580b57cec5SDimitry Andric   // Return the base type index if there aren't any modifiers. For example, the
20590b57cec5SDimitry Andric   // metadata could contain restrict wrappers around non-pointer types.
20600b57cec5SDimitry Andric   if (Mods == ModifierOptions::None)
20610b57cec5SDimitry Andric     return ModifiedTI;
20620b57cec5SDimitry Andric 
20630b57cec5SDimitry Andric   ModifierRecord MR(ModifiedTI, Mods);
20640b57cec5SDimitry Andric   return TypeTable.writeLeafType(MR);
20650b57cec5SDimitry Andric }
20660b57cec5SDimitry Andric 
lowerTypeFunction(const DISubroutineType * Ty)20670b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
20680b57cec5SDimitry Andric   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
20690b57cec5SDimitry Andric   for (const DIType *ArgType : Ty->getTypeArray())
20700b57cec5SDimitry Andric     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgType));
20710b57cec5SDimitry Andric 
20720b57cec5SDimitry Andric   // MSVC uses type none for variadic argument.
20730b57cec5SDimitry Andric   if (ReturnAndArgTypeIndices.size() > 1 &&
20740b57cec5SDimitry Andric       ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
20750b57cec5SDimitry Andric     ReturnAndArgTypeIndices.back() = TypeIndex::None();
20760b57cec5SDimitry Andric   }
20770b57cec5SDimitry Andric   TypeIndex ReturnTypeIndex = TypeIndex::Void();
2078bdd1243dSDimitry Andric   ArrayRef<TypeIndex> ArgTypeIndices = std::nullopt;
20790b57cec5SDimitry Andric   if (!ReturnAndArgTypeIndices.empty()) {
2080bdd1243dSDimitry Andric     auto ReturnAndArgTypesRef = ArrayRef(ReturnAndArgTypeIndices);
20810b57cec5SDimitry Andric     ReturnTypeIndex = ReturnAndArgTypesRef.front();
20820b57cec5SDimitry Andric     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
20830b57cec5SDimitry Andric   }
20840b57cec5SDimitry Andric 
20850b57cec5SDimitry Andric   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
20860b57cec5SDimitry Andric   TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
20870b57cec5SDimitry Andric 
20880b57cec5SDimitry Andric   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
20890b57cec5SDimitry Andric 
20900b57cec5SDimitry Andric   FunctionOptions FO = getFunctionOptions(Ty);
20910b57cec5SDimitry Andric   ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
20920b57cec5SDimitry Andric                             ArgListIndex);
20930b57cec5SDimitry Andric   return TypeTable.writeLeafType(Procedure);
20940b57cec5SDimitry Andric }
20950b57cec5SDimitry Andric 
lowerTypeMemberFunction(const DISubroutineType * Ty,const DIType * ClassTy,int ThisAdjustment,bool IsStaticMethod,FunctionOptions FO)20960b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
20970b57cec5SDimitry Andric                                                  const DIType *ClassTy,
20980b57cec5SDimitry Andric                                                  int ThisAdjustment,
20990b57cec5SDimitry Andric                                                  bool IsStaticMethod,
21000b57cec5SDimitry Andric                                                  FunctionOptions FO) {
21010b57cec5SDimitry Andric   // Lower the containing class type.
21020b57cec5SDimitry Andric   TypeIndex ClassType = getTypeIndex(ClassTy);
21030b57cec5SDimitry Andric 
21040b57cec5SDimitry Andric   DITypeRefArray ReturnAndArgs = Ty->getTypeArray();
21050b57cec5SDimitry Andric 
21060b57cec5SDimitry Andric   unsigned Index = 0;
21070b57cec5SDimitry Andric   SmallVector<TypeIndex, 8> ArgTypeIndices;
21080b57cec5SDimitry Andric   TypeIndex ReturnTypeIndex = TypeIndex::Void();
21090b57cec5SDimitry Andric   if (ReturnAndArgs.size() > Index) {
21100b57cec5SDimitry Andric     ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]);
21110b57cec5SDimitry Andric   }
21120b57cec5SDimitry Andric 
21130b57cec5SDimitry Andric   // If the first argument is a pointer type and this isn't a static method,
21140b57cec5SDimitry Andric   // treat it as the special 'this' parameter, which is encoded separately from
21150b57cec5SDimitry Andric   // the arguments.
21160b57cec5SDimitry Andric   TypeIndex ThisTypeIndex;
21170b57cec5SDimitry Andric   if (!IsStaticMethod && ReturnAndArgs.size() > Index) {
21180b57cec5SDimitry Andric     if (const DIDerivedType *PtrTy =
21190b57cec5SDimitry Andric             dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index])) {
21200b57cec5SDimitry Andric       if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) {
21210b57cec5SDimitry Andric         ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty);
21220b57cec5SDimitry Andric         Index++;
21230b57cec5SDimitry Andric       }
21240b57cec5SDimitry Andric     }
21250b57cec5SDimitry Andric   }
21260b57cec5SDimitry Andric 
21270b57cec5SDimitry Andric   while (Index < ReturnAndArgs.size())
21280b57cec5SDimitry Andric     ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++]));
21290b57cec5SDimitry Andric 
21300b57cec5SDimitry Andric   // MSVC uses type none for variadic argument.
21310b57cec5SDimitry Andric   if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void())
21320b57cec5SDimitry Andric     ArgTypeIndices.back() = TypeIndex::None();
21330b57cec5SDimitry Andric 
21340b57cec5SDimitry Andric   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
21350b57cec5SDimitry Andric   TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
21360b57cec5SDimitry Andric 
21370b57cec5SDimitry Andric   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
21380b57cec5SDimitry Andric 
21390b57cec5SDimitry Andric   MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
21400b57cec5SDimitry Andric                            ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
21410b57cec5SDimitry Andric   return TypeTable.writeLeafType(MFR);
21420b57cec5SDimitry Andric }
21430b57cec5SDimitry Andric 
lowerTypeVFTableShape(const DIDerivedType * Ty)21440b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
21450b57cec5SDimitry Andric   unsigned VSlotCount =
21460b57cec5SDimitry Andric       Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
21470b57cec5SDimitry Andric   SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
21480b57cec5SDimitry Andric 
21490b57cec5SDimitry Andric   VFTableShapeRecord VFTSR(Slots);
21500b57cec5SDimitry Andric   return TypeTable.writeLeafType(VFTSR);
21510b57cec5SDimitry Andric }
21520b57cec5SDimitry Andric 
translateAccessFlags(unsigned RecordTag,unsigned Flags)21530b57cec5SDimitry Andric static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
21540b57cec5SDimitry Andric   switch (Flags & DINode::FlagAccessibility) {
21550b57cec5SDimitry Andric   case DINode::FlagPrivate:   return MemberAccess::Private;
21560b57cec5SDimitry Andric   case DINode::FlagPublic:    return MemberAccess::Public;
21570b57cec5SDimitry Andric   case DINode::FlagProtected: return MemberAccess::Protected;
21580b57cec5SDimitry Andric   case 0:
21590b57cec5SDimitry Andric     // If there was no explicit access control, provide the default for the tag.
21600b57cec5SDimitry Andric     return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
21610b57cec5SDimitry Andric                                                  : MemberAccess::Public;
21620b57cec5SDimitry Andric   }
21630b57cec5SDimitry Andric   llvm_unreachable("access flags are exclusive");
21640b57cec5SDimitry Andric }
21650b57cec5SDimitry Andric 
translateMethodOptionFlags(const DISubprogram * SP)21660b57cec5SDimitry Andric static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
21670b57cec5SDimitry Andric   if (SP->isArtificial())
21680b57cec5SDimitry Andric     return MethodOptions::CompilerGenerated;
21690b57cec5SDimitry Andric 
21700b57cec5SDimitry Andric   // FIXME: Handle other MethodOptions.
21710b57cec5SDimitry Andric 
21720b57cec5SDimitry Andric   return MethodOptions::None;
21730b57cec5SDimitry Andric }
21740b57cec5SDimitry Andric 
translateMethodKindFlags(const DISubprogram * SP,bool Introduced)21750b57cec5SDimitry Andric static MethodKind translateMethodKindFlags(const DISubprogram *SP,
21760b57cec5SDimitry Andric                                            bool Introduced) {
21770b57cec5SDimitry Andric   if (SP->getFlags() & DINode::FlagStaticMember)
21780b57cec5SDimitry Andric     return MethodKind::Static;
21790b57cec5SDimitry Andric 
21800b57cec5SDimitry Andric   switch (SP->getVirtuality()) {
21810b57cec5SDimitry Andric   case dwarf::DW_VIRTUALITY_none:
21820b57cec5SDimitry Andric     break;
21830b57cec5SDimitry Andric   case dwarf::DW_VIRTUALITY_virtual:
21840b57cec5SDimitry Andric     return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
21850b57cec5SDimitry Andric   case dwarf::DW_VIRTUALITY_pure_virtual:
21860b57cec5SDimitry Andric     return Introduced ? MethodKind::PureIntroducingVirtual
21870b57cec5SDimitry Andric                       : MethodKind::PureVirtual;
21880b57cec5SDimitry Andric   default:
21890b57cec5SDimitry Andric     llvm_unreachable("unhandled virtuality case");
21900b57cec5SDimitry Andric   }
21910b57cec5SDimitry Andric 
21920b57cec5SDimitry Andric   return MethodKind::Vanilla;
21930b57cec5SDimitry Andric }
21940b57cec5SDimitry Andric 
getRecordKind(const DICompositeType * Ty)21950b57cec5SDimitry Andric static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
21960b57cec5SDimitry Andric   switch (Ty->getTag()) {
2197fe6060f1SDimitry Andric   case dwarf::DW_TAG_class_type:
2198fe6060f1SDimitry Andric     return TypeRecordKind::Class;
2199fe6060f1SDimitry Andric   case dwarf::DW_TAG_structure_type:
2200fe6060f1SDimitry Andric     return TypeRecordKind::Struct;
2201fe6060f1SDimitry Andric   default:
22020b57cec5SDimitry Andric     llvm_unreachable("unexpected tag");
22030b57cec5SDimitry Andric   }
2204fe6060f1SDimitry Andric }
22050b57cec5SDimitry Andric 
22060b57cec5SDimitry Andric /// Return ClassOptions that should be present on both the forward declaration
22070b57cec5SDimitry Andric /// and the defintion of a tag type.
getCommonClassOptions(const DICompositeType * Ty)22080b57cec5SDimitry Andric static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
22090b57cec5SDimitry Andric   ClassOptions CO = ClassOptions::None;
22100b57cec5SDimitry Andric 
22110b57cec5SDimitry Andric   // MSVC always sets this flag, even for local types. Clang doesn't always
22120b57cec5SDimitry Andric   // appear to give every type a linkage name, which may be problematic for us.
22130b57cec5SDimitry Andric   // FIXME: Investigate the consequences of not following them here.
22140b57cec5SDimitry Andric   if (!Ty->getIdentifier().empty())
22150b57cec5SDimitry Andric     CO |= ClassOptions::HasUniqueName;
22160b57cec5SDimitry Andric 
22170b57cec5SDimitry Andric   // Put the Nested flag on a type if it appears immediately inside a tag type.
22180b57cec5SDimitry Andric   // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
22190b57cec5SDimitry Andric   // here. That flag is only set on definitions, and not forward declarations.
22200b57cec5SDimitry Andric   const DIScope *ImmediateScope = Ty->getScope();
22210b57cec5SDimitry Andric   if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
22220b57cec5SDimitry Andric     CO |= ClassOptions::Nested;
22230b57cec5SDimitry Andric 
22240b57cec5SDimitry Andric   // Put the Scoped flag on function-local types. MSVC puts this flag for enum
22250b57cec5SDimitry Andric   // type only when it has an immediate function scope. Clang never puts enums
22260b57cec5SDimitry Andric   // inside DILexicalBlock scopes. Enum types, as generated by clang, are
22270b57cec5SDimitry Andric   // always in function, class, or file scopes.
22280b57cec5SDimitry Andric   if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
22290b57cec5SDimitry Andric     if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
22300b57cec5SDimitry Andric       CO |= ClassOptions::Scoped;
22310b57cec5SDimitry Andric   } else {
22320b57cec5SDimitry Andric     for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
22330b57cec5SDimitry Andric          Scope = Scope->getScope()) {
22340b57cec5SDimitry Andric       if (isa<DISubprogram>(Scope)) {
22350b57cec5SDimitry Andric         CO |= ClassOptions::Scoped;
22360b57cec5SDimitry Andric         break;
22370b57cec5SDimitry Andric       }
22380b57cec5SDimitry Andric     }
22390b57cec5SDimitry Andric   }
22400b57cec5SDimitry Andric 
22410b57cec5SDimitry Andric   return CO;
22420b57cec5SDimitry Andric }
22430b57cec5SDimitry Andric 
addUDTSrcLine(const DIType * Ty,TypeIndex TI)22440b57cec5SDimitry Andric void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
22450b57cec5SDimitry Andric   switch (Ty->getTag()) {
22460b57cec5SDimitry Andric   case dwarf::DW_TAG_class_type:
22470b57cec5SDimitry Andric   case dwarf::DW_TAG_structure_type:
22480b57cec5SDimitry Andric   case dwarf::DW_TAG_union_type:
22490b57cec5SDimitry Andric   case dwarf::DW_TAG_enumeration_type:
22500b57cec5SDimitry Andric     break;
22510b57cec5SDimitry Andric   default:
22520b57cec5SDimitry Andric     return;
22530b57cec5SDimitry Andric   }
22540b57cec5SDimitry Andric 
22550b57cec5SDimitry Andric   if (const auto *File = Ty->getFile()) {
22560b57cec5SDimitry Andric     StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
22570b57cec5SDimitry Andric     TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
22580b57cec5SDimitry Andric 
22590b57cec5SDimitry Andric     UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
22600b57cec5SDimitry Andric     TypeTable.writeLeafType(USLR);
22610b57cec5SDimitry Andric   }
22620b57cec5SDimitry Andric }
22630b57cec5SDimitry Andric 
lowerTypeEnum(const DICompositeType * Ty)22640b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
22650b57cec5SDimitry Andric   ClassOptions CO = getCommonClassOptions(Ty);
22660b57cec5SDimitry Andric   TypeIndex FTI;
22670b57cec5SDimitry Andric   unsigned EnumeratorCount = 0;
22680b57cec5SDimitry Andric 
22690b57cec5SDimitry Andric   if (Ty->isForwardDecl()) {
22700b57cec5SDimitry Andric     CO |= ClassOptions::ForwardReference;
22710b57cec5SDimitry Andric   } else {
22720b57cec5SDimitry Andric     ContinuationRecordBuilder ContinuationBuilder;
22730b57cec5SDimitry Andric     ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
22740b57cec5SDimitry Andric     for (const DINode *Element : Ty->getElements()) {
22750b57cec5SDimitry Andric       // We assume that the frontend provides all members in source declaration
22760b57cec5SDimitry Andric       // order, which is what MSVC does.
22770b57cec5SDimitry Andric       if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
2278fe6060f1SDimitry Andric         // FIXME: Is it correct to always emit these as unsigned here?
22790b57cec5SDimitry Andric         EnumeratorRecord ER(MemberAccess::Public,
22805ffd83dbSDimitry Andric                             APSInt(Enumerator->getValue(), true),
22810b57cec5SDimitry Andric                             Enumerator->getName());
22820b57cec5SDimitry Andric         ContinuationBuilder.writeMemberType(ER);
22830b57cec5SDimitry Andric         EnumeratorCount++;
22840b57cec5SDimitry Andric       }
22850b57cec5SDimitry Andric     }
22860b57cec5SDimitry Andric     FTI = TypeTable.insertRecord(ContinuationBuilder);
22870b57cec5SDimitry Andric   }
22880b57cec5SDimitry Andric 
22890b57cec5SDimitry Andric   std::string FullName = getFullyQualifiedName(Ty);
22900b57cec5SDimitry Andric 
22910b57cec5SDimitry Andric   EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
22920b57cec5SDimitry Andric                 getTypeIndex(Ty->getBaseType()));
22930b57cec5SDimitry Andric   TypeIndex EnumTI = TypeTable.writeLeafType(ER);
22940b57cec5SDimitry Andric 
22950b57cec5SDimitry Andric   addUDTSrcLine(Ty, EnumTI);
22960b57cec5SDimitry Andric 
22970b57cec5SDimitry Andric   return EnumTI;
22980b57cec5SDimitry Andric }
22990b57cec5SDimitry Andric 
23000b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
23010b57cec5SDimitry Andric // ClassInfo
23020b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
23030b57cec5SDimitry Andric 
23040b57cec5SDimitry Andric struct llvm::ClassInfo {
23050b57cec5SDimitry Andric   struct MemberInfo {
23060b57cec5SDimitry Andric     const DIDerivedType *MemberTypeNode;
23070b57cec5SDimitry Andric     uint64_t BaseOffset;
23080b57cec5SDimitry Andric   };
23090b57cec5SDimitry Andric   // [MemberInfo]
23100b57cec5SDimitry Andric   using MemberList = std::vector<MemberInfo>;
23110b57cec5SDimitry Andric 
23120b57cec5SDimitry Andric   using MethodsList = TinyPtrVector<const DISubprogram *>;
23130b57cec5SDimitry Andric   // MethodName -> MethodsList
23140b57cec5SDimitry Andric   using MethodsMap = MapVector<MDString *, MethodsList>;
23150b57cec5SDimitry Andric 
23160b57cec5SDimitry Andric   /// Base classes.
23170b57cec5SDimitry Andric   std::vector<const DIDerivedType *> Inheritance;
23180b57cec5SDimitry Andric 
23190b57cec5SDimitry Andric   /// Direct members.
23200b57cec5SDimitry Andric   MemberList Members;
23210b57cec5SDimitry Andric   // Direct overloaded methods gathered by name.
23220b57cec5SDimitry Andric   MethodsMap Methods;
23230b57cec5SDimitry Andric 
23240b57cec5SDimitry Andric   TypeIndex VShapeTI;
23250b57cec5SDimitry Andric 
23260b57cec5SDimitry Andric   std::vector<const DIType *> NestedTypes;
23270b57cec5SDimitry Andric };
23280b57cec5SDimitry Andric 
clear()23290b57cec5SDimitry Andric void CodeViewDebug::clear() {
23300b57cec5SDimitry Andric   assert(CurFn == nullptr);
23310b57cec5SDimitry Andric   FileIdMap.clear();
23320b57cec5SDimitry Andric   FnDebugInfo.clear();
23330b57cec5SDimitry Andric   FileToFilepathMap.clear();
23340b57cec5SDimitry Andric   LocalUDTs.clear();
23350b57cec5SDimitry Andric   GlobalUDTs.clear();
23360b57cec5SDimitry Andric   TypeIndices.clear();
23370b57cec5SDimitry Andric   CompleteTypeIndices.clear();
23380b57cec5SDimitry Andric   ScopeGlobals.clear();
2339349cc55cSDimitry Andric   CVGlobalVariableOffsets.clear();
23400b57cec5SDimitry Andric }
23410b57cec5SDimitry Andric 
collectMemberInfo(ClassInfo & Info,const DIDerivedType * DDTy)23420b57cec5SDimitry Andric void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
23430b57cec5SDimitry Andric                                       const DIDerivedType *DDTy) {
23440b57cec5SDimitry Andric   if (!DDTy->getName().empty()) {
23450b57cec5SDimitry Andric     Info.Members.push_back({DDTy, 0});
2346e8d8bef9SDimitry Andric 
2347e8d8bef9SDimitry Andric     // Collect static const data members with values.
2348e8d8bef9SDimitry Andric     if ((DDTy->getFlags() & DINode::FlagStaticMember) ==
2349e8d8bef9SDimitry Andric         DINode::FlagStaticMember) {
2350e8d8bef9SDimitry Andric       if (DDTy->getConstant() && (isa<ConstantInt>(DDTy->getConstant()) ||
2351e8d8bef9SDimitry Andric                                   isa<ConstantFP>(DDTy->getConstant())))
2352e8d8bef9SDimitry Andric         StaticConstMembers.push_back(DDTy);
2353e8d8bef9SDimitry Andric     }
2354e8d8bef9SDimitry Andric 
23550b57cec5SDimitry Andric     return;
23560b57cec5SDimitry Andric   }
23570b57cec5SDimitry Andric 
23580b57cec5SDimitry Andric   // An unnamed member may represent a nested struct or union. Attempt to
23590b57cec5SDimitry Andric   // interpret the unnamed member as a DICompositeType possibly wrapped in
23600b57cec5SDimitry Andric   // qualifier types. Add all the indirect fields to the current record if that
23610b57cec5SDimitry Andric   // succeeds, and drop the member if that fails.
23620b57cec5SDimitry Andric   assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
23630b57cec5SDimitry Andric   uint64_t Offset = DDTy->getOffsetInBits();
23640b57cec5SDimitry Andric   const DIType *Ty = DDTy->getBaseType();
23650b57cec5SDimitry Andric   bool FullyResolved = false;
23660b57cec5SDimitry Andric   while (!FullyResolved) {
23670b57cec5SDimitry Andric     switch (Ty->getTag()) {
23680b57cec5SDimitry Andric     case dwarf::DW_TAG_const_type:
23690b57cec5SDimitry Andric     case dwarf::DW_TAG_volatile_type:
23700b57cec5SDimitry Andric       // FIXME: we should apply the qualifier types to the indirect fields
23710b57cec5SDimitry Andric       // rather than dropping them.
23720b57cec5SDimitry Andric       Ty = cast<DIDerivedType>(Ty)->getBaseType();
23730b57cec5SDimitry Andric       break;
23740b57cec5SDimitry Andric     default:
23750b57cec5SDimitry Andric       FullyResolved = true;
23760b57cec5SDimitry Andric       break;
23770b57cec5SDimitry Andric     }
23780b57cec5SDimitry Andric   }
23790b57cec5SDimitry Andric 
23800b57cec5SDimitry Andric   const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
23810b57cec5SDimitry Andric   if (!DCTy)
23820b57cec5SDimitry Andric     return;
23830b57cec5SDimitry Andric 
23840b57cec5SDimitry Andric   ClassInfo NestedInfo = collectClassInfo(DCTy);
23850b57cec5SDimitry Andric   for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
23860b57cec5SDimitry Andric     Info.Members.push_back(
23870b57cec5SDimitry Andric         {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
23880b57cec5SDimitry Andric }
23890b57cec5SDimitry Andric 
collectClassInfo(const DICompositeType * Ty)23900b57cec5SDimitry Andric ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
23910b57cec5SDimitry Andric   ClassInfo Info;
23920b57cec5SDimitry Andric   // Add elements to structure type.
23930b57cec5SDimitry Andric   DINodeArray Elements = Ty->getElements();
23940b57cec5SDimitry Andric   for (auto *Element : Elements) {
23950b57cec5SDimitry Andric     // We assume that the frontend provides all members in source declaration
23960b57cec5SDimitry Andric     // order, which is what MSVC does.
23970b57cec5SDimitry Andric     if (!Element)
23980b57cec5SDimitry Andric       continue;
23990b57cec5SDimitry Andric     if (auto *SP = dyn_cast<DISubprogram>(Element)) {
24000b57cec5SDimitry Andric       Info.Methods[SP->getRawName()].push_back(SP);
24010b57cec5SDimitry Andric     } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
24020b57cec5SDimitry Andric       if (DDTy->getTag() == dwarf::DW_TAG_member) {
24030b57cec5SDimitry Andric         collectMemberInfo(Info, DDTy);
24040b57cec5SDimitry Andric       } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
24050b57cec5SDimitry Andric         Info.Inheritance.push_back(DDTy);
24060b57cec5SDimitry Andric       } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
24070b57cec5SDimitry Andric                  DDTy->getName() == "__vtbl_ptr_type") {
24080b57cec5SDimitry Andric         Info.VShapeTI = getTypeIndex(DDTy);
24090b57cec5SDimitry Andric       } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
24100b57cec5SDimitry Andric         Info.NestedTypes.push_back(DDTy);
24110b57cec5SDimitry Andric       } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
24120b57cec5SDimitry Andric         // Ignore friend members. It appears that MSVC emitted info about
24130b57cec5SDimitry Andric         // friends in the past, but modern versions do not.
24140b57cec5SDimitry Andric       }
24150b57cec5SDimitry Andric     } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
24160b57cec5SDimitry Andric       Info.NestedTypes.push_back(Composite);
24170b57cec5SDimitry Andric     }
24180b57cec5SDimitry Andric     // Skip other unrecognized kinds of elements.
24190b57cec5SDimitry Andric   }
24200b57cec5SDimitry Andric   return Info;
24210b57cec5SDimitry Andric }
24220b57cec5SDimitry Andric 
shouldAlwaysEmitCompleteClassType(const DICompositeType * Ty)24230b57cec5SDimitry Andric static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) {
24240b57cec5SDimitry Andric   // This routine is used by lowerTypeClass and lowerTypeUnion to determine
24250b57cec5SDimitry Andric   // if a complete type should be emitted instead of a forward reference.
24260b57cec5SDimitry Andric   return Ty->getName().empty() && Ty->getIdentifier().empty() &&
24270b57cec5SDimitry Andric       !Ty->isForwardDecl();
24280b57cec5SDimitry Andric }
24290b57cec5SDimitry Andric 
lowerTypeClass(const DICompositeType * Ty)24300b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
24310b57cec5SDimitry Andric   // Emit the complete type for unnamed structs.  C++ classes with methods
24320b57cec5SDimitry Andric   // which have a circular reference back to the class type are expected to
24330b57cec5SDimitry Andric   // be named by the front-end and should not be "unnamed".  C unnamed
24340b57cec5SDimitry Andric   // structs should not have circular references.
24350b57cec5SDimitry Andric   if (shouldAlwaysEmitCompleteClassType(Ty)) {
24360b57cec5SDimitry Andric     // If this unnamed complete type is already in the process of being defined
24370b57cec5SDimitry Andric     // then the description of the type is malformed and cannot be emitted
24380b57cec5SDimitry Andric     // into CodeView correctly so report a fatal error.
24390b57cec5SDimitry Andric     auto I = CompleteTypeIndices.find(Ty);
24400b57cec5SDimitry Andric     if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
24410b57cec5SDimitry Andric       report_fatal_error("cannot debug circular reference to unnamed type");
24420b57cec5SDimitry Andric     return getCompleteTypeIndex(Ty);
24430b57cec5SDimitry Andric   }
24440b57cec5SDimitry Andric 
24450b57cec5SDimitry Andric   // First, construct the forward decl.  Don't look into Ty to compute the
24460b57cec5SDimitry Andric   // forward decl options, since it might not be available in all TUs.
24470b57cec5SDimitry Andric   TypeRecordKind Kind = getRecordKind(Ty);
24480b57cec5SDimitry Andric   ClassOptions CO =
24490b57cec5SDimitry Andric       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
24500b57cec5SDimitry Andric   std::string FullName = getFullyQualifiedName(Ty);
24510b57cec5SDimitry Andric   ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
24520b57cec5SDimitry Andric                  FullName, Ty->getIdentifier());
24530b57cec5SDimitry Andric   TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
24540b57cec5SDimitry Andric   if (!Ty->isForwardDecl())
24550b57cec5SDimitry Andric     DeferredCompleteTypes.push_back(Ty);
24560b57cec5SDimitry Andric   return FwdDeclTI;
24570b57cec5SDimitry Andric }
24580b57cec5SDimitry Andric 
lowerCompleteTypeClass(const DICompositeType * Ty)24590b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
24600b57cec5SDimitry Andric   // Construct the field list and complete type record.
24610b57cec5SDimitry Andric   TypeRecordKind Kind = getRecordKind(Ty);
24620b57cec5SDimitry Andric   ClassOptions CO = getCommonClassOptions(Ty);
24630b57cec5SDimitry Andric   TypeIndex FieldTI;
24640b57cec5SDimitry Andric   TypeIndex VShapeTI;
24650b57cec5SDimitry Andric   unsigned FieldCount;
24660b57cec5SDimitry Andric   bool ContainsNestedClass;
24670b57cec5SDimitry Andric   std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
24680b57cec5SDimitry Andric       lowerRecordFieldList(Ty);
24690b57cec5SDimitry Andric 
24700b57cec5SDimitry Andric   if (ContainsNestedClass)
24710b57cec5SDimitry Andric     CO |= ClassOptions::ContainsNestedClass;
24720b57cec5SDimitry Andric 
24730b57cec5SDimitry Andric   // MSVC appears to set this flag by searching any destructor or method with
24740b57cec5SDimitry Andric   // FunctionOptions::Constructor among the emitted members. Clang AST has all
24750b57cec5SDimitry Andric   // the members, however special member functions are not yet emitted into
24760b57cec5SDimitry Andric   // debug information. For now checking a class's non-triviality seems enough.
24770b57cec5SDimitry Andric   // FIXME: not true for a nested unnamed struct.
24780b57cec5SDimitry Andric   if (isNonTrivial(Ty))
24790b57cec5SDimitry Andric     CO |= ClassOptions::HasConstructorOrDestructor;
24800b57cec5SDimitry Andric 
24810b57cec5SDimitry Andric   std::string FullName = getFullyQualifiedName(Ty);
24820b57cec5SDimitry Andric 
24830b57cec5SDimitry Andric   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
24840b57cec5SDimitry Andric 
24850b57cec5SDimitry Andric   ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
24860b57cec5SDimitry Andric                  SizeInBytes, FullName, Ty->getIdentifier());
24870b57cec5SDimitry Andric   TypeIndex ClassTI = TypeTable.writeLeafType(CR);
24880b57cec5SDimitry Andric 
24890b57cec5SDimitry Andric   addUDTSrcLine(Ty, ClassTI);
24900b57cec5SDimitry Andric 
24910b57cec5SDimitry Andric   addToUDTs(Ty);
24920b57cec5SDimitry Andric 
24930b57cec5SDimitry Andric   return ClassTI;
24940b57cec5SDimitry Andric }
24950b57cec5SDimitry Andric 
lowerTypeUnion(const DICompositeType * Ty)24960b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
24970b57cec5SDimitry Andric   // Emit the complete type for unnamed unions.
24980b57cec5SDimitry Andric   if (shouldAlwaysEmitCompleteClassType(Ty))
24990b57cec5SDimitry Andric     return getCompleteTypeIndex(Ty);
25000b57cec5SDimitry Andric 
25010b57cec5SDimitry Andric   ClassOptions CO =
25020b57cec5SDimitry Andric       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
25030b57cec5SDimitry Andric   std::string FullName = getFullyQualifiedName(Ty);
25040b57cec5SDimitry Andric   UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
25050b57cec5SDimitry Andric   TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
25060b57cec5SDimitry Andric   if (!Ty->isForwardDecl())
25070b57cec5SDimitry Andric     DeferredCompleteTypes.push_back(Ty);
25080b57cec5SDimitry Andric   return FwdDeclTI;
25090b57cec5SDimitry Andric }
25100b57cec5SDimitry Andric 
lowerCompleteTypeUnion(const DICompositeType * Ty)25110b57cec5SDimitry Andric TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
25120b57cec5SDimitry Andric   ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
25130b57cec5SDimitry Andric   TypeIndex FieldTI;
25140b57cec5SDimitry Andric   unsigned FieldCount;
25150b57cec5SDimitry Andric   bool ContainsNestedClass;
25160b57cec5SDimitry Andric   std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
25170b57cec5SDimitry Andric       lowerRecordFieldList(Ty);
25180b57cec5SDimitry Andric 
25190b57cec5SDimitry Andric   if (ContainsNestedClass)
25200b57cec5SDimitry Andric     CO |= ClassOptions::ContainsNestedClass;
25210b57cec5SDimitry Andric 
25220b57cec5SDimitry Andric   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
25230b57cec5SDimitry Andric   std::string FullName = getFullyQualifiedName(Ty);
25240b57cec5SDimitry Andric 
25250b57cec5SDimitry Andric   UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
25260b57cec5SDimitry Andric                  Ty->getIdentifier());
25270b57cec5SDimitry Andric   TypeIndex UnionTI = TypeTable.writeLeafType(UR);
25280b57cec5SDimitry Andric 
25290b57cec5SDimitry Andric   addUDTSrcLine(Ty, UnionTI);
25300b57cec5SDimitry Andric 
25310b57cec5SDimitry Andric   addToUDTs(Ty);
25320b57cec5SDimitry Andric 
25330b57cec5SDimitry Andric   return UnionTI;
25340b57cec5SDimitry Andric }
25350b57cec5SDimitry Andric 
25360b57cec5SDimitry Andric std::tuple<TypeIndex, TypeIndex, unsigned, bool>
lowerRecordFieldList(const DICompositeType * Ty)25370b57cec5SDimitry Andric CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
25380b57cec5SDimitry Andric   // Manually count members. MSVC appears to count everything that generates a
25390b57cec5SDimitry Andric   // field list record. Each individual overload in a method overload group
25400b57cec5SDimitry Andric   // contributes to this count, even though the overload group is a single field
25410b57cec5SDimitry Andric   // list record.
25420b57cec5SDimitry Andric   unsigned MemberCount = 0;
25430b57cec5SDimitry Andric   ClassInfo Info = collectClassInfo(Ty);
25440b57cec5SDimitry Andric   ContinuationRecordBuilder ContinuationBuilder;
25450b57cec5SDimitry Andric   ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
25460b57cec5SDimitry Andric 
25470b57cec5SDimitry Andric   // Create base classes.
25480b57cec5SDimitry Andric   for (const DIDerivedType *I : Info.Inheritance) {
25490b57cec5SDimitry Andric     if (I->getFlags() & DINode::FlagVirtual) {
25500b57cec5SDimitry Andric       // Virtual base.
25510b57cec5SDimitry Andric       unsigned VBPtrOffset = I->getVBPtrOffset();
25520b57cec5SDimitry Andric       // FIXME: Despite the accessor name, the offset is really in bytes.
25530b57cec5SDimitry Andric       unsigned VBTableIndex = I->getOffsetInBits() / 4;
25540b57cec5SDimitry Andric       auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
25550b57cec5SDimitry Andric                             ? TypeRecordKind::IndirectVirtualBaseClass
25560b57cec5SDimitry Andric                             : TypeRecordKind::VirtualBaseClass;
25570b57cec5SDimitry Andric       VirtualBaseClassRecord VBCR(
25580b57cec5SDimitry Andric           RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
25590b57cec5SDimitry Andric           getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
25600b57cec5SDimitry Andric           VBTableIndex);
25610b57cec5SDimitry Andric 
25620b57cec5SDimitry Andric       ContinuationBuilder.writeMemberType(VBCR);
25630b57cec5SDimitry Andric       MemberCount++;
25640b57cec5SDimitry Andric     } else {
25650b57cec5SDimitry Andric       assert(I->getOffsetInBits() % 8 == 0 &&
25660b57cec5SDimitry Andric              "bases must be on byte boundaries");
25670b57cec5SDimitry Andric       BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
25680b57cec5SDimitry Andric                           getTypeIndex(I->getBaseType()),
25690b57cec5SDimitry Andric                           I->getOffsetInBits() / 8);
25700b57cec5SDimitry Andric       ContinuationBuilder.writeMemberType(BCR);
25710b57cec5SDimitry Andric       MemberCount++;
25720b57cec5SDimitry Andric     }
25730b57cec5SDimitry Andric   }
25740b57cec5SDimitry Andric 
25750b57cec5SDimitry Andric   // Create members.
25760b57cec5SDimitry Andric   for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
25770b57cec5SDimitry Andric     const DIDerivedType *Member = MemberInfo.MemberTypeNode;
25780b57cec5SDimitry Andric     TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
25790b57cec5SDimitry Andric     StringRef MemberName = Member->getName();
25800b57cec5SDimitry Andric     MemberAccess Access =
25810b57cec5SDimitry Andric         translateAccessFlags(Ty->getTag(), Member->getFlags());
25820b57cec5SDimitry Andric 
25830b57cec5SDimitry Andric     if (Member->isStaticMember()) {
25840b57cec5SDimitry Andric       StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
25850b57cec5SDimitry Andric       ContinuationBuilder.writeMemberType(SDMR);
25860b57cec5SDimitry Andric       MemberCount++;
25870b57cec5SDimitry Andric       continue;
25880b57cec5SDimitry Andric     }
25890b57cec5SDimitry Andric 
25900b57cec5SDimitry Andric     // Virtual function pointer member.
25910b57cec5SDimitry Andric     if ((Member->getFlags() & DINode::FlagArtificial) &&
25925f757f3fSDimitry Andric         Member->getName().starts_with("_vptr$")) {
25930b57cec5SDimitry Andric       VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
25940b57cec5SDimitry Andric       ContinuationBuilder.writeMemberType(VFPR);
25950b57cec5SDimitry Andric       MemberCount++;
25960b57cec5SDimitry Andric       continue;
25970b57cec5SDimitry Andric     }
25980b57cec5SDimitry Andric 
25990b57cec5SDimitry Andric     // Data member.
26000b57cec5SDimitry Andric     uint64_t MemberOffsetInBits =
26010b57cec5SDimitry Andric         Member->getOffsetInBits() + MemberInfo.BaseOffset;
26020b57cec5SDimitry Andric     if (Member->isBitField()) {
26030b57cec5SDimitry Andric       uint64_t StartBitOffset = MemberOffsetInBits;
26040b57cec5SDimitry Andric       if (const auto *CI =
26050b57cec5SDimitry Andric               dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
26060b57cec5SDimitry Andric         MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
26070b57cec5SDimitry Andric       }
26080b57cec5SDimitry Andric       StartBitOffset -= MemberOffsetInBits;
26090b57cec5SDimitry Andric       BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
26100b57cec5SDimitry Andric                          StartBitOffset);
26110b57cec5SDimitry Andric       MemberBaseType = TypeTable.writeLeafType(BFR);
26120b57cec5SDimitry Andric     }
26130b57cec5SDimitry Andric     uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
26140b57cec5SDimitry Andric     DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
26150b57cec5SDimitry Andric                          MemberName);
26160b57cec5SDimitry Andric     ContinuationBuilder.writeMemberType(DMR);
26170b57cec5SDimitry Andric     MemberCount++;
26180b57cec5SDimitry Andric   }
26190b57cec5SDimitry Andric 
26200b57cec5SDimitry Andric   // Create methods
26210b57cec5SDimitry Andric   for (auto &MethodItr : Info.Methods) {
26220b57cec5SDimitry Andric     StringRef Name = MethodItr.first->getString();
26230b57cec5SDimitry Andric 
26240b57cec5SDimitry Andric     std::vector<OneMethodRecord> Methods;
26250b57cec5SDimitry Andric     for (const DISubprogram *SP : MethodItr.second) {
26260b57cec5SDimitry Andric       TypeIndex MethodType = getMemberFunctionType(SP, Ty);
26270b57cec5SDimitry Andric       bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
26280b57cec5SDimitry Andric 
26290b57cec5SDimitry Andric       unsigned VFTableOffset = -1;
26300b57cec5SDimitry Andric       if (Introduced)
26310b57cec5SDimitry Andric         VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
26320b57cec5SDimitry Andric 
26330b57cec5SDimitry Andric       Methods.push_back(OneMethodRecord(
26340b57cec5SDimitry Andric           MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
26350b57cec5SDimitry Andric           translateMethodKindFlags(SP, Introduced),
26360b57cec5SDimitry Andric           translateMethodOptionFlags(SP), VFTableOffset, Name));
26370b57cec5SDimitry Andric       MemberCount++;
26380b57cec5SDimitry Andric     }
26390b57cec5SDimitry Andric     assert(!Methods.empty() && "Empty methods map entry");
26400b57cec5SDimitry Andric     if (Methods.size() == 1)
26410b57cec5SDimitry Andric       ContinuationBuilder.writeMemberType(Methods[0]);
26420b57cec5SDimitry Andric     else {
26430b57cec5SDimitry Andric       // FIXME: Make this use its own ContinuationBuilder so that
26440b57cec5SDimitry Andric       // MethodOverloadList can be split correctly.
26450b57cec5SDimitry Andric       MethodOverloadListRecord MOLR(Methods);
26460b57cec5SDimitry Andric       TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
26470b57cec5SDimitry Andric 
26480b57cec5SDimitry Andric       OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
26490b57cec5SDimitry Andric       ContinuationBuilder.writeMemberType(OMR);
26500b57cec5SDimitry Andric     }
26510b57cec5SDimitry Andric   }
26520b57cec5SDimitry Andric 
26530b57cec5SDimitry Andric   // Create nested classes.
26540b57cec5SDimitry Andric   for (const DIType *Nested : Info.NestedTypes) {
26550b57cec5SDimitry Andric     NestedTypeRecord R(getTypeIndex(Nested), Nested->getName());
26560b57cec5SDimitry Andric     ContinuationBuilder.writeMemberType(R);
26570b57cec5SDimitry Andric     MemberCount++;
26580b57cec5SDimitry Andric   }
26590b57cec5SDimitry Andric 
26600b57cec5SDimitry Andric   TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
26610b57cec5SDimitry Andric   return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
26620b57cec5SDimitry Andric                          !Info.NestedTypes.empty());
26630b57cec5SDimitry Andric }
26640b57cec5SDimitry Andric 
getVBPTypeIndex()26650b57cec5SDimitry Andric TypeIndex CodeViewDebug::getVBPTypeIndex() {
26660b57cec5SDimitry Andric   if (!VBPType.getIndex()) {
26670b57cec5SDimitry Andric     // Make a 'const int *' type.
26680b57cec5SDimitry Andric     ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
26690b57cec5SDimitry Andric     TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
26700b57cec5SDimitry Andric 
26710b57cec5SDimitry Andric     PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
26720b57cec5SDimitry Andric                                                   : PointerKind::Near32;
26730b57cec5SDimitry Andric     PointerMode PM = PointerMode::Pointer;
26740b57cec5SDimitry Andric     PointerOptions PO = PointerOptions::None;
26750b57cec5SDimitry Andric     PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
26760b57cec5SDimitry Andric     VBPType = TypeTable.writeLeafType(PR);
26770b57cec5SDimitry Andric   }
26780b57cec5SDimitry Andric 
26790b57cec5SDimitry Andric   return VBPType;
26800b57cec5SDimitry Andric }
26810b57cec5SDimitry Andric 
getTypeIndex(const DIType * Ty,const DIType * ClassTy)26820b57cec5SDimitry Andric TypeIndex CodeViewDebug::getTypeIndex(const DIType *Ty, const DIType *ClassTy) {
26830b57cec5SDimitry Andric   // The null DIType is the void type. Don't try to hash it.
26840b57cec5SDimitry Andric   if (!Ty)
26850b57cec5SDimitry Andric     return TypeIndex::Void();
26860b57cec5SDimitry Andric 
26870b57cec5SDimitry Andric   // Check if we've already translated this type. Don't try to do a
26880b57cec5SDimitry Andric   // get-or-create style insertion that caches the hash lookup across the
26890b57cec5SDimitry Andric   // lowerType call. It will update the TypeIndices map.
26900b57cec5SDimitry Andric   auto I = TypeIndices.find({Ty, ClassTy});
26910b57cec5SDimitry Andric   if (I != TypeIndices.end())
26920b57cec5SDimitry Andric     return I->second;
26930b57cec5SDimitry Andric 
26940b57cec5SDimitry Andric   TypeLoweringScope S(*this);
26950b57cec5SDimitry Andric   TypeIndex TI = lowerType(Ty, ClassTy);
26960b57cec5SDimitry Andric   return recordTypeIndexForDINode(Ty, TI, ClassTy);
26970b57cec5SDimitry Andric }
26980b57cec5SDimitry Andric 
26990b57cec5SDimitry Andric codeview::TypeIndex
getTypeIndexForThisPtr(const DIDerivedType * PtrTy,const DISubroutineType * SubroutineTy)27000b57cec5SDimitry Andric CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy,
27010b57cec5SDimitry Andric                                       const DISubroutineType *SubroutineTy) {
27020b57cec5SDimitry Andric   assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type &&
27030b57cec5SDimitry Andric          "this type must be a pointer type");
27040b57cec5SDimitry Andric 
27050b57cec5SDimitry Andric   PointerOptions Options = PointerOptions::None;
27060b57cec5SDimitry Andric   if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference)
27070b57cec5SDimitry Andric     Options = PointerOptions::LValueRefThisPointer;
27080b57cec5SDimitry Andric   else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference)
27090b57cec5SDimitry Andric     Options = PointerOptions::RValueRefThisPointer;
27100b57cec5SDimitry Andric 
27110b57cec5SDimitry Andric   // Check if we've already translated this type.  If there is no ref qualifier
27120b57cec5SDimitry Andric   // on the function then we look up this pointer type with no associated class
27130b57cec5SDimitry Andric   // so that the TypeIndex for the this pointer can be shared with the type
27140b57cec5SDimitry Andric   // index for other pointers to this class type.  If there is a ref qualifier
27150b57cec5SDimitry Andric   // then we lookup the pointer using the subroutine as the parent type.
27160b57cec5SDimitry Andric   auto I = TypeIndices.find({PtrTy, SubroutineTy});
27170b57cec5SDimitry Andric   if (I != TypeIndices.end())
27180b57cec5SDimitry Andric     return I->second;
27190b57cec5SDimitry Andric 
27200b57cec5SDimitry Andric   TypeLoweringScope S(*this);
27210b57cec5SDimitry Andric   TypeIndex TI = lowerTypePointer(PtrTy, Options);
27220b57cec5SDimitry Andric   return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy);
27230b57cec5SDimitry Andric }
27240b57cec5SDimitry Andric 
getTypeIndexForReferenceTo(const DIType * Ty)27250b57cec5SDimitry Andric TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(const DIType *Ty) {
27260b57cec5SDimitry Andric   PointerRecord PR(getTypeIndex(Ty),
27270b57cec5SDimitry Andric                    getPointerSizeInBytes() == 8 ? PointerKind::Near64
27280b57cec5SDimitry Andric                                                 : PointerKind::Near32,
27290b57cec5SDimitry Andric                    PointerMode::LValueReference, PointerOptions::None,
27300b57cec5SDimitry Andric                    Ty->getSizeInBits() / 8);
27310b57cec5SDimitry Andric   return TypeTable.writeLeafType(PR);
27320b57cec5SDimitry Andric }
27330b57cec5SDimitry Andric 
getCompleteTypeIndex(const DIType * Ty)27340b57cec5SDimitry Andric TypeIndex CodeViewDebug::getCompleteTypeIndex(const DIType *Ty) {
27350b57cec5SDimitry Andric   // The null DIType is the void type. Don't try to hash it.
27360b57cec5SDimitry Andric   if (!Ty)
27370b57cec5SDimitry Andric     return TypeIndex::Void();
27380b57cec5SDimitry Andric 
27390b57cec5SDimitry Andric   // Look through typedefs when getting the complete type index. Call
27400b57cec5SDimitry Andric   // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are
27410b57cec5SDimitry Andric   // emitted only once.
27420b57cec5SDimitry Andric   if (Ty->getTag() == dwarf::DW_TAG_typedef)
27430b57cec5SDimitry Andric     (void)getTypeIndex(Ty);
27440b57cec5SDimitry Andric   while (Ty->getTag() == dwarf::DW_TAG_typedef)
27450b57cec5SDimitry Andric     Ty = cast<DIDerivedType>(Ty)->getBaseType();
27460b57cec5SDimitry Andric 
27470b57cec5SDimitry Andric   // If this is a non-record type, the complete type index is the same as the
27480b57cec5SDimitry Andric   // normal type index. Just call getTypeIndex.
27490b57cec5SDimitry Andric   switch (Ty->getTag()) {
27500b57cec5SDimitry Andric   case dwarf::DW_TAG_class_type:
27510b57cec5SDimitry Andric   case dwarf::DW_TAG_structure_type:
27520b57cec5SDimitry Andric   case dwarf::DW_TAG_union_type:
27530b57cec5SDimitry Andric     break;
27540b57cec5SDimitry Andric   default:
27550b57cec5SDimitry Andric     return getTypeIndex(Ty);
27560b57cec5SDimitry Andric   }
27570b57cec5SDimitry Andric 
27580b57cec5SDimitry Andric   const auto *CTy = cast<DICompositeType>(Ty);
27590b57cec5SDimitry Andric 
27600b57cec5SDimitry Andric   TypeLoweringScope S(*this);
27610b57cec5SDimitry Andric 
27620b57cec5SDimitry Andric   // Make sure the forward declaration is emitted first. It's unclear if this
27630b57cec5SDimitry Andric   // is necessary, but MSVC does it, and we should follow suit until we can show
27640b57cec5SDimitry Andric   // otherwise.
27650b57cec5SDimitry Andric   // We only emit a forward declaration for named types.
27660b57cec5SDimitry Andric   if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
27670b57cec5SDimitry Andric     TypeIndex FwdDeclTI = getTypeIndex(CTy);
27680b57cec5SDimitry Andric 
27690b57cec5SDimitry Andric     // Just use the forward decl if we don't have complete type info. This
27700b57cec5SDimitry Andric     // might happen if the frontend is using modules and expects the complete
27710b57cec5SDimitry Andric     // definition to be emitted elsewhere.
27720b57cec5SDimitry Andric     if (CTy->isForwardDecl())
27730b57cec5SDimitry Andric       return FwdDeclTI;
27740b57cec5SDimitry Andric   }
27750b57cec5SDimitry Andric 
27760b57cec5SDimitry Andric   // Check if we've already translated the complete record type.
27770b57cec5SDimitry Andric   // Insert the type with a null TypeIndex to signify that the type is currently
27780b57cec5SDimitry Andric   // being lowered.
27790b57cec5SDimitry Andric   auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
27800b57cec5SDimitry Andric   if (!InsertResult.second)
27810b57cec5SDimitry Andric     return InsertResult.first->second;
27820b57cec5SDimitry Andric 
27830b57cec5SDimitry Andric   TypeIndex TI;
27840b57cec5SDimitry Andric   switch (CTy->getTag()) {
27850b57cec5SDimitry Andric   case dwarf::DW_TAG_class_type:
27860b57cec5SDimitry Andric   case dwarf::DW_TAG_structure_type:
27870b57cec5SDimitry Andric     TI = lowerCompleteTypeClass(CTy);
27880b57cec5SDimitry Andric     break;
27890b57cec5SDimitry Andric   case dwarf::DW_TAG_union_type:
27900b57cec5SDimitry Andric     TI = lowerCompleteTypeUnion(CTy);
27910b57cec5SDimitry Andric     break;
27920b57cec5SDimitry Andric   default:
27930b57cec5SDimitry Andric     llvm_unreachable("not a record");
27940b57cec5SDimitry Andric   }
27950b57cec5SDimitry Andric 
27960b57cec5SDimitry Andric   // Update the type index associated with this CompositeType.  This cannot
27970b57cec5SDimitry Andric   // use the 'InsertResult' iterator above because it is potentially
27980b57cec5SDimitry Andric   // invalidated by map insertions which can occur while lowering the class
27990b57cec5SDimitry Andric   // type above.
28000b57cec5SDimitry Andric   CompleteTypeIndices[CTy] = TI;
28010b57cec5SDimitry Andric   return TI;
28020b57cec5SDimitry Andric }
28030b57cec5SDimitry Andric 
28040b57cec5SDimitry Andric /// Emit all the deferred complete record types. Try to do this in FIFO order,
28050b57cec5SDimitry Andric /// and do this until fixpoint, as each complete record type typically
28060b57cec5SDimitry Andric /// references
28070b57cec5SDimitry Andric /// many other record types.
emitDeferredCompleteTypes()28080b57cec5SDimitry Andric void CodeViewDebug::emitDeferredCompleteTypes() {
28090b57cec5SDimitry Andric   SmallVector<const DICompositeType *, 4> TypesToEmit;
28100b57cec5SDimitry Andric   while (!DeferredCompleteTypes.empty()) {
28110b57cec5SDimitry Andric     std::swap(DeferredCompleteTypes, TypesToEmit);
28120b57cec5SDimitry Andric     for (const DICompositeType *RecordTy : TypesToEmit)
28130b57cec5SDimitry Andric       getCompleteTypeIndex(RecordTy);
28140b57cec5SDimitry Andric     TypesToEmit.clear();
28150b57cec5SDimitry Andric   }
28160b57cec5SDimitry Andric }
28170b57cec5SDimitry Andric 
emitLocalVariableList(const FunctionInfo & FI,ArrayRef<LocalVariable> Locals)28180b57cec5SDimitry Andric void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
28190b57cec5SDimitry Andric                                           ArrayRef<LocalVariable> Locals) {
28200b57cec5SDimitry Andric   // Get the sorted list of parameters and emit them first.
28210b57cec5SDimitry Andric   SmallVector<const LocalVariable *, 6> Params;
28220b57cec5SDimitry Andric   for (const LocalVariable &L : Locals)
28230b57cec5SDimitry Andric     if (L.DIVar->isParameter())
28240b57cec5SDimitry Andric       Params.push_back(&L);
28250b57cec5SDimitry Andric   llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
28260b57cec5SDimitry Andric     return L->DIVar->getArg() < R->DIVar->getArg();
28270b57cec5SDimitry Andric   });
28280b57cec5SDimitry Andric   for (const LocalVariable *L : Params)
28290b57cec5SDimitry Andric     emitLocalVariable(FI, *L);
28300b57cec5SDimitry Andric 
28310b57cec5SDimitry Andric   // Next emit all non-parameters in the order that we found them.
2832bdd1243dSDimitry Andric   for (const LocalVariable &L : Locals) {
2833bdd1243dSDimitry Andric     if (!L.DIVar->isParameter()) {
2834bdd1243dSDimitry Andric       if (L.ConstantValue) {
2835bdd1243dSDimitry Andric         // If ConstantValue is set we will emit it as a S_CONSTANT instead of a
2836bdd1243dSDimitry Andric         // S_LOCAL in order to be able to represent it at all.
2837bdd1243dSDimitry Andric         const DIType *Ty = L.DIVar->getType();
2838bdd1243dSDimitry Andric         APSInt Val(*L.ConstantValue);
2839bdd1243dSDimitry Andric         emitConstantSymbolRecord(Ty, Val, std::string(L.DIVar->getName()));
2840bdd1243dSDimitry Andric       } else {
28410b57cec5SDimitry Andric         emitLocalVariable(FI, L);
28420b57cec5SDimitry Andric       }
2843bdd1243dSDimitry Andric     }
2844bdd1243dSDimitry Andric   }
2845bdd1243dSDimitry Andric }
28460b57cec5SDimitry Andric 
emitLocalVariable(const FunctionInfo & FI,const LocalVariable & Var)28470b57cec5SDimitry Andric void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
28480b57cec5SDimitry Andric                                       const LocalVariable &Var) {
28490b57cec5SDimitry Andric   // LocalSym record, see SymbolRecord.h for more info.
28500b57cec5SDimitry Andric   MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL);
28510b57cec5SDimitry Andric 
28520b57cec5SDimitry Andric   LocalSymFlags Flags = LocalSymFlags::None;
28530b57cec5SDimitry Andric   if (Var.DIVar->isParameter())
28540b57cec5SDimitry Andric     Flags |= LocalSymFlags::IsParameter;
28550b57cec5SDimitry Andric   if (Var.DefRanges.empty())
28560b57cec5SDimitry Andric     Flags |= LocalSymFlags::IsOptimizedOut;
28570b57cec5SDimitry Andric 
28580b57cec5SDimitry Andric   OS.AddComment("TypeIndex");
28590b57cec5SDimitry Andric   TypeIndex TI = Var.UseReferenceType
28600b57cec5SDimitry Andric                      ? getTypeIndexForReferenceTo(Var.DIVar->getType())
28610b57cec5SDimitry Andric                      : getCompleteTypeIndex(Var.DIVar->getType());
28625ffd83dbSDimitry Andric   OS.emitInt32(TI.getIndex());
28630b57cec5SDimitry Andric   OS.AddComment("Flags");
28645ffd83dbSDimitry Andric   OS.emitInt16(static_cast<uint16_t>(Flags));
28650b57cec5SDimitry Andric   // Truncate the name so we won't overflow the record length field.
28660b57cec5SDimitry Andric   emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
28670b57cec5SDimitry Andric   endSymbolRecord(LocalEnd);
28680b57cec5SDimitry Andric 
28690b57cec5SDimitry Andric   // Calculate the on disk prefix of the appropriate def range record. The
28700b57cec5SDimitry Andric   // records and on disk formats are described in SymbolRecords.h. BytePrefix
28710b57cec5SDimitry Andric   // should be big enough to hold all forms without memory allocation.
28720b57cec5SDimitry Andric   SmallString<20> BytePrefix;
287381ad6265SDimitry Andric   for (const auto &Pair : Var.DefRanges) {
287481ad6265SDimitry Andric     LocalVarDef DefRange = Pair.first;
287581ad6265SDimitry Andric     const auto &Ranges = Pair.second;
28760b57cec5SDimitry Andric     BytePrefix.clear();
28770b57cec5SDimitry Andric     if (DefRange.InMemory) {
28780b57cec5SDimitry Andric       int Offset = DefRange.DataOffset;
28790b57cec5SDimitry Andric       unsigned Reg = DefRange.CVRegister;
28800b57cec5SDimitry Andric 
28810b57cec5SDimitry Andric       // 32-bit x86 call sequences often use PUSH instructions, which disrupt
28820b57cec5SDimitry Andric       // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
28830b57cec5SDimitry Andric       // instead. In frames without stack realignment, $T0 will be the CFA.
28840b57cec5SDimitry Andric       if (RegisterId(Reg) == RegisterId::ESP) {
28850b57cec5SDimitry Andric         Reg = unsigned(RegisterId::VFRAME);
28860b57cec5SDimitry Andric         Offset += FI.OffsetAdjustment;
28870b57cec5SDimitry Andric       }
28880b57cec5SDimitry Andric 
28890b57cec5SDimitry Andric       // If we can use the chosen frame pointer for the frame and this isn't a
28900b57cec5SDimitry Andric       // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
28910b57cec5SDimitry Andric       // Otherwise, use S_DEFRANGE_REGISTER_REL.
28920b57cec5SDimitry Andric       EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU);
28930b57cec5SDimitry Andric       if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
28940b57cec5SDimitry Andric           (bool(Flags & LocalSymFlags::IsParameter)
28950b57cec5SDimitry Andric                ? (EncFP == FI.EncodedParamFramePtrReg)
28960b57cec5SDimitry Andric                : (EncFP == FI.EncodedLocalFramePtrReg))) {
28978bcb0991SDimitry Andric         DefRangeFramePointerRelHeader DRHdr;
28988bcb0991SDimitry Andric         DRHdr.Offset = Offset;
289981ad6265SDimitry Andric         OS.emitCVDefRangeDirective(Ranges, DRHdr);
29000b57cec5SDimitry Andric       } else {
29010b57cec5SDimitry Andric         uint16_t RegRelFlags = 0;
29020b57cec5SDimitry Andric         if (DefRange.IsSubfield) {
29030b57cec5SDimitry Andric           RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
29040b57cec5SDimitry Andric                         (DefRange.StructOffset
29050b57cec5SDimitry Andric                          << DefRangeRegisterRelSym::OffsetInParentShift);
29060b57cec5SDimitry Andric         }
29078bcb0991SDimitry Andric         DefRangeRegisterRelHeader DRHdr;
29080b57cec5SDimitry Andric         DRHdr.Register = Reg;
29090b57cec5SDimitry Andric         DRHdr.Flags = RegRelFlags;
29100b57cec5SDimitry Andric         DRHdr.BasePointerOffset = Offset;
291181ad6265SDimitry Andric         OS.emitCVDefRangeDirective(Ranges, DRHdr);
29120b57cec5SDimitry Andric       }
29130b57cec5SDimitry Andric     } else {
29140b57cec5SDimitry Andric       assert(DefRange.DataOffset == 0 && "unexpected offset into register");
29150b57cec5SDimitry Andric       if (DefRange.IsSubfield) {
29168bcb0991SDimitry Andric         DefRangeSubfieldRegisterHeader DRHdr;
29170b57cec5SDimitry Andric         DRHdr.Register = DefRange.CVRegister;
29180b57cec5SDimitry Andric         DRHdr.MayHaveNoName = 0;
29190b57cec5SDimitry Andric         DRHdr.OffsetInParent = DefRange.StructOffset;
292081ad6265SDimitry Andric         OS.emitCVDefRangeDirective(Ranges, DRHdr);
29210b57cec5SDimitry Andric       } else {
29228bcb0991SDimitry Andric         DefRangeRegisterHeader DRHdr;
29230b57cec5SDimitry Andric         DRHdr.Register = DefRange.CVRegister;
29240b57cec5SDimitry Andric         DRHdr.MayHaveNoName = 0;
292581ad6265SDimitry Andric         OS.emitCVDefRangeDirective(Ranges, DRHdr);
29260b57cec5SDimitry Andric       }
29270b57cec5SDimitry Andric     }
29280b57cec5SDimitry Andric   }
29290b57cec5SDimitry Andric }
29300b57cec5SDimitry Andric 
emitLexicalBlockList(ArrayRef<LexicalBlock * > Blocks,const FunctionInfo & FI)29310b57cec5SDimitry Andric void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
29320b57cec5SDimitry Andric                                          const FunctionInfo& FI) {
29330b57cec5SDimitry Andric   for (LexicalBlock *Block : Blocks)
29340b57cec5SDimitry Andric     emitLexicalBlock(*Block, FI);
29350b57cec5SDimitry Andric }
29360b57cec5SDimitry Andric 
29370b57cec5SDimitry Andric /// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
29380b57cec5SDimitry Andric /// lexical block scope.
emitLexicalBlock(const LexicalBlock & Block,const FunctionInfo & FI)29390b57cec5SDimitry Andric void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
29400b57cec5SDimitry Andric                                      const FunctionInfo& FI) {
29410b57cec5SDimitry Andric   MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32);
29420b57cec5SDimitry Andric   OS.AddComment("PtrParent");
29435ffd83dbSDimitry Andric   OS.emitInt32(0); // PtrParent
29440b57cec5SDimitry Andric   OS.AddComment("PtrEnd");
29455ffd83dbSDimitry Andric   OS.emitInt32(0); // PtrEnd
29460b57cec5SDimitry Andric   OS.AddComment("Code size");
29470b57cec5SDimitry Andric   OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4);   // Code Size
29480b57cec5SDimitry Andric   OS.AddComment("Function section relative address");
294981ad6265SDimitry Andric   OS.emitCOFFSecRel32(Block.Begin, /*Offset=*/0); // Func Offset
29500b57cec5SDimitry Andric   OS.AddComment("Function section index");
295181ad6265SDimitry Andric   OS.emitCOFFSectionIndex(FI.Begin); // Func Symbol
29520b57cec5SDimitry Andric   OS.AddComment("Lexical block name");
29530b57cec5SDimitry Andric   emitNullTerminatedSymbolName(OS, Block.Name);           // Name
29540b57cec5SDimitry Andric   endSymbolRecord(RecordEnd);
29550b57cec5SDimitry Andric 
29560b57cec5SDimitry Andric   // Emit variables local to this lexical block.
29570b57cec5SDimitry Andric   emitLocalVariableList(FI, Block.Locals);
29580b57cec5SDimitry Andric   emitGlobalVariableList(Block.Globals);
29590b57cec5SDimitry Andric 
29600b57cec5SDimitry Andric   // Emit lexical blocks contained within this block.
29610b57cec5SDimitry Andric   emitLexicalBlockList(Block.Children, FI);
29620b57cec5SDimitry Andric 
29630b57cec5SDimitry Andric   // Close the lexical block scope.
29640b57cec5SDimitry Andric   emitEndSymbolRecord(SymbolKind::S_END);
29650b57cec5SDimitry Andric }
29660b57cec5SDimitry Andric 
29670b57cec5SDimitry Andric /// Convenience routine for collecting lexical block information for a list
29680b57cec5SDimitry Andric /// of lexical scopes.
collectLexicalBlockInfo(SmallVectorImpl<LexicalScope * > & Scopes,SmallVectorImpl<LexicalBlock * > & Blocks,SmallVectorImpl<LocalVariable> & Locals,SmallVectorImpl<CVGlobalVariable> & Globals)29690b57cec5SDimitry Andric void CodeViewDebug::collectLexicalBlockInfo(
29700b57cec5SDimitry Andric         SmallVectorImpl<LexicalScope *> &Scopes,
29710b57cec5SDimitry Andric         SmallVectorImpl<LexicalBlock *> &Blocks,
29720b57cec5SDimitry Andric         SmallVectorImpl<LocalVariable> &Locals,
29730b57cec5SDimitry Andric         SmallVectorImpl<CVGlobalVariable> &Globals) {
29740b57cec5SDimitry Andric   for (LexicalScope *Scope : Scopes)
29750b57cec5SDimitry Andric     collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals);
29760b57cec5SDimitry Andric }
29770b57cec5SDimitry Andric 
29780b57cec5SDimitry Andric /// Populate the lexical blocks and local variable lists of the parent with
29790b57cec5SDimitry Andric /// information about the specified lexical scope.
collectLexicalBlockInfo(LexicalScope & Scope,SmallVectorImpl<LexicalBlock * > & ParentBlocks,SmallVectorImpl<LocalVariable> & ParentLocals,SmallVectorImpl<CVGlobalVariable> & ParentGlobals)29800b57cec5SDimitry Andric void CodeViewDebug::collectLexicalBlockInfo(
29810b57cec5SDimitry Andric     LexicalScope &Scope,
29820b57cec5SDimitry Andric     SmallVectorImpl<LexicalBlock *> &ParentBlocks,
29830b57cec5SDimitry Andric     SmallVectorImpl<LocalVariable> &ParentLocals,
29840b57cec5SDimitry Andric     SmallVectorImpl<CVGlobalVariable> &ParentGlobals) {
29850b57cec5SDimitry Andric   if (Scope.isAbstractScope())
29860b57cec5SDimitry Andric     return;
29870b57cec5SDimitry Andric 
29880b57cec5SDimitry Andric   // Gather information about the lexical scope including local variables,
29890b57cec5SDimitry Andric   // global variables, and address ranges.
29900b57cec5SDimitry Andric   bool IgnoreScope = false;
29910b57cec5SDimitry Andric   auto LI = ScopeVariables.find(&Scope);
29920b57cec5SDimitry Andric   SmallVectorImpl<LocalVariable> *Locals =
29930b57cec5SDimitry Andric       LI != ScopeVariables.end() ? &LI->second : nullptr;
29940b57cec5SDimitry Andric   auto GI = ScopeGlobals.find(Scope.getScopeNode());
29950b57cec5SDimitry Andric   SmallVectorImpl<CVGlobalVariable> *Globals =
29960b57cec5SDimitry Andric       GI != ScopeGlobals.end() ? GI->second.get() : nullptr;
29970b57cec5SDimitry Andric   const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
29980b57cec5SDimitry Andric   const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
29990b57cec5SDimitry Andric 
30000b57cec5SDimitry Andric   // Ignore lexical scopes which do not contain variables.
30010b57cec5SDimitry Andric   if (!Locals && !Globals)
30020b57cec5SDimitry Andric     IgnoreScope = true;
30030b57cec5SDimitry Andric 
30040b57cec5SDimitry Andric   // Ignore lexical scopes which are not lexical blocks.
30050b57cec5SDimitry Andric   if (!DILB)
30060b57cec5SDimitry Andric     IgnoreScope = true;
30070b57cec5SDimitry Andric 
30080b57cec5SDimitry Andric   // Ignore scopes which have too many address ranges to represent in the
30090b57cec5SDimitry Andric   // current CodeView format or do not have a valid address range.
30100b57cec5SDimitry Andric   //
30110b57cec5SDimitry Andric   // For lexical scopes with multiple address ranges you may be tempted to
30120b57cec5SDimitry Andric   // construct a single range covering every instruction where the block is
30130b57cec5SDimitry Andric   // live and everything in between.  Unfortunately, Visual Studio only
30140b57cec5SDimitry Andric   // displays variables from the first matching lexical block scope.  If the
30150b57cec5SDimitry Andric   // first lexical block contains exception handling code or cold code which
30160b57cec5SDimitry Andric   // is moved to the bottom of the routine creating a single range covering
30170b57cec5SDimitry Andric   // nearly the entire routine, then it will hide all other lexical blocks
30180b57cec5SDimitry Andric   // and the variables they contain.
30190b57cec5SDimitry Andric   if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second))
30200b57cec5SDimitry Andric     IgnoreScope = true;
30210b57cec5SDimitry Andric 
30220b57cec5SDimitry Andric   if (IgnoreScope) {
30230b57cec5SDimitry Andric     // This scope can be safely ignored and eliminating it will reduce the
30240b57cec5SDimitry Andric     // size of the debug information. Be sure to collect any variable and scope
30250b57cec5SDimitry Andric     // information from the this scope or any of its children and collapse them
30260b57cec5SDimitry Andric     // into the parent scope.
30270b57cec5SDimitry Andric     if (Locals)
30280b57cec5SDimitry Andric       ParentLocals.append(Locals->begin(), Locals->end());
30290b57cec5SDimitry Andric     if (Globals)
30300b57cec5SDimitry Andric       ParentGlobals.append(Globals->begin(), Globals->end());
30310b57cec5SDimitry Andric     collectLexicalBlockInfo(Scope.getChildren(),
30320b57cec5SDimitry Andric                             ParentBlocks,
30330b57cec5SDimitry Andric                             ParentLocals,
30340b57cec5SDimitry Andric                             ParentGlobals);
30350b57cec5SDimitry Andric     return;
30360b57cec5SDimitry Andric   }
30370b57cec5SDimitry Andric 
30380b57cec5SDimitry Andric   // Create a new CodeView lexical block for this lexical scope.  If we've
30390b57cec5SDimitry Andric   // seen this DILexicalBlock before then the scope tree is malformed and
30400b57cec5SDimitry Andric   // we can handle this gracefully by not processing it a second time.
30410b57cec5SDimitry Andric   auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
30420b57cec5SDimitry Andric   if (!BlockInsertion.second)
30430b57cec5SDimitry Andric     return;
30440b57cec5SDimitry Andric 
30455f757f3fSDimitry Andric   // Create a lexical block containing the variables and collect the
30460b57cec5SDimitry Andric   // lexical block information for the children.
30470b57cec5SDimitry Andric   const InsnRange &Range = Ranges.front();
30480b57cec5SDimitry Andric   assert(Range.first && Range.second);
30490b57cec5SDimitry Andric   LexicalBlock &Block = BlockInsertion.first->second;
30500b57cec5SDimitry Andric   Block.Begin = getLabelBeforeInsn(Range.first);
30510b57cec5SDimitry Andric   Block.End = getLabelAfterInsn(Range.second);
30520b57cec5SDimitry Andric   assert(Block.Begin && "missing label for scope begin");
30530b57cec5SDimitry Andric   assert(Block.End && "missing label for scope end");
30540b57cec5SDimitry Andric   Block.Name = DILB->getName();
30550b57cec5SDimitry Andric   if (Locals)
30560b57cec5SDimitry Andric     Block.Locals = std::move(*Locals);
30570b57cec5SDimitry Andric   if (Globals)
30580b57cec5SDimitry Andric     Block.Globals = std::move(*Globals);
30590b57cec5SDimitry Andric   ParentBlocks.push_back(&Block);
30600b57cec5SDimitry Andric   collectLexicalBlockInfo(Scope.getChildren(),
30610b57cec5SDimitry Andric                           Block.Children,
30620b57cec5SDimitry Andric                           Block.Locals,
30630b57cec5SDimitry Andric                           Block.Globals);
30640b57cec5SDimitry Andric }
30650b57cec5SDimitry Andric 
endFunctionImpl(const MachineFunction * MF)30660b57cec5SDimitry Andric void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
30670b57cec5SDimitry Andric   const Function &GV = MF->getFunction();
30680b57cec5SDimitry Andric   assert(FnDebugInfo.count(&GV));
30690b57cec5SDimitry Andric   assert(CurFn == FnDebugInfo[&GV].get());
30700b57cec5SDimitry Andric 
30710b57cec5SDimitry Andric   collectVariableInfo(GV.getSubprogram());
30720b57cec5SDimitry Andric 
30730b57cec5SDimitry Andric   // Build the lexical block structure to emit for this routine.
30740b57cec5SDimitry Andric   if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
30750b57cec5SDimitry Andric     collectLexicalBlockInfo(*CFS,
30760b57cec5SDimitry Andric                             CurFn->ChildBlocks,
30770b57cec5SDimitry Andric                             CurFn->Locals,
30780b57cec5SDimitry Andric                             CurFn->Globals);
30790b57cec5SDimitry Andric 
30800b57cec5SDimitry Andric   // Clear the scope and variable information from the map which will not be
30810b57cec5SDimitry Andric   // valid after we have finished processing this routine.  This also prepares
30820b57cec5SDimitry Andric   // the map for the subsequent routine.
30830b57cec5SDimitry Andric   ScopeVariables.clear();
30840b57cec5SDimitry Andric 
30850b57cec5SDimitry Andric   // Don't emit anything if we don't have any line tables.
30860b57cec5SDimitry Andric   // Thunks are compiler-generated and probably won't have source correlation.
30870b57cec5SDimitry Andric   if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
30880b57cec5SDimitry Andric     FnDebugInfo.erase(&GV);
30890b57cec5SDimitry Andric     CurFn = nullptr;
30900b57cec5SDimitry Andric     return;
30910b57cec5SDimitry Andric   }
30920b57cec5SDimitry Andric 
3093480093f4SDimitry Andric   // Find heap alloc sites and add to list.
3094480093f4SDimitry Andric   for (const auto &MBB : *MF) {
3095480093f4SDimitry Andric     for (const auto &MI : MBB) {
3096480093f4SDimitry Andric       if (MDNode *MD = MI.getHeapAllocMarker()) {
3097480093f4SDimitry Andric         CurFn->HeapAllocSites.push_back(std::make_tuple(getLabelBeforeInsn(&MI),
3098480093f4SDimitry Andric                                                         getLabelAfterInsn(&MI),
3099480093f4SDimitry Andric                                                         dyn_cast<DIType>(MD)));
3100480093f4SDimitry Andric       }
3101480093f4SDimitry Andric     }
3102480093f4SDimitry Andric   }
3103480093f4SDimitry Andric 
31045f757f3fSDimitry Andric   bool isThumb = Triple(MMI->getModule()->getTargetTriple()).getArch() ==
31055f757f3fSDimitry Andric                  llvm::Triple::ArchType::thumb;
31065f757f3fSDimitry Andric   collectDebugInfoForJumpTables(MF, isThumb);
31075f757f3fSDimitry Andric 
31080b57cec5SDimitry Andric   CurFn->Annotations = MF->getCodeViewAnnotations();
31090b57cec5SDimitry Andric 
31100b57cec5SDimitry Andric   CurFn->End = Asm->getFunctionEnd();
31110b57cec5SDimitry Andric 
31120b57cec5SDimitry Andric   CurFn = nullptr;
31130b57cec5SDimitry Andric }
31140b57cec5SDimitry Andric 
31158bcb0991SDimitry Andric // Usable locations are valid with non-zero line numbers. A line number of zero
31168bcb0991SDimitry Andric // corresponds to optimized code that doesn't have a distinct source location.
31178bcb0991SDimitry Andric // In this case, we try to use the previous or next source location depending on
31188bcb0991SDimitry Andric // the context.
isUsableDebugLoc(DebugLoc DL)31198bcb0991SDimitry Andric static bool isUsableDebugLoc(DebugLoc DL) {
31208bcb0991SDimitry Andric   return DL && DL.getLine() != 0;
31218bcb0991SDimitry Andric }
31228bcb0991SDimitry Andric 
beginInstruction(const MachineInstr * MI)31230b57cec5SDimitry Andric void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
31240b57cec5SDimitry Andric   DebugHandlerBase::beginInstruction(MI);
31250b57cec5SDimitry Andric 
31260b57cec5SDimitry Andric   // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
31270b57cec5SDimitry Andric   if (!Asm || !CurFn || MI->isDebugInstr() ||
31280b57cec5SDimitry Andric       MI->getFlag(MachineInstr::FrameSetup))
31290b57cec5SDimitry Andric     return;
31300b57cec5SDimitry Andric 
31310b57cec5SDimitry Andric   // If the first instruction of a new MBB has no location, find the first
31320b57cec5SDimitry Andric   // instruction with a location and use that.
31330b57cec5SDimitry Andric   DebugLoc DL = MI->getDebugLoc();
31348bcb0991SDimitry Andric   if (!isUsableDebugLoc(DL) && MI->getParent() != PrevInstBB) {
31350b57cec5SDimitry Andric     for (const auto &NextMI : *MI->getParent()) {
31360b57cec5SDimitry Andric       if (NextMI.isDebugInstr())
31370b57cec5SDimitry Andric         continue;
31380b57cec5SDimitry Andric       DL = NextMI.getDebugLoc();
31398bcb0991SDimitry Andric       if (isUsableDebugLoc(DL))
31400b57cec5SDimitry Andric         break;
31410b57cec5SDimitry Andric     }
31428bcb0991SDimitry Andric     // FIXME: Handle the case where the BB has no valid locations. This would
31438bcb0991SDimitry Andric     // probably require doing a real dataflow analysis.
31440b57cec5SDimitry Andric   }
31450b57cec5SDimitry Andric   PrevInstBB = MI->getParent();
31460b57cec5SDimitry Andric 
31470b57cec5SDimitry Andric   // If we still don't have a debug location, don't record a location.
31488bcb0991SDimitry Andric   if (!isUsableDebugLoc(DL))
31490b57cec5SDimitry Andric     return;
31500b57cec5SDimitry Andric 
31510b57cec5SDimitry Andric   maybeRecordLocation(DL, Asm->MF);
31520b57cec5SDimitry Andric }
31530b57cec5SDimitry Andric 
beginCVSubsection(DebugSubsectionKind Kind)31540b57cec5SDimitry Andric MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
31550b57cec5SDimitry Andric   MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
31560b57cec5SDimitry Andric            *EndLabel = MMI->getContext().createTempSymbol();
31575ffd83dbSDimitry Andric   OS.emitInt32(unsigned(Kind));
31580b57cec5SDimitry Andric   OS.AddComment("Subsection size");
31590b57cec5SDimitry Andric   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
31605ffd83dbSDimitry Andric   OS.emitLabel(BeginLabel);
31610b57cec5SDimitry Andric   return EndLabel;
31620b57cec5SDimitry Andric }
31630b57cec5SDimitry Andric 
endCVSubsection(MCSymbol * EndLabel)31640b57cec5SDimitry Andric void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
31655ffd83dbSDimitry Andric   OS.emitLabel(EndLabel);
31660b57cec5SDimitry Andric   // Every subsection must be aligned to a 4-byte boundary.
3167bdd1243dSDimitry Andric   OS.emitValueToAlignment(Align(4));
31680b57cec5SDimitry Andric }
31690b57cec5SDimitry Andric 
getSymbolName(SymbolKind SymKind)31700b57cec5SDimitry Andric static StringRef getSymbolName(SymbolKind SymKind) {
31710b57cec5SDimitry Andric   for (const EnumEntry<SymbolKind> &EE : getSymbolTypeNames())
31720b57cec5SDimitry Andric     if (EE.Value == SymKind)
31730b57cec5SDimitry Andric       return EE.Name;
31740b57cec5SDimitry Andric   return "";
31750b57cec5SDimitry Andric }
31760b57cec5SDimitry Andric 
beginSymbolRecord(SymbolKind SymKind)31770b57cec5SDimitry Andric MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) {
31780b57cec5SDimitry Andric   MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
31790b57cec5SDimitry Andric            *EndLabel = MMI->getContext().createTempSymbol();
31800b57cec5SDimitry Andric   OS.AddComment("Record length");
31810b57cec5SDimitry Andric   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
31825ffd83dbSDimitry Andric   OS.emitLabel(BeginLabel);
31830b57cec5SDimitry Andric   if (OS.isVerboseAsm())
31840b57cec5SDimitry Andric     OS.AddComment("Record kind: " + getSymbolName(SymKind));
31855ffd83dbSDimitry Andric   OS.emitInt16(unsigned(SymKind));
31860b57cec5SDimitry Andric   return EndLabel;
31870b57cec5SDimitry Andric }
31880b57cec5SDimitry Andric 
endSymbolRecord(MCSymbol * SymEnd)31890b57cec5SDimitry Andric void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) {
31900b57cec5SDimitry Andric   // MSVC does not pad out symbol records to four bytes, but LLVM does to avoid
31910b57cec5SDimitry Andric   // an extra copy of every symbol record in LLD. This increases object file
31920b57cec5SDimitry Andric   // size by less than 1% in the clang build, and is compatible with the Visual
31930b57cec5SDimitry Andric   // C++ linker.
3194bdd1243dSDimitry Andric   OS.emitValueToAlignment(Align(4));
31955ffd83dbSDimitry Andric   OS.emitLabel(SymEnd);
31960b57cec5SDimitry Andric }
31970b57cec5SDimitry Andric 
emitEndSymbolRecord(SymbolKind EndKind)31980b57cec5SDimitry Andric void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) {
31990b57cec5SDimitry Andric   OS.AddComment("Record length");
32005ffd83dbSDimitry Andric   OS.emitInt16(2);
32010b57cec5SDimitry Andric   if (OS.isVerboseAsm())
32020b57cec5SDimitry Andric     OS.AddComment("Record kind: " + getSymbolName(EndKind));
32035ffd83dbSDimitry Andric   OS.emitInt16(uint16_t(EndKind)); // Record Kind
32040b57cec5SDimitry Andric }
32050b57cec5SDimitry Andric 
emitDebugInfoForUDTs(const std::vector<std::pair<std::string,const DIType * >> & UDTs)32060b57cec5SDimitry Andric void CodeViewDebug::emitDebugInfoForUDTs(
32075ffd83dbSDimitry Andric     const std::vector<std::pair<std::string, const DIType *>> &UDTs) {
32085ffd83dbSDimitry Andric #ifndef NDEBUG
32095ffd83dbSDimitry Andric   size_t OriginalSize = UDTs.size();
32105ffd83dbSDimitry Andric #endif
32110b57cec5SDimitry Andric   for (const auto &UDT : UDTs) {
32120b57cec5SDimitry Andric     const DIType *T = UDT.second;
32130b57cec5SDimitry Andric     assert(shouldEmitUdt(T));
32140b57cec5SDimitry Andric     MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT);
32150b57cec5SDimitry Andric     OS.AddComment("Type");
32165ffd83dbSDimitry Andric     OS.emitInt32(getCompleteTypeIndex(T).getIndex());
32175ffd83dbSDimitry Andric     assert(OriginalSize == UDTs.size() &&
32185ffd83dbSDimitry Andric            "getCompleteTypeIndex found new UDTs!");
32190b57cec5SDimitry Andric     emitNullTerminatedSymbolName(OS, UDT.first);
32200b57cec5SDimitry Andric     endSymbolRecord(UDTRecordEnd);
32210b57cec5SDimitry Andric   }
32220b57cec5SDimitry Andric }
32230b57cec5SDimitry Andric 
collectGlobalVariableInfo()32240b57cec5SDimitry Andric void CodeViewDebug::collectGlobalVariableInfo() {
32250b57cec5SDimitry Andric   DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
32260b57cec5SDimitry Andric       GlobalMap;
32270b57cec5SDimitry Andric   for (const GlobalVariable &GV : MMI->getModule()->globals()) {
32280b57cec5SDimitry Andric     SmallVector<DIGlobalVariableExpression *, 1> GVEs;
32290b57cec5SDimitry Andric     GV.getDebugInfo(GVEs);
32300b57cec5SDimitry Andric     for (const auto *GVE : GVEs)
32310b57cec5SDimitry Andric       GlobalMap[GVE] = &GV;
32320b57cec5SDimitry Andric   }
32330b57cec5SDimitry Andric 
32340b57cec5SDimitry Andric   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
32350b57cec5SDimitry Andric   for (const MDNode *Node : CUs->operands()) {
32360b57cec5SDimitry Andric     const auto *CU = cast<DICompileUnit>(Node);
32370b57cec5SDimitry Andric     for (const auto *GVE : CU->getGlobalVariables()) {
32380b57cec5SDimitry Andric       const DIGlobalVariable *DIGV = GVE->getVariable();
32390b57cec5SDimitry Andric       const DIExpression *DIE = GVE->getExpression();
324081ad6265SDimitry Andric       // Don't emit string literals in CodeView, as the only useful parts are
324181ad6265SDimitry Andric       // generally the filename and line number, which isn't possible to output
324281ad6265SDimitry Andric       // in CodeView. String literals should be the only unnamed GlobalVariable
324381ad6265SDimitry Andric       // with debug info.
324481ad6265SDimitry Andric       if (DIGV->getName().empty()) continue;
32450b57cec5SDimitry Andric 
3246349cc55cSDimitry Andric       if ((DIE->getNumElements() == 2) &&
3247349cc55cSDimitry Andric           (DIE->getElement(0) == dwarf::DW_OP_plus_uconst))
3248349cc55cSDimitry Andric         // Record the constant offset for the variable.
3249349cc55cSDimitry Andric         //
3250349cc55cSDimitry Andric         // A Fortran common block uses this idiom to encode the offset
3251349cc55cSDimitry Andric         // of a variable from the common block's starting address.
3252349cc55cSDimitry Andric         CVGlobalVariableOffsets.insert(
3253349cc55cSDimitry Andric             std::make_pair(DIGV, DIE->getElement(1)));
3254349cc55cSDimitry Andric 
32550b57cec5SDimitry Andric       // Emit constant global variables in a global symbol section.
32560b57cec5SDimitry Andric       if (GlobalMap.count(GVE) == 0 && DIE->isConstant()) {
32570b57cec5SDimitry Andric         CVGlobalVariable CVGV = {DIGV, DIE};
32580b57cec5SDimitry Andric         GlobalVariables.emplace_back(std::move(CVGV));
32590b57cec5SDimitry Andric       }
32600b57cec5SDimitry Andric 
32610b57cec5SDimitry Andric       const auto *GV = GlobalMap.lookup(GVE);
32620b57cec5SDimitry Andric       if (!GV || GV->isDeclarationForLinker())
32630b57cec5SDimitry Andric         continue;
32640b57cec5SDimitry Andric 
32650b57cec5SDimitry Andric       DIScope *Scope = DIGV->getScope();
32660b57cec5SDimitry Andric       SmallVector<CVGlobalVariable, 1> *VariableList;
32670b57cec5SDimitry Andric       if (Scope && isa<DILocalScope>(Scope)) {
32680b57cec5SDimitry Andric         // Locate a global variable list for this scope, creating one if
32690b57cec5SDimitry Andric         // necessary.
32700b57cec5SDimitry Andric         auto Insertion = ScopeGlobals.insert(
32710b57cec5SDimitry Andric             {Scope, std::unique_ptr<GlobalVariableList>()});
32720b57cec5SDimitry Andric         if (Insertion.second)
32738bcb0991SDimitry Andric           Insertion.first->second = std::make_unique<GlobalVariableList>();
32740b57cec5SDimitry Andric         VariableList = Insertion.first->second.get();
32750b57cec5SDimitry Andric       } else if (GV->hasComdat())
32760b57cec5SDimitry Andric         // Emit this global variable into a COMDAT section.
32770b57cec5SDimitry Andric         VariableList = &ComdatVariables;
32780b57cec5SDimitry Andric       else
32790b57cec5SDimitry Andric         // Emit this global variable in a single global symbol section.
32800b57cec5SDimitry Andric         VariableList = &GlobalVariables;
32810b57cec5SDimitry Andric       CVGlobalVariable CVGV = {DIGV, GV};
32820b57cec5SDimitry Andric       VariableList->emplace_back(std::move(CVGV));
32830b57cec5SDimitry Andric     }
32840b57cec5SDimitry Andric   }
32850b57cec5SDimitry Andric }
32860b57cec5SDimitry Andric 
collectDebugInfoForGlobals()3287e8d8bef9SDimitry Andric void CodeViewDebug::collectDebugInfoForGlobals() {
3288e8d8bef9SDimitry Andric   for (const CVGlobalVariable &CVGV : GlobalVariables) {
3289e8d8bef9SDimitry Andric     const DIGlobalVariable *DIGV = CVGV.DIGV;
3290e8d8bef9SDimitry Andric     const DIScope *Scope = DIGV->getScope();
3291e8d8bef9SDimitry Andric     getCompleteTypeIndex(DIGV->getType());
3292e8d8bef9SDimitry Andric     getFullyQualifiedName(Scope, DIGV->getName());
3293e8d8bef9SDimitry Andric   }
3294e8d8bef9SDimitry Andric 
3295e8d8bef9SDimitry Andric   for (const CVGlobalVariable &CVGV : ComdatVariables) {
3296e8d8bef9SDimitry Andric     const DIGlobalVariable *DIGV = CVGV.DIGV;
3297e8d8bef9SDimitry Andric     const DIScope *Scope = DIGV->getScope();
3298e8d8bef9SDimitry Andric     getCompleteTypeIndex(DIGV->getType());
3299e8d8bef9SDimitry Andric     getFullyQualifiedName(Scope, DIGV->getName());
3300e8d8bef9SDimitry Andric   }
3301e8d8bef9SDimitry Andric }
3302e8d8bef9SDimitry Andric 
emitDebugInfoForGlobals()33030b57cec5SDimitry Andric void CodeViewDebug::emitDebugInfoForGlobals() {
33040b57cec5SDimitry Andric   // First, emit all globals that are not in a comdat in a single symbol
33050b57cec5SDimitry Andric   // substream. MSVC doesn't like it if the substream is empty, so only open
33060b57cec5SDimitry Andric   // it if we have at least one global to emit.
33070b57cec5SDimitry Andric   switchToDebugSectionForSymbol(nullptr);
3308e8d8bef9SDimitry Andric   if (!GlobalVariables.empty() || !StaticConstMembers.empty()) {
33090b57cec5SDimitry Andric     OS.AddComment("Symbol subsection for globals");
33100b57cec5SDimitry Andric     MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
33110b57cec5SDimitry Andric     emitGlobalVariableList(GlobalVariables);
3312e8d8bef9SDimitry Andric     emitStaticConstMemberList();
33130b57cec5SDimitry Andric     endCVSubsection(EndLabel);
33140b57cec5SDimitry Andric   }
33150b57cec5SDimitry Andric 
33160b57cec5SDimitry Andric   // Second, emit each global that is in a comdat into its own .debug$S
33170b57cec5SDimitry Andric   // section along with its own symbol substream.
33180b57cec5SDimitry Andric   for (const CVGlobalVariable &CVGV : ComdatVariables) {
331906c3fb27SDimitry Andric     const GlobalVariable *GV = cast<const GlobalVariable *>(CVGV.GVInfo);
33200b57cec5SDimitry Andric     MCSymbol *GVSym = Asm->getSymbol(GV);
33210b57cec5SDimitry Andric     OS.AddComment("Symbol subsection for " +
33220b57cec5SDimitry Andric                   Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
33230b57cec5SDimitry Andric     switchToDebugSectionForSymbol(GVSym);
33240b57cec5SDimitry Andric     MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
33250b57cec5SDimitry Andric     // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
33260b57cec5SDimitry Andric     emitDebugInfoForGlobal(CVGV);
33270b57cec5SDimitry Andric     endCVSubsection(EndLabel);
33280b57cec5SDimitry Andric   }
33290b57cec5SDimitry Andric }
33300b57cec5SDimitry Andric 
emitDebugInfoForRetainedTypes()33310b57cec5SDimitry Andric void CodeViewDebug::emitDebugInfoForRetainedTypes() {
33320b57cec5SDimitry Andric   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
33330b57cec5SDimitry Andric   for (const MDNode *Node : CUs->operands()) {
33340b57cec5SDimitry Andric     for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
33350b57cec5SDimitry Andric       if (DIType *RT = dyn_cast<DIType>(Ty)) {
33360b57cec5SDimitry Andric         getTypeIndex(RT);
33370b57cec5SDimitry Andric         // FIXME: Add to global/local DTU list.
33380b57cec5SDimitry Andric       }
33390b57cec5SDimitry Andric     }
33400b57cec5SDimitry Andric   }
33410b57cec5SDimitry Andric }
33420b57cec5SDimitry Andric 
33430b57cec5SDimitry Andric // Emit each global variable in the specified array.
emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals)33440b57cec5SDimitry Andric void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) {
33450b57cec5SDimitry Andric   for (const CVGlobalVariable &CVGV : Globals) {
33460b57cec5SDimitry Andric     // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
33470b57cec5SDimitry Andric     emitDebugInfoForGlobal(CVGV);
33480b57cec5SDimitry Andric   }
33490b57cec5SDimitry Andric }
33500b57cec5SDimitry Andric 
emitConstantSymbolRecord(const DIType * DTy,APSInt & Value,const std::string & QualifiedName)3351fe6060f1SDimitry Andric void CodeViewDebug::emitConstantSymbolRecord(const DIType *DTy, APSInt &Value,
3352fe6060f1SDimitry Andric                                              const std::string &QualifiedName) {
3353fe6060f1SDimitry Andric   MCSymbol *SConstantEnd = beginSymbolRecord(SymbolKind::S_CONSTANT);
3354fe6060f1SDimitry Andric   OS.AddComment("Type");
3355fe6060f1SDimitry Andric   OS.emitInt32(getTypeIndex(DTy).getIndex());
3356fe6060f1SDimitry Andric 
3357fe6060f1SDimitry Andric   OS.AddComment("Value");
3358fe6060f1SDimitry Andric 
3359fe6060f1SDimitry Andric   // Encoded integers shouldn't need more than 10 bytes.
3360fe6060f1SDimitry Andric   uint8_t Data[10];
33615f757f3fSDimitry Andric   BinaryStreamWriter Writer(Data, llvm::endianness::little);
3362fe6060f1SDimitry Andric   CodeViewRecordIO IO(Writer);
3363fe6060f1SDimitry Andric   cantFail(IO.mapEncodedInteger(Value));
3364fe6060f1SDimitry Andric   StringRef SRef((char *)Data, Writer.getOffset());
3365fe6060f1SDimitry Andric   OS.emitBinaryData(SRef);
3366fe6060f1SDimitry Andric 
3367fe6060f1SDimitry Andric   OS.AddComment("Name");
3368fe6060f1SDimitry Andric   emitNullTerminatedSymbolName(OS, QualifiedName);
3369fe6060f1SDimitry Andric   endSymbolRecord(SConstantEnd);
3370fe6060f1SDimitry Andric }
3371fe6060f1SDimitry Andric 
emitStaticConstMemberList()3372e8d8bef9SDimitry Andric void CodeViewDebug::emitStaticConstMemberList() {
3373e8d8bef9SDimitry Andric   for (const DIDerivedType *DTy : StaticConstMembers) {
3374e8d8bef9SDimitry Andric     const DIScope *Scope = DTy->getScope();
3375e8d8bef9SDimitry Andric 
3376e8d8bef9SDimitry Andric     APSInt Value;
3377e8d8bef9SDimitry Andric     if (const ConstantInt *CI =
3378e8d8bef9SDimitry Andric             dyn_cast_or_null<ConstantInt>(DTy->getConstant()))
3379e8d8bef9SDimitry Andric       Value = APSInt(CI->getValue(),
3380e8d8bef9SDimitry Andric                      DebugHandlerBase::isUnsignedDIType(DTy->getBaseType()));
3381e8d8bef9SDimitry Andric     else if (const ConstantFP *CFP =
3382e8d8bef9SDimitry Andric                  dyn_cast_or_null<ConstantFP>(DTy->getConstant()))
3383e8d8bef9SDimitry Andric       Value = APSInt(CFP->getValueAPF().bitcastToAPInt(), true);
3384e8d8bef9SDimitry Andric     else
3385e8d8bef9SDimitry Andric       llvm_unreachable("cannot emit a constant without a value");
3386e8d8bef9SDimitry Andric 
3387fe6060f1SDimitry Andric     emitConstantSymbolRecord(DTy->getBaseType(), Value,
3388fe6060f1SDimitry Andric                              getFullyQualifiedName(Scope, DTy->getName()));
3389e8d8bef9SDimitry Andric   }
3390e8d8bef9SDimitry Andric }
3391e8d8bef9SDimitry Andric 
isFloatDIType(const DIType * Ty)3392e8d8bef9SDimitry Andric static bool isFloatDIType(const DIType *Ty) {
3393e8d8bef9SDimitry Andric   if (isa<DICompositeType>(Ty))
3394e8d8bef9SDimitry Andric     return false;
3395e8d8bef9SDimitry Andric 
3396e8d8bef9SDimitry Andric   if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
3397e8d8bef9SDimitry Andric     dwarf::Tag T = (dwarf::Tag)Ty->getTag();
3398e8d8bef9SDimitry Andric     if (T == dwarf::DW_TAG_pointer_type ||
3399e8d8bef9SDimitry Andric         T == dwarf::DW_TAG_ptr_to_member_type ||
3400e8d8bef9SDimitry Andric         T == dwarf::DW_TAG_reference_type ||
3401e8d8bef9SDimitry Andric         T == dwarf::DW_TAG_rvalue_reference_type)
3402e8d8bef9SDimitry Andric       return false;
3403e8d8bef9SDimitry Andric     assert(DTy->getBaseType() && "Expected valid base type");
3404e8d8bef9SDimitry Andric     return isFloatDIType(DTy->getBaseType());
3405e8d8bef9SDimitry Andric   }
3406e8d8bef9SDimitry Andric 
3407e8d8bef9SDimitry Andric   auto *BTy = cast<DIBasicType>(Ty);
3408e8d8bef9SDimitry Andric   return (BTy->getEncoding() == dwarf::DW_ATE_float);
3409e8d8bef9SDimitry Andric }
3410e8d8bef9SDimitry Andric 
emitDebugInfoForGlobal(const CVGlobalVariable & CVGV)34110b57cec5SDimitry Andric void CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable &CVGV) {
34120b57cec5SDimitry Andric   const DIGlobalVariable *DIGV = CVGV.DIGV;
34135ffd83dbSDimitry Andric 
34145ffd83dbSDimitry Andric   const DIScope *Scope = DIGV->getScope();
34155ffd83dbSDimitry Andric   // For static data members, get the scope from the declaration.
34165ffd83dbSDimitry Andric   if (const auto *MemberDecl = dyn_cast_or_null<DIDerivedType>(
34175ffd83dbSDimitry Andric           DIGV->getRawStaticDataMemberDeclaration()))
34185ffd83dbSDimitry Andric     Scope = MemberDecl->getScope();
3419bdd1243dSDimitry Andric   // For static local variables and Fortran, the scoping portion is elided
3420bdd1243dSDimitry Andric   // in its name so that we can reference the variable in the command line
3421bdd1243dSDimitry Andric   // of the VS debugger.
3422349cc55cSDimitry Andric   std::string QualifiedName =
3423bdd1243dSDimitry Andric       (moduleIsInFortran() || (Scope && isa<DILocalScope>(Scope)))
3424bdd1243dSDimitry Andric           ? std::string(DIGV->getName())
3425349cc55cSDimitry Andric           : getFullyQualifiedName(Scope, DIGV->getName());
34265ffd83dbSDimitry Andric 
34270b57cec5SDimitry Andric   if (const GlobalVariable *GV =
342806c3fb27SDimitry Andric           dyn_cast_if_present<const GlobalVariable *>(CVGV.GVInfo)) {
34290b57cec5SDimitry Andric     // DataSym record, see SymbolRecord.h for more info. Thread local data
34300b57cec5SDimitry Andric     // happens to have the same format as global data.
34310b57cec5SDimitry Andric     MCSymbol *GVSym = Asm->getSymbol(GV);
34320b57cec5SDimitry Andric     SymbolKind DataSym = GV->isThreadLocal()
34330b57cec5SDimitry Andric                              ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32
34340b57cec5SDimitry Andric                                                       : SymbolKind::S_GTHREAD32)
34350b57cec5SDimitry Andric                              : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32
34360b57cec5SDimitry Andric                                                       : SymbolKind::S_GDATA32);
34370b57cec5SDimitry Andric     MCSymbol *DataEnd = beginSymbolRecord(DataSym);
34380b57cec5SDimitry Andric     OS.AddComment("Type");
34395ffd83dbSDimitry Andric     OS.emitInt32(getCompleteTypeIndex(DIGV->getType()).getIndex());
34400b57cec5SDimitry Andric     OS.AddComment("DataOffset");
3441349cc55cSDimitry Andric 
3442349cc55cSDimitry Andric     uint64_t Offset = 0;
344306c3fb27SDimitry Andric     if (CVGlobalVariableOffsets.contains(DIGV))
3444349cc55cSDimitry Andric       // Use the offset seen while collecting info on globals.
3445349cc55cSDimitry Andric       Offset = CVGlobalVariableOffsets[DIGV];
344681ad6265SDimitry Andric     OS.emitCOFFSecRel32(GVSym, Offset);
3447349cc55cSDimitry Andric 
34480b57cec5SDimitry Andric     OS.AddComment("Segment");
344981ad6265SDimitry Andric     OS.emitCOFFSectionIndex(GVSym);
34500b57cec5SDimitry Andric     OS.AddComment("Name");
34510b57cec5SDimitry Andric     const unsigned LengthOfDataRecord = 12;
34525ffd83dbSDimitry Andric     emitNullTerminatedSymbolName(OS, QualifiedName, LengthOfDataRecord);
34530b57cec5SDimitry Andric     endSymbolRecord(DataEnd);
34540b57cec5SDimitry Andric   } else {
345506c3fb27SDimitry Andric     const DIExpression *DIE = cast<const DIExpression *>(CVGV.GVInfo);
34560b57cec5SDimitry Andric     assert(DIE->isConstant() &&
34570b57cec5SDimitry Andric            "Global constant variables must contain a constant expression.");
3458e8d8bef9SDimitry Andric 
3459e8d8bef9SDimitry Andric     // Use unsigned for floats.
3460e8d8bef9SDimitry Andric     bool isUnsigned = isFloatDIType(DIGV->getType())
3461e8d8bef9SDimitry Andric                           ? true
3462e8d8bef9SDimitry Andric                           : DebugHandlerBase::isUnsignedDIType(DIGV->getType());
3463e8d8bef9SDimitry Andric     APSInt Value(APInt(/*BitWidth=*/64, DIE->getElement(1)), isUnsigned);
3464fe6060f1SDimitry Andric     emitConstantSymbolRecord(DIGV->getType(), Value, QualifiedName);
34650b57cec5SDimitry Andric   }
34660b57cec5SDimitry Andric }
34675f757f3fSDimitry Andric 
forEachJumpTableBranch(const MachineFunction * MF,bool isThumb,const std::function<void (const MachineJumpTableInfo &,const MachineInstr &,int64_t)> & Callback)34685f757f3fSDimitry Andric void forEachJumpTableBranch(
34695f757f3fSDimitry Andric     const MachineFunction *MF, bool isThumb,
34705f757f3fSDimitry Andric     const std::function<void(const MachineJumpTableInfo &, const MachineInstr &,
34715f757f3fSDimitry Andric                              int64_t)> &Callback) {
34725f757f3fSDimitry Andric   auto JTI = MF->getJumpTableInfo();
34735f757f3fSDimitry Andric   if (JTI && !JTI->isEmpty()) {
34745f757f3fSDimitry Andric #ifndef NDEBUG
34755f757f3fSDimitry Andric     auto UsedJTs = llvm::SmallBitVector(JTI->getJumpTables().size());
34765f757f3fSDimitry Andric #endif
34775f757f3fSDimitry Andric     for (const auto &MBB : *MF) {
34785f757f3fSDimitry Andric       // Search for indirect branches...
34795f757f3fSDimitry Andric       const auto LastMI = MBB.getFirstTerminator();
34805f757f3fSDimitry Andric       if (LastMI != MBB.end() && LastMI->isIndirectBranch()) {
34815f757f3fSDimitry Andric         if (isThumb) {
34825f757f3fSDimitry Andric           // ... that directly use jump table operands.
34835f757f3fSDimitry Andric           // NOTE: ARM uses pattern matching to lower its BR_JT SDNode to
34845f757f3fSDimitry Andric           // machine instructions, hence inserting a JUMP_TABLE_DEBUG_INFO node
34855f757f3fSDimitry Andric           // interferes with this process *but* the resulting pseudo-instruction
34865f757f3fSDimitry Andric           // uses a Jump Table operand, so extract the jump table index directly
34875f757f3fSDimitry Andric           // from that.
34885f757f3fSDimitry Andric           for (const auto &MO : LastMI->operands()) {
34895f757f3fSDimitry Andric             if (MO.isJTI()) {
34905f757f3fSDimitry Andric               unsigned Index = MO.getIndex();
34915f757f3fSDimitry Andric #ifndef NDEBUG
34925f757f3fSDimitry Andric               UsedJTs.set(Index);
34935f757f3fSDimitry Andric #endif
34945f757f3fSDimitry Andric               Callback(*JTI, *LastMI, Index);
34955f757f3fSDimitry Andric               break;
34965f757f3fSDimitry Andric             }
34975f757f3fSDimitry Andric           }
34985f757f3fSDimitry Andric         } else {
34995f757f3fSDimitry Andric           // ... that have jump table debug info.
35005f757f3fSDimitry Andric           // NOTE: The debug info is inserted as a JUMP_TABLE_DEBUG_INFO node
35015f757f3fSDimitry Andric           // when lowering the BR_JT SDNode to an indirect branch.
35025f757f3fSDimitry Andric           for (auto I = MBB.instr_rbegin(), E = MBB.instr_rend(); I != E; ++I) {
35035f757f3fSDimitry Andric             if (I->isJumpTableDebugInfo()) {
35045f757f3fSDimitry Andric               unsigned Index = I->getOperand(0).getImm();
35055f757f3fSDimitry Andric #ifndef NDEBUG
35065f757f3fSDimitry Andric               UsedJTs.set(Index);
35075f757f3fSDimitry Andric #endif
35085f757f3fSDimitry Andric               Callback(*JTI, *LastMI, Index);
35095f757f3fSDimitry Andric               break;
35105f757f3fSDimitry Andric             }
35115f757f3fSDimitry Andric           }
35125f757f3fSDimitry Andric         }
35135f757f3fSDimitry Andric       }
35145f757f3fSDimitry Andric     }
35155f757f3fSDimitry Andric #ifndef NDEBUG
35165f757f3fSDimitry Andric     assert(UsedJTs.all() &&
35175f757f3fSDimitry Andric            "Some of jump tables were not used in a debug info instruction");
35185f757f3fSDimitry Andric #endif
35195f757f3fSDimitry Andric   }
35205f757f3fSDimitry Andric }
35215f757f3fSDimitry Andric 
discoverJumpTableBranches(const MachineFunction * MF,bool isThumb)35225f757f3fSDimitry Andric void CodeViewDebug::discoverJumpTableBranches(const MachineFunction *MF,
35235f757f3fSDimitry Andric                                               bool isThumb) {
35245f757f3fSDimitry Andric   forEachJumpTableBranch(
35255f757f3fSDimitry Andric       MF, isThumb,
35265f757f3fSDimitry Andric       [this](const MachineJumpTableInfo &, const MachineInstr &BranchMI,
35275f757f3fSDimitry Andric              int64_t) { requestLabelBeforeInsn(&BranchMI); });
35285f757f3fSDimitry Andric }
35295f757f3fSDimitry Andric 
collectDebugInfoForJumpTables(const MachineFunction * MF,bool isThumb)35305f757f3fSDimitry Andric void CodeViewDebug::collectDebugInfoForJumpTables(const MachineFunction *MF,
35315f757f3fSDimitry Andric                                                   bool isThumb) {
35325f757f3fSDimitry Andric   forEachJumpTableBranch(
35335f757f3fSDimitry Andric       MF, isThumb,
35345f757f3fSDimitry Andric       [this, MF](const MachineJumpTableInfo &JTI, const MachineInstr &BranchMI,
35355f757f3fSDimitry Andric                  int64_t JumpTableIndex) {
35365f757f3fSDimitry Andric         // For label-difference jump tables, find the base expression.
35375f757f3fSDimitry Andric         // Otherwise the jump table uses an absolute address (so no base
35385f757f3fSDimitry Andric         // is required).
35395f757f3fSDimitry Andric         const MCSymbol *Base;
35405f757f3fSDimitry Andric         uint64_t BaseOffset = 0;
35415f757f3fSDimitry Andric         const MCSymbol *Branch = getLabelBeforeInsn(&BranchMI);
35425f757f3fSDimitry Andric         JumpTableEntrySize EntrySize;
35435f757f3fSDimitry Andric         switch (JTI.getEntryKind()) {
35445f757f3fSDimitry Andric         case MachineJumpTableInfo::EK_Custom32:
35455f757f3fSDimitry Andric         case MachineJumpTableInfo::EK_GPRel32BlockAddress:
35465f757f3fSDimitry Andric         case MachineJumpTableInfo::EK_GPRel64BlockAddress:
35475f757f3fSDimitry Andric           llvm_unreachable(
35485f757f3fSDimitry Andric               "EK_Custom32, EK_GPRel32BlockAddress, and "
35495f757f3fSDimitry Andric               "EK_GPRel64BlockAddress should never be emitted for COFF");
35505f757f3fSDimitry Andric         case MachineJumpTableInfo::EK_BlockAddress:
35515f757f3fSDimitry Andric           // Each entry is an absolute address.
35525f757f3fSDimitry Andric           EntrySize = JumpTableEntrySize::Pointer;
35535f757f3fSDimitry Andric           Base = nullptr;
35545f757f3fSDimitry Andric           break;
35555f757f3fSDimitry Andric         case MachineJumpTableInfo::EK_Inline:
35565f757f3fSDimitry Andric         case MachineJumpTableInfo::EK_LabelDifference32:
35575f757f3fSDimitry Andric         case MachineJumpTableInfo::EK_LabelDifference64:
35585f757f3fSDimitry Andric           // Ask the AsmPrinter.
35595f757f3fSDimitry Andric           std::tie(Base, BaseOffset, Branch, EntrySize) =
35605f757f3fSDimitry Andric               Asm->getCodeViewJumpTableInfo(JumpTableIndex, &BranchMI, Branch);
35615f757f3fSDimitry Andric           break;
35625f757f3fSDimitry Andric         }
35635f757f3fSDimitry Andric 
35645f757f3fSDimitry Andric         CurFn->JumpTables.push_back(
35655f757f3fSDimitry Andric             {EntrySize, Base, BaseOffset, Branch,
35665f757f3fSDimitry Andric              MF->getJTISymbol(JumpTableIndex, MMI->getContext()),
35675f757f3fSDimitry Andric              JTI.getJumpTables()[JumpTableIndex].MBBs.size()});
35685f757f3fSDimitry Andric       });
35695f757f3fSDimitry Andric }
35705f757f3fSDimitry Andric 
emitDebugInfoForJumpTables(const FunctionInfo & FI)35715f757f3fSDimitry Andric void CodeViewDebug::emitDebugInfoForJumpTables(const FunctionInfo &FI) {
35725f757f3fSDimitry Andric   for (auto JumpTable : FI.JumpTables) {
35735f757f3fSDimitry Andric     MCSymbol *JumpTableEnd = beginSymbolRecord(SymbolKind::S_ARMSWITCHTABLE);
35745f757f3fSDimitry Andric     if (JumpTable.Base) {
35755f757f3fSDimitry Andric       OS.AddComment("Base offset");
35765f757f3fSDimitry Andric       OS.emitCOFFSecRel32(JumpTable.Base, JumpTable.BaseOffset);
35775f757f3fSDimitry Andric       OS.AddComment("Base section index");
35785f757f3fSDimitry Andric       OS.emitCOFFSectionIndex(JumpTable.Base);
35795f757f3fSDimitry Andric     } else {
35805f757f3fSDimitry Andric       OS.AddComment("Base offset");
35815f757f3fSDimitry Andric       OS.emitInt32(0);
35825f757f3fSDimitry Andric       OS.AddComment("Base section index");
35835f757f3fSDimitry Andric       OS.emitInt16(0);
35845f757f3fSDimitry Andric     }
35855f757f3fSDimitry Andric     OS.AddComment("Switch type");
35865f757f3fSDimitry Andric     OS.emitInt16(static_cast<uint16_t>(JumpTable.EntrySize));
35875f757f3fSDimitry Andric     OS.AddComment("Branch offset");
35885f757f3fSDimitry Andric     OS.emitCOFFSecRel32(JumpTable.Branch, /*Offset=*/0);
35895f757f3fSDimitry Andric     OS.AddComment("Table offset");
35905f757f3fSDimitry Andric     OS.emitCOFFSecRel32(JumpTable.Table, /*Offset=*/0);
35915f757f3fSDimitry Andric     OS.AddComment("Branch section index");
35925f757f3fSDimitry Andric     OS.emitCOFFSectionIndex(JumpTable.Branch);
35935f757f3fSDimitry Andric     OS.AddComment("Table section index");
35945f757f3fSDimitry Andric     OS.emitCOFFSectionIndex(JumpTable.Table);
35955f757f3fSDimitry Andric     OS.AddComment("Entries count");
35965f757f3fSDimitry Andric     OS.emitInt32(JumpTable.TableSize);
35975f757f3fSDimitry Andric     endSymbolRecord(JumpTableEnd);
35985f757f3fSDimitry Andric   }
35995f757f3fSDimitry Andric }
36005f757f3fSDimitry Andric 
emitInlinees(const SmallSet<codeview::TypeIndex,1> & Inlinees)36015f757f3fSDimitry Andric void CodeViewDebug::emitInlinees(
36025f757f3fSDimitry Andric     const SmallSet<codeview::TypeIndex, 1> &Inlinees) {
36035f757f3fSDimitry Andric   // Divide the list of inlinees into chunks such that each chunk fits within
36045f757f3fSDimitry Andric   // one record.
36055f757f3fSDimitry Andric   constexpr size_t ChunkSize =
36065f757f3fSDimitry Andric       (MaxRecordLength - sizeof(SymbolKind) - sizeof(uint32_t)) /
36075f757f3fSDimitry Andric       sizeof(uint32_t);
36085f757f3fSDimitry Andric 
36095f757f3fSDimitry Andric   SmallVector<TypeIndex> SortedInlinees{Inlinees.begin(), Inlinees.end()};
36105f757f3fSDimitry Andric   llvm::sort(SortedInlinees);
36115f757f3fSDimitry Andric 
36125f757f3fSDimitry Andric   size_t CurrentIndex = 0;
36135f757f3fSDimitry Andric   while (CurrentIndex < SortedInlinees.size()) {
36145f757f3fSDimitry Andric     auto Symbol = beginSymbolRecord(SymbolKind::S_INLINEES);
36155f757f3fSDimitry Andric     auto CurrentChunkSize =
36165f757f3fSDimitry Andric         std::min(ChunkSize, SortedInlinees.size() - CurrentIndex);
36175f757f3fSDimitry Andric     OS.AddComment("Count");
36185f757f3fSDimitry Andric     OS.emitInt32(CurrentChunkSize);
36195f757f3fSDimitry Andric 
36205f757f3fSDimitry Andric     const size_t CurrentChunkEnd = CurrentIndex + CurrentChunkSize;
36215f757f3fSDimitry Andric     for (; CurrentIndex < CurrentChunkEnd; ++CurrentIndex) {
36225f757f3fSDimitry Andric       OS.AddComment("Inlinee");
36235f757f3fSDimitry Andric       OS.emitInt32(SortedInlinees[CurrentIndex].getIndex());
36245f757f3fSDimitry Andric     }
36255f757f3fSDimitry Andric     endSymbolRecord(Symbol);
36265f757f3fSDimitry Andric   }
36275f757f3fSDimitry Andric }
3628