LCOV - code coverage report
Current view: top level - lib/CodeGen/AsmPrinter - CodeViewDebug.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 1189 1264 94.1 %
Date: 2017-09-14 15:23:50 Functions: 72 75 96.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This file contains support for writing Microsoft CodeView debug info.
      11             : //
      12             : //===----------------------------------------------------------------------===//
      13             : 
      14             : #include "CodeViewDebug.h"
      15             : #include "DwarfExpression.h"
      16             : #include "llvm/ADT/APSInt.h"
      17             : #include "llvm/ADT/ArrayRef.h"
      18             : #include "llvm/ADT/DenseMap.h"
      19             : #include "llvm/ADT/DenseSet.h"
      20             : #include "llvm/ADT/MapVector.h"
      21             : #include "llvm/ADT/None.h"
      22             : #include "llvm/ADT/Optional.h"
      23             : #include "llvm/ADT/SmallString.h"
      24             : #include "llvm/ADT/SmallVector.h"
      25             : #include "llvm/ADT/STLExtras.h"
      26             : #include "llvm/ADT/StringRef.h"
      27             : #include "llvm/ADT/TinyPtrVector.h"
      28             : #include "llvm/ADT/Triple.h"
      29             : #include "llvm/ADT/Twine.h"
      30             : #include "llvm/BinaryFormat/COFF.h"
      31             : #include "llvm/BinaryFormat/Dwarf.h"
      32             : #include "llvm/CodeGen/AsmPrinter.h"
      33             : #include "llvm/CodeGen/LexicalScopes.h"
      34             : #include "llvm/CodeGen/MachineFunction.h"
      35             : #include "llvm/CodeGen/MachineInstr.h"
      36             : #include "llvm/CodeGen/MachineModuleInfo.h"
      37             : #include "llvm/CodeGen/MachineOperand.h"
      38             : #include "llvm/Config/llvm-config.h"
      39             : #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
      40             : #include "llvm/DebugInfo/CodeView/CodeView.h"
      41             : #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
      42             : #include "llvm/DebugInfo/CodeView/Line.h"
      43             : #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
      44             : #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
      45             : #include "llvm/DebugInfo/CodeView/TypeIndex.h"
      46             : #include "llvm/DebugInfo/CodeView/TypeRecord.h"
      47             : #include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
      48             : #include "llvm/IR/Constants.h"
      49             : #include "llvm/IR/DataLayout.h"
      50             : #include "llvm/IR/DebugInfoMetadata.h"
      51             : #include "llvm/IR/DebugLoc.h"
      52             : #include "llvm/IR/Function.h"
      53             : #include "llvm/IR/GlobalValue.h"
      54             : #include "llvm/IR/GlobalVariable.h"
      55             : #include "llvm/IR/Metadata.h"
      56             : #include "llvm/IR/Module.h"
      57             : #include "llvm/MC/MCAsmInfo.h"
      58             : #include "llvm/MC/MCContext.h"
      59             : #include "llvm/MC/MCSectionCOFF.h"
      60             : #include "llvm/MC/MCStreamer.h"
      61             : #include "llvm/MC/MCSymbol.h"
      62             : #include "llvm/Support/BinaryByteStream.h"
      63             : #include "llvm/Support/BinaryStreamReader.h"
      64             : #include "llvm/Support/Casting.h"
      65             : #include "llvm/Support/Compiler.h"
      66             : #include "llvm/Support/Endian.h"
      67             : #include "llvm/Support/Error.h"
      68             : #include "llvm/Support/ErrorHandling.h"
      69             : #include "llvm/Support/ScopedPrinter.h"
      70             : #include "llvm/Support/SMLoc.h"
      71             : #include "llvm/Target/TargetFrameLowering.h"
      72             : #include "llvm/Target/TargetLoweringObjectFile.h"
      73             : #include "llvm/Target/TargetMachine.h"
      74             : #include "llvm/Target/TargetRegisterInfo.h"
      75             : #include "llvm/Target/TargetSubtargetInfo.h"
      76             : #include <algorithm>
      77             : #include <cassert>
      78             : #include <cctype>
      79             : #include <cstddef>
      80             : #include <cstdint>
      81             : #include <iterator>
      82             : #include <limits>
      83             : #include <string>
      84             : #include <utility>
      85             : #include <vector>
      86             : 
      87             : using namespace llvm;
      88             : using namespace llvm::codeview;
      89             : 
      90          94 : CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
      91        1410 :     : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {
      92             :   // If module doesn't have named metadata anchors or COFF debug section
      93             :   // is not available, skip any debug info related stuff.
      94         374 :   if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
      95          93 :       !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
      96           1 :     Asm = nullptr;
      97           1 :     return;
      98             :   }
      99             : 
     100             :   // Tell MMI that we have debug info.
     101          93 :   MMI->setDebugInfoAvailability(true);
     102             : }
     103             : 
     104         150 : StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
     105         150 :   std::string &Filepath = FileToFilepathMap[File];
     106         150 :   if (!Filepath.empty())
     107          56 :     return Filepath;
     108             : 
     109         282 :   StringRef Dir = File->getDirectory(), Filename = File->getFilename();
     110             : 
     111             :   // Clang emits directory and relative filename info into the IR, but CodeView
     112             :   // operates on full paths.  We could change Clang to emit full paths too, but
     113             :   // that would increase the IR size and probably not needed for other users.
     114             :   // For now, just concatenate and canonicalize the path here.
     115           1 :   if (Filename.find(':') == 1)
     116           2 :     Filepath = Filename;
     117             :   else
     118         372 :     Filepath = (Dir + "\\" + Filename).str();
     119             : 
     120             :   // Canonicalize the path.  We have to do it textually because we may no longer
     121             :   // have access the file in the filesystem.
     122             :   // First, replace all slashes with backslashes.
     123         282 :   std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
     124             : 
     125             :   // Remove all "\.\" with "\".
     126             :   size_t Cursor = 0;
     127         100 :   while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
     128           3 :     Filepath.erase(Cursor, 2);
     129             : 
     130             :   // Replace all "\XXX\..\" with "\".  Don't try too hard though as the original
     131             :   // path should be well-formatted, e.g. start with a drive letter, etc.
     132             :   Cursor = 0;
     133          96 :   while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
     134             :     // Something's wrong if the path starts with "\..\", abort.
     135           1 :     if (Cursor == 0)
     136             :       break;
     137             : 
     138           1 :     size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
     139           1 :     if (PrevSlash == std::string::npos)
     140             :       // Something's wrong, abort.
     141             :       break;
     142             : 
     143           1 :     Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
     144             :     // The next ".." might be following the one we've just erased.
     145           1 :     Cursor = PrevSlash;
     146             :   }
     147             : 
     148             :   // Remove all duplicate backslashes.
     149             :   Cursor = 0;
     150         164 :   while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
     151          35 :     Filepath.erase(Cursor, 1);
     152             : 
     153          94 :   return Filepath;
     154             : }
     155             : 
     156         216 : unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
     157         432 :   unsigned NextId = FileIdMap.size() + 1;
     158         648 :   auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
     159         216 :   if (Insertion.second) {
     160             :     // We have to compute the full filepath and emit a .cv_file directive.
     161          86 :     StringRef FullPath = getFullFilepath(F);
     162          86 :     bool Success = OS.EmitCVFileDirective(NextId, FullPath);
     163             :     (void)Success;
     164             :     assert(Success && ".cv_file directive failed");
     165             :   }
     166         216 :   return Insertion.first->second;
     167             : }
     168             : 
     169             : CodeViewDebug::InlineSite &
     170         108 : CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
     171             :                              const DISubprogram *Inlinee) {
     172         540 :   auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
     173         108 :   InlineSite *Site = &SiteInsertion.first->second;
     174         108 :   if (SiteInsertion.second) {
     175          24 :     unsigned ParentFuncId = CurFn->FuncId;
     176          30 :     if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
     177           6 :       ParentFuncId =
     178          12 :           getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
     179             :               .SiteFuncId;
     180             : 
     181          24 :     Site->SiteFuncId = NextFuncId++;
     182          96 :     OS.EmitCVInlineSiteIdDirective(
     183          48 :         Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
     184          24 :         InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
     185          24 :     Site->Inlinee = Inlinee;
     186          24 :     InlinedSubprograms.insert(Inlinee);
     187          24 :     getFuncIdForSubprogram(Inlinee);
     188             :   }
     189         108 :   return *Site;
     190             : }
     191             : 
     192         385 : static StringRef getPrettyScopeName(const DIScope *Scope) {
     193         385 :   StringRef ScopeName = Scope->getName();
     194         385 :   if (!ScopeName.empty())
     195         268 :     return ScopeName;
     196             : 
     197         117 :   switch (Scope->getTag()) {
     198           5 :   case dwarf::DW_TAG_enumeration_type:
     199             :   case dwarf::DW_TAG_class_type:
     200             :   case dwarf::DW_TAG_structure_type:
     201             :   case dwarf::DW_TAG_union_type:
     202           5 :     return "<unnamed-tag>";
     203           0 :   case dwarf::DW_TAG_namespace:
     204           0 :     return "`anonymous namespace'";
     205             :   }
     206             : 
     207         112 :   return StringRef();
     208             : }
     209             : 
     210         342 : static const DISubprogram *getQualifiedNameComponents(
     211             :     const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
     212         342 :   const DISubprogram *ClosestSubprogram = nullptr;
     213         676 :   while (Scope != nullptr) {
     214         167 :     if (ClosestSubprogram == nullptr)
     215             :       ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
     216         167 :     StringRef ScopeName = getPrettyScopeName(Scope);
     217         167 :     if (!ScopeName.empty())
     218          55 :       QualifiedNameComponents.push_back(ScopeName);
     219         334 :     Scope = Scope->getScope().resolve();
     220             :   }
     221         342 :   return ClosestSubprogram;
     222             : }
     223             : 
     224         342 : static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
     225             :                                     StringRef TypeName) {
     226         342 :   std::string FullyQualifiedName;
     227             :   for (StringRef QualifiedNameComponent :
     228        1478 :        llvm::reverse(QualifiedNameComponents)) {
     229         165 :     FullyQualifiedName.append(QualifiedNameComponent);
     230          55 :     FullyQualifiedName.append("::");
     231             :   }
     232        1026 :   FullyQualifiedName.append(TypeName);
     233         342 :   return FullyQualifiedName;
     234             : }
     235             : 
     236         269 : static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
     237         538 :   SmallVector<StringRef, 5> QualifiedNameComponents;
     238         269 :   getQualifiedNameComponents(Scope, QualifiedNameComponents);
     239         538 :   return getQualifiedName(QualifiedNameComponents, Name);
     240             : }
     241             : 
     242             : struct CodeViewDebug::TypeLoweringScope {
     243         519 :   TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
     244         585 :   ~TypeLoweringScope() {
     245             :     // Don't decrement TypeEmissionLevel until after emitting deferred types, so
     246             :     // inner TypeLoweringScopes don't attempt to emit deferred types.
     247         519 :     if (CVD.TypeEmissionLevel == 1)
     248         223 :       CVD.emitDeferredCompleteTypes();
     249         519 :     --CVD.TypeEmissionLevel;
     250          66 :   }
     251             :   CodeViewDebug &CVD;
     252             : };
     253             : 
     254         145 : static std::string getFullyQualifiedName(const DIScope *Ty) {
     255         290 :   const DIScope *Scope = Ty->getScope().resolve();
     256         145 :   return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
     257             : }
     258             : 
     259         134 : TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
     260             :   // No scope means global scope and that uses the zero index.
     261         265 :   if (!Scope || isa<DIFile>(Scope))
     262         131 :     return TypeIndex();
     263             : 
     264             :   assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
     265             : 
     266             :   // Check if we've already translated this scope.
     267           6 :   auto I = TypeIndices.find({Scope, nullptr});
     268           9 :   if (I != TypeIndices.end())
     269           1 :     return I->second;
     270             : 
     271             :   // Build the fully qualified name of the scope.
     272           2 :   std::string ScopeName = getFullyQualifiedName(Scope);
     273           6 :   StringIdRecord SID(TypeIndex(), ScopeName);
     274           2 :   auto TI = TypeTable.writeKnownType(SID);
     275           4 :   return recordTypeIndexForDINode(Scope, TI);
     276             : }
     277             : 
     278         153 : TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
     279             :   assert(SP);
     280             : 
     281             :   // Check if we've already translated this subprogram.
     282         306 :   auto I = TypeIndices.find({SP, nullptr});
     283         459 :   if (I != TypeIndices.end())
     284           2 :     return I->second;
     285             : 
     286             :   // The display name includes function template arguments. Drop them to match
     287             :   // MSVC.
     288         302 :   StringRef DisplayName = SP->getName().split('<').first;
     289             : 
     290         453 :   const DIScope *Scope = SP->getScope().resolve();
     291         151 :   TypeIndex TI;
     292          20 :   if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
     293             :     // If the scope is a DICompositeType, then this must be a method. Member
     294             :     // function types take some special handling, and require access to the
     295             :     // subprogram.
     296          34 :     TypeIndex ClassType = getTypeIndex(Class);
     297             :     MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
     298          34 :                                DisplayName);
     299          17 :     TI = TypeTable.writeKnownType(MFuncId);
     300             :   } else {
     301             :     // Otherwise, this must be a free function.
     302         134 :     TypeIndex ParentScope = getScopeIndex(Scope);
     303         536 :     FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
     304         134 :     TI = TypeTable.writeKnownType(FuncId);
     305             :   }
     306             : 
     307         151 :   return recordTypeIndexForDINode(SP, TI);
     308             : }
     309             : 
     310          54 : TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
     311             :                                                const DICompositeType *Class) {
     312             :   // Always use the method declaration as the key for the function type. The
     313             :   // method declaration contains the this adjustment.
     314          71 :   if (SP->getDeclaration())
     315          34 :     SP = SP->getDeclaration();
     316             :   assert(!SP->getDeclaration() && "should use declaration as key");
     317             : 
     318             :   // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
     319             :   // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
     320         108 :   auto I = TypeIndices.find({SP, Class});
     321         162 :   if (I != TypeIndices.end())
     322           5 :     return I->second;
     323             : 
     324             :   // Make sure complete type info for the class is emitted *after* the member
     325             :   // function type, as the complete class type is likely to reference this
     326             :   // member function type.
     327          49 :   TypeLoweringScope S(*this);
     328             :   TypeIndex TI =
     329          98 :       lowerTypeMemberFunction(SP->getType(), Class, SP->getThisAdjustment());
     330          98 :   return recordTypeIndexForDINode(SP, TI, Class);
     331             : }
     332             : 
     333           0 : TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
     334             :                                                   TypeIndex TI,
     335             :                                                   const DIType *ClassTy) {
     336        2424 :   auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
     337             :   (void)InsertResult;
     338             :   assert(InsertResult.second && "DINode was already assigned a type index");
     339         606 :   return TI;
     340             : }
     341             : 
     342          18 : unsigned CodeViewDebug::getPointerSizeInBytes() {
     343          36 :   return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
     344             : }
     345             : 
     346         132 : void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
     347             :                                         const DILocation *InlinedAt) {
     348         132 :   if (InlinedAt) {
     349             :     // This variable was inlined. Associate it with the InlineSite.
     350          16 :     const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
     351           8 :     InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
     352           8 :     Site.InlinedLocals.emplace_back(Var);
     353             :   } else {
     354             :     // This variable goes in the main ProcSym.
     355         124 :     CurFn->Locals.emplace_back(Var);
     356             :   }
     357         132 : }
     358             : 
     359          53 : static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
     360             :                                const DILocation *Loc) {
     361         159 :   auto B = Locs.begin(), E = Locs.end();
     362          53 :   if (std::find(B, E, Loc) == E)
     363          24 :     Locs.push_back(Loc);
     364          53 : }
     365             : 
     366         857 : void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
     367             :                                         const MachineFunction *MF) {
     368             :   // Skip this instruction if it has the same location as the previous one.
     369        1714 :   if (!DL || DL == PrevInstLoc)
     370         375 :     return;
     371             : 
     372         964 :   const DIScope *Scope = DL.get()->getScope();
     373         482 :   if (!Scope)
     374             :     return;
     375             : 
     376             :   // Skip this line if it is longer than the maximum we can record.
     377         482 :   LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
     378        1446 :   if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
     379         482 :       LI.isNeverStepInto())
     380             :     return;
     381             : 
     382         964 :   ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
     383         482 :   if (CI.getStartColumn() != DL.getCol())
     384             :     return;
     385             : 
     386         482 :   if (!CurFn->HaveLineInfo)
     387         129 :     CurFn->HaveLineInfo = true;
     388         482 :   unsigned FileId = 0;
     389        1894 :   if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
     390         336 :     FileId = CurFn->LastFileId;
     391             :   else
     392         292 :     FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
     393         964 :   PrevInstLoc = DL;
     394             : 
     395         482 :   unsigned FuncId = CurFn->FuncId;
     396         523 :   if (const DILocation *SiteLoc = DL->getInlinedAt()) {
     397          41 :     const DILocation *Loc = DL.get();
     398             : 
     399             :     // If this location was actually inlined from somewhere else, give it the ID
     400             :     // of the inline call site.
     401          41 :     FuncId =
     402          41 :         getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
     403             : 
     404             :     // Ensure we have links in the tree of inline call sites.
     405          41 :     bool FirstLoc = true;
     406          53 :     while ((SiteLoc = Loc->getInlinedAt())) {
     407             :       InlineSite &Site =
     408          53 :           getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
     409          53 :       if (!FirstLoc)
     410          12 :         addLocIfNotPresent(Site.ChildSites, Loc);
     411             :       FirstLoc = false;
     412             :       Loc = SiteLoc;
     413             :     }
     414          41 :     addLocIfNotPresent(CurFn->ChildSites, Loc);
     415             :   }
     416             : 
     417        1446 :   OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
     418             :                         /*PrologueEnd=*/false, /*IsStmt=*/false,
     419         482 :                         DL->getFilename(), SMLoc());
     420             : }
     421             : 
     422         203 : void CodeViewDebug::emitCodeViewMagicVersion() {
     423         203 :   OS.EmitValueToAlignment(4);
     424         406 :   OS.AddComment("Debug section magic");
     425         203 :   OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
     426         203 : }
     427             : 
     428          94 : void CodeViewDebug::endModule() {
     429          94 :   if (!Asm || !MMI->hasDebugInfo())
     430             :     return;
     431             : 
     432             :   assert(Asm != nullptr);
     433             : 
     434             :   // The COFF .debug$S section consists of several subsections, each starting
     435             :   // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
     436             :   // of the payload followed by the payload itself.  The subsections are 4-byte
     437             :   // aligned.
     438             : 
     439             :   // Use the generic .debug$S section, and make a subsection for all the inlined
     440             :   // subprograms.
     441          93 :   switchToDebugSectionForSymbol(nullptr);
     442             : 
     443          93 :   MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
     444          93 :   emitCompilerInformation();
     445          93 :   endCVSubsection(CompilerInfo);
     446             : 
     447          93 :   emitInlineeLinesSubsection();
     448             : 
     449             :   // Emit per-function debug information.
     450         501 :   for (auto &P : FnDebugInfo)
     451         258 :     if (!P.first->isDeclarationForLinker())
     452         129 :       emitDebugInfoForFunction(P.first, P.second);
     453             : 
     454             :   // Emit global variable debug information.
     455          93 :   setCurrentSubprogram(nullptr);
     456          93 :   emitDebugInfoForGlobals();
     457             : 
     458             :   // Emit retained types.
     459          93 :   emitDebugInfoForRetainedTypes();
     460             : 
     461             :   // Switch back to the generic .debug$S section after potentially processing
     462             :   // comdat symbol sections.
     463          93 :   switchToDebugSectionForSymbol(nullptr);
     464             : 
     465             :   // Emit UDT records for any types used by global variables.
     466         186 :   if (!GlobalUDTs.empty()) {
     467          32 :     MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
     468          64 :     emitDebugInfoForUDTs(GlobalUDTs);
     469          32 :     endCVSubsection(SymbolsEnd);
     470             :   }
     471             : 
     472             :   // This subsection holds a file index to offset in string table table.
     473         186 :   OS.AddComment("File index to string table offset subsection");
     474          93 :   OS.EmitCVFileChecksumsDirective();
     475             : 
     476             :   // This subsection holds the string table.
     477         186 :   OS.AddComment("String table");
     478          93 :   OS.EmitCVStringTableDirective();
     479             : 
     480             :   // Emit type information last, so that any types we translate while emitting
     481             :   // function info are included.
     482          93 :   emitTypeInformation();
     483             : 
     484          93 :   clear();
     485             : }
     486             : 
     487         479 : static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
     488             :   // The maximum CV record length is 0xFF00. Most of the strings we emit appear
     489             :   // after a fixed length portion of the record. The fixed length portion should
     490             :   // always be less than 0xF00 (3840) bytes, so truncate the string so that the
     491             :   // overall record size is less than the maximum allowed.
     492         479 :   unsigned MaxFixedRecordLength = 0xF00;
     493             :   SmallString<32> NullTerminatedString(
     494        1916 :       S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
     495         479 :   NullTerminatedString.push_back('\0');
     496         958 :   OS.EmitBytes(NullTerminatedString);
     497         479 : }
     498             : 
     499          93 : void CodeViewDebug::emitTypeInformation() {
     500             :   // Do nothing if we have no debug info or if no non-trivial types were emitted
     501             :   // to TypeTable during codegen.
     502         186 :   NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
     503          93 :   if (!CU_Nodes)
     504           5 :     return;
     505         186 :   if (TypeTable.empty())
     506             :     return;
     507             : 
     508             :   // Start the .debug$T section with 0x4.
     509          88 :   OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
     510          88 :   emitCodeViewMagicVersion();
     511             : 
     512         176 :   SmallString<8> CommentPrefix;
     513          88 :   if (OS.isVerboseAsm()) {
     514          41 :     CommentPrefix += '\t';
     515          82 :     CommentPrefix += Asm->MAI->getCommentString();
     516             :     CommentPrefix += ' ';
     517             :   }
     518             : 
     519         264 :   TypeTableCollection Table(TypeTable.records());
     520         176 :   Optional<TypeIndex> B = Table.getFirst();
     521        1706 :   while (B) {
     522             :     // This will fail if the record data is invalid.
     523        1618 :     CVType Record = Table.getType(*B);
     524             : 
     525         809 :     if (OS.isVerboseAsm()) {
     526             :       // Emit a block comment describing the type record for readability.
     527         424 :       SmallString<512> CommentBlock;
     528         424 :       raw_svector_ostream CommentOS(CommentBlock);
     529         212 :       ScopedPrinter SP(CommentOS);
     530         424 :       SP.setPrefix(CommentPrefix);
     531         424 :       TypeDumpVisitor TDV(Table, &SP, false);
     532             : 
     533         424 :       Error E = codeview::visitTypeRecord(Record, *B, TDV);
     534         212 :       if (E) {
     535           0 :         logAllUnhandledErrors(std::move(E), errs(), "error: ");
     536           0 :         llvm_unreachable("produced malformed type record");
     537             :       }
     538             :       // emitRawComment will insert its own tab and comment string before
     539             :       // the first line, so strip off our first one. It also prints its own
     540             :       // newline.
     541         424 :       OS.emitRawComment(
     542        1272 :           CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
     543             :     }
     544        1618 :     OS.EmitBinaryData(Record.str_data());
     545        2427 :     B = Table.getNext(*B);
     546             :   }
     547             : }
     548             : 
     549             : static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
     550             :   switch (DWLang) {
     551             :   case dwarf::DW_LANG_C:
     552             :   case dwarf::DW_LANG_C89:
     553             :   case dwarf::DW_LANG_C99:
     554             :   case dwarf::DW_LANG_C11:
     555             :   case dwarf::DW_LANG_ObjC:
     556             :     return SourceLanguage::C;
     557             :   case dwarf::DW_LANG_C_plus_plus:
     558             :   case dwarf::DW_LANG_C_plus_plus_03:
     559             :   case dwarf::DW_LANG_C_plus_plus_11:
     560             :   case dwarf::DW_LANG_C_plus_plus_14:
     561             :     return SourceLanguage::Cpp;
     562             :   case dwarf::DW_LANG_Fortran77:
     563             :   case dwarf::DW_LANG_Fortran90:
     564             :   case dwarf::DW_LANG_Fortran03:
     565             :   case dwarf::DW_LANG_Fortran08:
     566             :     return SourceLanguage::Fortran;
     567             :   case dwarf::DW_LANG_Pascal83:
     568             :     return SourceLanguage::Pascal;
     569             :   case dwarf::DW_LANG_Cobol74:
     570             :   case dwarf::DW_LANG_Cobol85:
     571             :     return SourceLanguage::Cobol;
     572             :   case dwarf::DW_LANG_Java:
     573             :     return SourceLanguage::Java;
     574             :   case dwarf::DW_LANG_D:
     575             :     return SourceLanguage::D;
     576             :   default:
     577             :     // There's no CodeView representation for this language, and CV doesn't
     578             :     // have an "unknown" option for the language field, so we'll use MASM,
     579             :     // as it's very low level.
     580             :     return SourceLanguage::Masm;
     581             :   }
     582             : }
     583             : 
     584             : namespace {
     585             : struct Version {
     586             :   int Part[4];
     587             : };
     588             : } // end anonymous namespace
     589             : 
     590             : // Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
     591             : // the version number.
     592          93 : static Version parseVersion(StringRef Name) {
     593          93 :   Version V = {{0}};
     594          93 :   int N = 0;
     595        1858 :   for (const char C : Name) {
     596        1761 :     if (isdigit(C)) {
     597         246 :       V.Part[N] *= 10;
     598         246 :       V.Part[N] += C - '0';
     599        1515 :     } else if (C == '.') {
     600         158 :       ++N;
     601         158 :       if (N >= 4)
     602           0 :         return V;
     603        1357 :     } else if (N > 0)
     604          89 :       return V;
     605             :   }
     606           4 :   return V;
     607             : }
     608             : 
     609          93 : static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
     610          93 :   switch (Type) {
     611             :   case Triple::ArchType::x86:
     612             :     return CPUType::Pentium3;
     613          51 :   case Triple::ArchType::x86_64:
     614          51 :     return CPUType::X64;
     615           1 :   case Triple::ArchType::thumb:
     616           1 :     return CPUType::Thumb;
     617           1 :   case Triple::ArchType::aarch64:
     618           1 :     return CPUType::ARM64;
     619           0 :   default:
     620           0 :     report_fatal_error("target architecture doesn't map to a CodeView CPUType");
     621             :   }
     622             : }
     623             : 
     624          93 : void CodeViewDebug::emitCompilerInformation() {
     625         186 :   MCContext &Context = MMI->getContext();
     626          93 :   MCSymbol *CompilerBegin = Context.createTempSymbol(),
     627          93 :            *CompilerEnd = Context.createTempSymbol();
     628         186 :   OS.AddComment("Record length");
     629          93 :   OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
     630          93 :   OS.EmitLabel(CompilerBegin);
     631         186 :   OS.AddComment("Record kind: S_COMPILE3");
     632          93 :   OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
     633          93 :   uint32_t Flags = 0;
     634             : 
     635         186 :   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
     636         186 :   const MDNode *Node = *CUs->operands().begin();
     637          93 :   const auto *CU = cast<DICompileUnit>(Node);
     638             : 
     639             :   // The low byte of the flags indicates the source language.
     640          93 :   Flags = MapDWLangToCVLang(CU->getSourceLanguage());
     641             :   // TODO:  Figure out which other flags need to be set.
     642             : 
     643         186 :   OS.AddComment("Flags and language");
     644          93 :   OS.EmitIntValue(Flags, 4);
     645             : 
     646         186 :   OS.AddComment("CPUType");
     647             :   CPUType CPU =
     648         372 :       mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
     649          93 :   OS.EmitIntValue(static_cast<uint64_t>(CPU), 2);
     650             : 
     651          93 :   StringRef CompilerVersion = CU->getProducer();
     652          93 :   Version FrontVer = parseVersion(CompilerVersion);
     653         186 :   OS.AddComment("Frontend version");
     654         465 :   for (int N = 0; N < 4; ++N)
     655         372 :     OS.EmitIntValue(FrontVer.Part[N], 2);
     656             : 
     657             :   // Some Microsoft tools, like Binscope, expect a backend version number of at
     658             :   // least 8.something, so we'll coerce the LLVM version into a form that
     659             :   // guarantees it'll be big enough without really lying about the version.
     660          93 :   int Major = 1000 * LLVM_VERSION_MAJOR +
     661             :               10 * LLVM_VERSION_MINOR +
     662             :               LLVM_VERSION_PATCH;
     663             :   // Clamp it for builds that use unusually large version numbers.
     664          93 :   Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
     665          93 :   Version BackVer = {{ Major, 0, 0, 0 }};
     666         186 :   OS.AddComment("Backend version");
     667         465 :   for (int N = 0; N < 4; ++N)
     668         372 :     OS.EmitIntValue(BackVer.Part[N], 2);
     669             : 
     670         186 :   OS.AddComment("Null-terminated compiler version string");
     671          93 :   emitNullTerminatedSymbolName(OS, CompilerVersion);
     672             : 
     673          93 :   OS.EmitLabel(CompilerEnd);
     674          93 : }
     675             : 
     676          93 : void CodeViewDebug::emitInlineeLinesSubsection() {
     677         186 :   if (InlinedSubprograms.empty())
     678             :     return;
     679             : 
     680          24 :   OS.AddComment("Inlinee lines subsection");
     681          12 :   MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
     682             : 
     683             :   // We don't provide any extra file info.
     684             :   // FIXME: Find out if debuggers use this info.
     685          24 :   OS.AddComment("Inlinee lines signature");
     686          12 :   OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
     687             : 
     688          58 :   for (const DISubprogram *SP : InlinedSubprograms) {
     689             :     assert(TypeIndices.count({SP, nullptr}));
     690          66 :     TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
     691             : 
     692          22 :     OS.AddBlankLine();
     693          44 :     unsigned FileId = maybeRecordFile(SP->getFile());
     694         176 :     OS.AddComment("Inlined function " + SP->getName() + " starts at " +
     695         176 :                   SP->getFilename() + Twine(':') + Twine(SP->getLine()));
     696          22 :     OS.AddBlankLine();
     697             :     // The filechecksum table uses 8 byte entries for now, and file ids start at
     698             :     // 1.
     699          22 :     unsigned FileOffset = (FileId - 1) * 8;
     700          44 :     OS.AddComment("Type index of inlined function");
     701          44 :     OS.EmitIntValue(InlineeIdx.getIndex(), 4);
     702          44 :     OS.AddComment("Offset into filechecksum table");
     703          22 :     OS.EmitIntValue(FileOffset, 4);
     704          44 :     OS.AddComment("Starting line number");
     705          22 :     OS.EmitIntValue(SP->getLine(), 4);
     706             :   }
     707             : 
     708          12 :   endCVSubsection(InlineEnd);
     709             : }
     710             : 
     711          24 : void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
     712             :                                         const DILocation *InlinedAt,
     713             :                                         const InlineSite &Site) {
     714          48 :   MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
     715          48 :            *InlineEnd = MMI->getContext().createTempSymbol();
     716             : 
     717             :   assert(TypeIndices.count({Site.Inlinee, nullptr}));
     718          72 :   TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
     719             : 
     720             :   // SymbolRecord
     721          48 :   OS.AddComment("Record length");
     722          24 :   OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2);   // RecordLength
     723          24 :   OS.EmitLabel(InlineBegin);
     724          48 :   OS.AddComment("Record kind: S_INLINESITE");
     725          24 :   OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
     726             : 
     727          48 :   OS.AddComment("PtrParent");
     728          24 :   OS.EmitIntValue(0, 4);
     729          48 :   OS.AddComment("PtrEnd");
     730          24 :   OS.EmitIntValue(0, 4);
     731          48 :   OS.AddComment("Inlinee type index");
     732          48 :   OS.EmitIntValue(InlineeIdx.getIndex(), 4);
     733             : 
     734          48 :   unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
     735          24 :   unsigned StartLineNum = Site.Inlinee->getLine();
     736             : 
     737          48 :   OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
     738          24 :                                     FI.Begin, FI.End);
     739             : 
     740          24 :   OS.EmitLabel(InlineEnd);
     741             : 
     742          48 :   emitLocalVariableList(Site.InlinedLocals);
     743             : 
     744             :   // Recurse on child inlined call sites before closing the scope.
     745          78 :   for (const DILocation *ChildSite : Site.ChildSites) {
     746          12 :     auto I = FI.InlineSites.find(ChildSite);
     747             :     assert(I != FI.InlineSites.end() &&
     748             :            "child site not in function inline site map");
     749           6 :     emitInlinedCallSite(FI, ChildSite, I->second);
     750             :   }
     751             : 
     752             :   // Close the scope.
     753          48 :   OS.AddComment("Record length");
     754          24 :   OS.EmitIntValue(2, 2);                                  // RecordLength
     755          48 :   OS.AddComment("Record kind: S_INLINESITE_END");
     756          24 :   OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
     757          24 : }
     758             : 
     759         412 : void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
     760             :   // If we have a symbol, it may be in a section that is COMDAT. If so, find the
     761             :   // comdat key. A section may be comdat because of -ffunction-sections or
     762             :   // because it is comdat in the IR.
     763             :   MCSectionCOFF *GVSec =
     764         676 :       GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
     765         132 :   const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
     766             : 
     767         824 :   MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
     768         824 :       Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
     769         412 :   DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
     770             : 
     771         412 :   OS.SwitchSection(DebugSec);
     772             : 
     773             :   // Emit the magic version number if this is the first time we've switched to
     774             :   // this section.
     775         824 :   if (ComdatDebugSections.insert(DebugSec).second)
     776         115 :     emitCodeViewMagicVersion();
     777         412 : }
     778             : 
     779         129 : void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
     780             :                                              FunctionInfo &FI) {
     781             :   // For each function there is a separate subsection
     782             :   // which holds the PC to file:line table.
     783         129 :   const MCSymbol *Fn = Asm->getSymbol(GV);
     784             :   assert(Fn);
     785             : 
     786             :   // Switch to the to a comdat section, if appropriate.
     787         129 :   switchToDebugSectionForSymbol(Fn);
     788             : 
     789         258 :   std::string FuncName;
     790         129 :   auto *SP = GV->getSubprogram();
     791             :   assert(SP);
     792         129 :   setCurrentSubprogram(SP);
     793             : 
     794             :   // If we have a display name, build the fully qualified name by walking the
     795             :   // chain of scopes.
     796         129 :   if (!SP->getName().empty())
     797         124 :     FuncName =
     798         496 :         getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
     799             : 
     800             :   // If our DISubprogram name is empty, use the mangled name.
     801         129 :   if (FuncName.empty())
     802          15 :     FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
     803             : 
     804             :   // Emit a symbol subsection, required by VS2012+ to find function boundaries.
     805         516 :   OS.AddComment("Symbol subsection for " + Twine(FuncName));
     806         129 :   MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
     807             :   {
     808         258 :     MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
     809         258 :              *ProcRecordEnd = MMI->getContext().createTempSymbol();
     810         258 :     OS.AddComment("Record length");
     811         129 :     OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
     812         129 :     OS.EmitLabel(ProcRecordBegin);
     813             : 
     814         247 :     if (GV->hasLocalLinkage()) {
     815          22 :       OS.AddComment("Record kind: S_LPROC32_ID");
     816          11 :       OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
     817             :     } else {
     818         236 :       OS.AddComment("Record kind: S_GPROC32_ID");
     819         118 :       OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
     820             :     }
     821             : 
     822             :     // These fields are filled in by tools like CVPACK which run after the fact.
     823         258 :     OS.AddComment("PtrParent");
     824         129 :     OS.EmitIntValue(0, 4);
     825         258 :     OS.AddComment("PtrEnd");
     826         129 :     OS.EmitIntValue(0, 4);
     827         258 :     OS.AddComment("PtrNext");
     828         129 :     OS.EmitIntValue(0, 4);
     829             :     // This is the important bit that tells the debugger where the function
     830             :     // code is located and what's its size:
     831         258 :     OS.AddComment("Code size");
     832         129 :     OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
     833         258 :     OS.AddComment("Offset after prologue");
     834         129 :     OS.EmitIntValue(0, 4);
     835         258 :     OS.AddComment("Offset before epilogue");
     836         129 :     OS.EmitIntValue(0, 4);
     837         258 :     OS.AddComment("Function type index");
     838         258 :     OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
     839         258 :     OS.AddComment("Function section relative address");
     840         129 :     OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
     841         258 :     OS.AddComment("Function section index");
     842         129 :     OS.EmitCOFFSectionIndex(Fn);
     843         258 :     OS.AddComment("Flags");
     844         129 :     OS.EmitIntValue(0, 1);
     845             :     // Emit the function display name as a null-terminated string.
     846         258 :     OS.AddComment("Function name");
     847             :     // Truncate the name so we won't overflow the record length field.
     848         129 :     emitNullTerminatedSymbolName(OS, FuncName);
     849         129 :     OS.EmitLabel(ProcRecordEnd);
     850             : 
     851         258 :     emitLocalVariableList(FI.Locals);
     852             : 
     853             :     // Emit inlined call site information. Only emit functions inlined directly
     854             :     // into the parent function. We'll emit the other sites recursively as part
     855             :     // of their parent inline site.
     856         405 :     for (const DILocation *InlinedAt : FI.ChildSites) {
     857          36 :       auto I = FI.InlineSites.find(InlinedAt);
     858             :       assert(I != FI.InlineSites.end() &&
     859             :              "child site not in function inline site map");
     860          18 :       emitInlinedCallSite(FI, InlinedAt, I->second);
     861             :     }
     862             : 
     863         517 :     for (auto Annot : FI.Annotations) {
     864           1 :       MCSymbol *Label = Annot.first;
     865           2 :       MDTuple *Strs = cast<MDTuple>(Annot.second);
     866           2 :       MCSymbol *AnnotBegin = MMI->getContext().createTempSymbol(),
     867           2 :                *AnnotEnd = MMI->getContext().createTempSymbol();
     868           2 :       OS.AddComment("Record length");
     869           1 :       OS.emitAbsoluteSymbolDiff(AnnotEnd, AnnotBegin, 2);
     870           1 :       OS.EmitLabel(AnnotBegin);
     871           2 :       OS.AddComment("Record kind: S_ANNOTATION");
     872           1 :       OS.EmitIntValue(SymbolKind::S_ANNOTATION, 2);
     873           1 :       OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
     874             :       // FIXME: Make sure we don't overflow the max record size.
     875           1 :       OS.EmitCOFFSectionIndex(Label);
     876           1 :       OS.EmitIntValue(Strs->getNumOperands(), 2);
     877           6 :       for (Metadata *MD : Strs->operands()) {
     878             :         // MDStrings are null terminated, so we can do EmitBytes and get the
     879             :         // nice .asciz directive.
     880           2 :         StringRef Str = cast<MDString>(MD)->getString();
     881             :         assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
     882           8 :         OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
     883             :       }
     884           1 :       OS.EmitLabel(AnnotEnd);
     885             :     }
     886             : 
     887         129 :     if (SP != nullptr)
     888         258 :       emitDebugInfoForUDTs(LocalUDTs);
     889             : 
     890             :     // We're done with this function.
     891         258 :     OS.AddComment("Record length");
     892         129 :     OS.EmitIntValue(0x0002, 2);
     893         258 :     OS.AddComment("Record kind: S_PROC_ID_END");
     894         129 :     OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
     895             :   }
     896         129 :   endCVSubsection(SymbolsEnd);
     897             : 
     898             :   // We have an assembler directive that takes care of the whole line table.
     899         129 :   OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
     900         129 : }
     901             : 
     902             : CodeViewDebug::LocalVarDefRange
     903           0 : CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
     904          95 :   LocalVarDefRange DR;
     905          95 :   DR.InMemory = -1;
     906          95 :   DR.DataOffset = Offset;
     907             :   assert(DR.DataOffset == Offset && "truncation");
     908          95 :   DR.IsSubfield = 0;
     909          95 :   DR.StructOffset = 0;
     910          95 :   DR.CVRegister = CVRegister;
     911           0 :   return DR;
     912             : }
     913             : 
     914             : CodeViewDebug::LocalVarDefRange
     915           0 : CodeViewDebug::createDefRangeGeneral(uint16_t CVRegister, bool InMemory,
     916             :                                      int Offset, bool IsSubfield,
     917             :                                      uint16_t StructOffset) {
     918           0 :   LocalVarDefRange DR;
     919           0 :   DR.InMemory = InMemory;
     920           0 :   DR.DataOffset = Offset;
     921           0 :   DR.IsSubfield = IsSubfield;
     922           0 :   DR.StructOffset = StructOffset;
     923           0 :   DR.CVRegister = CVRegister;
     924           0 :   return DR;
     925             : }
     926             : 
     927         129 : void CodeViewDebug::collectVariableInfoFromMFTable(
     928             :     DenseSet<InlinedVariable> &Processed) {
     929         129 :   const MachineFunction &MF = *Asm->MF;
     930         129 :   const TargetSubtargetInfo &TSI = MF.getSubtarget();
     931         129 :   const TargetFrameLowering *TFI = TSI.getFrameLowering();
     932         129 :   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
     933             : 
     934         482 :   for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
     935          95 :     if (!VI.Var)
     936           0 :       continue;
     937             :     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
     938             :            "Expected inlined-at fields to agree");
     939             : 
     940         380 :     Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
     941          95 :     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
     942             : 
     943             :     // If variable scope is not found then skip this variable.
     944          95 :     if (!Scope)
     945           0 :       continue;
     946             : 
     947             :     // If the variable has an attached offset expression, extract it.
     948             :     // FIXME: Try to handle DW_OP_deref as well.
     949          95 :     int64_t ExprOffset = 0;
     950          95 :     if (VI.Expr)
     951          95 :       if (!VI.Expr->extractIfOffset(ExprOffset))
     952           0 :         continue;
     953             : 
     954             :     // Get the frame register used and the offset.
     955          95 :     unsigned FrameReg = 0;
     956          95 :     int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
     957          95 :     uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
     958             : 
     959             :     // Calculate the label ranges.
     960             :     LocalVarDefRange DefRange =
     961         285 :         createDefRangeMem(CVReg, FrameOffset + ExprOffset);
     962         380 :     for (const InsnRange &Range : Scope->getRanges()) {
     963          95 :       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
     964          95 :       const MCSymbol *End = getLabelAfterInsn(Range.second);
     965          95 :       End = End ? End : Asm->getFunctionEnd();
     966          95 :       DefRange.Ranges.emplace_back(Begin, End);
     967             :     }
     968             : 
     969         190 :     LocalVariable Var;
     970          95 :     Var.DIVar = VI.Var;
     971          95 :     Var.DefRanges.emplace_back(std::move(DefRange));
     972         190 :     recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
     973             :   }
     974         129 : }
     975             : 
     976             : static bool canUseReferenceType(const DbgVariableLocation &Loc) {
     977          12 :   return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
     978             : }
     979             : 
     980             : static bool needsReferenceType(const DbgVariableLocation &Loc) {
     981         120 :   return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
     982             : }
     983             : 
     984          41 : void CodeViewDebug::calculateRanges(
     985             :     LocalVariable &Var, const DbgValueHistoryMap::InstrRanges &Ranges) {
     986          41 :   const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
     987             : 
     988             :   // Calculate the definition ranges.
     989         191 :   for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
     990          72 :     const InsnRange &Range = *I;
     991          72 :     const MachineInstr *DVInst = Range.first;
     992             :     assert(DVInst->isDebugValue() && "Invalid History entry");
     993             :     // FIXME: Find a way to represent constant variables, since they are
     994             :     // relatively common.
     995             :     Optional<DbgVariableLocation> Location =
     996         132 :         DbgVariableLocation::extractFromMachineInstruction(*DVInst);
     997          72 :     if (!Location)
     998          16 :       continue;
     999             : 
    1000             :     // CodeView can only express variables in register and variables in memory
    1001             :     // at a constant offset from a register. However, for variables passed
    1002             :     // indirectly by pointer, it is common for that pointer to be spilled to a
    1003             :     // stack location. For the special case of one offseted load followed by a
    1004             :     // zero offset load (a pointer spilled to the stack), we change the type of
    1005             :     // the local variable from a value type to a reference type. This tricks the
    1006             :     // debugger into doing the load for us.
    1007          64 :     if (Var.UseReferenceType) {
    1008             :       // We're using a reference type. Drop the last zero offset load.
    1009          12 :       if (canUseReferenceType(*Location))
    1010           6 :         Location->LoadChain.pop_back();
    1011             :       else
    1012           0 :         continue;
    1013          62 :     } else if (needsReferenceType(*Location)) {
    1014             :       // This location can't be expressed without switching to a reference type.
    1015             :       // Start over using that.
    1016           4 :       Var.UseReferenceType = true;
    1017           4 :       Var.DefRanges.clear();
    1018           4 :       calculateRanges(Var, Ranges);
    1019           4 :       return;
    1020             :     }
    1021             : 
    1022             :     // We can only handle a register or an offseted load of a register.
    1023         180 :     if (Location->Register == 0 || Location->LoadChain.size() > 1)
    1024           0 :       continue;
    1025             :     {
    1026         120 :       LocalVarDefRange DR;
    1027         120 :       DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
    1028          60 :       DR.InMemory = !Location->LoadChain.empty();
    1029          71 :       DR.DataOffset =
    1030          82 :           !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
    1031          60 :       if (Location->FragmentInfo) {
    1032          16 :         DR.IsSubfield = true;
    1033          32 :         DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
    1034             :       } else {
    1035          44 :         DR.IsSubfield = false;
    1036          44 :         DR.StructOffset = 0;
    1037             :       }
    1038             : 
    1039          85 :       if (Var.DefRanges.empty() ||
    1040          50 :           Var.DefRanges.back().isDifferentLocation(DR)) {
    1041          42 :         Var.DefRanges.emplace_back(std::move(DR));
    1042             :       }
    1043             :     }
    1044             : 
    1045             :     // Compute the label range.
    1046          60 :     const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
    1047          60 :     const MCSymbol *End = getLabelAfterInsn(Range.second);
    1048          60 :     if (!End) {
    1049             :       // This range is valid until the next overlapping bitpiece. In the
    1050             :       // common case, ranges will not be bitpieces, so they will overlap.
    1051          19 :       auto J = std::next(I);
    1052          19 :       const DIExpression *DIExpr = DVInst->getDebugExpression();
    1053          34 :       while (J != E &&
    1054           7 :              !fragmentsOverlap(DIExpr, J->first->getDebugExpression()))
    1055           4 :         ++J;
    1056          19 :       if (J != E)
    1057           3 :         End = getLabelBeforeInsn(J->first);
    1058             :       else
    1059          16 :         End = Asm->getFunctionEnd();
    1060             :     }
    1061             : 
    1062             :     // If the last range end is our begin, just extend the last range.
    1063             :     // Otherwise make a new range.
    1064             :     SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
    1065         120 :         Var.DefRanges.back().Ranges;
    1066          78 :     if (!R.empty() && R.back().second == Begin)
    1067          30 :       R.back().second = End;
    1068             :     else
    1069          45 :       R.emplace_back(Begin, End);
    1070             : 
    1071             :     // FIXME: Do more range combining.
    1072             :   }
    1073             : }
    1074             : 
    1075         129 : void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
    1076         258 :   DenseSet<InlinedVariable> Processed;
    1077             :   // Grab the variable info that was squirreled away in the MMI side-table.
    1078         129 :   collectVariableInfoFromMFTable(Processed);
    1079             : 
    1080         553 :   for (const auto &I : DbgValues) {
    1081          37 :     InlinedVariable IV = I.first;
    1082          37 :     if (Processed.count(IV))
    1083           0 :       continue;
    1084          37 :     const DILocalVariable *DIVar = IV.first;
    1085          37 :     const DILocation *InlinedAt = IV.second;
    1086             : 
    1087             :     // Instruction ranges, specifying where IV is accessible.
    1088          37 :     const auto &Ranges = I.second;
    1089             : 
    1090          37 :     LexicalScope *Scope = nullptr;
    1091          37 :     if (InlinedAt)
    1092           8 :       Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
    1093             :     else
    1094          66 :       Scope = LScopes.findLexicalScope(DIVar->getScope());
    1095             :     // If variable scope is not found then skip this variable.
    1096           0 :     if (!Scope)
    1097           0 :       continue;
    1098             : 
    1099          74 :     LocalVariable Var;
    1100          37 :     Var.DIVar = DIVar;
    1101             : 
    1102          37 :     calculateRanges(Var, Ranges);
    1103          37 :     recordLocalVariable(std::move(Var), InlinedAt);
    1104             :   }
    1105         129 : }
    1106             : 
    1107         129 : void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
    1108         129 :   const Function *GV = MF->getFunction();
    1109             :   assert(FnDebugInfo.count(GV) == false);
    1110         129 :   CurFn = &FnDebugInfo[GV];
    1111         129 :   CurFn->FuncId = NextFuncId++;
    1112         129 :   CurFn->Begin = Asm->getFunctionBegin();
    1113             : 
    1114         129 :   OS.EmitCVFuncIdDirective(CurFn->FuncId);
    1115             : 
    1116             :   // Find the end of the function prolog.  First known non-DBG_VALUE and
    1117             :   // non-frame setup location marks the beginning of the function body.
    1118             :   // FIXME: is there a simpler a way to do this? Can we just search
    1119             :   // for the first instruction of the function, not the last of the prolog?
    1120         258 :   DebugLoc PrologEndLoc;
    1121         129 :   bool EmptyPrologue = true;
    1122         573 :   for (const auto &MBB : *MF) {
    1123        1836 :     for (const auto &MI : MBB) {
    1124         827 :       if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
    1125         562 :           MI.getDebugLoc()) {
    1126         180 :         PrologEndLoc = MI.getDebugLoc();
    1127             :         break;
    1128           1 :       } else if (!MI.isMetaInstruction()) {
    1129             :         EmptyPrologue = false;
    1130             :       }
    1131             :     }
    1132             :   }
    1133             : 
    1134             :   // Record beginning of function if we have a non-empty prologue.
    1135         129 :   if (PrologEndLoc && !EmptyPrologue) {
    1136         182 :     DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
    1137          91 :     maybeRecordLocation(FnStartDL, MF);
    1138             :   }
    1139         129 : }
    1140             : 
    1141          77 : static bool shouldEmitUdt(const DIType *T) {
    1142          77 :   if (!T)
    1143             :     return false;
    1144             : 
    1145             :   // MSVC does not emit UDTs for typedefs that are scoped to classes.
    1146          77 :   if (T->getTag() == dwarf::DW_TAG_typedef) {
    1147          17 :     if (DIScope *Scope = T->getScope().resolve()) {
    1148           4 :       switch (Scope->getTag()) {
    1149             :       case dwarf::DW_TAG_structure_type:
    1150             :       case dwarf::DW_TAG_class_type:
    1151             :       case dwarf::DW_TAG_union_type:
    1152             :         return false;
    1153             :       }
    1154             :     }
    1155             :   }
    1156             : 
    1157             :   while (true) {
    1158         172 :     if (!T || T->isForwardDecl())
    1159             :       return false;
    1160             : 
    1161          12 :     const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
    1162             :     if (!DT)
    1163             :       return true;
    1164          12 :     T = DT->getBaseType().resolve();
    1165             :   }
    1166             :   return true;
    1167             : }
    1168             : 
    1169          79 : void CodeViewDebug::addToUDTs(const DIType *Ty) {
    1170             :   // Don't record empty UDTs.
    1171         158 :   if (Ty->getName().empty())
    1172           6 :     return;
    1173          77 :   if (!shouldEmitUdt(Ty))
    1174             :     return;
    1175             : 
    1176         146 :   SmallVector<StringRef, 5> QualifiedNameComponents;
    1177             :   const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
    1178         219 :       Ty->getScope().resolve(), QualifiedNameComponents);
    1179             : 
    1180             :   std::string FullyQualifiedName =
    1181         219 :       getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
    1182             : 
    1183          73 :   if (ClosestSubprogram == nullptr) {
    1184          70 :     GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
    1185           3 :   } else if (ClosestSubprogram == CurrentSubprogram) {
    1186           3 :     LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
    1187             :   }
    1188             : 
    1189             :   // TODO: What if the ClosestSubprogram is neither null or the current
    1190             :   // subprogram?  Currently, the UDT just gets dropped on the floor.
    1191             :   //
    1192             :   // The current behavior is not desirable.  To get maximal fidelity, we would
    1193             :   // need to perform all type translation before beginning emission of .debug$S
    1194             :   // and then make LocalUDTs a member of FunctionInfo
    1195             : }
    1196             : 
    1197         404 : TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
    1198             :   // Generic dispatch for lowering an unknown type.
    1199         808 :   switch (Ty->getTag()) {
    1200          10 :   case dwarf::DW_TAG_array_type:
    1201          10 :     return lowerTypeArray(cast<DICompositeType>(Ty));
    1202          13 :   case dwarf::DW_TAG_typedef:
    1203          13 :     return lowerTypeAlias(cast<DIDerivedType>(Ty));
    1204          85 :   case dwarf::DW_TAG_base_type:
    1205          85 :     return lowerTypeBasic(cast<DIBasicType>(Ty));
    1206          80 :   case dwarf::DW_TAG_pointer_type:
    1207         246 :     if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
    1208           6 :       return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
    1209             :     LLVM_FALLTHROUGH;
    1210             :   case dwarf::DW_TAG_reference_type:
    1211             :   case dwarf::DW_TAG_rvalue_reference_type:
    1212          74 :     return lowerTypePointer(cast<DIDerivedType>(Ty));
    1213          12 :   case dwarf::DW_TAG_ptr_to_member_type:
    1214          12 :     return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
    1215          15 :   case dwarf::DW_TAG_const_type:
    1216             :   case dwarf::DW_TAG_volatile_type:
    1217             :   // TODO: add support for DW_TAG_atomic_type here
    1218          15 :     return lowerTypeModifier(cast<DIDerivedType>(Ty));
    1219         112 :   case dwarf::DW_TAG_subroutine_type:
    1220         112 :     if (ClassTy) {
    1221             :       // The member function type of a member function pointer has no
    1222             :       // ThisAdjustment.
    1223             :       return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
    1224           6 :                                      /*ThisAdjustment=*/0);
    1225             :     }
    1226         106 :     return lowerTypeFunction(cast<DISubroutineType>(Ty));
    1227           4 :   case dwarf::DW_TAG_enumeration_type:
    1228           4 :     return lowerTypeEnum(cast<DICompositeType>(Ty));
    1229          70 :   case dwarf::DW_TAG_class_type:
    1230             :   case dwarf::DW_TAG_structure_type:
    1231          70 :     return lowerTypeClass(cast<DICompositeType>(Ty));
    1232           3 :   case dwarf::DW_TAG_union_type:
    1233           3 :     return lowerTypeUnion(cast<DICompositeType>(Ty));
    1234           0 :   default:
    1235             :     // Use the null type index.
    1236           0 :     return TypeIndex();
    1237             :   }
    1238             : }
    1239             : 
    1240          13 : TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
    1241          13 :   DITypeRef UnderlyingTypeRef = Ty->getBaseType();
    1242          13 :   TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
    1243          26 :   StringRef TypeName = Ty->getName();
    1244             : 
    1245          13 :   addToUDTs(Ty);
    1246             : 
    1247          39 :   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
    1248           0 :       TypeName == "HRESULT")
    1249           0 :     return TypeIndex(SimpleTypeKind::HResult);
    1250          39 :   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
    1251           0 :       TypeName == "wchar_t")
    1252           0 :     return TypeIndex(SimpleTypeKind::WideCharacter);
    1253             : 
    1254          13 :   return UnderlyingTypeIndex;
    1255             : }
    1256             : 
    1257          10 : TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
    1258          10 :   DITypeRef ElementTypeRef = Ty->getBaseType();
    1259          10 :   TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
    1260             :   // IndexType is size_t, which depends on the bitness of the target.
    1261          20 :   TypeIndex IndexType = Asm->TM.getPointerSize() == 8
    1262             :                             ? TypeIndex(SimpleTypeKind::UInt64Quad)
    1263          10 :                             : TypeIndex(SimpleTypeKind::UInt32Long);
    1264             : 
    1265          10 :   uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
    1266             : 
    1267             :   // Add subranges to array type.
    1268          10 :   DINodeArray Elements = Ty->getElements();
    1269          22 :   for (int i = Elements.size() - 1; i >= 0; --i) {
    1270          24 :     const DINode *Element = Elements[i];
    1271             :     assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
    1272             : 
    1273          12 :     const DISubrange *Subrange = cast<DISubrange>(Element);
    1274             :     assert(Subrange->getLowerBound() == 0 &&
    1275             :            "codeview doesn't support subranges with lower bounds");
    1276          12 :     int64_t Count = Subrange->getCount();
    1277             : 
    1278             :     // Variable Length Array (VLA) has Count equal to '-1'.
    1279             :     // Replace with Count '1', assume it is the minimum VLA length.
    1280             :     // FIXME: Make front-end support VLA subrange and emit LF_DIMVARLU.
    1281          12 :     if (Count == -1)
    1282           1 :       Count = 1;
    1283             : 
    1284             :     // Update the element size and element type index for subsequent subranges.
    1285          12 :     ElementSize *= Count;
    1286             : 
    1287             :     // If this is the outermost array, use the size from the array. It will be
    1288             :     // more accurate if we had a VLA or an incomplete element type size.
    1289             :     uint64_t ArraySize =
    1290          12 :         (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
    1291             : 
    1292          22 :     StringRef Name = (i == 0) ? Ty->getName() : "";
    1293          12 :     ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
    1294          12 :     ElementTypeIndex = TypeTable.writeKnownType(AR);
    1295             :   }
    1296             : 
    1297          10 :   return ElementTypeIndex;
    1298             : }
    1299             : 
    1300          85 : TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
    1301          85 :   TypeIndex Index;
    1302             :   dwarf::TypeKind Kind;
    1303             :   uint32_t ByteSize;
    1304             : 
    1305          85 :   Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
    1306          85 :   ByteSize = Ty->getSizeInBits() / 8;
    1307             : 
    1308          85 :   SimpleTypeKind STK = SimpleTypeKind::None;
    1309          85 :   switch (Kind) {
    1310             :   case dwarf::DW_ATE_address:
    1311             :     // FIXME: Translate
    1312             :     break;
    1313           0 :   case dwarf::DW_ATE_boolean:
    1314           0 :     switch (ByteSize) {
    1315           0 :     case 1:  STK = SimpleTypeKind::Boolean8;   break;
    1316           0 :     case 2:  STK = SimpleTypeKind::Boolean16;  break;
    1317           0 :     case 4:  STK = SimpleTypeKind::Boolean32;  break;
    1318           0 :     case 8:  STK = SimpleTypeKind::Boolean64;  break;
    1319           0 :     case 16: STK = SimpleTypeKind::Boolean128; break;
    1320             :     }
    1321             :     break;
    1322           0 :   case dwarf::DW_ATE_complex_float:
    1323           0 :     switch (ByteSize) {
    1324           0 :     case 2:  STK = SimpleTypeKind::Complex16;  break;
    1325           0 :     case 4:  STK = SimpleTypeKind::Complex32;  break;
    1326           0 :     case 8:  STK = SimpleTypeKind::Complex64;  break;
    1327           0 :     case 10: STK = SimpleTypeKind::Complex80;  break;
    1328           0 :     case 16: STK = SimpleTypeKind::Complex128; break;
    1329             :     }
    1330             :     break;
    1331           7 :   case dwarf::DW_ATE_float:
    1332           7 :     switch (ByteSize) {
    1333           0 :     case 2:  STK = SimpleTypeKind::Float16;  break;
    1334           4 :     case 4:  STK = SimpleTypeKind::Float32;  break;
    1335           0 :     case 6:  STK = SimpleTypeKind::Float48;  break;
    1336           3 :     case 8:  STK = SimpleTypeKind::Float64;  break;
    1337           0 :     case 10: STK = SimpleTypeKind::Float80;  break;
    1338           0 :     case 16: STK = SimpleTypeKind::Float128; break;
    1339             :     }
    1340             :     break;
    1341          62 :   case dwarf::DW_ATE_signed:
    1342          62 :     switch (ByteSize) {
    1343           1 :     case 1:  STK = SimpleTypeKind::SignedCharacter; break;
    1344           1 :     case 2:  STK = SimpleTypeKind::Int16Short;      break;
    1345          59 :     case 4:  STK = SimpleTypeKind::Int32;           break;
    1346           1 :     case 8:  STK = SimpleTypeKind::Int64Quad;       break;
    1347           0 :     case 16: STK = SimpleTypeKind::Int128Oct;       break;
    1348             :     }
    1349             :     break;
    1350           7 :   case dwarf::DW_ATE_unsigned:
    1351           7 :     switch (ByteSize) {
    1352           1 :     case 1:  STK = SimpleTypeKind::UnsignedCharacter; break;
    1353           3 :     case 2:  STK = SimpleTypeKind::UInt16Short;       break;
    1354           3 :     case 4:  STK = SimpleTypeKind::UInt32;            break;
    1355           0 :     case 8:  STK = SimpleTypeKind::UInt64Quad;        break;
    1356           0 :     case 16: STK = SimpleTypeKind::UInt128Oct;        break;
    1357             :     }
    1358             :     break;
    1359           2 :   case dwarf::DW_ATE_UTF:
    1360           2 :     switch (ByteSize) {
    1361           1 :     case 2: STK = SimpleTypeKind::Character16; break;
    1362           1 :     case 4: STK = SimpleTypeKind::Character32; break;
    1363             :     }
    1364             :     break;
    1365           5 :   case dwarf::DW_ATE_signed_char:
    1366           5 :     if (ByteSize == 1)
    1367           5 :       STK = SimpleTypeKind::SignedCharacter;
    1368             :     break;
    1369           2 :   case dwarf::DW_ATE_unsigned_char:
    1370           2 :     if (ByteSize == 1)
    1371           2 :       STK = SimpleTypeKind::UnsignedCharacter;
    1372             :     break;
    1373             :   default:
    1374             :     break;
    1375             :   }
    1376             : 
    1377             :   // Apply some fixups based on the source-level type name.
    1378         118 :   if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
    1379             :     STK = SimpleTypeKind::Int32Long;
    1380          83 :   if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
    1381             :     STK = SimpleTypeKind::UInt32Long;
    1382          83 :   if (STK == SimpleTypeKind::UInt16Short &&
    1383           8 :       (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
    1384             :     STK = SimpleTypeKind::WideCharacter;
    1385         170 :   if ((STK == SimpleTypeKind::SignedCharacter ||
    1386         170 :        STK == SimpleTypeKind::UnsignedCharacter) &&
    1387          18 :       Ty->getName() == "char")
    1388             :     STK = SimpleTypeKind::NarrowCharacter;
    1389             : 
    1390          85 :   return TypeIndex(STK);
    1391             : }
    1392             : 
    1393          74 : TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
    1394         148 :   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
    1395             : 
    1396             :   // Pointers to simple types can use SimpleTypeMode, rather than having a
    1397             :   // dedicated pointer type record.
    1398          80 :   if (PointeeTI.isSimple() &&
    1399          86 :       PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
    1400           6 :       Ty->getTag() == dwarf::DW_TAG_pointer_type) {
    1401           6 :     SimpleTypeMode Mode = Ty->getSizeInBits() == 64
    1402           6 :                               ? SimpleTypeMode::NearPointer64
    1403           6 :                               : SimpleTypeMode::NearPointer32;
    1404          12 :     return TypeIndex(PointeeTI.getSimpleKind(), Mode);
    1405             :   }
    1406             : 
    1407             :   PointerKind PK =
    1408         136 :       Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
    1409          68 :   PointerMode PM = PointerMode::Pointer;
    1410         136 :   switch (Ty->getTag()) {
    1411           0 :   default: llvm_unreachable("not a pointer tag type");
    1412             :   case dwarf::DW_TAG_pointer_type:
    1413             :     PM = PointerMode::Pointer;
    1414             :     break;
    1415           0 :   case dwarf::DW_TAG_reference_type:
    1416           0 :     PM = PointerMode::LValueReference;
    1417           0 :     break;
    1418           0 :   case dwarf::DW_TAG_rvalue_reference_type:
    1419           0 :     PM = PointerMode::RValueReference;
    1420           0 :     break;
    1421             :   }
    1422             :   // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
    1423             :   // 'this' pointer, but not normal contexts. Figure out what we're supposed to
    1424             :   // do.
    1425          68 :   PointerOptions PO = PointerOptions::None;
    1426         136 :   PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
    1427          68 :   return TypeTable.writeKnownType(PR);
    1428             : }
    1429             : 
    1430             : static PointerToMemberRepresentation
    1431          12 : translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
    1432             :   // SizeInBytes being zero generally implies that the member pointer type was
    1433             :   // incomplete, which can happen if it is part of a function prototype. In this
    1434             :   // case, use the unknown model instead of the general model.
    1435          12 :   if (IsPMF) {
    1436           6 :     switch (Flags & DINode::FlagPtrToMemberRep) {
    1437           3 :     case 0:
    1438           3 :       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
    1439             :                               : PointerToMemberRepresentation::GeneralFunction;
    1440             :     case DINode::FlagSingleInheritance:
    1441             :       return PointerToMemberRepresentation::SingleInheritanceFunction;
    1442           1 :     case DINode::FlagMultipleInheritance:
    1443           1 :       return PointerToMemberRepresentation::MultipleInheritanceFunction;
    1444           1 :     case DINode::FlagVirtualInheritance:
    1445           1 :       return PointerToMemberRepresentation::VirtualInheritanceFunction;
    1446             :     }
    1447             :   } else {
    1448           6 :     switch (Flags & DINode::FlagPtrToMemberRep) {
    1449           3 :     case 0:
    1450           3 :       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
    1451             :                               : PointerToMemberRepresentation::GeneralData;
    1452             :     case DINode::FlagSingleInheritance:
    1453             :       return PointerToMemberRepresentation::SingleInheritanceData;
    1454           1 :     case DINode::FlagMultipleInheritance:
    1455           1 :       return PointerToMemberRepresentation::MultipleInheritanceData;
    1456           1 :     case DINode::FlagVirtualInheritance:
    1457           1 :       return PointerToMemberRepresentation::VirtualInheritanceData;
    1458             :     }
    1459             :   }
    1460           0 :   llvm_unreachable("invalid ptr to member representation");
    1461             : }
    1462             : 
    1463          12 : TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
    1464             :   assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
    1465          24 :   TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
    1466          24 :   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
    1467          24 :   PointerKind PK = Asm->TM.getPointerSize() == 8 ? PointerKind::Near64
    1468          12 :                                                  : PointerKind::Near32;
    1469          24 :   bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
    1470          12 :   PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
    1471             :                          : PointerMode::PointerToDataMember;
    1472          12 :   PointerOptions PO = PointerOptions::None; // FIXME
    1473             :   assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
    1474          12 :   uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
    1475             :   MemberPointerInfo MPI(
    1476          24 :       ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
    1477          36 :   PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
    1478          24 :   return TypeTable.writeKnownType(PR);
    1479             : }
    1480             : 
    1481             : /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
    1482             : /// have a translation, use the NearC convention.
    1483             : static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
    1484             :   switch (DwarfCC) {
    1485             :   case dwarf::DW_CC_normal:             return CallingConvention::NearC;
    1486             :   case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
    1487             :   case dwarf::DW_CC_BORLAND_thiscall:   return CallingConvention::ThisCall;
    1488             :   case dwarf::DW_CC_BORLAND_stdcall:    return CallingConvention::NearStdCall;
    1489             :   case dwarf::DW_CC_BORLAND_pascal:     return CallingConvention::NearPascal;
    1490             :   case dwarf::DW_CC_LLVM_vectorcall:    return CallingConvention::NearVector;
    1491             :   }
    1492             :   return CallingConvention::NearC;
    1493             : }
    1494             : 
    1495          15 : TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
    1496          15 :   ModifierOptions Mods = ModifierOptions::None;
    1497          15 :   bool IsModifier = true;
    1498          15 :   const DIType *BaseTy = Ty;
    1499          45 :   while (IsModifier && BaseTy) {
    1500             :     // FIXME: Need to add DWARF tags for __unaligned and _Atomic
    1501          60 :     switch (BaseTy->getTag()) {
    1502           9 :     case dwarf::DW_TAG_const_type:
    1503             :       Mods |= ModifierOptions::Const;
    1504             :       break;
    1505           7 :     case dwarf::DW_TAG_volatile_type:
    1506             :       Mods |= ModifierOptions::Volatile;
    1507             :       break;
    1508             :     default:
    1509             :       IsModifier = false;
    1510             :       break;
    1511             :     }
    1512          16 :     if (IsModifier)
    1513          32 :       BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
    1514             :   }
    1515          30 :   TypeIndex ModifiedTI = getTypeIndex(BaseTy);
    1516          30 :   ModifierRecord MR(ModifiedTI, Mods);
    1517          15 :   return TypeTable.writeKnownType(MR);
    1518             : }
    1519             : 
    1520         106 : TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
    1521         212 :   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
    1522         456 :   for (DITypeRef ArgTypeRef : Ty->getTypeArray())
    1523         138 :     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
    1524             : 
    1525         106 :   TypeIndex ReturnTypeIndex = TypeIndex::Void();
    1526         106 :   ArrayRef<TypeIndex> ArgTypeIndices = None;
    1527         106 :   if (!ReturnAndArgTypeIndices.empty()) {
    1528          96 :     auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
    1529          96 :     ReturnTypeIndex = ReturnAndArgTypesRef.front();
    1530          96 :     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
    1531             :   }
    1532             : 
    1533         212 :   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
    1534         106 :   TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
    1535             : 
    1536         106 :   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
    1537             : 
    1538             :   ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
    1539         212 :                             ArgTypeIndices.size(), ArgListIndex);
    1540         212 :   return TypeTable.writeKnownType(Procedure);
    1541             : }
    1542             : 
    1543          55 : TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
    1544             :                                                  const DIType *ClassTy,
    1545             :                                                  int ThisAdjustment) {
    1546             :   // Lower the containing class type.
    1547         110 :   TypeIndex ClassType = getTypeIndex(ClassTy);
    1548             : 
    1549         110 :   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
    1550         277 :   for (DITypeRef ArgTypeRef : Ty->getTypeArray())
    1551         112 :     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
    1552             : 
    1553          55 :   TypeIndex ReturnTypeIndex = TypeIndex::Void();
    1554          55 :   ArrayRef<TypeIndex> ArgTypeIndices = None;
    1555          55 :   if (!ReturnAndArgTypeIndices.empty()) {
    1556          55 :     auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
    1557          55 :     ReturnTypeIndex = ReturnAndArgTypesRef.front();
    1558          55 :     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
    1559             :   }
    1560          55 :   TypeIndex ThisTypeIndex = TypeIndex::Void();
    1561          55 :   if (!ArgTypeIndices.empty()) {
    1562          55 :     ThisTypeIndex = ArgTypeIndices.front();
    1563          55 :     ArgTypeIndices = ArgTypeIndices.drop_front();
    1564             :   }
    1565             : 
    1566         110 :   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
    1567          55 :   TypeIndex ArgListIndex = TypeTable.writeKnownType(ArgListRec);
    1568             : 
    1569          55 :   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
    1570             : 
    1571             :   // TODO: Need to use the correct values for:
    1572             :   //       FunctionOptions
    1573             :   //       ThisPointerAdjustment.
    1574             :   MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC,
    1575          55 :                            FunctionOptions::None, ArgTypeIndices.size(),
    1576         110 :                            ArgListIndex, ThisAdjustment);
    1577          55 :   TypeIndex TI = TypeTable.writeKnownType(MFR);
    1578             : 
    1579         110 :   return TI;
    1580             : }
    1581             : 
    1582           6 : TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
    1583             :   unsigned VSlotCount =
    1584           6 :       Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
    1585          18 :   SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
    1586             : 
    1587          18 :   VFTableShapeRecord VFTSR(Slots);
    1588          12 :   return TypeTable.writeKnownType(VFTSR);
    1589             : }
    1590             : 
    1591             : static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
    1592         146 :   switch (Flags & DINode::FlagAccessibility) {
    1593             :   case DINode::FlagPrivate:   return MemberAccess::Private;
    1594           3 :   case DINode::FlagPublic:    return MemberAccess::Public;
    1595           2 :   case DINode::FlagProtected: return MemberAccess::Protected;
    1596         140 :   case 0:
    1597             :     // If there was no explicit access control, provide the default for the tag.
    1598         140 :     return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
    1599             :                                                  : MemberAccess::Public;
    1600             :   }
    1601           0 :   llvm_unreachable("access flags are exclusive");
    1602             : }
    1603             : 
    1604             : static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
    1605          37 :   if (SP->isArtificial())
    1606             :     return MethodOptions::CompilerGenerated;
    1607             : 
    1608             :   // FIXME: Handle other MethodOptions.
    1609             : 
    1610             :   return MethodOptions::None;
    1611             : }
    1612             : 
    1613             : static MethodKind translateMethodKindFlags(const DISubprogram *SP,
    1614             :                                            bool Introduced) {
    1615          37 :   switch (SP->getVirtuality()) {
    1616             :   case dwarf::DW_VIRTUALITY_none:
    1617             :     break;
    1618          15 :   case dwarf::DW_VIRTUALITY_virtual:
    1619          15 :     return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
    1620           3 :   case dwarf::DW_VIRTUALITY_pure_virtual:
    1621           3 :     return Introduced ? MethodKind::PureIntroducingVirtual
    1622             :                       : MethodKind::PureVirtual;
    1623           0 :   default:
    1624           0 :     llvm_unreachable("unhandled virtuality case");
    1625             :   }
    1626             : 
    1627             :   // FIXME: Get Clang to mark DISubprogram as static and do something with it.
    1628             : 
    1629             :   return MethodKind::Vanilla;
    1630             : }
    1631             : 
    1632             : static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
    1633         133 :   switch (Ty->getTag()) {
    1634             :   case dwarf::DW_TAG_class_type:     return TypeRecordKind::Class;
    1635         129 :   case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
    1636             :   }
    1637           0 :   llvm_unreachable("unexpected tag");
    1638             : }
    1639             : 
    1640             : /// Return ClassOptions that should be present on both the forward declaration
    1641             : /// and the defintion of a tag type.
    1642         143 : static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
    1643         143 :   ClassOptions CO = ClassOptions::None;
    1644             : 
    1645             :   // MSVC always sets this flag, even for local types. Clang doesn't always
    1646             :   // appear to give every type a linkage name, which may be problematic for us.
    1647             :   // FIXME: Investigate the consequences of not following them here.
    1648         143 :   if (!Ty->getIdentifier().empty())
    1649             :     CO |= ClassOptions::HasUniqueName;
    1650             : 
    1651             :   // Put the Nested flag on a type if it appears immediately inside a tag type.
    1652             :   // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
    1653             :   // here. That flag is only set on definitions, and not forward declarations.
    1654         306 :   const DIScope *ImmediateScope = Ty->getScope().resolve();
    1655          40 :   if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
    1656             :     CO |= ClassOptions::Nested;
    1657             : 
    1658             :   // Put the Scoped flag on function-local types.
    1659         145 :   for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
    1660          36 :        Scope = Scope->getScope().resolve()) {
    1661          44 :     if (isa<DISubprogram>(Scope)) {
    1662             :       CO |= ClassOptions::Scoped;
    1663             :       break;
    1664             :     }
    1665             :   }
    1666             : 
    1667         143 :   return CO;
    1668             : }
    1669             : 
    1670           4 : TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
    1671           4 :   ClassOptions CO = getCommonClassOptions(Ty);
    1672           4 :   TypeIndex FTI;
    1673           4 :   unsigned EnumeratorCount = 0;
    1674             : 
    1675           8 :   if (Ty->isForwardDecl()) {
    1676             :     CO |= ClassOptions::ForwardReference;
    1677             :   } else {
    1678           8 :     FieldListRecordBuilder FLRB(TypeTable);
    1679             : 
    1680           4 :     FLRB.begin();
    1681        5711 :     for (const DINode *Element : Ty->getElements()) {
    1682             :       // We assume that the frontend provides all members in source declaration
    1683             :       // order, which is what MSVC does.
    1684        5699 :       if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
    1685             :         EnumeratorRecord ER(MemberAccess::Public,
    1686       11398 :                             APSInt::getUnsigned(Enumerator->getValue()),
    1687       17097 :                             Enumerator->getName());
    1688        5699 :         FLRB.writeMemberType(ER);
    1689        5699 :         EnumeratorCount++;
    1690             :       }
    1691             :     }
    1692           4 :     FTI = FLRB.end(true);
    1693             :   }
    1694             : 
    1695           8 :   std::string FullName = getFullyQualifiedName(Ty);
    1696             : 
    1697             :   EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
    1698          20 :                 getTypeIndex(Ty->getBaseType()));
    1699           8 :   return TypeTable.writeKnownType(ER);
    1700             : }
    1701             : 
    1702             : //===----------------------------------------------------------------------===//
    1703             : // ClassInfo
    1704             : //===----------------------------------------------------------------------===//
    1705             : 
    1706         737 : struct llvm::ClassInfo {
    1707             :   struct MemberInfo {
    1708             :     const DIDerivedType *MemberTypeNode;
    1709             :     uint64_t BaseOffset;
    1710             :   };
    1711             :   // [MemberInfo]
    1712             :   using MemberList = std::vector<MemberInfo>;
    1713             : 
    1714             :   using MethodsList = TinyPtrVector<const DISubprogram *>;
    1715             :   // MethodName -> MethodsList
    1716             :   using MethodsMap = MapVector<MDString *, MethodsList>;
    1717             : 
    1718             :   /// Base classes.
    1719             :   std::vector<const DIDerivedType *> Inheritance;
    1720             : 
    1721             :   /// Direct members.
    1722             :   MemberList Members;
    1723             :   // Direct overloaded methods gathered by name.
    1724             :   MethodsMap Methods;
    1725             : 
    1726             :   TypeIndex VShapeTI;
    1727             : 
    1728             :   std::vector<const DIType *> NestedTypes;
    1729             : };
    1730             : 
    1731          93 : void CodeViewDebug::clear() {
    1732             :   assert(CurFn == nullptr);
    1733          93 :   FileIdMap.clear();
    1734          93 :   FnDebugInfo.clear();
    1735         186 :   FileToFilepathMap.clear();
    1736          93 :   LocalUDTs.clear();
    1737          93 :   GlobalUDTs.clear();
    1738          93 :   TypeIndices.clear();
    1739          93 :   CompleteTypeIndices.clear();
    1740          93 : }
    1741             : 
    1742          93 : void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
    1743             :                                       const DIDerivedType *DDTy) {
    1744         186 :   if (!DDTy->getName().empty()) {
    1745         184 :     Info.Members.push_back({DDTy, 0});
    1746          92 :     return;
    1747             :   }
    1748             :   // An unnamed member must represent a nested struct or union. Add all the
    1749             :   // indirect fields to the current record.
    1750             :   assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
    1751           1 :   uint64_t Offset = DDTy->getOffsetInBits();
    1752           2 :   const DIType *Ty = DDTy->getBaseType().resolve();
    1753           1 :   const DICompositeType *DCTy = cast<DICompositeType>(Ty);
    1754           2 :   ClassInfo NestedInfo = collectClassInfo(DCTy);
    1755           5 :   for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
    1756           4 :     Info.Members.push_back(
    1757           2 :         {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
    1758             : }
    1759             : 
    1760          67 : ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
    1761          67 :   ClassInfo Info;
    1762             :   // Add elements to structure type.
    1763          67 :   DINodeArray Elements = Ty->getElements();
    1764         361 :   for (auto *Element : Elements) {
    1765             :     // We assume that the frontend provides all members in source declaration
    1766             :     // order, which is what MSVC does.
    1767           0 :     if (!Element)
    1768           0 :       continue;
    1769         160 :     if (auto *SP = dyn_cast<DISubprogram>(Element)) {
    1770          37 :       Info.Methods[SP->getRawName()].push_back(SP);
    1771         123 :     } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
    1772         236 :       if (DDTy->getTag() == dwarf::DW_TAG_member) {
    1773          93 :         collectMemberInfo(Info, DDTy);
    1774          25 :       } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
    1775          34 :         Info.Inheritance.push_back(DDTy);
    1776           8 :       } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
    1777          15 :                  DDTy->getName() == "__vtbl_ptr_type") {
    1778          10 :         Info.VShapeTI = getTypeIndex(DDTy);
    1779           6 :       } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
    1780           6 :         Info.NestedTypes.push_back(DDTy);
    1781             :       } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
    1782             :         // Ignore friend members. It appears that MSVC emitted info about
    1783             :         // friends in the past, but modern versions do not.
    1784             :       }
    1785           5 :     } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
    1786          10 :       Info.NestedTypes.push_back(Composite);
    1787             :     }
    1788             :     // Skip other unrecognized kinds of elements.
    1789             :   }
    1790          67 :   return Info;
    1791             : }
    1792             : 
    1793          70 : TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
    1794             :   // First, construct the forward decl.  Don't look into Ty to compute the
    1795             :   // forward decl options, since it might not be available in all TUs.
    1796         140 :   TypeRecordKind Kind = getRecordKind(Ty);
    1797             :   ClassOptions CO =
    1798         140 :       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
    1799         140 :   std::string FullName = getFullyQualifiedName(Ty);
    1800             :   ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
    1801         490 :                  FullName, Ty->getIdentifier());
    1802          70 :   TypeIndex FwdDeclTI = TypeTable.writeKnownType(CR);
    1803         140 :   if (!Ty->isForwardDecl())
    1804          63 :     DeferredCompleteTypes.push_back(Ty);
    1805         140 :   return FwdDeclTI;
    1806             : }
    1807             : 
    1808          63 : TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
    1809             :   // Construct the field list and complete type record.
    1810          63 :   TypeRecordKind Kind = getRecordKind(Ty);
    1811          63 :   ClassOptions CO = getCommonClassOptions(Ty);
    1812          63 :   TypeIndex FieldTI;
    1813          63 :   TypeIndex VShapeTI;
    1814             :   unsigned FieldCount;
    1815             :   bool ContainsNestedClass;
    1816          63 :   std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
    1817         189 :       lowerRecordFieldList(Ty);
    1818             : 
    1819          63 :   if (ContainsNestedClass)
    1820             :     CO |= ClassOptions::ContainsNestedClass;
    1821             : 
    1822         126 :   std::string FullName = getFullyQualifiedName(Ty);
    1823             : 
    1824          63 :   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
    1825             : 
    1826             :   ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
    1827         252 :                  SizeInBytes, FullName, Ty->getIdentifier());
    1828          63 :   TypeIndex ClassTI = TypeTable.writeKnownType(CR);
    1829             : 
    1830         124 :   if (const auto *File = Ty->getFile()) {
    1831         183 :     StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
    1832          61 :     TypeIndex SIDI = TypeTable.writeKnownType(SIDR);
    1833         122 :     UdtSourceLineRecord USLR(ClassTI, SIDI, Ty->getLine());
    1834          61 :     TypeTable.writeKnownType(USLR);
    1835             :   }
    1836             : 
    1837          63 :   addToUDTs(Ty);
    1838             : 
    1839         126 :   return ClassTI;
    1840             : }
    1841             : 
    1842           3 : TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
    1843             :   ClassOptions CO =
    1844           6 :       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
    1845           6 :   std::string FullName = getFullyQualifiedName(Ty);
    1846          15 :   UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
    1847           3 :   TypeIndex FwdDeclTI = TypeTable.writeKnownType(UR);
    1848           6 :   if (!Ty->isForwardDecl())
    1849           3 :     DeferredCompleteTypes.push_back(Ty);
    1850           6 :   return FwdDeclTI;
    1851             : }
    1852             : 
    1853           3 : TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
    1854           6 :   ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
    1855           3 :   TypeIndex FieldTI;
    1856             :   unsigned FieldCount;
    1857             :   bool ContainsNestedClass;
    1858           3 :   std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
    1859           9 :       lowerRecordFieldList(Ty);
    1860             : 
    1861           3 :   if (ContainsNestedClass)
    1862             :     CO |= ClassOptions::ContainsNestedClass;
    1863             : 
    1864           3 :   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
    1865           6 :   std::string FullName = getFullyQualifiedName(Ty);
    1866             : 
    1867             :   UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
    1868           9 :                  Ty->getIdentifier());
    1869           3 :   TypeIndex UnionTI = TypeTable.writeKnownType(UR);
    1870             : 
    1871          12 :   StringIdRecord SIR(TypeIndex(0x0), getFullFilepath(Ty->getFile()));
    1872           3 :   TypeIndex SIRI = TypeTable.writeKnownType(SIR);
    1873           6 :   UdtSourceLineRecord USLR(UnionTI, SIRI, Ty->getLine());
    1874           3 :   TypeTable.writeKnownType(USLR);
    1875             : 
    1876           3 :   addToUDTs(Ty);
    1877             : 
    1878           6 :   return UnionTI;
    1879             : }
    1880             : 
    1881             : std::tuple<TypeIndex, TypeIndex, unsigned, bool>
    1882          66 : CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
    1883             :   // Manually count members. MSVC appears to count everything that generates a
    1884             :   // field list record. Each individual overload in a method overload group
    1885             :   // contributes to this count, even though the overload group is a single field
    1886             :   // list record.
    1887          66 :   unsigned MemberCount = 0;
    1888         132 :   ClassInfo Info = collectClassInfo(Ty);
    1889         132 :   FieldListRecordBuilder FLBR(TypeTable);
    1890          66 :   FLBR.begin();
    1891             : 
    1892             :   // Create base classes.
    1893         281 :   for (const DIDerivedType *I : Info.Inheritance) {
    1894          34 :     if (I->getFlags() & DINode::FlagVirtual) {
    1895             :       // Virtual base.
    1896             :       // FIXME: Emit VBPtrOffset when the frontend provides it.
    1897           5 :       unsigned VBPtrOffset = 0;
    1898             :       // FIXME: Despite the accessor name, the offset is really in bytes.
    1899           5 :       unsigned VBTableIndex = I->getOffsetInBits() / 4;
    1900          10 :       auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
    1901           5 :                             ? TypeRecordKind::IndirectVirtualBaseClass
    1902           5 :                             : TypeRecordKind::VirtualBaseClass;
    1903             :       VirtualBaseClassRecord VBCR(
    1904           5 :           RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
    1905           5 :           getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
    1906          25 :           VBTableIndex);
    1907             : 
    1908           5 :       FLBR.writeMemberType(VBCR);
    1909             :     } else {
    1910             :       assert(I->getOffsetInBits() % 8 == 0 &&
    1911             :              "bases must be on byte boundaries");
    1912          12 :       BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
    1913          12 :                           getTypeIndex(I->getBaseType()),
    1914          60 :                           I->getOffsetInBits() / 8);
    1915          12 :       FLBR.writeMemberType(BCR);
    1916             :     }
    1917             :   }
    1918             : 
    1919             :   // Create members.
    1920         356 :   for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
    1921          92 :     const DIDerivedType *Member = MemberInfo.MemberTypeNode;
    1922         184 :     TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
    1923         184 :     StringRef MemberName = Member->getName();
    1924             :     MemberAccess Access =
    1925         184 :         translateAccessFlags(Ty->getTag(), Member->getFlags());
    1926             : 
    1927         184 :     if (Member->isStaticMember()) {
    1928           2 :       StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
    1929           2 :       FLBR.writeMemberType(SDMR);
    1930           2 :       MemberCount++;
    1931           2 :       continue;
    1932             :     }
    1933             : 
    1934             :     // Virtual function pointer member.
    1935         180 :     if ((Member->getFlags() & DINode::FlagArtificial) &&
    1936          24 :         Member->getName().startswith("_vptr$")) {
    1937          24 :       VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
    1938           8 :       FLBR.writeMemberType(VFPR);
    1939           8 :       MemberCount++;
    1940           8 :       continue;
    1941             :     }
    1942             : 
    1943             :     // Data member.
    1944             :     uint64_t MemberOffsetInBits =
    1945          82 :         Member->getOffsetInBits() + MemberInfo.BaseOffset;
    1946         164 :     if (Member->isBitField()) {
    1947           6 :       uint64_t StartBitOffset = MemberOffsetInBits;
    1948             :       if (const auto *CI =
    1949          12 :               dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
    1950           6 :         MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
    1951             :       }
    1952           6 :       StartBitOffset -= MemberOffsetInBits;
    1953           6 :       BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
    1954          18 :                          StartBitOffset);
    1955           6 :       MemberBaseType = TypeTable.writeKnownType(BFR);
    1956             :     }
    1957          82 :     uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
    1958             :     DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
    1959          82 :                          MemberName);
    1960          82 :     FLBR.writeMemberType(DMR);
    1961          82 :     MemberCount++;
    1962             :   }
    1963             : 
    1964             :   // Create methods
    1965         300 :   for (auto &MethodItr : Info.Methods) {
    1966          36 :     StringRef Name = MethodItr.first->getString();
    1967             : 
    1968          72 :     std::vector<OneMethodRecord> Methods;
    1969         145 :     for (const DISubprogram *SP : MethodItr.second) {
    1970          37 :       TypeIndex MethodType = getMemberFunctionType(SP, Ty);
    1971          74 :       bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
    1972             : 
    1973          37 :       unsigned VFTableOffset = -1;
    1974          37 :       if (Introduced)
    1975           8 :         VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
    1976             : 
    1977         259 :       Methods.push_back(OneMethodRecord(
    1978          37 :           MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
    1979             :           translateMethodKindFlags(SP, Introduced),
    1980             :           translateMethodOptionFlags(SP), VFTableOffset, Name));
    1981          37 :       MemberCount++;
    1982             :     }
    1983             :     assert(!Methods.empty() && "Empty methods map entry");
    1984          72 :     if (Methods.size() == 1)
    1985          35 :       FLBR.writeMemberType(Methods[0]);
    1986             :     else {
    1987           3 :       MethodOverloadListRecord MOLR(Methods);
    1988           1 :       TypeIndex MethodList = TypeTable.writeKnownType(MOLR);
    1989           3 :       OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
    1990           1 :       FLBR.writeMemberType(OMR);
    1991             :     }
    1992             :   }
    1993             : 
    1994             :   // Create nested classes.
    1995         272 :   for (const DIType *Nested : Info.NestedTypes) {
    1996          24 :     NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
    1997           8 :     FLBR.writeMemberType(R);
    1998           8 :     MemberCount++;
    1999             :   }
    2000             : 
    2001          66 :   TypeIndex FieldTI = FLBR.end(true);
    2002             :   return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
    2003         198 :                          !Info.NestedTypes.empty());
    2004             : }
    2005             : 
    2006           5 : TypeIndex CodeViewDebug::getVBPTypeIndex() {
    2007          10 :   if (!VBPType.getIndex()) {
    2008             :     // Make a 'const int *' type.
    2009           6 :     ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
    2010           3 :     TypeIndex ModifiedTI = TypeTable.writeKnownType(MR);
    2011             : 
    2012           3 :     PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
    2013           3 :                                                   : PointerKind::Near32;
    2014           3 :     PointerMode PM = PointerMode::Pointer;
    2015           3 :     PointerOptions PO = PointerOptions::None;
    2016           9 :     PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
    2017             : 
    2018           3 :     VBPType = TypeTable.writeKnownType(PR);
    2019             :   }
    2020             : 
    2021           5 :   return VBPType;
    2022             : }
    2023             : 
    2024         944 : TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
    2025         944 :   const DIType *Ty = TypeRef.resolve();
    2026         944 :   const DIType *ClassTy = ClassTyRef.resolve();
    2027             : 
    2028             :   // The null DIType is the void type. Don't try to hash it.
    2029         944 :   if (!Ty)
    2030             :     return TypeIndex::Void();
    2031             : 
    2032             :   // Check if we've already translated this type. Don't try to do a
    2033             :   // get-or-create style insertion that caches the hash lookup across the
    2034             :   // lowerType call. It will update the TypeIndices map.
    2035        1646 :   auto I = TypeIndices.find({Ty, ClassTy});
    2036        2469 :   if (I != TypeIndices.end())
    2037         419 :     return I->second;
    2038             : 
    2039         404 :   TypeLoweringScope S(*this);
    2040         404 :   TypeIndex TI = lowerType(Ty, ClassTy);
    2041         808 :   return recordTypeIndexForDINode(Ty, TI, ClassTy);
    2042             : }
    2043             : 
    2044           4 : TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(DITypeRef TypeRef) {
    2045           4 :   DIType *Ty = TypeRef.resolve();
    2046           4 :   PointerRecord PR(getTypeIndex(Ty),
    2047           4 :                    getPointerSizeInBytes() == 8 ? PointerKind::Near64
    2048             :                                                 : PointerKind::Near32,
    2049             :                    PointerMode::LValueReference, PointerOptions::None,
    2050          20 :                    Ty->getSizeInBits() / 8);
    2051           8 :   return TypeTable.writeKnownType(PR);
    2052             : }
    2053             : 
    2054         319 : TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
    2055         319 :   const DIType *Ty = TypeRef.resolve();
    2056             : 
    2057             :   // The null DIType is the void type. Don't try to hash it.
    2058             :   if (!Ty)
    2059             :     return TypeIndex::Void();
    2060             : 
    2061             :   // If this is a non-record type, the complete type index is the same as the
    2062             :   // normal type index. Just call getTypeIndex.
    2063         319 :   switch (Ty->getTag()) {
    2064             :   case dwarf::DW_TAG_class_type:
    2065             :   case dwarf::DW_TAG_structure_type:
    2066             :   case dwarf::DW_TAG_union_type:
    2067             :     break;
    2068         146 :   default:
    2069         292 :     return getTypeIndex(Ty);
    2070             :   }
    2071             : 
    2072             :   // Check if we've already translated the complete record type.  Lowering a
    2073             :   // complete type should never trigger lowering another complete type, so we
    2074             :   // can reuse the hash table lookup result.
    2075         173 :   const auto *CTy = cast<DICompositeType>(Ty);
    2076         692 :   auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
    2077         173 :   if (!InsertResult.second)
    2078         107 :     return InsertResult.first->second;
    2079             : 
    2080         132 :   TypeLoweringScope S(*this);
    2081             : 
    2082             :   // Make sure the forward declaration is emitted first. It's unclear if this
    2083             :   // is necessary, but MSVC does it, and we should follow suit until we can show
    2084             :   // otherwise.
    2085         132 :   TypeIndex FwdDeclTI = getTypeIndex(CTy);
    2086             : 
    2087             :   // Just use the forward decl if we don't have complete type info. This might
    2088             :   // happen if the frontend is using modules and expects the complete definition
    2089             :   // to be emitted elsewhere.
    2090         132 :   if (CTy->isForwardDecl())
    2091           0 :     return FwdDeclTI;
    2092             : 
    2093          66 :   TypeIndex TI;
    2094         132 :   switch (CTy->getTag()) {
    2095          63 :   case dwarf::DW_TAG_class_type:
    2096             :   case dwarf::DW_TAG_structure_type:
    2097          63 :     TI = lowerCompleteTypeClass(CTy);
    2098          63 :     break;
    2099           3 :   case dwarf::DW_TAG_union_type:
    2100           3 :     TI = lowerCompleteTypeUnion(CTy);
    2101           3 :     break;
    2102           0 :   default:
    2103           0 :     llvm_unreachable("not a record");
    2104             :   }
    2105             : 
    2106          66 :   InsertResult.first->second = TI;
    2107          66 :   return TI;
    2108             : }
    2109             : 
    2110             : /// Emit all the deferred complete record types. Try to do this in FIFO order,
    2111             : /// and do this until fixpoint, as each complete record type typically
    2112             : /// references
    2113             : /// many other record types.
    2114         223 : void CodeViewDebug::emitDeferredCompleteTypes() {
    2115         223 :   SmallVector<const DICompositeType *, 4> TypesToEmit;
    2116         283 :   while (!DeferredCompleteTypes.empty()) {
    2117         120 :     std::swap(DeferredCompleteTypes, TypesToEmit);
    2118         246 :     for (const DICompositeType *RecordTy : TypesToEmit)
    2119          66 :       getCompleteTypeIndex(RecordTy);
    2120             :     TypesToEmit.clear();
    2121             :   }
    2122         223 : }
    2123             : 
    2124         153 : void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
    2125             :   // Get the sorted list of parameters and emit them first.
    2126         306 :   SmallVector<const LocalVariable *, 6> Params;
    2127         438 :   for (const LocalVariable &L : Locals)
    2128         264 :     if (L.DIVar->isParameter())
    2129          59 :       Params.push_back(&L);
    2130         459 :   std::sort(Params.begin(), Params.end(),
    2131             :             [](const LocalVariable *L, const LocalVariable *R) {
    2132          33 :               return L->DIVar->getArg() < R->DIVar->getArg();
    2133             :             });
    2134         518 :   for (const LocalVariable *L : Params)
    2135          59 :     emitLocalVariable(*L);
    2136             : 
    2137             :   // Next emit all non-parameters in the order that we found them.
    2138         417 :   for (const LocalVariable &L : Locals)
    2139         264 :     if (!L.DIVar->isParameter())
    2140          73 :       emitLocalVariable(L);
    2141         153 : }
    2142             : 
    2143         132 : void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
    2144             :   // LocalSym record, see SymbolRecord.h for more info.
    2145         264 :   MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
    2146         264 :            *LocalEnd = MMI->getContext().createTempSymbol();
    2147         264 :   OS.AddComment("Record length");
    2148         132 :   OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
    2149         132 :   OS.EmitLabel(LocalBegin);
    2150             : 
    2151         264 :   OS.AddComment("Record kind: S_LOCAL");
    2152         132 :   OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
    2153             : 
    2154         132 :   LocalSymFlags Flags = LocalSymFlags::None;
    2155         264 :   if (Var.DIVar->isParameter())
    2156             :     Flags |= LocalSymFlags::IsParameter;
    2157         132 :   if (Var.DefRanges.empty())
    2158             :     Flags |= LocalSymFlags::IsOptimizedOut;
    2159             : 
    2160         264 :   OS.AddComment("TypeIndex");
    2161         132 :   TypeIndex TI = Var.UseReferenceType
    2162           8 :                      ? getTypeIndexForReferenceTo(Var.DIVar->getType())
    2163         264 :                      : getCompleteTypeIndex(Var.DIVar->getType());
    2164         264 :   OS.EmitIntValue(TI.getIndex(), 4);
    2165         264 :   OS.AddComment("Flags");
    2166         132 :   OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
    2167             :   // Truncate the name so we won't overflow the record length field.
    2168         264 :   emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
    2169         132 :   OS.EmitLabel(LocalEnd);
    2170             : 
    2171             :   // Calculate the on disk prefix of the appropriate def range record. The
    2172             :   // records and on disk formats are described in SymbolRecords.h. BytePrefix
    2173             :   // should be big enough to hold all forms without memory allocation.
    2174         264 :   SmallString<20> BytePrefix;
    2175         533 :   for (const LocalVarDefRange &DefRange : Var.DefRanges) {
    2176         137 :     BytePrefix.clear();
    2177         137 :     if (DefRange.InMemory) {
    2178         106 :       uint16_t RegRelFlags = 0;
    2179         106 :       if (DefRange.IsSubfield) {
    2180           2 :         RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
    2181           2 :                       (DefRange.StructOffset
    2182           2 :                        << DefRangeRegisterRelSym::OffsetInParentShift);
    2183             :       }
    2184         212 :       DefRangeRegisterRelSym Sym(S_DEFRANGE_REGISTER_REL);
    2185         212 :       Sym.Hdr.Register = DefRange.CVRegister;
    2186         212 :       Sym.Hdr.Flags = RegRelFlags;
    2187         212 :       Sym.Hdr.BasePointerOffset = DefRange.DataOffset;
    2188         106 :       ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
    2189         106 :       BytePrefix +=
    2190         212 :           StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
    2191         106 :       BytePrefix +=
    2192         212 :           StringRef(reinterpret_cast<const char *>(&Sym.Hdr), sizeof(Sym.Hdr));
    2193             :     } else {
    2194             :       assert(DefRange.DataOffset == 0 && "unexpected offset into register");
    2195          31 :       if (DefRange.IsSubfield) {
    2196             :         // Unclear what matters here.
    2197          20 :         DefRangeSubfieldRegisterSym Sym(S_DEFRANGE_SUBFIELD_REGISTER);
    2198          20 :         Sym.Hdr.Register = DefRange.CVRegister;
    2199          10 :         Sym.Hdr.MayHaveNoName = 0;
    2200          20 :         Sym.Hdr.OffsetInParent = DefRange.StructOffset;
    2201             : 
    2202          10 :         ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_SUBFIELD_REGISTER);
    2203          10 :         BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
    2204          20 :                                 sizeof(SymKind));
    2205          10 :         BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
    2206          20 :                                 sizeof(Sym.Hdr));
    2207             :       } else {
    2208             :         // Unclear what matters here.
    2209          42 :         DefRangeRegisterSym Sym(S_DEFRANGE_REGISTER);
    2210          42 :         Sym.Hdr.Register = DefRange.CVRegister;
    2211          21 :         Sym.Hdr.MayHaveNoName = 0;
    2212          21 :         ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
    2213          21 :         BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
    2214          42 :                                 sizeof(SymKind));
    2215          21 :         BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
    2216          42 :                                 sizeof(Sym.Hdr));
    2217             :       }
    2218             :     }
    2219         411 :     OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
    2220             :   }
    2221         132 : }
    2222             : 
    2223         129 : void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
    2224         129 :   const Function *GV = MF->getFunction();
    2225             :   assert(FnDebugInfo.count(GV));
    2226             :   assert(CurFn == &FnDebugInfo[GV]);
    2227             : 
    2228         129 :   collectVariableInfo(GV->getSubprogram());
    2229             : 
    2230             :   // Don't emit anything if we don't have any line tables.
    2231         129 :   if (!CurFn->HaveLineInfo) {
    2232           0 :     FnDebugInfo.erase(GV);
    2233           0 :     CurFn = nullptr;
    2234           0 :     return;
    2235             :   }
    2236             : 
    2237         516 :   CurFn->Annotations = MF->getCodeViewAnnotations();
    2238             : 
    2239         129 :   CurFn->End = Asm->getFunctionEnd();
    2240             : 
    2241         129 :   CurFn = nullptr;
    2242             : }
    2243             : 
    2244        1298 : void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
    2245        1298 :   DebugHandlerBase::beginInstruction(MI);
    2246             : 
    2247             :   // Ignore DBG_VALUE locations and function prologue.
    2248        3768 :   if (!Asm || !CurFn || MI->isDebugValue() ||
    2249        1200 :       MI->getFlag(MachineInstr::FrameSetup))
    2250         532 :     return;
    2251             : 
    2252             :   // If the first instruction of a new MBB has no location, find the first
    2253             :   // instruction with a location and use that.
    2254        2634 :   DebugLoc DL = MI->getDebugLoc();
    2255         934 :   if (!DL && MI->getParent() != PrevInstBB) {
    2256         169 :     for (const auto &NextMI : *MI->getParent()) {
    2257          53 :       if (NextMI.isDebugValue())
    2258           6 :         continue;
    2259          94 :       DL = NextMI.getDebugLoc();
    2260          47 :       if (DL)
    2261             :         break;
    2262             :     }
    2263             :   }
    2264         934 :   PrevInstBB = MI->getParent();
    2265             : 
    2266             :   // If we still don't have a debug location, don't record a location.
    2267         934 :   if (!DL)
    2268             :     return;
    2269             : 
    2270         766 :   maybeRecordLocation(DL, Asm->MF);
    2271             : }
    2272             : 
    2273         295 : MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
    2274         590 :   MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
    2275         590 :            *EndLabel = MMI->getContext().createTempSymbol();
    2276         295 :   OS.EmitIntValue(unsigned(Kind), 4);
    2277         590 :   OS.AddComment("Subsection size");
    2278         295 :   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
    2279         295 :   OS.EmitLabel(BeginLabel);
    2280         295 :   return EndLabel;
    2281             : }
    2282             : 
    2283         295 : void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
    2284         295 :   OS.EmitLabel(EndLabel);
    2285             :   // Every subsection must be aligned to a 4-byte boundary.
    2286         295 :   OS.EmitValueToAlignment(4);
    2287         295 : }
    2288             : 
    2289         161 : void CodeViewDebug::emitDebugInfoForUDTs(
    2290             :     ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
    2291         395 :   for (const auto &UDT : UDTs) {
    2292          73 :     const DIType *T = UDT.second;
    2293             :     assert(shouldEmitUdt(T));
    2294             : 
    2295         146 :     MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
    2296         146 :              *UDTRecordEnd = MMI->getContext().createTempSymbol();
    2297         146 :     OS.AddComment("Record length");
    2298          73 :     OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
    2299          73 :     OS.EmitLabel(UDTRecordBegin);
    2300             : 
    2301         146 :     OS.AddComment("Record kind: S_UDT");
    2302          73 :     OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
    2303             : 
    2304         146 :     OS.AddComment("Type");
    2305         219 :     OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
    2306             : 
    2307         146 :     emitNullTerminatedSymbolName(OS, UDT.first);
    2308          73 :     OS.EmitLabel(UDTRecordEnd);
    2309             :   }
    2310         161 : }
    2311             : 
    2312          93 : void CodeViewDebug::emitDebugInfoForGlobals() {
    2313             :   DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
    2314         186 :       GlobalMap;
    2315         321 :   for (const GlobalVariable &GV : MMI->getModule()->globals()) {
    2316         270 :     SmallVector<DIGlobalVariableExpression *, 1> GVEs;
    2317         135 :     GV.getDebugInfo(GVEs);
    2318         458 :     for (const auto *GVE : GVEs)
    2319          53 :       GlobalMap[GVE] = &GV;
    2320             :   }
    2321             : 
    2322         186 :   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
    2323         187 :   for (const MDNode *Node : CUs->operands()) {
    2324          94 :     const auto *CU = cast<DICompileUnit>(Node);
    2325             : 
    2326             :     // First, emit all globals that are not in a comdat in a single symbol
    2327             :     // substream. MSVC doesn't like it if the substream is empty, so only open
    2328             :     // it if we have at least one global to emit.
    2329          94 :     switchToDebugSectionForSymbol(nullptr);
    2330          94 :     MCSymbol *EndLabel = nullptr;
    2331         336 :     for (const auto *GVE : CU->getGlobalVariables()) {
    2332          54 :       if (const auto *GV = GlobalMap.lookup(GVE))
    2333         155 :         if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
    2334          49 :           if (!EndLabel) {
    2335          52 :             OS.AddComment("Symbol subsection for globals");
    2336          26 :             EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
    2337             :           }
    2338             :           // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
    2339          98 :           emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
    2340             :         }
    2341             :     }
    2342          94 :     if (EndLabel)
    2343          26 :       endCVSubsection(EndLabel);
    2344             : 
    2345             :     // Second, emit each global that is in a comdat into its own .debug$S
    2346             :     // section along with its own symbol substream.
    2347         336 :     for (const auto *GVE : CU->getGlobalVariables()) {
    2348          54 :       if (const auto *GV = GlobalMap.lookup(GVE)) {
    2349         106 :         if (GV->hasComdat()) {
    2350           3 :           MCSymbol *GVSym = Asm->getSymbol(GV);
    2351           6 :           OS.AddComment("Symbol subsection for " +
    2352          12 :                         Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
    2353           3 :           switchToDebugSectionForSymbol(GVSym);
    2354           3 :           EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
    2355             :           // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
    2356           3 :           emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
    2357           3 :           endCVSubsection(EndLabel);
    2358             :         }
    2359             :       }
    2360             :     }
    2361             :   }
    2362          93 : }
    2363             : 
    2364          93 : void CodeViewDebug::emitDebugInfoForRetainedTypes() {
    2365         186 :   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
    2366         187 :   for (const MDNode *Node : CUs->operands()) {
    2367         378 :     for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
    2368           2 :       if (DIType *RT = dyn_cast<DIType>(Ty)) {
    2369           4 :         getTypeIndex(RT);
    2370             :         // FIXME: Add to global/local DTU list.
    2371             :       }
    2372             :     }
    2373             :   }
    2374          93 : }
    2375             : 
    2376          52 : void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
    2377             :                                            const GlobalVariable *GV,
    2378             :                                            MCSymbol *GVSym) {
    2379             :   // DataSym record, see SymbolRecord.h for more info.
    2380             :   // FIXME: Thread local data, etc
    2381         104 :   MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
    2382         104 :            *DataEnd = MMI->getContext().createTempSymbol();
    2383         104 :   OS.AddComment("Record length");
    2384          52 :   OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
    2385          52 :   OS.EmitLabel(DataBegin);
    2386          52 :   if (DIGV->isLocalToUnit()) {
    2387           8 :     if (GV->isThreadLocal()) {
    2388           0 :       OS.AddComment("Record kind: S_LTHREAD32");
    2389           0 :       OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
    2390             :     } else {
    2391           8 :       OS.AddComment("Record kind: S_LDATA32");
    2392           4 :       OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
    2393             :     }
    2394             :   } else {
    2395          96 :     if (GV->isThreadLocal()) {
    2396           6 :       OS.AddComment("Record kind: S_GTHREAD32");
    2397           3 :       OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
    2398             :     } else {
    2399          90 :       OS.AddComment("Record kind: S_GDATA32");
    2400          45 :       OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
    2401             :     }
    2402             :   }
    2403         104 :   OS.AddComment("Type");
    2404         156 :   OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
    2405         104 :   OS.AddComment("DataOffset");
    2406          52 :   OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
    2407         104 :   OS.AddComment("Segment");
    2408          52 :   OS.EmitCOFFSectionIndex(GVSym);
    2409         104 :   OS.AddComment("Name");
    2410         104 :   emitNullTerminatedSymbolName(OS, DIGV->getName());
    2411          52 :   OS.EmitLabel(DataEnd);
    2412          52 : }

Generated by: LCOV version 1.13