xref: /llvm-project/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp (revision 7fac5c8d940c91e1e7b8b704186b4649170b029f)
1 //===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains support for writing Microsoft CodeView debug info.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CodeViewDebug.h"
14 #include "DwarfExpression.h"
15 #include "llvm/ADT/APSInt.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/TinyPtrVector.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/BinaryFormat/COFF.h"
30 #include "llvm/BinaryFormat/Dwarf.h"
31 #include "llvm/CodeGen/AsmPrinter.h"
32 #include "llvm/CodeGen/LexicalScopes.h"
33 #include "llvm/CodeGen/MachineFrameInfo.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/CodeGen/TargetFrameLowering.h"
39 #include "llvm/CodeGen/TargetRegisterInfo.h"
40 #include "llvm/CodeGen/TargetSubtargetInfo.h"
41 #include "llvm/Config/llvm-config.h"
42 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
43 #include "llvm/DebugInfo/CodeView/CodeView.h"
44 #include "llvm/DebugInfo/CodeView/CodeViewRecordIO.h"
45 #include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h"
46 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
47 #include "llvm/DebugInfo/CodeView/EnumTables.h"
48 #include "llvm/DebugInfo/CodeView/Line.h"
49 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
50 #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
51 #include "llvm/DebugInfo/CodeView/TypeIndex.h"
52 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
53 #include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugInfoMetadata.h"
57 #include "llvm/IR/DebugLoc.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/GlobalValue.h"
60 #include "llvm/IR/GlobalVariable.h"
61 #include "llvm/IR/Metadata.h"
62 #include "llvm/IR/Module.h"
63 #include "llvm/MC/MCAsmInfo.h"
64 #include "llvm/MC/MCContext.h"
65 #include "llvm/MC/MCSectionCOFF.h"
66 #include "llvm/MC/MCStreamer.h"
67 #include "llvm/MC/MCSymbol.h"
68 #include "llvm/Support/BinaryByteStream.h"
69 #include "llvm/Support/BinaryStreamReader.h"
70 #include "llvm/Support/BinaryStreamWriter.h"
71 #include "llvm/Support/Casting.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/Endian.h"
75 #include "llvm/Support/Error.h"
76 #include "llvm/Support/ErrorHandling.h"
77 #include "llvm/Support/FormatVariadic.h"
78 #include "llvm/Support/Path.h"
79 #include "llvm/Support/SMLoc.h"
80 #include "llvm/Support/ScopedPrinter.h"
81 #include "llvm/Target/TargetLoweringObjectFile.h"
82 #include "llvm/Target/TargetMachine.h"
83 #include <algorithm>
84 #include <cassert>
85 #include <cctype>
86 #include <cstddef>
87 #include <cstdint>
88 #include <iterator>
89 #include <limits>
90 #include <string>
91 #include <utility>
92 #include <vector>
93 
94 using namespace llvm;
95 using namespace llvm::codeview;
96 
97 static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
98   switch (Type) {
99   case Triple::ArchType::x86:
100     return CPUType::Pentium3;
101   case Triple::ArchType::x86_64:
102     return CPUType::X64;
103   case Triple::ArchType::thumb:
104     return CPUType::Thumb;
105   case Triple::ArchType::aarch64:
106     return CPUType::ARM64;
107   default:
108     report_fatal_error("target architecture doesn't map to a CodeView CPUType");
109   }
110 }
111 
112 CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
113     : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {
114   // If module doesn't have named metadata anchors or COFF debug section
115   // is not available, skip any debug info related stuff.
116   if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
117       !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
118     Asm = nullptr;
119     MMI->setDebugInfoAvailability(false);
120     return;
121   }
122   // Tell MMI that we have debug info.
123   MMI->setDebugInfoAvailability(true);
124 
125   TheCPU =
126       mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
127 
128   collectGlobalVariableInfo();
129 
130   // Check if we should emit type record hashes.
131   ConstantInt *GH = mdconst::extract_or_null<ConstantInt>(
132       MMI->getModule()->getModuleFlag("CodeViewGHash"));
133   EmitDebugGlobalHashes = GH && !GH->isZero();
134 }
135 
136 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
137   std::string &Filepath = FileToFilepathMap[File];
138   if (!Filepath.empty())
139     return Filepath;
140 
141   StringRef Dir = File->getDirectory(), Filename = File->getFilename();
142 
143   // If this is a Unix-style path, just use it as is. Don't try to canonicalize
144   // it textually because one of the path components could be a symlink.
145   if (Dir.startswith("/") || Filename.startswith("/")) {
146     if (llvm::sys::path::is_absolute(Filename, llvm::sys::path::Style::posix))
147       return Filename;
148     Filepath = Dir;
149     if (Dir.back() != '/')
150       Filepath += '/';
151     Filepath += Filename;
152     return Filepath;
153   }
154 
155   // Clang emits directory and relative filename info into the IR, but CodeView
156   // operates on full paths.  We could change Clang to emit full paths too, but
157   // that would increase the IR size and probably not needed for other users.
158   // For now, just concatenate and canonicalize the path here.
159   if (Filename.find(':') == 1)
160     Filepath = Filename;
161   else
162     Filepath = (Dir + "\\" + Filename).str();
163 
164   // Canonicalize the path.  We have to do it textually because we may no longer
165   // have access the file in the filesystem.
166   // First, replace all slashes with backslashes.
167   std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
168 
169   // Remove all "\.\" with "\".
170   size_t Cursor = 0;
171   while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
172     Filepath.erase(Cursor, 2);
173 
174   // Replace all "\XXX\..\" with "\".  Don't try too hard though as the original
175   // path should be well-formatted, e.g. start with a drive letter, etc.
176   Cursor = 0;
177   while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
178     // Something's wrong if the path starts with "\..\", abort.
179     if (Cursor == 0)
180       break;
181 
182     size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
183     if (PrevSlash == std::string::npos)
184       // Something's wrong, abort.
185       break;
186 
187     Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
188     // The next ".." might be following the one we've just erased.
189     Cursor = PrevSlash;
190   }
191 
192   // Remove all duplicate backslashes.
193   Cursor = 0;
194   while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
195     Filepath.erase(Cursor, 1);
196 
197   return Filepath;
198 }
199 
200 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
201   StringRef FullPath = getFullFilepath(F);
202   unsigned NextId = FileIdMap.size() + 1;
203   auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
204   if (Insertion.second) {
205     // We have to compute the full filepath and emit a .cv_file directive.
206     ArrayRef<uint8_t> ChecksumAsBytes;
207     FileChecksumKind CSKind = FileChecksumKind::None;
208     if (F->getChecksum()) {
209       std::string Checksum = fromHex(F->getChecksum()->Value);
210       void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
211       memcpy(CKMem, Checksum.data(), Checksum.size());
212       ChecksumAsBytes = ArrayRef<uint8_t>(
213           reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
214       switch (F->getChecksum()->Kind) {
215       case DIFile::CSK_MD5:  CSKind = FileChecksumKind::MD5; break;
216       case DIFile::CSK_SHA1: CSKind = FileChecksumKind::SHA1; break;
217       }
218     }
219     bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
220                                           static_cast<unsigned>(CSKind));
221     (void)Success;
222     assert(Success && ".cv_file directive failed");
223   }
224   return Insertion.first->second;
225 }
226 
227 CodeViewDebug::InlineSite &
228 CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
229                              const DISubprogram *Inlinee) {
230   auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
231   InlineSite *Site = &SiteInsertion.first->second;
232   if (SiteInsertion.second) {
233     unsigned ParentFuncId = CurFn->FuncId;
234     if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
235       ParentFuncId =
236           getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
237               .SiteFuncId;
238 
239     Site->SiteFuncId = NextFuncId++;
240     OS.EmitCVInlineSiteIdDirective(
241         Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
242         InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
243     Site->Inlinee = Inlinee;
244     InlinedSubprograms.insert(Inlinee);
245     getFuncIdForSubprogram(Inlinee);
246   }
247   return *Site;
248 }
249 
250 static StringRef getPrettyScopeName(const DIScope *Scope) {
251   StringRef ScopeName = Scope->getName();
252   if (!ScopeName.empty())
253     return ScopeName;
254 
255   switch (Scope->getTag()) {
256   case dwarf::DW_TAG_enumeration_type:
257   case dwarf::DW_TAG_class_type:
258   case dwarf::DW_TAG_structure_type:
259   case dwarf::DW_TAG_union_type:
260     return "<unnamed-tag>";
261   case dwarf::DW_TAG_namespace:
262     return "`anonymous namespace'";
263   }
264 
265   return StringRef();
266 }
267 
268 static const DISubprogram *getQualifiedNameComponents(
269     const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
270   const DISubprogram *ClosestSubprogram = nullptr;
271   while (Scope != nullptr) {
272     if (ClosestSubprogram == nullptr)
273       ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
274     StringRef ScopeName = getPrettyScopeName(Scope);
275     if (!ScopeName.empty())
276       QualifiedNameComponents.push_back(ScopeName);
277     Scope = Scope->getScope();
278   }
279   return ClosestSubprogram;
280 }
281 
282 static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
283                                     StringRef TypeName) {
284   std::string FullyQualifiedName;
285   for (StringRef QualifiedNameComponent :
286        llvm::reverse(QualifiedNameComponents)) {
287     FullyQualifiedName.append(QualifiedNameComponent);
288     FullyQualifiedName.append("::");
289   }
290   FullyQualifiedName.append(TypeName);
291   return FullyQualifiedName;
292 }
293 
294 static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
295   SmallVector<StringRef, 5> QualifiedNameComponents;
296   getQualifiedNameComponents(Scope, QualifiedNameComponents);
297   return getQualifiedName(QualifiedNameComponents, Name);
298 }
299 
300 struct CodeViewDebug::TypeLoweringScope {
301   TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
302   ~TypeLoweringScope() {
303     // Don't decrement TypeEmissionLevel until after emitting deferred types, so
304     // inner TypeLoweringScopes don't attempt to emit deferred types.
305     if (CVD.TypeEmissionLevel == 1)
306       CVD.emitDeferredCompleteTypes();
307     --CVD.TypeEmissionLevel;
308   }
309   CodeViewDebug &CVD;
310 };
311 
312 static std::string getFullyQualifiedName(const DIScope *Ty) {
313   const DIScope *Scope = Ty->getScope();
314   return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
315 }
316 
317 TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
318   // No scope means global scope and that uses the zero index.
319   if (!Scope || isa<DIFile>(Scope))
320     return TypeIndex();
321 
322   assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
323 
324   // Check if we've already translated this scope.
325   auto I = TypeIndices.find({Scope, nullptr});
326   if (I != TypeIndices.end())
327     return I->second;
328 
329   // Build the fully qualified name of the scope.
330   std::string ScopeName = getFullyQualifiedName(Scope);
331   StringIdRecord SID(TypeIndex(), ScopeName);
332   auto TI = TypeTable.writeLeafType(SID);
333   return recordTypeIndexForDINode(Scope, TI);
334 }
335 
336 TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
337   assert(SP);
338 
339   // Check if we've already translated this subprogram.
340   auto I = TypeIndices.find({SP, nullptr});
341   if (I != TypeIndices.end())
342     return I->second;
343 
344   // The display name includes function template arguments. Drop them to match
345   // MSVC.
346   StringRef DisplayName = SP->getName().split('<').first;
347 
348   const DIScope *Scope = SP->getScope();
349   TypeIndex TI;
350   if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
351     // If the scope is a DICompositeType, then this must be a method. Member
352     // function types take some special handling, and require access to the
353     // subprogram.
354     TypeIndex ClassType = getTypeIndex(Class);
355     MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
356                                DisplayName);
357     TI = TypeTable.writeLeafType(MFuncId);
358   } else {
359     // Otherwise, this must be a free function.
360     TypeIndex ParentScope = getScopeIndex(Scope);
361     FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
362     TI = TypeTable.writeLeafType(FuncId);
363   }
364 
365   return recordTypeIndexForDINode(SP, TI);
366 }
367 
368 static bool isNonTrivial(const DICompositeType *DCTy) {
369   return ((DCTy->getFlags() & DINode::FlagNonTrivial) == DINode::FlagNonTrivial);
370 }
371 
372 static FunctionOptions
373 getFunctionOptions(const DISubroutineType *Ty,
374                    const DICompositeType *ClassTy = nullptr,
375                    StringRef SPName = StringRef("")) {
376   FunctionOptions FO = FunctionOptions::None;
377   const DIType *ReturnTy = nullptr;
378   if (auto TypeArray = Ty->getTypeArray()) {
379     if (TypeArray.size())
380       ReturnTy = TypeArray[0];
381   }
382 
383   if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy)) {
384     if (isNonTrivial(ReturnDCTy))
385       FO |= FunctionOptions::CxxReturnUdt;
386   }
387 
388   // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison.
389   if (ClassTy && isNonTrivial(ClassTy) && SPName == ClassTy->getName()) {
390     FO |= FunctionOptions::Constructor;
391 
392   // TODO: put the FunctionOptions::ConstructorWithVirtualBases flag.
393 
394   }
395   return FO;
396 }
397 
398 TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
399                                                const DICompositeType *Class) {
400   // Always use the method declaration as the key for the function type. The
401   // method declaration contains the this adjustment.
402   if (SP->getDeclaration())
403     SP = SP->getDeclaration();
404   assert(!SP->getDeclaration() && "should use declaration as key");
405 
406   // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
407   // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
408   auto I = TypeIndices.find({SP, Class});
409   if (I != TypeIndices.end())
410     return I->second;
411 
412   // Make sure complete type info for the class is emitted *after* the member
413   // function type, as the complete class type is likely to reference this
414   // member function type.
415   TypeLoweringScope S(*this);
416   const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
417 
418   FunctionOptions FO = getFunctionOptions(SP->getType(), Class, SP->getName());
419   TypeIndex TI = lowerTypeMemberFunction(
420       SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO);
421   return recordTypeIndexForDINode(SP, TI, Class);
422 }
423 
424 TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
425                                                   TypeIndex TI,
426                                                   const DIType *ClassTy) {
427   auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
428   (void)InsertResult;
429   assert(InsertResult.second && "DINode was already assigned a type index");
430   return TI;
431 }
432 
433 unsigned CodeViewDebug::getPointerSizeInBytes() {
434   return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
435 }
436 
437 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
438                                         const LexicalScope *LS) {
439   if (const DILocation *InlinedAt = LS->getInlinedAt()) {
440     // This variable was inlined. Associate it with the InlineSite.
441     const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
442     InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
443     Site.InlinedLocals.emplace_back(Var);
444   } else {
445     // This variable goes into the corresponding lexical scope.
446     ScopeVariables[LS].emplace_back(Var);
447   }
448 }
449 
450 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
451                                const DILocation *Loc) {
452   auto B = Locs.begin(), E = Locs.end();
453   if (std::find(B, E, Loc) == E)
454     Locs.push_back(Loc);
455 }
456 
457 void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
458                                         const MachineFunction *MF) {
459   // Skip this instruction if it has the same location as the previous one.
460   if (!DL || DL == PrevInstLoc)
461     return;
462 
463   const DIScope *Scope = DL.get()->getScope();
464   if (!Scope)
465     return;
466 
467   // Skip this line if it is longer than the maximum we can record.
468   LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
469   if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
470       LI.isNeverStepInto())
471     return;
472 
473   ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
474   if (CI.getStartColumn() != DL.getCol())
475     return;
476 
477   if (!CurFn->HaveLineInfo)
478     CurFn->HaveLineInfo = true;
479   unsigned FileId = 0;
480   if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
481     FileId = CurFn->LastFileId;
482   else
483     FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
484   PrevInstLoc = DL;
485 
486   unsigned FuncId = CurFn->FuncId;
487   if (const DILocation *SiteLoc = DL->getInlinedAt()) {
488     const DILocation *Loc = DL.get();
489 
490     // If this location was actually inlined from somewhere else, give it the ID
491     // of the inline call site.
492     FuncId =
493         getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
494 
495     // Ensure we have links in the tree of inline call sites.
496     bool FirstLoc = true;
497     while ((SiteLoc = Loc->getInlinedAt())) {
498       InlineSite &Site =
499           getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
500       if (!FirstLoc)
501         addLocIfNotPresent(Site.ChildSites, Loc);
502       FirstLoc = false;
503       Loc = SiteLoc;
504     }
505     addLocIfNotPresent(CurFn->ChildSites, Loc);
506   }
507 
508   OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
509                         /*PrologueEnd=*/false, /*IsStmt=*/false,
510                         DL->getFilename(), SMLoc());
511 }
512 
513 void CodeViewDebug::emitCodeViewMagicVersion() {
514   OS.EmitValueToAlignment(4);
515   OS.AddComment("Debug section magic");
516   OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
517 }
518 
519 void CodeViewDebug::endModule() {
520   if (!Asm || !MMI->hasDebugInfo())
521     return;
522 
523   assert(Asm != nullptr);
524 
525   // The COFF .debug$S section consists of several subsections, each starting
526   // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
527   // of the payload followed by the payload itself.  The subsections are 4-byte
528   // aligned.
529 
530   // Use the generic .debug$S section, and make a subsection for all the inlined
531   // subprograms.
532   switchToDebugSectionForSymbol(nullptr);
533 
534   MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
535   emitCompilerInformation();
536   endCVSubsection(CompilerInfo);
537 
538   emitInlineeLinesSubsection();
539 
540   // Emit per-function debug information.
541   for (auto &P : FnDebugInfo)
542     if (!P.first->isDeclarationForLinker())
543       emitDebugInfoForFunction(P.first, *P.second);
544 
545   // Emit global variable debug information.
546   setCurrentSubprogram(nullptr);
547   emitDebugInfoForGlobals();
548 
549   // Emit retained types.
550   emitDebugInfoForRetainedTypes();
551 
552   // Switch back to the generic .debug$S section after potentially processing
553   // comdat symbol sections.
554   switchToDebugSectionForSymbol(nullptr);
555 
556   // Emit UDT records for any types used by global variables.
557   if (!GlobalUDTs.empty()) {
558     MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
559     emitDebugInfoForUDTs(GlobalUDTs);
560     endCVSubsection(SymbolsEnd);
561   }
562 
563   // This subsection holds a file index to offset in string table table.
564   OS.AddComment("File index to string table offset subsection");
565   OS.EmitCVFileChecksumsDirective();
566 
567   // This subsection holds the string table.
568   OS.AddComment("String table");
569   OS.EmitCVStringTableDirective();
570 
571   // Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol
572   // subsection in the generic .debug$S section at the end. There is no
573   // particular reason for this ordering other than to match MSVC.
574   emitBuildInfo();
575 
576   // Emit type information and hashes last, so that any types we translate while
577   // emitting function info are included.
578   emitTypeInformation();
579 
580   if (EmitDebugGlobalHashes)
581     emitTypeGlobalHashes();
582 
583   clear();
584 }
585 
586 static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S,
587     unsigned MaxFixedRecordLength = 0xF00) {
588   // The maximum CV record length is 0xFF00. Most of the strings we emit appear
589   // after a fixed length portion of the record. The fixed length portion should
590   // always be less than 0xF00 (3840) bytes, so truncate the string so that the
591   // overall record size is less than the maximum allowed.
592   SmallString<32> NullTerminatedString(
593       S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
594   NullTerminatedString.push_back('\0');
595   OS.EmitBytes(NullTerminatedString);
596 }
597 
598 void CodeViewDebug::emitTypeInformation() {
599   if (TypeTable.empty())
600     return;
601 
602   // Start the .debug$T or .debug$P section with 0x4.
603   OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
604   emitCodeViewMagicVersion();
605 
606   SmallString<8> CommentPrefix;
607   if (OS.isVerboseAsm()) {
608     CommentPrefix += '\t';
609     CommentPrefix += Asm->MAI->getCommentString();
610     CommentPrefix += ' ';
611   }
612 
613   TypeTableCollection Table(TypeTable.records());
614   Optional<TypeIndex> B = Table.getFirst();
615   while (B) {
616     // This will fail if the record data is invalid.
617     CVType Record = Table.getType(*B);
618 
619     if (OS.isVerboseAsm()) {
620       // Emit a block comment describing the type record for readability.
621       SmallString<512> CommentBlock;
622       raw_svector_ostream CommentOS(CommentBlock);
623       ScopedPrinter SP(CommentOS);
624       SP.setPrefix(CommentPrefix);
625       TypeDumpVisitor TDV(Table, &SP, false);
626 
627       Error E = codeview::visitTypeRecord(Record, *B, TDV);
628       if (E) {
629         logAllUnhandledErrors(std::move(E), errs(), "error: ");
630         llvm_unreachable("produced malformed type record");
631       }
632       // emitRawComment will insert its own tab and comment string before
633       // the first line, so strip off our first one. It also prints its own
634       // newline.
635       OS.emitRawComment(
636           CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
637     }
638     OS.EmitBinaryData(Record.str_data());
639     B = Table.getNext(*B);
640   }
641 }
642 
643 void CodeViewDebug::emitTypeGlobalHashes() {
644   if (TypeTable.empty())
645     return;
646 
647   // Start the .debug$H section with the version and hash algorithm, currently
648   // hardcoded to version 0, SHA1.
649   OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
650 
651   OS.EmitValueToAlignment(4);
652   OS.AddComment("Magic");
653   OS.EmitIntValue(COFF::DEBUG_HASHES_SECTION_MAGIC, 4);
654   OS.AddComment("Section Version");
655   OS.EmitIntValue(0, 2);
656   OS.AddComment("Hash Algorithm");
657   OS.EmitIntValue(uint16_t(GlobalTypeHashAlg::SHA1_8), 2);
658 
659   TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
660   for (const auto &GHR : TypeTable.hashes()) {
661     if (OS.isVerboseAsm()) {
662       // Emit an EOL-comment describing which TypeIndex this hash corresponds
663       // to, as well as the stringified SHA1 hash.
664       SmallString<32> Comment;
665       raw_svector_ostream CommentOS(Comment);
666       CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
667       OS.AddComment(Comment);
668       ++TI;
669     }
670     assert(GHR.Hash.size() == 8);
671     StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
672                 GHR.Hash.size());
673     OS.EmitBinaryData(S);
674   }
675 }
676 
677 static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
678   switch (DWLang) {
679   case dwarf::DW_LANG_C:
680   case dwarf::DW_LANG_C89:
681   case dwarf::DW_LANG_C99:
682   case dwarf::DW_LANG_C11:
683   case dwarf::DW_LANG_ObjC:
684     return SourceLanguage::C;
685   case dwarf::DW_LANG_C_plus_plus:
686   case dwarf::DW_LANG_C_plus_plus_03:
687   case dwarf::DW_LANG_C_plus_plus_11:
688   case dwarf::DW_LANG_C_plus_plus_14:
689     return SourceLanguage::Cpp;
690   case dwarf::DW_LANG_Fortran77:
691   case dwarf::DW_LANG_Fortran90:
692   case dwarf::DW_LANG_Fortran03:
693   case dwarf::DW_LANG_Fortran08:
694     return SourceLanguage::Fortran;
695   case dwarf::DW_LANG_Pascal83:
696     return SourceLanguage::Pascal;
697   case dwarf::DW_LANG_Cobol74:
698   case dwarf::DW_LANG_Cobol85:
699     return SourceLanguage::Cobol;
700   case dwarf::DW_LANG_Java:
701     return SourceLanguage::Java;
702   case dwarf::DW_LANG_D:
703     return SourceLanguage::D;
704   case dwarf::DW_LANG_Swift:
705     return SourceLanguage::Swift;
706   default:
707     // There's no CodeView representation for this language, and CV doesn't
708     // have an "unknown" option for the language field, so we'll use MASM,
709     // as it's very low level.
710     return SourceLanguage::Masm;
711   }
712 }
713 
714 namespace {
715 struct Version {
716   int Part[4];
717 };
718 } // end anonymous namespace
719 
720 // Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
721 // the version number.
722 static Version parseVersion(StringRef Name) {
723   Version V = {{0}};
724   int N = 0;
725   for (const char C : Name) {
726     if (isdigit(C)) {
727       V.Part[N] *= 10;
728       V.Part[N] += C - '0';
729     } else if (C == '.') {
730       ++N;
731       if (N >= 4)
732         return V;
733     } else if (N > 0)
734       return V;
735   }
736   return V;
737 }
738 
739 void CodeViewDebug::emitCompilerInformation() {
740   MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_COMPILE3);
741   uint32_t Flags = 0;
742 
743   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
744   const MDNode *Node = *CUs->operands().begin();
745   const auto *CU = cast<DICompileUnit>(Node);
746 
747   // The low byte of the flags indicates the source language.
748   Flags = MapDWLangToCVLang(CU->getSourceLanguage());
749   // TODO:  Figure out which other flags need to be set.
750 
751   OS.AddComment("Flags and language");
752   OS.EmitIntValue(Flags, 4);
753 
754   OS.AddComment("CPUType");
755   OS.EmitIntValue(static_cast<uint64_t>(TheCPU), 2);
756 
757   StringRef CompilerVersion = CU->getProducer();
758   Version FrontVer = parseVersion(CompilerVersion);
759   OS.AddComment("Frontend version");
760   for (int N = 0; N < 4; ++N)
761     OS.EmitIntValue(FrontVer.Part[N], 2);
762 
763   // Some Microsoft tools, like Binscope, expect a backend version number of at
764   // least 8.something, so we'll coerce the LLVM version into a form that
765   // guarantees it'll be big enough without really lying about the version.
766   int Major = 1000 * LLVM_VERSION_MAJOR +
767               10 * LLVM_VERSION_MINOR +
768               LLVM_VERSION_PATCH;
769   // Clamp it for builds that use unusually large version numbers.
770   Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
771   Version BackVer = {{ Major, 0, 0, 0 }};
772   OS.AddComment("Backend version");
773   for (int N = 0; N < 4; ++N)
774     OS.EmitIntValue(BackVer.Part[N], 2);
775 
776   OS.AddComment("Null-terminated compiler version string");
777   emitNullTerminatedSymbolName(OS, CompilerVersion);
778 
779   endSymbolRecord(CompilerEnd);
780 }
781 
782 static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable,
783                                     StringRef S) {
784   StringIdRecord SIR(TypeIndex(0x0), S);
785   return TypeTable.writeLeafType(SIR);
786 }
787 
788 void CodeViewDebug::emitBuildInfo() {
789   // First, make LF_BUILDINFO. It's a sequence of strings with various bits of
790   // build info. The known prefix is:
791   // - Absolute path of current directory
792   // - Compiler path
793   // - Main source file path, relative to CWD or absolute
794   // - Type server PDB file
795   // - Canonical compiler command line
796   // If frontend and backend compilation are separated (think llc or LTO), it's
797   // not clear if the compiler path should refer to the executable for the
798   // frontend or the backend. Leave it blank for now.
799   TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {};
800   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
801   const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs.
802   const auto *CU = cast<DICompileUnit>(Node);
803   const DIFile *MainSourceFile = CU->getFile();
804   BuildInfoArgs[BuildInfoRecord::CurrentDirectory] =
805       getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory());
806   BuildInfoArgs[BuildInfoRecord::SourceFile] =
807       getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename());
808   // FIXME: Path to compiler and command line. PDB is intentionally blank unless
809   // we implement /Zi type servers.
810   BuildInfoRecord BIR(BuildInfoArgs);
811   TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR);
812 
813   // Make a new .debug$S subsection for the S_BUILDINFO record, which points
814   // from the module symbols into the type stream.
815   MCSymbol *BISubsecEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
816   MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO);
817   OS.AddComment("LF_BUILDINFO index");
818   OS.EmitIntValue(BuildInfoIndex.getIndex(), 4);
819   endSymbolRecord(BIEnd);
820   endCVSubsection(BISubsecEnd);
821 }
822 
823 void CodeViewDebug::emitInlineeLinesSubsection() {
824   if (InlinedSubprograms.empty())
825     return;
826 
827   OS.AddComment("Inlinee lines subsection");
828   MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
829 
830   // We emit the checksum info for files.  This is used by debuggers to
831   // determine if a pdb matches the source before loading it.  Visual Studio,
832   // for instance, will display a warning that the breakpoints are not valid if
833   // the pdb does not match the source.
834   OS.AddComment("Inlinee lines signature");
835   OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
836 
837   for (const DISubprogram *SP : InlinedSubprograms) {
838     assert(TypeIndices.count({SP, nullptr}));
839     TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
840 
841     OS.AddBlankLine();
842     unsigned FileId = maybeRecordFile(SP->getFile());
843     OS.AddComment("Inlined function " + SP->getName() + " starts at " +
844                   SP->getFilename() + Twine(':') + Twine(SP->getLine()));
845     OS.AddBlankLine();
846     OS.AddComment("Type index of inlined function");
847     OS.EmitIntValue(InlineeIdx.getIndex(), 4);
848     OS.AddComment("Offset into filechecksum table");
849     OS.EmitCVFileChecksumOffsetDirective(FileId);
850     OS.AddComment("Starting line number");
851     OS.EmitIntValue(SP->getLine(), 4);
852   }
853 
854   endCVSubsection(InlineEnd);
855 }
856 
857 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
858                                         const DILocation *InlinedAt,
859                                         const InlineSite &Site) {
860   assert(TypeIndices.count({Site.Inlinee, nullptr}));
861   TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
862 
863   // SymbolRecord
864   MCSymbol *InlineEnd = beginSymbolRecord(SymbolKind::S_INLINESITE);
865 
866   OS.AddComment("PtrParent");
867   OS.EmitIntValue(0, 4);
868   OS.AddComment("PtrEnd");
869   OS.EmitIntValue(0, 4);
870   OS.AddComment("Inlinee type index");
871   OS.EmitIntValue(InlineeIdx.getIndex(), 4);
872 
873   unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
874   unsigned StartLineNum = Site.Inlinee->getLine();
875 
876   OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
877                                     FI.Begin, FI.End);
878 
879   endSymbolRecord(InlineEnd);
880 
881   emitLocalVariableList(FI, Site.InlinedLocals);
882 
883   // Recurse on child inlined call sites before closing the scope.
884   for (const DILocation *ChildSite : Site.ChildSites) {
885     auto I = FI.InlineSites.find(ChildSite);
886     assert(I != FI.InlineSites.end() &&
887            "child site not in function inline site map");
888     emitInlinedCallSite(FI, ChildSite, I->second);
889   }
890 
891   // Close the scope.
892   emitEndSymbolRecord(SymbolKind::S_INLINESITE_END);
893 }
894 
895 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
896   // If we have a symbol, it may be in a section that is COMDAT. If so, find the
897   // comdat key. A section may be comdat because of -ffunction-sections or
898   // because it is comdat in the IR.
899   MCSectionCOFF *GVSec =
900       GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
901   const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
902 
903   MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
904       Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
905   DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
906 
907   OS.SwitchSection(DebugSec);
908 
909   // Emit the magic version number if this is the first time we've switched to
910   // this section.
911   if (ComdatDebugSections.insert(DebugSec).second)
912     emitCodeViewMagicVersion();
913 }
914 
915 // Emit an S_THUNK32/S_END symbol pair for a thunk routine.
916 // The only supported thunk ordinal is currently the standard type.
917 void CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
918                                           FunctionInfo &FI,
919                                           const MCSymbol *Fn) {
920   std::string FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
921   const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
922 
923   OS.AddComment("Symbol subsection for " + Twine(FuncName));
924   MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
925 
926   // Emit S_THUNK32
927   MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32);
928   OS.AddComment("PtrParent");
929   OS.EmitIntValue(0, 4);
930   OS.AddComment("PtrEnd");
931   OS.EmitIntValue(0, 4);
932   OS.AddComment("PtrNext");
933   OS.EmitIntValue(0, 4);
934   OS.AddComment("Thunk section relative address");
935   OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
936   OS.AddComment("Thunk section index");
937   OS.EmitCOFFSectionIndex(Fn);
938   OS.AddComment("Code size");
939   OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
940   OS.AddComment("Ordinal");
941   OS.EmitIntValue(unsigned(ordinal), 1);
942   OS.AddComment("Function name");
943   emitNullTerminatedSymbolName(OS, FuncName);
944   // Additional fields specific to the thunk ordinal would go here.
945   endSymbolRecord(ThunkRecordEnd);
946 
947   // Local variables/inlined routines are purposely omitted here.  The point of
948   // marking this as a thunk is so Visual Studio will NOT stop in this routine.
949 
950   // Emit S_PROC_ID_END
951   emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
952 
953   endCVSubsection(SymbolsEnd);
954 }
955 
956 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
957                                              FunctionInfo &FI) {
958   // For each function there is a separate subsection which holds the PC to
959   // file:line table.
960   const MCSymbol *Fn = Asm->getSymbol(GV);
961   assert(Fn);
962 
963   // Switch to the to a comdat section, if appropriate.
964   switchToDebugSectionForSymbol(Fn);
965 
966   std::string FuncName;
967   auto *SP = GV->getSubprogram();
968   assert(SP);
969   setCurrentSubprogram(SP);
970 
971   if (SP->isThunk()) {
972     emitDebugInfoForThunk(GV, FI, Fn);
973     return;
974   }
975 
976   // If we have a display name, build the fully qualified name by walking the
977   // chain of scopes.
978   if (!SP->getName().empty())
979     FuncName = getFullyQualifiedName(SP->getScope(), SP->getName());
980 
981   // If our DISubprogram name is empty, use the mangled name.
982   if (FuncName.empty())
983     FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
984 
985   // Emit FPO data, but only on 32-bit x86. No other platforms use it.
986   if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
987     OS.EmitCVFPOData(Fn);
988 
989   // Emit a symbol subsection, required by VS2012+ to find function boundaries.
990   OS.AddComment("Symbol subsection for " + Twine(FuncName));
991   MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
992   {
993     SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID
994                                                 : SymbolKind::S_GPROC32_ID;
995     MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind);
996 
997     // These fields are filled in by tools like CVPACK which run after the fact.
998     OS.AddComment("PtrParent");
999     OS.EmitIntValue(0, 4);
1000     OS.AddComment("PtrEnd");
1001     OS.EmitIntValue(0, 4);
1002     OS.AddComment("PtrNext");
1003     OS.EmitIntValue(0, 4);
1004     // This is the important bit that tells the debugger where the function
1005     // code is located and what's its size:
1006     OS.AddComment("Code size");
1007     OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
1008     OS.AddComment("Offset after prologue");
1009     OS.EmitIntValue(0, 4);
1010     OS.AddComment("Offset before epilogue");
1011     OS.EmitIntValue(0, 4);
1012     OS.AddComment("Function type index");
1013     OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
1014     OS.AddComment("Function section relative address");
1015     OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
1016     OS.AddComment("Function section index");
1017     OS.EmitCOFFSectionIndex(Fn);
1018     OS.AddComment("Flags");
1019     OS.EmitIntValue(0, 1);
1020     // Emit the function display name as a null-terminated string.
1021     OS.AddComment("Function name");
1022     // Truncate the name so we won't overflow the record length field.
1023     emitNullTerminatedSymbolName(OS, FuncName);
1024     endSymbolRecord(ProcRecordEnd);
1025 
1026     MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC);
1027     // Subtract out the CSR size since MSVC excludes that and we include it.
1028     OS.AddComment("FrameSize");
1029     OS.EmitIntValue(FI.FrameSize - FI.CSRSize, 4);
1030     OS.AddComment("Padding");
1031     OS.EmitIntValue(0, 4);
1032     OS.AddComment("Offset of padding");
1033     OS.EmitIntValue(0, 4);
1034     OS.AddComment("Bytes of callee saved registers");
1035     OS.EmitIntValue(FI.CSRSize, 4);
1036     OS.AddComment("Exception handler offset");
1037     OS.EmitIntValue(0, 4);
1038     OS.AddComment("Exception handler section");
1039     OS.EmitIntValue(0, 2);
1040     OS.AddComment("Flags (defines frame register)");
1041     OS.EmitIntValue(uint32_t(FI.FrameProcOpts), 4);
1042     endSymbolRecord(FrameProcEnd);
1043 
1044     emitLocalVariableList(FI, FI.Locals);
1045     emitGlobalVariableList(FI.Globals);
1046     emitLexicalBlockList(FI.ChildBlocks, FI);
1047 
1048     // Emit inlined call site information. Only emit functions inlined directly
1049     // into the parent function. We'll emit the other sites recursively as part
1050     // of their parent inline site.
1051     for (const DILocation *InlinedAt : FI.ChildSites) {
1052       auto I = FI.InlineSites.find(InlinedAt);
1053       assert(I != FI.InlineSites.end() &&
1054              "child site not in function inline site map");
1055       emitInlinedCallSite(FI, InlinedAt, I->second);
1056     }
1057 
1058     for (auto Annot : FI.Annotations) {
1059       MCSymbol *Label = Annot.first;
1060       MDTuple *Strs = cast<MDTuple>(Annot.second);
1061       MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION);
1062       OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
1063       // FIXME: Make sure we don't overflow the max record size.
1064       OS.EmitCOFFSectionIndex(Label);
1065       OS.EmitIntValue(Strs->getNumOperands(), 2);
1066       for (Metadata *MD : Strs->operands()) {
1067         // MDStrings are null terminated, so we can do EmitBytes and get the
1068         // nice .asciz directive.
1069         StringRef Str = cast<MDString>(MD)->getString();
1070         assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
1071         OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
1072       }
1073       endSymbolRecord(AnnotEnd);
1074     }
1075 
1076     for (auto HeapAllocSite : FI.HeapAllocSites) {
1077       MCSymbol *BeginLabel = std::get<0>(HeapAllocSite);
1078       MCSymbol *EndLabel = std::get<1>(HeapAllocSite);
1079 
1080       // The labels might not be defined if the instruction was replaced
1081       // somewhere in the codegen pipeline.
1082       if (!BeginLabel->isDefined() || !EndLabel->isDefined())
1083         continue;
1084 
1085       DIType *DITy = std::get<2>(HeapAllocSite);
1086       MCSymbol *HeapAllocEnd = beginSymbolRecord(SymbolKind::S_HEAPALLOCSITE);
1087       OS.AddComment("Call site offset");
1088       OS.EmitCOFFSecRel32(BeginLabel, /*Offset=*/0);
1089       OS.AddComment("Call site section index");
1090       OS.EmitCOFFSectionIndex(BeginLabel);
1091       OS.AddComment("Call instruction length");
1092       OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
1093       OS.AddComment("Type index");
1094       OS.EmitIntValue(getCompleteTypeIndex(DITy).getIndex(), 4);
1095       endSymbolRecord(HeapAllocEnd);
1096     }
1097 
1098     if (SP != nullptr)
1099       emitDebugInfoForUDTs(LocalUDTs);
1100 
1101     // We're done with this function.
1102     emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
1103   }
1104   endCVSubsection(SymbolsEnd);
1105 
1106   // We have an assembler directive that takes care of the whole line table.
1107   OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
1108 }
1109 
1110 CodeViewDebug::LocalVarDefRange
1111 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
1112   LocalVarDefRange DR;
1113   DR.InMemory = -1;
1114   DR.DataOffset = Offset;
1115   assert(DR.DataOffset == Offset && "truncation");
1116   DR.IsSubfield = 0;
1117   DR.StructOffset = 0;
1118   DR.CVRegister = CVRegister;
1119   return DR;
1120 }
1121 
1122 void CodeViewDebug::collectVariableInfoFromMFTable(
1123     DenseSet<InlinedEntity> &Processed) {
1124   const MachineFunction &MF = *Asm->MF;
1125   const TargetSubtargetInfo &TSI = MF.getSubtarget();
1126   const TargetFrameLowering *TFI = TSI.getFrameLowering();
1127   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1128 
1129   for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
1130     if (!VI.Var)
1131       continue;
1132     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1133            "Expected inlined-at fields to agree");
1134 
1135     Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
1136     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1137 
1138     // If variable scope is not found then skip this variable.
1139     if (!Scope)
1140       continue;
1141 
1142     // If the variable has an attached offset expression, extract it.
1143     // FIXME: Try to handle DW_OP_deref as well.
1144     int64_t ExprOffset = 0;
1145     bool Deref = false;
1146     if (VI.Expr) {
1147       // If there is one DW_OP_deref element, use offset of 0 and keep going.
1148       if (VI.Expr->getNumElements() == 1 &&
1149           VI.Expr->getElement(0) == llvm::dwarf::DW_OP_deref)
1150         Deref = true;
1151       else if (!VI.Expr->extractIfOffset(ExprOffset))
1152         continue;
1153     }
1154 
1155     // Get the frame register used and the offset.
1156     unsigned FrameReg = 0;
1157     int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
1158     uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
1159 
1160     // Calculate the label ranges.
1161     LocalVarDefRange DefRange =
1162         createDefRangeMem(CVReg, FrameOffset + ExprOffset);
1163 
1164     for (const InsnRange &Range : Scope->getRanges()) {
1165       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1166       const MCSymbol *End = getLabelAfterInsn(Range.second);
1167       End = End ? End : Asm->getFunctionEnd();
1168       DefRange.Ranges.emplace_back(Begin, End);
1169     }
1170 
1171     LocalVariable Var;
1172     Var.DIVar = VI.Var;
1173     Var.DefRanges.emplace_back(std::move(DefRange));
1174     if (Deref)
1175       Var.UseReferenceType = true;
1176 
1177     recordLocalVariable(std::move(Var), Scope);
1178   }
1179 }
1180 
1181 static bool canUseReferenceType(const DbgVariableLocation &Loc) {
1182   return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
1183 }
1184 
1185 static bool needsReferenceType(const DbgVariableLocation &Loc) {
1186   return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
1187 }
1188 
1189 void CodeViewDebug::calculateRanges(
1190     LocalVariable &Var, const DbgValueHistoryMap::Entries &Entries) {
1191   const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1192 
1193   // Calculate the definition ranges.
1194   for (auto I = Entries.begin(), E = Entries.end(); I != E; ++I) {
1195     const auto &Entry = *I;
1196     if (!Entry.isDbgValue())
1197       continue;
1198     const MachineInstr *DVInst = Entry.getInstr();
1199     assert(DVInst->isDebugValue() && "Invalid History entry");
1200     // FIXME: Find a way to represent constant variables, since they are
1201     // relatively common.
1202     Optional<DbgVariableLocation> Location =
1203         DbgVariableLocation::extractFromMachineInstruction(*DVInst);
1204     if (!Location)
1205       continue;
1206 
1207     // CodeView can only express variables in register and variables in memory
1208     // at a constant offset from a register. However, for variables passed
1209     // indirectly by pointer, it is common for that pointer to be spilled to a
1210     // stack location. For the special case of one offseted load followed by a
1211     // zero offset load (a pointer spilled to the stack), we change the type of
1212     // the local variable from a value type to a reference type. This tricks the
1213     // debugger into doing the load for us.
1214     if (Var.UseReferenceType) {
1215       // We're using a reference type. Drop the last zero offset load.
1216       if (canUseReferenceType(*Location))
1217         Location->LoadChain.pop_back();
1218       else
1219         continue;
1220     } else if (needsReferenceType(*Location)) {
1221       // This location can't be expressed without switching to a reference type.
1222       // Start over using that.
1223       Var.UseReferenceType = true;
1224       Var.DefRanges.clear();
1225       calculateRanges(Var, Entries);
1226       return;
1227     }
1228 
1229     // We can only handle a register or an offseted load of a register.
1230     if (Location->Register == 0 || Location->LoadChain.size() > 1)
1231       continue;
1232     {
1233       LocalVarDefRange DR;
1234       DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
1235       DR.InMemory = !Location->LoadChain.empty();
1236       DR.DataOffset =
1237           !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
1238       if (Location->FragmentInfo) {
1239         DR.IsSubfield = true;
1240         DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
1241       } else {
1242         DR.IsSubfield = false;
1243         DR.StructOffset = 0;
1244       }
1245 
1246       if (Var.DefRanges.empty() ||
1247           Var.DefRanges.back().isDifferentLocation(DR)) {
1248         Var.DefRanges.emplace_back(std::move(DR));
1249       }
1250     }
1251 
1252     // Compute the label range.
1253     const MCSymbol *Begin = getLabelBeforeInsn(Entry.getInstr());
1254     const MCSymbol *End;
1255     if (Entry.getEndIndex() != DbgValueHistoryMap::NoEntry) {
1256       auto &EndingEntry = Entries[Entry.getEndIndex()];
1257       End = EndingEntry.isDbgValue()
1258                 ? getLabelBeforeInsn(EndingEntry.getInstr())
1259                 : getLabelAfterInsn(EndingEntry.getInstr());
1260     } else
1261       End = Asm->getFunctionEnd();
1262 
1263     // If the last range end is our begin, just extend the last range.
1264     // Otherwise make a new range.
1265     SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1266         Var.DefRanges.back().Ranges;
1267     if (!R.empty() && R.back().second == Begin)
1268       R.back().second = End;
1269     else
1270       R.emplace_back(Begin, End);
1271 
1272     // FIXME: Do more range combining.
1273   }
1274 }
1275 
1276 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
1277   DenseSet<InlinedEntity> Processed;
1278   // Grab the variable info that was squirreled away in the MMI side-table.
1279   collectVariableInfoFromMFTable(Processed);
1280 
1281   for (const auto &I : DbgValues) {
1282     InlinedEntity IV = I.first;
1283     if (Processed.count(IV))
1284       continue;
1285     const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
1286     const DILocation *InlinedAt = IV.second;
1287 
1288     // Instruction ranges, specifying where IV is accessible.
1289     const auto &Entries = I.second;
1290 
1291     LexicalScope *Scope = nullptr;
1292     if (InlinedAt)
1293       Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1294     else
1295       Scope = LScopes.findLexicalScope(DIVar->getScope());
1296     // If variable scope is not found then skip this variable.
1297     if (!Scope)
1298       continue;
1299 
1300     LocalVariable Var;
1301     Var.DIVar = DIVar;
1302 
1303     calculateRanges(Var, Entries);
1304     recordLocalVariable(std::move(Var), Scope);
1305   }
1306 }
1307 
1308 void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
1309   const TargetSubtargetInfo &TSI = MF->getSubtarget();
1310   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1311   const MachineFrameInfo &MFI = MF->getFrameInfo();
1312   const Function &GV = MF->getFunction();
1313   auto Insertion = FnDebugInfo.insert({&GV, llvm::make_unique<FunctionInfo>()});
1314   assert(Insertion.second && "function already has info");
1315   CurFn = Insertion.first->second.get();
1316   CurFn->FuncId = NextFuncId++;
1317   CurFn->Begin = Asm->getFunctionBegin();
1318 
1319   // The S_FRAMEPROC record reports the stack size, and how many bytes of
1320   // callee-saved registers were used. For targets that don't use a PUSH
1321   // instruction (AArch64), this will be zero.
1322   CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
1323   CurFn->FrameSize = MFI.getStackSize();
1324   CurFn->OffsetAdjustment = MFI.getOffsetAdjustment();
1325   CurFn->HasStackRealignment = TRI->needsStackRealignment(*MF);
1326 
1327   // For this function S_FRAMEPROC record, figure out which codeview register
1328   // will be the frame pointer.
1329   CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
1330   CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
1331   if (CurFn->FrameSize > 0) {
1332     if (!TSI.getFrameLowering()->hasFP(*MF)) {
1333       CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1334       CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
1335     } else {
1336       // If there is an FP, parameters are always relative to it.
1337       CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
1338       if (CurFn->HasStackRealignment) {
1339         // If the stack needs realignment, locals are relative to SP or VFRAME.
1340         CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1341       } else {
1342         // Otherwise, locals are relative to EBP, and we probably have VLAs or
1343         // other stack adjustments.
1344         CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
1345       }
1346     }
1347   }
1348 
1349   // Compute other frame procedure options.
1350   FrameProcedureOptions FPO = FrameProcedureOptions::None;
1351   if (MFI.hasVarSizedObjects())
1352     FPO |= FrameProcedureOptions::HasAlloca;
1353   if (MF->exposesReturnsTwice())
1354     FPO |= FrameProcedureOptions::HasSetJmp;
1355   // FIXME: Set HasLongJmp if we ever track that info.
1356   if (MF->hasInlineAsm())
1357     FPO |= FrameProcedureOptions::HasInlineAssembly;
1358   if (GV.hasPersonalityFn()) {
1359     if (isAsynchronousEHPersonality(
1360             classifyEHPersonality(GV.getPersonalityFn())))
1361       FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
1362     else
1363       FPO |= FrameProcedureOptions::HasExceptionHandling;
1364   }
1365   if (GV.hasFnAttribute(Attribute::InlineHint))
1366     FPO |= FrameProcedureOptions::MarkedInline;
1367   if (GV.hasFnAttribute(Attribute::Naked))
1368     FPO |= FrameProcedureOptions::Naked;
1369   if (MFI.hasStackProtectorIndex())
1370     FPO |= FrameProcedureOptions::SecurityChecks;
1371   FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
1372   FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
1373   if (Asm->TM.getOptLevel() != CodeGenOpt::None &&
1374       !GV.hasOptSize() && !GV.hasOptNone())
1375     FPO |= FrameProcedureOptions::OptimizedForSpeed;
1376   // FIXME: Set GuardCfg when it is implemented.
1377   CurFn->FrameProcOpts = FPO;
1378 
1379   OS.EmitCVFuncIdDirective(CurFn->FuncId);
1380 
1381   // Find the end of the function prolog.  First known non-DBG_VALUE and
1382   // non-frame setup location marks the beginning of the function body.
1383   // FIXME: is there a simpler a way to do this? Can we just search
1384   // for the first instruction of the function, not the last of the prolog?
1385   DebugLoc PrologEndLoc;
1386   bool EmptyPrologue = true;
1387   for (const auto &MBB : *MF) {
1388     for (const auto &MI : MBB) {
1389       if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1390           MI.getDebugLoc()) {
1391         PrologEndLoc = MI.getDebugLoc();
1392         break;
1393       } else if (!MI.isMetaInstruction()) {
1394         EmptyPrologue = false;
1395       }
1396     }
1397   }
1398 
1399   // Record beginning of function if we have a non-empty prologue.
1400   if (PrologEndLoc && !EmptyPrologue) {
1401     DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
1402     maybeRecordLocation(FnStartDL, MF);
1403   }
1404 }
1405 
1406 static bool shouldEmitUdt(const DIType *T) {
1407   if (!T)
1408     return false;
1409 
1410   // MSVC does not emit UDTs for typedefs that are scoped to classes.
1411   if (T->getTag() == dwarf::DW_TAG_typedef) {
1412     if (DIScope *Scope = T->getScope()) {
1413       switch (Scope->getTag()) {
1414       case dwarf::DW_TAG_structure_type:
1415       case dwarf::DW_TAG_class_type:
1416       case dwarf::DW_TAG_union_type:
1417         return false;
1418       }
1419     }
1420   }
1421 
1422   while (true) {
1423     if (!T || T->isForwardDecl())
1424       return false;
1425 
1426     const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
1427     if (!DT)
1428       return true;
1429     T = DT->getBaseType();
1430   }
1431   return true;
1432 }
1433 
1434 void CodeViewDebug::addToUDTs(const DIType *Ty) {
1435   // Don't record empty UDTs.
1436   if (Ty->getName().empty())
1437     return;
1438   if (!shouldEmitUdt(Ty))
1439     return;
1440 
1441   SmallVector<StringRef, 5> QualifiedNameComponents;
1442   const DISubprogram *ClosestSubprogram =
1443       getQualifiedNameComponents(Ty->getScope(), QualifiedNameComponents);
1444 
1445   std::string FullyQualifiedName =
1446       getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
1447 
1448   if (ClosestSubprogram == nullptr) {
1449     GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1450   } else if (ClosestSubprogram == CurrentSubprogram) {
1451     LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1452   }
1453 
1454   // TODO: What if the ClosestSubprogram is neither null or the current
1455   // subprogram?  Currently, the UDT just gets dropped on the floor.
1456   //
1457   // The current behavior is not desirable.  To get maximal fidelity, we would
1458   // need to perform all type translation before beginning emission of .debug$S
1459   // and then make LocalUDTs a member of FunctionInfo
1460 }
1461 
1462 TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
1463   // Generic dispatch for lowering an unknown type.
1464   switch (Ty->getTag()) {
1465   case dwarf::DW_TAG_array_type:
1466     return lowerTypeArray(cast<DICompositeType>(Ty));
1467   case dwarf::DW_TAG_typedef:
1468     return lowerTypeAlias(cast<DIDerivedType>(Ty));
1469   case dwarf::DW_TAG_base_type:
1470     return lowerTypeBasic(cast<DIBasicType>(Ty));
1471   case dwarf::DW_TAG_pointer_type:
1472     if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1473       return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1474     LLVM_FALLTHROUGH;
1475   case dwarf::DW_TAG_reference_type:
1476   case dwarf::DW_TAG_rvalue_reference_type:
1477     return lowerTypePointer(cast<DIDerivedType>(Ty));
1478   case dwarf::DW_TAG_ptr_to_member_type:
1479     return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1480   case dwarf::DW_TAG_restrict_type:
1481   case dwarf::DW_TAG_const_type:
1482   case dwarf::DW_TAG_volatile_type:
1483   // TODO: add support for DW_TAG_atomic_type here
1484     return lowerTypeModifier(cast<DIDerivedType>(Ty));
1485   case dwarf::DW_TAG_subroutine_type:
1486     if (ClassTy) {
1487       // The member function type of a member function pointer has no
1488       // ThisAdjustment.
1489       return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1490                                      /*ThisAdjustment=*/0,
1491                                      /*IsStaticMethod=*/false);
1492     }
1493     return lowerTypeFunction(cast<DISubroutineType>(Ty));
1494   case dwarf::DW_TAG_enumeration_type:
1495     return lowerTypeEnum(cast<DICompositeType>(Ty));
1496   case dwarf::DW_TAG_class_type:
1497   case dwarf::DW_TAG_structure_type:
1498     return lowerTypeClass(cast<DICompositeType>(Ty));
1499   case dwarf::DW_TAG_union_type:
1500     return lowerTypeUnion(cast<DICompositeType>(Ty));
1501   case dwarf::DW_TAG_unspecified_type:
1502     if (Ty->getName() == "decltype(nullptr)")
1503       return TypeIndex::NullptrT();
1504     return TypeIndex::None();
1505   default:
1506     // Use the null type index.
1507     return TypeIndex();
1508   }
1509 }
1510 
1511 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
1512   TypeIndex UnderlyingTypeIndex = getTypeIndex(Ty->getBaseType());
1513   StringRef TypeName = Ty->getName();
1514 
1515   addToUDTs(Ty);
1516 
1517   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
1518       TypeName == "HRESULT")
1519     return TypeIndex(SimpleTypeKind::HResult);
1520   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
1521       TypeName == "wchar_t")
1522     return TypeIndex(SimpleTypeKind::WideCharacter);
1523 
1524   return UnderlyingTypeIndex;
1525 }
1526 
1527 TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1528   const DIType *ElementType = Ty->getBaseType();
1529   TypeIndex ElementTypeIndex = getTypeIndex(ElementType);
1530   // IndexType is size_t, which depends on the bitness of the target.
1531   TypeIndex IndexType = getPointerSizeInBytes() == 8
1532                             ? TypeIndex(SimpleTypeKind::UInt64Quad)
1533                             : TypeIndex(SimpleTypeKind::UInt32Long);
1534 
1535   uint64_t ElementSize = getBaseTypeSize(ElementType) / 8;
1536 
1537   // Add subranges to array type.
1538   DINodeArray Elements = Ty->getElements();
1539   for (int i = Elements.size() - 1; i >= 0; --i) {
1540     const DINode *Element = Elements[i];
1541     assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1542 
1543     const DISubrange *Subrange = cast<DISubrange>(Element);
1544     assert(Subrange->getLowerBound() == 0 &&
1545            "codeview doesn't support subranges with lower bounds");
1546     int64_t Count = -1;
1547     if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>())
1548       Count = CI->getSExtValue();
1549 
1550     // Forward declarations of arrays without a size and VLAs use a count of -1.
1551     // Emit a count of zero in these cases to match what MSVC does for arrays
1552     // without a size. MSVC doesn't support VLAs, so it's not clear what we
1553     // should do for them even if we could distinguish them.
1554     if (Count == -1)
1555       Count = 0;
1556 
1557     // Update the element size and element type index for subsequent subranges.
1558     ElementSize *= Count;
1559 
1560     // If this is the outermost array, use the size from the array. It will be
1561     // more accurate if we had a VLA or an incomplete element type size.
1562     uint64_t ArraySize =
1563         (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1564 
1565     StringRef Name = (i == 0) ? Ty->getName() : "";
1566     ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1567     ElementTypeIndex = TypeTable.writeLeafType(AR);
1568   }
1569 
1570   return ElementTypeIndex;
1571 }
1572 
1573 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1574   TypeIndex Index;
1575   dwarf::TypeKind Kind;
1576   uint32_t ByteSize;
1577 
1578   Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
1579   ByteSize = Ty->getSizeInBits() / 8;
1580 
1581   SimpleTypeKind STK = SimpleTypeKind::None;
1582   switch (Kind) {
1583   case dwarf::DW_ATE_address:
1584     // FIXME: Translate
1585     break;
1586   case dwarf::DW_ATE_boolean:
1587     switch (ByteSize) {
1588     case 1:  STK = SimpleTypeKind::Boolean8;   break;
1589     case 2:  STK = SimpleTypeKind::Boolean16;  break;
1590     case 4:  STK = SimpleTypeKind::Boolean32;  break;
1591     case 8:  STK = SimpleTypeKind::Boolean64;  break;
1592     case 16: STK = SimpleTypeKind::Boolean128; break;
1593     }
1594     break;
1595   case dwarf::DW_ATE_complex_float:
1596     switch (ByteSize) {
1597     case 2:  STK = SimpleTypeKind::Complex16;  break;
1598     case 4:  STK = SimpleTypeKind::Complex32;  break;
1599     case 8:  STK = SimpleTypeKind::Complex64;  break;
1600     case 10: STK = SimpleTypeKind::Complex80;  break;
1601     case 16: STK = SimpleTypeKind::Complex128; break;
1602     }
1603     break;
1604   case dwarf::DW_ATE_float:
1605     switch (ByteSize) {
1606     case 2:  STK = SimpleTypeKind::Float16;  break;
1607     case 4:  STK = SimpleTypeKind::Float32;  break;
1608     case 6:  STK = SimpleTypeKind::Float48;  break;
1609     case 8:  STK = SimpleTypeKind::Float64;  break;
1610     case 10: STK = SimpleTypeKind::Float80;  break;
1611     case 16: STK = SimpleTypeKind::Float128; break;
1612     }
1613     break;
1614   case dwarf::DW_ATE_signed:
1615     switch (ByteSize) {
1616     case 1:  STK = SimpleTypeKind::SignedCharacter; break;
1617     case 2:  STK = SimpleTypeKind::Int16Short;      break;
1618     case 4:  STK = SimpleTypeKind::Int32;           break;
1619     case 8:  STK = SimpleTypeKind::Int64Quad;       break;
1620     case 16: STK = SimpleTypeKind::Int128Oct;       break;
1621     }
1622     break;
1623   case dwarf::DW_ATE_unsigned:
1624     switch (ByteSize) {
1625     case 1:  STK = SimpleTypeKind::UnsignedCharacter; break;
1626     case 2:  STK = SimpleTypeKind::UInt16Short;       break;
1627     case 4:  STK = SimpleTypeKind::UInt32;            break;
1628     case 8:  STK = SimpleTypeKind::UInt64Quad;        break;
1629     case 16: STK = SimpleTypeKind::UInt128Oct;        break;
1630     }
1631     break;
1632   case dwarf::DW_ATE_UTF:
1633     switch (ByteSize) {
1634     case 2: STK = SimpleTypeKind::Character16; break;
1635     case 4: STK = SimpleTypeKind::Character32; break;
1636     }
1637     break;
1638   case dwarf::DW_ATE_signed_char:
1639     if (ByteSize == 1)
1640       STK = SimpleTypeKind::SignedCharacter;
1641     break;
1642   case dwarf::DW_ATE_unsigned_char:
1643     if (ByteSize == 1)
1644       STK = SimpleTypeKind::UnsignedCharacter;
1645     break;
1646   default:
1647     break;
1648   }
1649 
1650   // Apply some fixups based on the source-level type name.
1651   if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1652     STK = SimpleTypeKind::Int32Long;
1653   if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1654     STK = SimpleTypeKind::UInt32Long;
1655   if (STK == SimpleTypeKind::UInt16Short &&
1656       (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
1657     STK = SimpleTypeKind::WideCharacter;
1658   if ((STK == SimpleTypeKind::SignedCharacter ||
1659        STK == SimpleTypeKind::UnsignedCharacter) &&
1660       Ty->getName() == "char")
1661     STK = SimpleTypeKind::NarrowCharacter;
1662 
1663   return TypeIndex(STK);
1664 }
1665 
1666 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
1667                                           PointerOptions PO) {
1668   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1669 
1670   // Pointers to simple types without any options can use SimpleTypeMode, rather
1671   // than having a dedicated pointer type record.
1672   if (PointeeTI.isSimple() && PO == PointerOptions::None &&
1673       PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1674       Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1675     SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1676                               ? SimpleTypeMode::NearPointer64
1677                               : SimpleTypeMode::NearPointer32;
1678     return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1679   }
1680 
1681   PointerKind PK =
1682       Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1683   PointerMode PM = PointerMode::Pointer;
1684   switch (Ty->getTag()) {
1685   default: llvm_unreachable("not a pointer tag type");
1686   case dwarf::DW_TAG_pointer_type:
1687     PM = PointerMode::Pointer;
1688     break;
1689   case dwarf::DW_TAG_reference_type:
1690     PM = PointerMode::LValueReference;
1691     break;
1692   case dwarf::DW_TAG_rvalue_reference_type:
1693     PM = PointerMode::RValueReference;
1694     break;
1695   }
1696 
1697   if (Ty->isObjectPointer())
1698     PO |= PointerOptions::Const;
1699 
1700   PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1701   return TypeTable.writeLeafType(PR);
1702 }
1703 
1704 static PointerToMemberRepresentation
1705 translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1706   // SizeInBytes being zero generally implies that the member pointer type was
1707   // incomplete, which can happen if it is part of a function prototype. In this
1708   // case, use the unknown model instead of the general model.
1709   if (IsPMF) {
1710     switch (Flags & DINode::FlagPtrToMemberRep) {
1711     case 0:
1712       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1713                               : PointerToMemberRepresentation::GeneralFunction;
1714     case DINode::FlagSingleInheritance:
1715       return PointerToMemberRepresentation::SingleInheritanceFunction;
1716     case DINode::FlagMultipleInheritance:
1717       return PointerToMemberRepresentation::MultipleInheritanceFunction;
1718     case DINode::FlagVirtualInheritance:
1719       return PointerToMemberRepresentation::VirtualInheritanceFunction;
1720     }
1721   } else {
1722     switch (Flags & DINode::FlagPtrToMemberRep) {
1723     case 0:
1724       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1725                               : PointerToMemberRepresentation::GeneralData;
1726     case DINode::FlagSingleInheritance:
1727       return PointerToMemberRepresentation::SingleInheritanceData;
1728     case DINode::FlagMultipleInheritance:
1729       return PointerToMemberRepresentation::MultipleInheritanceData;
1730     case DINode::FlagVirtualInheritance:
1731       return PointerToMemberRepresentation::VirtualInheritanceData;
1732     }
1733   }
1734   llvm_unreachable("invalid ptr to member representation");
1735 }
1736 
1737 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
1738                                                 PointerOptions PO) {
1739   assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1740   TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
1741   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
1742   PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1743                                                 : PointerKind::Near32;
1744   bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1745   PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1746                          : PointerMode::PointerToDataMember;
1747 
1748   assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1749   uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1750   MemberPointerInfo MPI(
1751       ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
1752   PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
1753   return TypeTable.writeLeafType(PR);
1754 }
1755 
1756 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1757 /// have a translation, use the NearC convention.
1758 static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1759   switch (DwarfCC) {
1760   case dwarf::DW_CC_normal:             return CallingConvention::NearC;
1761   case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1762   case dwarf::DW_CC_BORLAND_thiscall:   return CallingConvention::ThisCall;
1763   case dwarf::DW_CC_BORLAND_stdcall:    return CallingConvention::NearStdCall;
1764   case dwarf::DW_CC_BORLAND_pascal:     return CallingConvention::NearPascal;
1765   case dwarf::DW_CC_LLVM_vectorcall:    return CallingConvention::NearVector;
1766   }
1767   return CallingConvention::NearC;
1768 }
1769 
1770 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1771   ModifierOptions Mods = ModifierOptions::None;
1772   PointerOptions PO = PointerOptions::None;
1773   bool IsModifier = true;
1774   const DIType *BaseTy = Ty;
1775   while (IsModifier && BaseTy) {
1776     // FIXME: Need to add DWARF tags for __unaligned and _Atomic
1777     switch (BaseTy->getTag()) {
1778     case dwarf::DW_TAG_const_type:
1779       Mods |= ModifierOptions::Const;
1780       PO |= PointerOptions::Const;
1781       break;
1782     case dwarf::DW_TAG_volatile_type:
1783       Mods |= ModifierOptions::Volatile;
1784       PO |= PointerOptions::Volatile;
1785       break;
1786     case dwarf::DW_TAG_restrict_type:
1787       // Only pointer types be marked with __restrict. There is no known flag
1788       // for __restrict in LF_MODIFIER records.
1789       PO |= PointerOptions::Restrict;
1790       break;
1791     default:
1792       IsModifier = false;
1793       break;
1794     }
1795     if (IsModifier)
1796       BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType();
1797   }
1798 
1799   // Check if the inner type will use an LF_POINTER record. If so, the
1800   // qualifiers will go in the LF_POINTER record. This comes up for types like
1801   // 'int *const' and 'int *__restrict', not the more common cases like 'const
1802   // char *'.
1803   if (BaseTy) {
1804     switch (BaseTy->getTag()) {
1805     case dwarf::DW_TAG_pointer_type:
1806     case dwarf::DW_TAG_reference_type:
1807     case dwarf::DW_TAG_rvalue_reference_type:
1808       return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
1809     case dwarf::DW_TAG_ptr_to_member_type:
1810       return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
1811     default:
1812       break;
1813     }
1814   }
1815 
1816   TypeIndex ModifiedTI = getTypeIndex(BaseTy);
1817 
1818   // Return the base type index if there aren't any modifiers. For example, the
1819   // metadata could contain restrict wrappers around non-pointer types.
1820   if (Mods == ModifierOptions::None)
1821     return ModifiedTI;
1822 
1823   ModifierRecord MR(ModifiedTI, Mods);
1824   return TypeTable.writeLeafType(MR);
1825 }
1826 
1827 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1828   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1829   for (const DIType *ArgType : Ty->getTypeArray())
1830     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgType));
1831 
1832   // MSVC uses type none for variadic argument.
1833   if (ReturnAndArgTypeIndices.size() > 1 &&
1834       ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1835     ReturnAndArgTypeIndices.back() = TypeIndex::None();
1836   }
1837   TypeIndex ReturnTypeIndex = TypeIndex::Void();
1838   ArrayRef<TypeIndex> ArgTypeIndices = None;
1839   if (!ReturnAndArgTypeIndices.empty()) {
1840     auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1841     ReturnTypeIndex = ReturnAndArgTypesRef.front();
1842     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1843   }
1844 
1845   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1846   TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
1847 
1848   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1849 
1850   FunctionOptions FO = getFunctionOptions(Ty);
1851   ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
1852                             ArgListIndex);
1853   return TypeTable.writeLeafType(Procedure);
1854 }
1855 
1856 TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
1857                                                  const DIType *ClassTy,
1858                                                  int ThisAdjustment,
1859                                                  bool IsStaticMethod,
1860                                                  FunctionOptions FO) {
1861   // Lower the containing class type.
1862   TypeIndex ClassType = getTypeIndex(ClassTy);
1863 
1864   DITypeRefArray ReturnAndArgs = Ty->getTypeArray();
1865 
1866   unsigned Index = 0;
1867   SmallVector<TypeIndex, 8> ArgTypeIndices;
1868   TypeIndex ReturnTypeIndex = TypeIndex::Void();
1869   if (ReturnAndArgs.size() > Index) {
1870     ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]);
1871   }
1872 
1873   // If the first argument is a pointer type and this isn't a static method,
1874   // treat it as the special 'this' parameter, which is encoded separately from
1875   // the arguments.
1876   TypeIndex ThisTypeIndex;
1877   if (!IsStaticMethod && ReturnAndArgs.size() > Index) {
1878     if (const DIDerivedType *PtrTy =
1879             dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index])) {
1880       if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) {
1881         ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty);
1882         Index++;
1883       }
1884     }
1885   }
1886 
1887   while (Index < ReturnAndArgs.size())
1888     ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++]));
1889 
1890   // MSVC uses type none for variadic argument.
1891   if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void())
1892     ArgTypeIndices.back() = TypeIndex::None();
1893 
1894   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1895   TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
1896 
1897   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1898 
1899   MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
1900                            ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
1901   return TypeTable.writeLeafType(MFR);
1902 }
1903 
1904 TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
1905   unsigned VSlotCount =
1906       Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
1907   SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
1908 
1909   VFTableShapeRecord VFTSR(Slots);
1910   return TypeTable.writeLeafType(VFTSR);
1911 }
1912 
1913 static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1914   switch (Flags & DINode::FlagAccessibility) {
1915   case DINode::FlagPrivate:   return MemberAccess::Private;
1916   case DINode::FlagPublic:    return MemberAccess::Public;
1917   case DINode::FlagProtected: return MemberAccess::Protected;
1918   case 0:
1919     // If there was no explicit access control, provide the default for the tag.
1920     return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1921                                                  : MemberAccess::Public;
1922   }
1923   llvm_unreachable("access flags are exclusive");
1924 }
1925 
1926 static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1927   if (SP->isArtificial())
1928     return MethodOptions::CompilerGenerated;
1929 
1930   // FIXME: Handle other MethodOptions.
1931 
1932   return MethodOptions::None;
1933 }
1934 
1935 static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1936                                            bool Introduced) {
1937   if (SP->getFlags() & DINode::FlagStaticMember)
1938     return MethodKind::Static;
1939 
1940   switch (SP->getVirtuality()) {
1941   case dwarf::DW_VIRTUALITY_none:
1942     break;
1943   case dwarf::DW_VIRTUALITY_virtual:
1944     return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1945   case dwarf::DW_VIRTUALITY_pure_virtual:
1946     return Introduced ? MethodKind::PureIntroducingVirtual
1947                       : MethodKind::PureVirtual;
1948   default:
1949     llvm_unreachable("unhandled virtuality case");
1950   }
1951 
1952   return MethodKind::Vanilla;
1953 }
1954 
1955 static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1956   switch (Ty->getTag()) {
1957   case dwarf::DW_TAG_class_type:     return TypeRecordKind::Class;
1958   case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1959   }
1960   llvm_unreachable("unexpected tag");
1961 }
1962 
1963 /// Return ClassOptions that should be present on both the forward declaration
1964 /// and the defintion of a tag type.
1965 static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1966   ClassOptions CO = ClassOptions::None;
1967 
1968   // MSVC always sets this flag, even for local types. Clang doesn't always
1969   // appear to give every type a linkage name, which may be problematic for us.
1970   // FIXME: Investigate the consequences of not following them here.
1971   if (!Ty->getIdentifier().empty())
1972     CO |= ClassOptions::HasUniqueName;
1973 
1974   // Put the Nested flag on a type if it appears immediately inside a tag type.
1975   // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1976   // here. That flag is only set on definitions, and not forward declarations.
1977   const DIScope *ImmediateScope = Ty->getScope();
1978   if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1979     CO |= ClassOptions::Nested;
1980 
1981   // Put the Scoped flag on function-local types. MSVC puts this flag for enum
1982   // type only when it has an immediate function scope. Clang never puts enums
1983   // inside DILexicalBlock scopes. Enum types, as generated by clang, are
1984   // always in function, class, or file scopes.
1985   if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
1986     if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
1987       CO |= ClassOptions::Scoped;
1988   } else {
1989     for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1990          Scope = Scope->getScope()) {
1991       if (isa<DISubprogram>(Scope)) {
1992         CO |= ClassOptions::Scoped;
1993         break;
1994       }
1995     }
1996   }
1997 
1998   return CO;
1999 }
2000 
2001 void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
2002   switch (Ty->getTag()) {
2003   case dwarf::DW_TAG_class_type:
2004   case dwarf::DW_TAG_structure_type:
2005   case dwarf::DW_TAG_union_type:
2006   case dwarf::DW_TAG_enumeration_type:
2007     break;
2008   default:
2009     return;
2010   }
2011 
2012   if (const auto *File = Ty->getFile()) {
2013     StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
2014     TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
2015 
2016     UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
2017     TypeTable.writeLeafType(USLR);
2018   }
2019 }
2020 
2021 TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
2022   ClassOptions CO = getCommonClassOptions(Ty);
2023   TypeIndex FTI;
2024   unsigned EnumeratorCount = 0;
2025 
2026   if (Ty->isForwardDecl()) {
2027     CO |= ClassOptions::ForwardReference;
2028   } else {
2029     ContinuationRecordBuilder ContinuationBuilder;
2030     ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
2031     for (const DINode *Element : Ty->getElements()) {
2032       // We assume that the frontend provides all members in source declaration
2033       // order, which is what MSVC does.
2034       if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
2035         EnumeratorRecord ER(MemberAccess::Public,
2036                             APSInt::getUnsigned(Enumerator->getValue()),
2037                             Enumerator->getName());
2038         ContinuationBuilder.writeMemberType(ER);
2039         EnumeratorCount++;
2040       }
2041     }
2042     FTI = TypeTable.insertRecord(ContinuationBuilder);
2043   }
2044 
2045   std::string FullName = getFullyQualifiedName(Ty);
2046 
2047   EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
2048                 getTypeIndex(Ty->getBaseType()));
2049   TypeIndex EnumTI = TypeTable.writeLeafType(ER);
2050 
2051   addUDTSrcLine(Ty, EnumTI);
2052 
2053   return EnumTI;
2054 }
2055 
2056 //===----------------------------------------------------------------------===//
2057 // ClassInfo
2058 //===----------------------------------------------------------------------===//
2059 
2060 struct llvm::ClassInfo {
2061   struct MemberInfo {
2062     const DIDerivedType *MemberTypeNode;
2063     uint64_t BaseOffset;
2064   };
2065   // [MemberInfo]
2066   using MemberList = std::vector<MemberInfo>;
2067 
2068   using MethodsList = TinyPtrVector<const DISubprogram *>;
2069   // MethodName -> MethodsList
2070   using MethodsMap = MapVector<MDString *, MethodsList>;
2071 
2072   /// Base classes.
2073   std::vector<const DIDerivedType *> Inheritance;
2074 
2075   /// Direct members.
2076   MemberList Members;
2077   // Direct overloaded methods gathered by name.
2078   MethodsMap Methods;
2079 
2080   TypeIndex VShapeTI;
2081 
2082   std::vector<const DIType *> NestedTypes;
2083 };
2084 
2085 void CodeViewDebug::clear() {
2086   assert(CurFn == nullptr);
2087   FileIdMap.clear();
2088   FnDebugInfo.clear();
2089   FileToFilepathMap.clear();
2090   LocalUDTs.clear();
2091   GlobalUDTs.clear();
2092   TypeIndices.clear();
2093   CompleteTypeIndices.clear();
2094   ScopeGlobals.clear();
2095 }
2096 
2097 void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
2098                                       const DIDerivedType *DDTy) {
2099   if (!DDTy->getName().empty()) {
2100     Info.Members.push_back({DDTy, 0});
2101     return;
2102   }
2103 
2104   // An unnamed member may represent a nested struct or union. Attempt to
2105   // interpret the unnamed member as a DICompositeType possibly wrapped in
2106   // qualifier types. Add all the indirect fields to the current record if that
2107   // succeeds, and drop the member if that fails.
2108   assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
2109   uint64_t Offset = DDTy->getOffsetInBits();
2110   const DIType *Ty = DDTy->getBaseType();
2111   bool FullyResolved = false;
2112   while (!FullyResolved) {
2113     switch (Ty->getTag()) {
2114     case dwarf::DW_TAG_const_type:
2115     case dwarf::DW_TAG_volatile_type:
2116       // FIXME: we should apply the qualifier types to the indirect fields
2117       // rather than dropping them.
2118       Ty = cast<DIDerivedType>(Ty)->getBaseType();
2119       break;
2120     default:
2121       FullyResolved = true;
2122       break;
2123     }
2124   }
2125 
2126   const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
2127   if (!DCTy)
2128     return;
2129 
2130   ClassInfo NestedInfo = collectClassInfo(DCTy);
2131   for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
2132     Info.Members.push_back(
2133         {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
2134 }
2135 
2136 ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
2137   ClassInfo Info;
2138   // Add elements to structure type.
2139   DINodeArray Elements = Ty->getElements();
2140   for (auto *Element : Elements) {
2141     // We assume that the frontend provides all members in source declaration
2142     // order, which is what MSVC does.
2143     if (!Element)
2144       continue;
2145     if (auto *SP = dyn_cast<DISubprogram>(Element)) {
2146       Info.Methods[SP->getRawName()].push_back(SP);
2147     } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
2148       if (DDTy->getTag() == dwarf::DW_TAG_member) {
2149         collectMemberInfo(Info, DDTy);
2150       } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
2151         Info.Inheritance.push_back(DDTy);
2152       } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
2153                  DDTy->getName() == "__vtbl_ptr_type") {
2154         Info.VShapeTI = getTypeIndex(DDTy);
2155       } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
2156         Info.NestedTypes.push_back(DDTy);
2157       } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
2158         // Ignore friend members. It appears that MSVC emitted info about
2159         // friends in the past, but modern versions do not.
2160       }
2161     } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
2162       Info.NestedTypes.push_back(Composite);
2163     }
2164     // Skip other unrecognized kinds of elements.
2165   }
2166   return Info;
2167 }
2168 
2169 static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) {
2170   // This routine is used by lowerTypeClass and lowerTypeUnion to determine
2171   // if a complete type should be emitted instead of a forward reference.
2172   return Ty->getName().empty() && Ty->getIdentifier().empty() &&
2173       !Ty->isForwardDecl();
2174 }
2175 
2176 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
2177   // Emit the complete type for unnamed structs.  C++ classes with methods
2178   // which have a circular reference back to the class type are expected to
2179   // be named by the front-end and should not be "unnamed".  C unnamed
2180   // structs should not have circular references.
2181   if (shouldAlwaysEmitCompleteClassType(Ty)) {
2182     // If this unnamed complete type is already in the process of being defined
2183     // then the description of the type is malformed and cannot be emitted
2184     // into CodeView correctly so report a fatal error.
2185     auto I = CompleteTypeIndices.find(Ty);
2186     if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
2187       report_fatal_error("cannot debug circular reference to unnamed type");
2188     return getCompleteTypeIndex(Ty);
2189   }
2190 
2191   // First, construct the forward decl.  Don't look into Ty to compute the
2192   // forward decl options, since it might not be available in all TUs.
2193   TypeRecordKind Kind = getRecordKind(Ty);
2194   ClassOptions CO =
2195       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2196   std::string FullName = getFullyQualifiedName(Ty);
2197   ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
2198                  FullName, Ty->getIdentifier());
2199   TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
2200   if (!Ty->isForwardDecl())
2201     DeferredCompleteTypes.push_back(Ty);
2202   return FwdDeclTI;
2203 }
2204 
2205 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
2206   // Construct the field list and complete type record.
2207   TypeRecordKind Kind = getRecordKind(Ty);
2208   ClassOptions CO = getCommonClassOptions(Ty);
2209   TypeIndex FieldTI;
2210   TypeIndex VShapeTI;
2211   unsigned FieldCount;
2212   bool ContainsNestedClass;
2213   std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
2214       lowerRecordFieldList(Ty);
2215 
2216   if (ContainsNestedClass)
2217     CO |= ClassOptions::ContainsNestedClass;
2218 
2219   // MSVC appears to set this flag by searching any destructor or method with
2220   // FunctionOptions::Constructor among the emitted members. Clang AST has all
2221   // the members, however special member functions are not yet emitted into
2222   // debug information. For now checking a class's non-triviality seems enough.
2223   // FIXME: not true for a nested unnamed struct.
2224   if (isNonTrivial(Ty))
2225     CO |= ClassOptions::HasConstructorOrDestructor;
2226 
2227   std::string FullName = getFullyQualifiedName(Ty);
2228 
2229   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2230 
2231   ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
2232                  SizeInBytes, FullName, Ty->getIdentifier());
2233   TypeIndex ClassTI = TypeTable.writeLeafType(CR);
2234 
2235   addUDTSrcLine(Ty, ClassTI);
2236 
2237   addToUDTs(Ty);
2238 
2239   return ClassTI;
2240 }
2241 
2242 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
2243   // Emit the complete type for unnamed unions.
2244   if (shouldAlwaysEmitCompleteClassType(Ty))
2245     return getCompleteTypeIndex(Ty);
2246 
2247   ClassOptions CO =
2248       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2249   std::string FullName = getFullyQualifiedName(Ty);
2250   UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
2251   TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
2252   if (!Ty->isForwardDecl())
2253     DeferredCompleteTypes.push_back(Ty);
2254   return FwdDeclTI;
2255 }
2256 
2257 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
2258   ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
2259   TypeIndex FieldTI;
2260   unsigned FieldCount;
2261   bool ContainsNestedClass;
2262   std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
2263       lowerRecordFieldList(Ty);
2264 
2265   if (ContainsNestedClass)
2266     CO |= ClassOptions::ContainsNestedClass;
2267 
2268   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2269   std::string FullName = getFullyQualifiedName(Ty);
2270 
2271   UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
2272                  Ty->getIdentifier());
2273   TypeIndex UnionTI = TypeTable.writeLeafType(UR);
2274 
2275   addUDTSrcLine(Ty, UnionTI);
2276 
2277   addToUDTs(Ty);
2278 
2279   return UnionTI;
2280 }
2281 
2282 std::tuple<TypeIndex, TypeIndex, unsigned, bool>
2283 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
2284   // Manually count members. MSVC appears to count everything that generates a
2285   // field list record. Each individual overload in a method overload group
2286   // contributes to this count, even though the overload group is a single field
2287   // list record.
2288   unsigned MemberCount = 0;
2289   ClassInfo Info = collectClassInfo(Ty);
2290   ContinuationRecordBuilder ContinuationBuilder;
2291   ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
2292 
2293   // Create base classes.
2294   for (const DIDerivedType *I : Info.Inheritance) {
2295     if (I->getFlags() & DINode::FlagVirtual) {
2296       // Virtual base.
2297       unsigned VBPtrOffset = I->getVBPtrOffset();
2298       // FIXME: Despite the accessor name, the offset is really in bytes.
2299       unsigned VBTableIndex = I->getOffsetInBits() / 4;
2300       auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
2301                             ? TypeRecordKind::IndirectVirtualBaseClass
2302                             : TypeRecordKind::VirtualBaseClass;
2303       VirtualBaseClassRecord VBCR(
2304           RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
2305           getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
2306           VBTableIndex);
2307 
2308       ContinuationBuilder.writeMemberType(VBCR);
2309       MemberCount++;
2310     } else {
2311       assert(I->getOffsetInBits() % 8 == 0 &&
2312              "bases must be on byte boundaries");
2313       BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
2314                           getTypeIndex(I->getBaseType()),
2315                           I->getOffsetInBits() / 8);
2316       ContinuationBuilder.writeMemberType(BCR);
2317       MemberCount++;
2318     }
2319   }
2320 
2321   // Create members.
2322   for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
2323     const DIDerivedType *Member = MemberInfo.MemberTypeNode;
2324     TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
2325     StringRef MemberName = Member->getName();
2326     MemberAccess Access =
2327         translateAccessFlags(Ty->getTag(), Member->getFlags());
2328 
2329     if (Member->isStaticMember()) {
2330       StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
2331       ContinuationBuilder.writeMemberType(SDMR);
2332       MemberCount++;
2333       continue;
2334     }
2335 
2336     // Virtual function pointer member.
2337     if ((Member->getFlags() & DINode::FlagArtificial) &&
2338         Member->getName().startswith("_vptr$")) {
2339       VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
2340       ContinuationBuilder.writeMemberType(VFPR);
2341       MemberCount++;
2342       continue;
2343     }
2344 
2345     // Data member.
2346     uint64_t MemberOffsetInBits =
2347         Member->getOffsetInBits() + MemberInfo.BaseOffset;
2348     if (Member->isBitField()) {
2349       uint64_t StartBitOffset = MemberOffsetInBits;
2350       if (const auto *CI =
2351               dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
2352         MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
2353       }
2354       StartBitOffset -= MemberOffsetInBits;
2355       BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2356                          StartBitOffset);
2357       MemberBaseType = TypeTable.writeLeafType(BFR);
2358     }
2359     uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
2360     DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2361                          MemberName);
2362     ContinuationBuilder.writeMemberType(DMR);
2363     MemberCount++;
2364   }
2365 
2366   // Create methods
2367   for (auto &MethodItr : Info.Methods) {
2368     StringRef Name = MethodItr.first->getString();
2369 
2370     std::vector<OneMethodRecord> Methods;
2371     for (const DISubprogram *SP : MethodItr.second) {
2372       TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2373       bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
2374 
2375       unsigned VFTableOffset = -1;
2376       if (Introduced)
2377         VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2378 
2379       Methods.push_back(OneMethodRecord(
2380           MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
2381           translateMethodKindFlags(SP, Introduced),
2382           translateMethodOptionFlags(SP), VFTableOffset, Name));
2383       MemberCount++;
2384     }
2385     assert(!Methods.empty() && "Empty methods map entry");
2386     if (Methods.size() == 1)
2387       ContinuationBuilder.writeMemberType(Methods[0]);
2388     else {
2389       // FIXME: Make this use its own ContinuationBuilder so that
2390       // MethodOverloadList can be split correctly.
2391       MethodOverloadListRecord MOLR(Methods);
2392       TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
2393 
2394       OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
2395       ContinuationBuilder.writeMemberType(OMR);
2396     }
2397   }
2398 
2399   // Create nested classes.
2400   for (const DIType *Nested : Info.NestedTypes) {
2401     NestedTypeRecord R(getTypeIndex(Nested), Nested->getName());
2402     ContinuationBuilder.writeMemberType(R);
2403     MemberCount++;
2404   }
2405 
2406   TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
2407   return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
2408                          !Info.NestedTypes.empty());
2409 }
2410 
2411 TypeIndex CodeViewDebug::getVBPTypeIndex() {
2412   if (!VBPType.getIndex()) {
2413     // Make a 'const int *' type.
2414     ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
2415     TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
2416 
2417     PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2418                                                   : PointerKind::Near32;
2419     PointerMode PM = PointerMode::Pointer;
2420     PointerOptions PO = PointerOptions::None;
2421     PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
2422     VBPType = TypeTable.writeLeafType(PR);
2423   }
2424 
2425   return VBPType;
2426 }
2427 
2428 TypeIndex CodeViewDebug::getTypeIndex(const DIType *Ty, const DIType *ClassTy) {
2429   // The null DIType is the void type. Don't try to hash it.
2430   if (!Ty)
2431     return TypeIndex::Void();
2432 
2433   // Check if we've already translated this type. Don't try to do a
2434   // get-or-create style insertion that caches the hash lookup across the
2435   // lowerType call. It will update the TypeIndices map.
2436   auto I = TypeIndices.find({Ty, ClassTy});
2437   if (I != TypeIndices.end())
2438     return I->second;
2439 
2440   TypeLoweringScope S(*this);
2441   TypeIndex TI = lowerType(Ty, ClassTy);
2442   return recordTypeIndexForDINode(Ty, TI, ClassTy);
2443 }
2444 
2445 codeview::TypeIndex
2446 CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy,
2447                                       const DISubroutineType *SubroutineTy) {
2448   assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type &&
2449          "this type must be a pointer type");
2450 
2451   PointerOptions Options = PointerOptions::None;
2452   if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference)
2453     Options = PointerOptions::LValueRefThisPointer;
2454   else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference)
2455     Options = PointerOptions::RValueRefThisPointer;
2456 
2457   // Check if we've already translated this type.  If there is no ref qualifier
2458   // on the function then we look up this pointer type with no associated class
2459   // so that the TypeIndex for the this pointer can be shared with the type
2460   // index for other pointers to this class type.  If there is a ref qualifier
2461   // then we lookup the pointer using the subroutine as the parent type.
2462   auto I = TypeIndices.find({PtrTy, SubroutineTy});
2463   if (I != TypeIndices.end())
2464     return I->second;
2465 
2466   TypeLoweringScope S(*this);
2467   TypeIndex TI = lowerTypePointer(PtrTy, Options);
2468   return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy);
2469 }
2470 
2471 TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(const DIType *Ty) {
2472   PointerRecord PR(getTypeIndex(Ty),
2473                    getPointerSizeInBytes() == 8 ? PointerKind::Near64
2474                                                 : PointerKind::Near32,
2475                    PointerMode::LValueReference, PointerOptions::None,
2476                    Ty->getSizeInBits() / 8);
2477   return TypeTable.writeLeafType(PR);
2478 }
2479 
2480 TypeIndex CodeViewDebug::getCompleteTypeIndex(const DIType *Ty) {
2481   // The null DIType is the void type. Don't try to hash it.
2482   if (!Ty)
2483     return TypeIndex::Void();
2484 
2485   // Look through typedefs when getting the complete type index. Call
2486   // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are
2487   // emitted only once.
2488   if (Ty->getTag() == dwarf::DW_TAG_typedef)
2489     (void)getTypeIndex(Ty);
2490   while (Ty->getTag() == dwarf::DW_TAG_typedef)
2491     Ty = cast<DIDerivedType>(Ty)->getBaseType();
2492 
2493   // If this is a non-record type, the complete type index is the same as the
2494   // normal type index. Just call getTypeIndex.
2495   switch (Ty->getTag()) {
2496   case dwarf::DW_TAG_class_type:
2497   case dwarf::DW_TAG_structure_type:
2498   case dwarf::DW_TAG_union_type:
2499     break;
2500   default:
2501     return getTypeIndex(Ty);
2502   }
2503 
2504   const auto *CTy = cast<DICompositeType>(Ty);
2505 
2506   TypeLoweringScope S(*this);
2507 
2508   // Make sure the forward declaration is emitted first. It's unclear if this
2509   // is necessary, but MSVC does it, and we should follow suit until we can show
2510   // otherwise.
2511   // We only emit a forward declaration for named types.
2512   if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
2513     TypeIndex FwdDeclTI = getTypeIndex(CTy);
2514 
2515     // Just use the forward decl if we don't have complete type info. This
2516     // might happen if the frontend is using modules and expects the complete
2517     // definition to be emitted elsewhere.
2518     if (CTy->isForwardDecl())
2519       return FwdDeclTI;
2520   }
2521 
2522   // Check if we've already translated the complete record type.
2523   // Insert the type with a null TypeIndex to signify that the type is currently
2524   // being lowered.
2525   auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
2526   if (!InsertResult.second)
2527     return InsertResult.first->second;
2528 
2529   TypeIndex TI;
2530   switch (CTy->getTag()) {
2531   case dwarf::DW_TAG_class_type:
2532   case dwarf::DW_TAG_structure_type:
2533     TI = lowerCompleteTypeClass(CTy);
2534     break;
2535   case dwarf::DW_TAG_union_type:
2536     TI = lowerCompleteTypeUnion(CTy);
2537     break;
2538   default:
2539     llvm_unreachable("not a record");
2540   }
2541 
2542   // Update the type index associated with this CompositeType.  This cannot
2543   // use the 'InsertResult' iterator above because it is potentially
2544   // invalidated by map insertions which can occur while lowering the class
2545   // type above.
2546   CompleteTypeIndices[CTy] = TI;
2547   return TI;
2548 }
2549 
2550 /// Emit all the deferred complete record types. Try to do this in FIFO order,
2551 /// and do this until fixpoint, as each complete record type typically
2552 /// references
2553 /// many other record types.
2554 void CodeViewDebug::emitDeferredCompleteTypes() {
2555   SmallVector<const DICompositeType *, 4> TypesToEmit;
2556   while (!DeferredCompleteTypes.empty()) {
2557     std::swap(DeferredCompleteTypes, TypesToEmit);
2558     for (const DICompositeType *RecordTy : TypesToEmit)
2559       getCompleteTypeIndex(RecordTy);
2560     TypesToEmit.clear();
2561   }
2562 }
2563 
2564 void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
2565                                           ArrayRef<LocalVariable> Locals) {
2566   // Get the sorted list of parameters and emit them first.
2567   SmallVector<const LocalVariable *, 6> Params;
2568   for (const LocalVariable &L : Locals)
2569     if (L.DIVar->isParameter())
2570       Params.push_back(&L);
2571   llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
2572     return L->DIVar->getArg() < R->DIVar->getArg();
2573   });
2574   for (const LocalVariable *L : Params)
2575     emitLocalVariable(FI, *L);
2576 
2577   // Next emit all non-parameters in the order that we found them.
2578   for (const LocalVariable &L : Locals)
2579     if (!L.DIVar->isParameter())
2580       emitLocalVariable(FI, L);
2581 }
2582 
2583 /// Only call this on endian-specific types like ulittle16_t and little32_t, or
2584 /// structs composed of them.
2585 template <typename T>
2586 static void copyBytesForDefRange(SmallString<20> &BytePrefix,
2587                                  SymbolKind SymKind, const T &DefRangeHeader) {
2588   BytePrefix.resize(2 + sizeof(T));
2589   ulittle16_t SymKindLE = ulittle16_t(SymKind);
2590   memcpy(&BytePrefix[0], &SymKindLE, 2);
2591   memcpy(&BytePrefix[2], &DefRangeHeader, sizeof(T));
2592 }
2593 
2594 void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
2595                                       const LocalVariable &Var) {
2596   // LocalSym record, see SymbolRecord.h for more info.
2597   MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL);
2598 
2599   LocalSymFlags Flags = LocalSymFlags::None;
2600   if (Var.DIVar->isParameter())
2601     Flags |= LocalSymFlags::IsParameter;
2602   if (Var.DefRanges.empty())
2603     Flags |= LocalSymFlags::IsOptimizedOut;
2604 
2605   OS.AddComment("TypeIndex");
2606   TypeIndex TI = Var.UseReferenceType
2607                      ? getTypeIndexForReferenceTo(Var.DIVar->getType())
2608                      : getCompleteTypeIndex(Var.DIVar->getType());
2609   OS.EmitIntValue(TI.getIndex(), 4);
2610   OS.AddComment("Flags");
2611   OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
2612   // Truncate the name so we won't overflow the record length field.
2613   emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
2614   endSymbolRecord(LocalEnd);
2615 
2616   // Calculate the on disk prefix of the appropriate def range record. The
2617   // records and on disk formats are described in SymbolRecords.h. BytePrefix
2618   // should be big enough to hold all forms without memory allocation.
2619   SmallString<20> BytePrefix;
2620   for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2621     BytePrefix.clear();
2622     if (DefRange.InMemory) {
2623       int Offset = DefRange.DataOffset;
2624       unsigned Reg = DefRange.CVRegister;
2625 
2626       // 32-bit x86 call sequences often use PUSH instructions, which disrupt
2627       // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
2628       // instead. In frames without stack realignment, $T0 will be the CFA.
2629       if (RegisterId(Reg) == RegisterId::ESP) {
2630         Reg = unsigned(RegisterId::VFRAME);
2631         Offset += FI.OffsetAdjustment;
2632       }
2633 
2634       // If we can use the chosen frame pointer for the frame and this isn't a
2635       // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
2636       // Otherwise, use S_DEFRANGE_REGISTER_REL.
2637       EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU);
2638       if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
2639           (bool(Flags & LocalSymFlags::IsParameter)
2640                ? (EncFP == FI.EncodedParamFramePtrReg)
2641                : (EncFP == FI.EncodedLocalFramePtrReg))) {
2642         little32_t FPOffset = little32_t(Offset);
2643         copyBytesForDefRange(BytePrefix, S_DEFRANGE_FRAMEPOINTER_REL, FPOffset);
2644       } else {
2645         uint16_t RegRelFlags = 0;
2646         if (DefRange.IsSubfield) {
2647           RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2648                         (DefRange.StructOffset
2649                          << DefRangeRegisterRelSym::OffsetInParentShift);
2650         }
2651         DefRangeRegisterRelSym::Header DRHdr;
2652         DRHdr.Register = Reg;
2653         DRHdr.Flags = RegRelFlags;
2654         DRHdr.BasePointerOffset = Offset;
2655         copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER_REL, DRHdr);
2656       }
2657     } else {
2658       assert(DefRange.DataOffset == 0 && "unexpected offset into register");
2659       if (DefRange.IsSubfield) {
2660         DefRangeSubfieldRegisterSym::Header DRHdr;
2661         DRHdr.Register = DefRange.CVRegister;
2662         DRHdr.MayHaveNoName = 0;
2663         DRHdr.OffsetInParent = DefRange.StructOffset;
2664         copyBytesForDefRange(BytePrefix, S_DEFRANGE_SUBFIELD_REGISTER, DRHdr);
2665       } else {
2666         DefRangeRegisterSym::Header DRHdr;
2667         DRHdr.Register = DefRange.CVRegister;
2668         DRHdr.MayHaveNoName = 0;
2669         copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER, DRHdr);
2670       }
2671     }
2672     OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2673   }
2674 }
2675 
2676 void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
2677                                          const FunctionInfo& FI) {
2678   for (LexicalBlock *Block : Blocks)
2679     emitLexicalBlock(*Block, FI);
2680 }
2681 
2682 /// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
2683 /// lexical block scope.
2684 void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
2685                                      const FunctionInfo& FI) {
2686   MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32);
2687   OS.AddComment("PtrParent");
2688   OS.EmitIntValue(0, 4);                                  // PtrParent
2689   OS.AddComment("PtrEnd");
2690   OS.EmitIntValue(0, 4);                                  // PtrEnd
2691   OS.AddComment("Code size");
2692   OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4);   // Code Size
2693   OS.AddComment("Function section relative address");
2694   OS.EmitCOFFSecRel32(Block.Begin, /*Offset=*/0);         // Func Offset
2695   OS.AddComment("Function section index");
2696   OS.EmitCOFFSectionIndex(FI.Begin);                      // Func Symbol
2697   OS.AddComment("Lexical block name");
2698   emitNullTerminatedSymbolName(OS, Block.Name);           // Name
2699   endSymbolRecord(RecordEnd);
2700 
2701   // Emit variables local to this lexical block.
2702   emitLocalVariableList(FI, Block.Locals);
2703   emitGlobalVariableList(Block.Globals);
2704 
2705   // Emit lexical blocks contained within this block.
2706   emitLexicalBlockList(Block.Children, FI);
2707 
2708   // Close the lexical block scope.
2709   emitEndSymbolRecord(SymbolKind::S_END);
2710 }
2711 
2712 /// Convenience routine for collecting lexical block information for a list
2713 /// of lexical scopes.
2714 void CodeViewDebug::collectLexicalBlockInfo(
2715         SmallVectorImpl<LexicalScope *> &Scopes,
2716         SmallVectorImpl<LexicalBlock *> &Blocks,
2717         SmallVectorImpl<LocalVariable> &Locals,
2718         SmallVectorImpl<CVGlobalVariable> &Globals) {
2719   for (LexicalScope *Scope : Scopes)
2720     collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals);
2721 }
2722 
2723 /// Populate the lexical blocks and local variable lists of the parent with
2724 /// information about the specified lexical scope.
2725 void CodeViewDebug::collectLexicalBlockInfo(
2726     LexicalScope &Scope,
2727     SmallVectorImpl<LexicalBlock *> &ParentBlocks,
2728     SmallVectorImpl<LocalVariable> &ParentLocals,
2729     SmallVectorImpl<CVGlobalVariable> &ParentGlobals) {
2730   if (Scope.isAbstractScope())
2731     return;
2732 
2733   // Gather information about the lexical scope including local variables,
2734   // global variables, and address ranges.
2735   bool IgnoreScope = false;
2736   auto LI = ScopeVariables.find(&Scope);
2737   SmallVectorImpl<LocalVariable> *Locals =
2738       LI != ScopeVariables.end() ? &LI->second : nullptr;
2739   auto GI = ScopeGlobals.find(Scope.getScopeNode());
2740   SmallVectorImpl<CVGlobalVariable> *Globals =
2741       GI != ScopeGlobals.end() ? GI->second.get() : nullptr;
2742   const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
2743   const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
2744 
2745   // Ignore lexical scopes which do not contain variables.
2746   if (!Locals && !Globals)
2747     IgnoreScope = true;
2748 
2749   // Ignore lexical scopes which are not lexical blocks.
2750   if (!DILB)
2751     IgnoreScope = true;
2752 
2753   // Ignore scopes which have too many address ranges to represent in the
2754   // current CodeView format or do not have a valid address range.
2755   //
2756   // For lexical scopes with multiple address ranges you may be tempted to
2757   // construct a single range covering every instruction where the block is
2758   // live and everything in between.  Unfortunately, Visual Studio only
2759   // displays variables from the first matching lexical block scope.  If the
2760   // first lexical block contains exception handling code or cold code which
2761   // is moved to the bottom of the routine creating a single range covering
2762   // nearly the entire routine, then it will hide all other lexical blocks
2763   // and the variables they contain.
2764   if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second))
2765     IgnoreScope = true;
2766 
2767   if (IgnoreScope) {
2768     // This scope can be safely ignored and eliminating it will reduce the
2769     // size of the debug information. Be sure to collect any variable and scope
2770     // information from the this scope or any of its children and collapse them
2771     // into the parent scope.
2772     if (Locals)
2773       ParentLocals.append(Locals->begin(), Locals->end());
2774     if (Globals)
2775       ParentGlobals.append(Globals->begin(), Globals->end());
2776     collectLexicalBlockInfo(Scope.getChildren(),
2777                             ParentBlocks,
2778                             ParentLocals,
2779                             ParentGlobals);
2780     return;
2781   }
2782 
2783   // Create a new CodeView lexical block for this lexical scope.  If we've
2784   // seen this DILexicalBlock before then the scope tree is malformed and
2785   // we can handle this gracefully by not processing it a second time.
2786   auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
2787   if (!BlockInsertion.second)
2788     return;
2789 
2790   // Create a lexical block containing the variables and collect the the
2791   // lexical block information for the children.
2792   const InsnRange &Range = Ranges.front();
2793   assert(Range.first && Range.second);
2794   LexicalBlock &Block = BlockInsertion.first->second;
2795   Block.Begin = getLabelBeforeInsn(Range.first);
2796   Block.End = getLabelAfterInsn(Range.second);
2797   assert(Block.Begin && "missing label for scope begin");
2798   assert(Block.End && "missing label for scope end");
2799   Block.Name = DILB->getName();
2800   if (Locals)
2801     Block.Locals = std::move(*Locals);
2802   if (Globals)
2803     Block.Globals = std::move(*Globals);
2804   ParentBlocks.push_back(&Block);
2805   collectLexicalBlockInfo(Scope.getChildren(),
2806                           Block.Children,
2807                           Block.Locals,
2808                           Block.Globals);
2809 }
2810 
2811 void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
2812   const Function &GV = MF->getFunction();
2813   assert(FnDebugInfo.count(&GV));
2814   assert(CurFn == FnDebugInfo[&GV].get());
2815 
2816   collectVariableInfo(GV.getSubprogram());
2817 
2818   // Build the lexical block structure to emit for this routine.
2819   if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
2820     collectLexicalBlockInfo(*CFS,
2821                             CurFn->ChildBlocks,
2822                             CurFn->Locals,
2823                             CurFn->Globals);
2824 
2825   // Clear the scope and variable information from the map which will not be
2826   // valid after we have finished processing this routine.  This also prepares
2827   // the map for the subsequent routine.
2828   ScopeVariables.clear();
2829 
2830   // Don't emit anything if we don't have any line tables.
2831   // Thunks are compiler-generated and probably won't have source correlation.
2832   if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
2833     FnDebugInfo.erase(&GV);
2834     CurFn = nullptr;
2835     return;
2836   }
2837 
2838   CurFn->Annotations = MF->getCodeViewAnnotations();
2839   CurFn->HeapAllocSites = MF->getCodeViewHeapAllocSites();
2840 
2841   CurFn->End = Asm->getFunctionEnd();
2842 
2843   CurFn = nullptr;
2844 }
2845 
2846 void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
2847   DebugHandlerBase::beginInstruction(MI);
2848 
2849   // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
2850   if (!Asm || !CurFn || MI->isDebugInstr() ||
2851       MI->getFlag(MachineInstr::FrameSetup))
2852     return;
2853 
2854   // If the first instruction of a new MBB has no location, find the first
2855   // instruction with a location and use that.
2856   DebugLoc DL = MI->getDebugLoc();
2857   if (!DL && MI->getParent() != PrevInstBB) {
2858     for (const auto &NextMI : *MI->getParent()) {
2859       if (NextMI.isDebugInstr())
2860         continue;
2861       DL = NextMI.getDebugLoc();
2862       if (DL)
2863         break;
2864     }
2865   }
2866   PrevInstBB = MI->getParent();
2867 
2868   // If we still don't have a debug location, don't record a location.
2869   if (!DL)
2870     return;
2871 
2872   maybeRecordLocation(DL, Asm->MF);
2873 }
2874 
2875 MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
2876   MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2877            *EndLabel = MMI->getContext().createTempSymbol();
2878   OS.EmitIntValue(unsigned(Kind), 4);
2879   OS.AddComment("Subsection size");
2880   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2881   OS.EmitLabel(BeginLabel);
2882   return EndLabel;
2883 }
2884 
2885 void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2886   OS.EmitLabel(EndLabel);
2887   // Every subsection must be aligned to a 4-byte boundary.
2888   OS.EmitValueToAlignment(4);
2889 }
2890 
2891 static StringRef getSymbolName(SymbolKind SymKind) {
2892   for (const EnumEntry<SymbolKind> &EE : getSymbolTypeNames())
2893     if (EE.Value == SymKind)
2894       return EE.Name;
2895   return "";
2896 }
2897 
2898 MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) {
2899   MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2900            *EndLabel = MMI->getContext().createTempSymbol();
2901   OS.AddComment("Record length");
2902   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
2903   OS.EmitLabel(BeginLabel);
2904   if (OS.isVerboseAsm())
2905     OS.AddComment("Record kind: " + getSymbolName(SymKind));
2906   OS.EmitIntValue(unsigned(SymKind), 2);
2907   return EndLabel;
2908 }
2909 
2910 void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) {
2911   // MSVC does not pad out symbol records to four bytes, but LLVM does to avoid
2912   // an extra copy of every symbol record in LLD. This increases object file
2913   // size by less than 1% in the clang build, and is compatible with the Visual
2914   // C++ linker.
2915   OS.EmitValueToAlignment(4);
2916   OS.EmitLabel(SymEnd);
2917 }
2918 
2919 void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) {
2920   OS.AddComment("Record length");
2921   OS.EmitIntValue(2, 2);
2922   if (OS.isVerboseAsm())
2923     OS.AddComment("Record kind: " + getSymbolName(EndKind));
2924   OS.EmitIntValue(unsigned(EndKind), 2); // Record Kind
2925 }
2926 
2927 void CodeViewDebug::emitDebugInfoForUDTs(
2928     ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
2929   for (const auto &UDT : UDTs) {
2930     const DIType *T = UDT.second;
2931     assert(shouldEmitUdt(T));
2932 
2933     MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT);
2934     OS.AddComment("Type");
2935     OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
2936     emitNullTerminatedSymbolName(OS, UDT.first);
2937     endSymbolRecord(UDTRecordEnd);
2938   }
2939 }
2940 
2941 void CodeViewDebug::collectGlobalVariableInfo() {
2942   DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2943       GlobalMap;
2944   for (const GlobalVariable &GV : MMI->getModule()->globals()) {
2945     SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2946     GV.getDebugInfo(GVEs);
2947     for (const auto *GVE : GVEs)
2948       GlobalMap[GVE] = &GV;
2949   }
2950 
2951   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2952   for (const MDNode *Node : CUs->operands()) {
2953     const auto *CU = cast<DICompileUnit>(Node);
2954     for (const auto *GVE : CU->getGlobalVariables()) {
2955       const DIGlobalVariable *DIGV = GVE->getVariable();
2956       const DIExpression *DIE = GVE->getExpression();
2957 
2958       // Emit constant global variables in a global symbol section.
2959       if (GlobalMap.count(GVE) == 0 && DIE->isConstant()) {
2960         CVGlobalVariable CVGV = {DIGV, DIE};
2961         GlobalVariables.emplace_back(std::move(CVGV));
2962       }
2963 
2964       const auto *GV = GlobalMap.lookup(GVE);
2965       if (!GV || GV->isDeclarationForLinker())
2966         continue;
2967 
2968       DIScope *Scope = DIGV->getScope();
2969       SmallVector<CVGlobalVariable, 1> *VariableList;
2970       if (Scope && isa<DILocalScope>(Scope)) {
2971         // Locate a global variable list for this scope, creating one if
2972         // necessary.
2973         auto Insertion = ScopeGlobals.insert(
2974             {Scope, std::unique_ptr<GlobalVariableList>()});
2975         if (Insertion.second)
2976           Insertion.first->second = llvm::make_unique<GlobalVariableList>();
2977         VariableList = Insertion.first->second.get();
2978       } else if (GV->hasComdat())
2979         // Emit this global variable into a COMDAT section.
2980         VariableList = &ComdatVariables;
2981       else
2982         // Emit this global variable in a single global symbol section.
2983         VariableList = &GlobalVariables;
2984       CVGlobalVariable CVGV = {DIGV, GV};
2985       VariableList->emplace_back(std::move(CVGV));
2986     }
2987   }
2988 }
2989 
2990 void CodeViewDebug::emitDebugInfoForGlobals() {
2991   // First, emit all globals that are not in a comdat in a single symbol
2992   // substream. MSVC doesn't like it if the substream is empty, so only open
2993   // it if we have at least one global to emit.
2994   switchToDebugSectionForSymbol(nullptr);
2995   if (!GlobalVariables.empty()) {
2996     OS.AddComment("Symbol subsection for globals");
2997     MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
2998     emitGlobalVariableList(GlobalVariables);
2999     endCVSubsection(EndLabel);
3000   }
3001 
3002   // Second, emit each global that is in a comdat into its own .debug$S
3003   // section along with its own symbol substream.
3004   for (const CVGlobalVariable &CVGV : ComdatVariables) {
3005     const GlobalVariable *GV = CVGV.GVInfo.get<const GlobalVariable *>();
3006     MCSymbol *GVSym = Asm->getSymbol(GV);
3007     OS.AddComment("Symbol subsection for " +
3008                   Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
3009     switchToDebugSectionForSymbol(GVSym);
3010     MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
3011     // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3012     emitDebugInfoForGlobal(CVGV);
3013     endCVSubsection(EndLabel);
3014   }
3015 }
3016 
3017 void CodeViewDebug::emitDebugInfoForRetainedTypes() {
3018   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
3019   for (const MDNode *Node : CUs->operands()) {
3020     for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
3021       if (DIType *RT = dyn_cast<DIType>(Ty)) {
3022         getTypeIndex(RT);
3023         // FIXME: Add to global/local DTU list.
3024       }
3025     }
3026   }
3027 }
3028 
3029 // Emit each global variable in the specified array.
3030 void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) {
3031   for (const CVGlobalVariable &CVGV : Globals) {
3032     // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3033     emitDebugInfoForGlobal(CVGV);
3034   }
3035 }
3036 
3037 void CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable &CVGV) {
3038   const DIGlobalVariable *DIGV = CVGV.DIGV;
3039   if (const GlobalVariable *GV =
3040           CVGV.GVInfo.dyn_cast<const GlobalVariable *>()) {
3041     // DataSym record, see SymbolRecord.h for more info. Thread local data
3042     // happens to have the same format as global data.
3043     MCSymbol *GVSym = Asm->getSymbol(GV);
3044     SymbolKind DataSym = GV->isThreadLocal()
3045                              ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32
3046                                                       : SymbolKind::S_GTHREAD32)
3047                              : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32
3048                                                       : SymbolKind::S_GDATA32);
3049     MCSymbol *DataEnd = beginSymbolRecord(DataSym);
3050     OS.AddComment("Type");
3051     OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
3052     OS.AddComment("DataOffset");
3053     OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
3054     OS.AddComment("Segment");
3055     OS.EmitCOFFSectionIndex(GVSym);
3056     OS.AddComment("Name");
3057     const unsigned LengthOfDataRecord = 12;
3058     emitNullTerminatedSymbolName(OS, DIGV->getName(), LengthOfDataRecord);
3059     endSymbolRecord(DataEnd);
3060   } else {
3061     // FIXME: Currently this only emits the global variables in the IR metadata.
3062     // This should also emit enums and static data members.
3063     const DIExpression *DIE = CVGV.GVInfo.get<const DIExpression *>();
3064     assert(DIE->isConstant() &&
3065            "Global constant variables must contain a constant expression.");
3066     uint64_t Val = DIE->getElement(1);
3067 
3068     MCSymbol *SConstantEnd = beginSymbolRecord(SymbolKind::S_CONSTANT);
3069     OS.AddComment("Type");
3070     OS.EmitIntValue(getTypeIndex(DIGV->getType()).getIndex(), 4);
3071     OS.AddComment("Value");
3072 
3073     // Encoded integers shouldn't need more than 10 bytes.
3074     uint8_t data[10];
3075     BinaryStreamWriter Writer(data, llvm::support::endianness::little);
3076     CodeViewRecordIO IO(Writer);
3077     cantFail(IO.mapEncodedInteger(Val));
3078     StringRef SRef((char *)data, Writer.getOffset());
3079     OS.EmitBinaryData(SRef);
3080 
3081     OS.AddComment("Name");
3082     const DIScope *Scope = DIGV->getScope();
3083     // For static data members, get the scope from the declaration.
3084     if (const auto *MemberDecl = dyn_cast_or_null<DIDerivedType>(
3085             DIGV->getRawStaticDataMemberDeclaration()))
3086       Scope = MemberDecl->getScope();
3087     emitNullTerminatedSymbolName(OS,
3088                                  getFullyQualifiedName(Scope, DIGV->getName()));
3089     endSymbolRecord(SConstantEnd);
3090   }
3091 }
3092