xref: /llvm-project/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp (revision c2029068bc5de3428ba5431d85466946f7937359)
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     if (VI.Expr)
1146       if (!VI.Expr->extractIfOffset(ExprOffset))
1147         continue;
1148 
1149     // Get the frame register used and the offset.
1150     unsigned FrameReg = 0;
1151     int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
1152     uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
1153 
1154     // Calculate the label ranges.
1155     LocalVarDefRange DefRange =
1156         createDefRangeMem(CVReg, FrameOffset + ExprOffset);
1157     for (const InsnRange &Range : Scope->getRanges()) {
1158       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1159       const MCSymbol *End = getLabelAfterInsn(Range.second);
1160       End = End ? End : Asm->getFunctionEnd();
1161       DefRange.Ranges.emplace_back(Begin, End);
1162     }
1163 
1164     LocalVariable Var;
1165     Var.DIVar = VI.Var;
1166     Var.DefRanges.emplace_back(std::move(DefRange));
1167     recordLocalVariable(std::move(Var), Scope);
1168   }
1169 }
1170 
1171 static bool canUseReferenceType(const DbgVariableLocation &Loc) {
1172   return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
1173 }
1174 
1175 static bool needsReferenceType(const DbgVariableLocation &Loc) {
1176   return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
1177 }
1178 
1179 void CodeViewDebug::calculateRanges(
1180     LocalVariable &Var, const DbgValueHistoryMap::Entries &Entries) {
1181   const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1182 
1183   // Calculate the definition ranges.
1184   for (auto I = Entries.begin(), E = Entries.end(); I != E; ++I) {
1185     const auto &Entry = *I;
1186     if (!Entry.isDbgValue())
1187       continue;
1188     const MachineInstr *DVInst = Entry.getInstr();
1189     assert(DVInst->isDebugValue() && "Invalid History entry");
1190     // FIXME: Find a way to represent constant variables, since they are
1191     // relatively common.
1192     Optional<DbgVariableLocation> Location =
1193         DbgVariableLocation::extractFromMachineInstruction(*DVInst);
1194     if (!Location)
1195       continue;
1196 
1197     // CodeView can only express variables in register and variables in memory
1198     // at a constant offset from a register. However, for variables passed
1199     // indirectly by pointer, it is common for that pointer to be spilled to a
1200     // stack location. For the special case of one offseted load followed by a
1201     // zero offset load (a pointer spilled to the stack), we change the type of
1202     // the local variable from a value type to a reference type. This tricks the
1203     // debugger into doing the load for us.
1204     if (Var.UseReferenceType) {
1205       // We're using a reference type. Drop the last zero offset load.
1206       if (canUseReferenceType(*Location))
1207         Location->LoadChain.pop_back();
1208       else
1209         continue;
1210     } else if (needsReferenceType(*Location)) {
1211       // This location can't be expressed without switching to a reference type.
1212       // Start over using that.
1213       Var.UseReferenceType = true;
1214       Var.DefRanges.clear();
1215       calculateRanges(Var, Entries);
1216       return;
1217     }
1218 
1219     // We can only handle a register or an offseted load of a register.
1220     if (Location->Register == 0 || Location->LoadChain.size() > 1)
1221       continue;
1222     {
1223       LocalVarDefRange DR;
1224       DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
1225       DR.InMemory = !Location->LoadChain.empty();
1226       DR.DataOffset =
1227           !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
1228       if (Location->FragmentInfo) {
1229         DR.IsSubfield = true;
1230         DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
1231       } else {
1232         DR.IsSubfield = false;
1233         DR.StructOffset = 0;
1234       }
1235 
1236       if (Var.DefRanges.empty() ||
1237           Var.DefRanges.back().isDifferentLocation(DR)) {
1238         Var.DefRanges.emplace_back(std::move(DR));
1239       }
1240     }
1241 
1242     // Compute the label range.
1243     const MCSymbol *Begin = getLabelBeforeInsn(Entry.getInstr());
1244     const MCSymbol *End;
1245     if (Entry.getEndIndex() != DbgValueHistoryMap::NoEntry) {
1246       auto &EndingEntry = Entries[Entry.getEndIndex()];
1247       End = EndingEntry.isDbgValue()
1248                 ? getLabelBeforeInsn(EndingEntry.getInstr())
1249                 : getLabelAfterInsn(EndingEntry.getInstr());
1250     } else
1251       End = Asm->getFunctionEnd();
1252 
1253     // If the last range end is our begin, just extend the last range.
1254     // Otherwise make a new range.
1255     SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1256         Var.DefRanges.back().Ranges;
1257     if (!R.empty() && R.back().second == Begin)
1258       R.back().second = End;
1259     else
1260       R.emplace_back(Begin, End);
1261 
1262     // FIXME: Do more range combining.
1263   }
1264 }
1265 
1266 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
1267   DenseSet<InlinedEntity> Processed;
1268   // Grab the variable info that was squirreled away in the MMI side-table.
1269   collectVariableInfoFromMFTable(Processed);
1270 
1271   for (const auto &I : DbgValues) {
1272     InlinedEntity IV = I.first;
1273     if (Processed.count(IV))
1274       continue;
1275     const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
1276     const DILocation *InlinedAt = IV.second;
1277 
1278     // Instruction ranges, specifying where IV is accessible.
1279     const auto &Entries = I.second;
1280 
1281     LexicalScope *Scope = nullptr;
1282     if (InlinedAt)
1283       Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1284     else
1285       Scope = LScopes.findLexicalScope(DIVar->getScope());
1286     // If variable scope is not found then skip this variable.
1287     if (!Scope)
1288       continue;
1289 
1290     LocalVariable Var;
1291     Var.DIVar = DIVar;
1292 
1293     calculateRanges(Var, Entries);
1294     recordLocalVariable(std::move(Var), Scope);
1295   }
1296 }
1297 
1298 void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
1299   const TargetSubtargetInfo &TSI = MF->getSubtarget();
1300   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1301   const MachineFrameInfo &MFI = MF->getFrameInfo();
1302   const Function &GV = MF->getFunction();
1303   auto Insertion = FnDebugInfo.insert({&GV, llvm::make_unique<FunctionInfo>()});
1304   assert(Insertion.second && "function already has info");
1305   CurFn = Insertion.first->second.get();
1306   CurFn->FuncId = NextFuncId++;
1307   CurFn->Begin = Asm->getFunctionBegin();
1308 
1309   // The S_FRAMEPROC record reports the stack size, and how many bytes of
1310   // callee-saved registers were used. For targets that don't use a PUSH
1311   // instruction (AArch64), this will be zero.
1312   CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
1313   CurFn->FrameSize = MFI.getStackSize();
1314   CurFn->OffsetAdjustment = MFI.getOffsetAdjustment();
1315   CurFn->HasStackRealignment = TRI->needsStackRealignment(*MF);
1316 
1317   // For this function S_FRAMEPROC record, figure out which codeview register
1318   // will be the frame pointer.
1319   CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
1320   CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
1321   if (CurFn->FrameSize > 0) {
1322     if (!TSI.getFrameLowering()->hasFP(*MF)) {
1323       CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1324       CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
1325     } else {
1326       // If there is an FP, parameters are always relative to it.
1327       CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
1328       if (CurFn->HasStackRealignment) {
1329         // If the stack needs realignment, locals are relative to SP or VFRAME.
1330         CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1331       } else {
1332         // Otherwise, locals are relative to EBP, and we probably have VLAs or
1333         // other stack adjustments.
1334         CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
1335       }
1336     }
1337   }
1338 
1339   // Compute other frame procedure options.
1340   FrameProcedureOptions FPO = FrameProcedureOptions::None;
1341   if (MFI.hasVarSizedObjects())
1342     FPO |= FrameProcedureOptions::HasAlloca;
1343   if (MF->exposesReturnsTwice())
1344     FPO |= FrameProcedureOptions::HasSetJmp;
1345   // FIXME: Set HasLongJmp if we ever track that info.
1346   if (MF->hasInlineAsm())
1347     FPO |= FrameProcedureOptions::HasInlineAssembly;
1348   if (GV.hasPersonalityFn()) {
1349     if (isAsynchronousEHPersonality(
1350             classifyEHPersonality(GV.getPersonalityFn())))
1351       FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
1352     else
1353       FPO |= FrameProcedureOptions::HasExceptionHandling;
1354   }
1355   if (GV.hasFnAttribute(Attribute::InlineHint))
1356     FPO |= FrameProcedureOptions::MarkedInline;
1357   if (GV.hasFnAttribute(Attribute::Naked))
1358     FPO |= FrameProcedureOptions::Naked;
1359   if (MFI.hasStackProtectorIndex())
1360     FPO |= FrameProcedureOptions::SecurityChecks;
1361   FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
1362   FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
1363   if (Asm->TM.getOptLevel() != CodeGenOpt::None &&
1364       !GV.hasOptSize() && !GV.hasOptNone())
1365     FPO |= FrameProcedureOptions::OptimizedForSpeed;
1366   // FIXME: Set GuardCfg when it is implemented.
1367   CurFn->FrameProcOpts = FPO;
1368 
1369   OS.EmitCVFuncIdDirective(CurFn->FuncId);
1370 
1371   // Find the end of the function prolog.  First known non-DBG_VALUE and
1372   // non-frame setup location marks the beginning of the function body.
1373   // FIXME: is there a simpler a way to do this? Can we just search
1374   // for the first instruction of the function, not the last of the prolog?
1375   DebugLoc PrologEndLoc;
1376   bool EmptyPrologue = true;
1377   for (const auto &MBB : *MF) {
1378     for (const auto &MI : MBB) {
1379       if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1380           MI.getDebugLoc()) {
1381         PrologEndLoc = MI.getDebugLoc();
1382         break;
1383       } else if (!MI.isMetaInstruction()) {
1384         EmptyPrologue = false;
1385       }
1386     }
1387   }
1388 
1389   // Record beginning of function if we have a non-empty prologue.
1390   if (PrologEndLoc && !EmptyPrologue) {
1391     DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
1392     maybeRecordLocation(FnStartDL, MF);
1393   }
1394 }
1395 
1396 static bool shouldEmitUdt(const DIType *T) {
1397   if (!T)
1398     return false;
1399 
1400   // MSVC does not emit UDTs for typedefs that are scoped to classes.
1401   if (T->getTag() == dwarf::DW_TAG_typedef) {
1402     if (DIScope *Scope = T->getScope()) {
1403       switch (Scope->getTag()) {
1404       case dwarf::DW_TAG_structure_type:
1405       case dwarf::DW_TAG_class_type:
1406       case dwarf::DW_TAG_union_type:
1407         return false;
1408       }
1409     }
1410   }
1411 
1412   while (true) {
1413     if (!T || T->isForwardDecl())
1414       return false;
1415 
1416     const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
1417     if (!DT)
1418       return true;
1419     T = DT->getBaseType();
1420   }
1421   return true;
1422 }
1423 
1424 void CodeViewDebug::addToUDTs(const DIType *Ty) {
1425   // Don't record empty UDTs.
1426   if (Ty->getName().empty())
1427     return;
1428   if (!shouldEmitUdt(Ty))
1429     return;
1430 
1431   SmallVector<StringRef, 5> QualifiedNameComponents;
1432   const DISubprogram *ClosestSubprogram =
1433       getQualifiedNameComponents(Ty->getScope(), QualifiedNameComponents);
1434 
1435   std::string FullyQualifiedName =
1436       getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
1437 
1438   if (ClosestSubprogram == nullptr) {
1439     GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1440   } else if (ClosestSubprogram == CurrentSubprogram) {
1441     LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1442   }
1443 
1444   // TODO: What if the ClosestSubprogram is neither null or the current
1445   // subprogram?  Currently, the UDT just gets dropped on the floor.
1446   //
1447   // The current behavior is not desirable.  To get maximal fidelity, we would
1448   // need to perform all type translation before beginning emission of .debug$S
1449   // and then make LocalUDTs a member of FunctionInfo
1450 }
1451 
1452 TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
1453   // Generic dispatch for lowering an unknown type.
1454   switch (Ty->getTag()) {
1455   case dwarf::DW_TAG_array_type:
1456     return lowerTypeArray(cast<DICompositeType>(Ty));
1457   case dwarf::DW_TAG_typedef:
1458     return lowerTypeAlias(cast<DIDerivedType>(Ty));
1459   case dwarf::DW_TAG_base_type:
1460     return lowerTypeBasic(cast<DIBasicType>(Ty));
1461   case dwarf::DW_TAG_pointer_type:
1462     if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1463       return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1464     LLVM_FALLTHROUGH;
1465   case dwarf::DW_TAG_reference_type:
1466   case dwarf::DW_TAG_rvalue_reference_type:
1467     return lowerTypePointer(cast<DIDerivedType>(Ty));
1468   case dwarf::DW_TAG_ptr_to_member_type:
1469     return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1470   case dwarf::DW_TAG_restrict_type:
1471   case dwarf::DW_TAG_const_type:
1472   case dwarf::DW_TAG_volatile_type:
1473   // TODO: add support for DW_TAG_atomic_type here
1474     return lowerTypeModifier(cast<DIDerivedType>(Ty));
1475   case dwarf::DW_TAG_subroutine_type:
1476     if (ClassTy) {
1477       // The member function type of a member function pointer has no
1478       // ThisAdjustment.
1479       return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1480                                      /*ThisAdjustment=*/0,
1481                                      /*IsStaticMethod=*/false);
1482     }
1483     return lowerTypeFunction(cast<DISubroutineType>(Ty));
1484   case dwarf::DW_TAG_enumeration_type:
1485     return lowerTypeEnum(cast<DICompositeType>(Ty));
1486   case dwarf::DW_TAG_class_type:
1487   case dwarf::DW_TAG_structure_type:
1488     return lowerTypeClass(cast<DICompositeType>(Ty));
1489   case dwarf::DW_TAG_union_type:
1490     return lowerTypeUnion(cast<DICompositeType>(Ty));
1491   case dwarf::DW_TAG_unspecified_type:
1492     if (Ty->getName() == "decltype(nullptr)")
1493       return TypeIndex::NullptrT();
1494     return TypeIndex::None();
1495   default:
1496     // Use the null type index.
1497     return TypeIndex();
1498   }
1499 }
1500 
1501 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
1502   TypeIndex UnderlyingTypeIndex = getTypeIndex(Ty->getBaseType());
1503   StringRef TypeName = Ty->getName();
1504 
1505   addToUDTs(Ty);
1506 
1507   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
1508       TypeName == "HRESULT")
1509     return TypeIndex(SimpleTypeKind::HResult);
1510   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
1511       TypeName == "wchar_t")
1512     return TypeIndex(SimpleTypeKind::WideCharacter);
1513 
1514   return UnderlyingTypeIndex;
1515 }
1516 
1517 TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1518   const DIType *ElementType = Ty->getBaseType();
1519   TypeIndex ElementTypeIndex = getTypeIndex(ElementType);
1520   // IndexType is size_t, which depends on the bitness of the target.
1521   TypeIndex IndexType = getPointerSizeInBytes() == 8
1522                             ? TypeIndex(SimpleTypeKind::UInt64Quad)
1523                             : TypeIndex(SimpleTypeKind::UInt32Long);
1524 
1525   uint64_t ElementSize = getBaseTypeSize(ElementType) / 8;
1526 
1527   // Add subranges to array type.
1528   DINodeArray Elements = Ty->getElements();
1529   for (int i = Elements.size() - 1; i >= 0; --i) {
1530     const DINode *Element = Elements[i];
1531     assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1532 
1533     const DISubrange *Subrange = cast<DISubrange>(Element);
1534     assert(Subrange->getLowerBound() == 0 &&
1535            "codeview doesn't support subranges with lower bounds");
1536     int64_t Count = -1;
1537     if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>())
1538       Count = CI->getSExtValue();
1539 
1540     // Forward declarations of arrays without a size and VLAs use a count of -1.
1541     // Emit a count of zero in these cases to match what MSVC does for arrays
1542     // without a size. MSVC doesn't support VLAs, so it's not clear what we
1543     // should do for them even if we could distinguish them.
1544     if (Count == -1)
1545       Count = 0;
1546 
1547     // Update the element size and element type index for subsequent subranges.
1548     ElementSize *= Count;
1549 
1550     // If this is the outermost array, use the size from the array. It will be
1551     // more accurate if we had a VLA or an incomplete element type size.
1552     uint64_t ArraySize =
1553         (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1554 
1555     StringRef Name = (i == 0) ? Ty->getName() : "";
1556     ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1557     ElementTypeIndex = TypeTable.writeLeafType(AR);
1558   }
1559 
1560   return ElementTypeIndex;
1561 }
1562 
1563 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1564   TypeIndex Index;
1565   dwarf::TypeKind Kind;
1566   uint32_t ByteSize;
1567 
1568   Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
1569   ByteSize = Ty->getSizeInBits() / 8;
1570 
1571   SimpleTypeKind STK = SimpleTypeKind::None;
1572   switch (Kind) {
1573   case dwarf::DW_ATE_address:
1574     // FIXME: Translate
1575     break;
1576   case dwarf::DW_ATE_boolean:
1577     switch (ByteSize) {
1578     case 1:  STK = SimpleTypeKind::Boolean8;   break;
1579     case 2:  STK = SimpleTypeKind::Boolean16;  break;
1580     case 4:  STK = SimpleTypeKind::Boolean32;  break;
1581     case 8:  STK = SimpleTypeKind::Boolean64;  break;
1582     case 16: STK = SimpleTypeKind::Boolean128; break;
1583     }
1584     break;
1585   case dwarf::DW_ATE_complex_float:
1586     switch (ByteSize) {
1587     case 2:  STK = SimpleTypeKind::Complex16;  break;
1588     case 4:  STK = SimpleTypeKind::Complex32;  break;
1589     case 8:  STK = SimpleTypeKind::Complex64;  break;
1590     case 10: STK = SimpleTypeKind::Complex80;  break;
1591     case 16: STK = SimpleTypeKind::Complex128; break;
1592     }
1593     break;
1594   case dwarf::DW_ATE_float:
1595     switch (ByteSize) {
1596     case 2:  STK = SimpleTypeKind::Float16;  break;
1597     case 4:  STK = SimpleTypeKind::Float32;  break;
1598     case 6:  STK = SimpleTypeKind::Float48;  break;
1599     case 8:  STK = SimpleTypeKind::Float64;  break;
1600     case 10: STK = SimpleTypeKind::Float80;  break;
1601     case 16: STK = SimpleTypeKind::Float128; break;
1602     }
1603     break;
1604   case dwarf::DW_ATE_signed:
1605     switch (ByteSize) {
1606     case 1:  STK = SimpleTypeKind::SignedCharacter; break;
1607     case 2:  STK = SimpleTypeKind::Int16Short;      break;
1608     case 4:  STK = SimpleTypeKind::Int32;           break;
1609     case 8:  STK = SimpleTypeKind::Int64Quad;       break;
1610     case 16: STK = SimpleTypeKind::Int128Oct;       break;
1611     }
1612     break;
1613   case dwarf::DW_ATE_unsigned:
1614     switch (ByteSize) {
1615     case 1:  STK = SimpleTypeKind::UnsignedCharacter; break;
1616     case 2:  STK = SimpleTypeKind::UInt16Short;       break;
1617     case 4:  STK = SimpleTypeKind::UInt32;            break;
1618     case 8:  STK = SimpleTypeKind::UInt64Quad;        break;
1619     case 16: STK = SimpleTypeKind::UInt128Oct;        break;
1620     }
1621     break;
1622   case dwarf::DW_ATE_UTF:
1623     switch (ByteSize) {
1624     case 2: STK = SimpleTypeKind::Character16; break;
1625     case 4: STK = SimpleTypeKind::Character32; break;
1626     }
1627     break;
1628   case dwarf::DW_ATE_signed_char:
1629     if (ByteSize == 1)
1630       STK = SimpleTypeKind::SignedCharacter;
1631     break;
1632   case dwarf::DW_ATE_unsigned_char:
1633     if (ByteSize == 1)
1634       STK = SimpleTypeKind::UnsignedCharacter;
1635     break;
1636   default:
1637     break;
1638   }
1639 
1640   // Apply some fixups based on the source-level type name.
1641   if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1642     STK = SimpleTypeKind::Int32Long;
1643   if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1644     STK = SimpleTypeKind::UInt32Long;
1645   if (STK == SimpleTypeKind::UInt16Short &&
1646       (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
1647     STK = SimpleTypeKind::WideCharacter;
1648   if ((STK == SimpleTypeKind::SignedCharacter ||
1649        STK == SimpleTypeKind::UnsignedCharacter) &&
1650       Ty->getName() == "char")
1651     STK = SimpleTypeKind::NarrowCharacter;
1652 
1653   return TypeIndex(STK);
1654 }
1655 
1656 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
1657                                           PointerOptions PO) {
1658   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1659 
1660   // Pointers to simple types without any options can use SimpleTypeMode, rather
1661   // than having a dedicated pointer type record.
1662   if (PointeeTI.isSimple() && PO == PointerOptions::None &&
1663       PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1664       Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1665     SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1666                               ? SimpleTypeMode::NearPointer64
1667                               : SimpleTypeMode::NearPointer32;
1668     return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1669   }
1670 
1671   PointerKind PK =
1672       Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1673   PointerMode PM = PointerMode::Pointer;
1674   switch (Ty->getTag()) {
1675   default: llvm_unreachable("not a pointer tag type");
1676   case dwarf::DW_TAG_pointer_type:
1677     PM = PointerMode::Pointer;
1678     break;
1679   case dwarf::DW_TAG_reference_type:
1680     PM = PointerMode::LValueReference;
1681     break;
1682   case dwarf::DW_TAG_rvalue_reference_type:
1683     PM = PointerMode::RValueReference;
1684     break;
1685   }
1686 
1687   if (Ty->isObjectPointer())
1688     PO |= PointerOptions::Const;
1689 
1690   PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1691   return TypeTable.writeLeafType(PR);
1692 }
1693 
1694 static PointerToMemberRepresentation
1695 translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1696   // SizeInBytes being zero generally implies that the member pointer type was
1697   // incomplete, which can happen if it is part of a function prototype. In this
1698   // case, use the unknown model instead of the general model.
1699   if (IsPMF) {
1700     switch (Flags & DINode::FlagPtrToMemberRep) {
1701     case 0:
1702       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1703                               : PointerToMemberRepresentation::GeneralFunction;
1704     case DINode::FlagSingleInheritance:
1705       return PointerToMemberRepresentation::SingleInheritanceFunction;
1706     case DINode::FlagMultipleInheritance:
1707       return PointerToMemberRepresentation::MultipleInheritanceFunction;
1708     case DINode::FlagVirtualInheritance:
1709       return PointerToMemberRepresentation::VirtualInheritanceFunction;
1710     }
1711   } else {
1712     switch (Flags & DINode::FlagPtrToMemberRep) {
1713     case 0:
1714       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1715                               : PointerToMemberRepresentation::GeneralData;
1716     case DINode::FlagSingleInheritance:
1717       return PointerToMemberRepresentation::SingleInheritanceData;
1718     case DINode::FlagMultipleInheritance:
1719       return PointerToMemberRepresentation::MultipleInheritanceData;
1720     case DINode::FlagVirtualInheritance:
1721       return PointerToMemberRepresentation::VirtualInheritanceData;
1722     }
1723   }
1724   llvm_unreachable("invalid ptr to member representation");
1725 }
1726 
1727 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
1728                                                 PointerOptions PO) {
1729   assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1730   TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
1731   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
1732   PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1733                                                 : PointerKind::Near32;
1734   bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1735   PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1736                          : PointerMode::PointerToDataMember;
1737 
1738   assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1739   uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1740   MemberPointerInfo MPI(
1741       ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
1742   PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
1743   return TypeTable.writeLeafType(PR);
1744 }
1745 
1746 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1747 /// have a translation, use the NearC convention.
1748 static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1749   switch (DwarfCC) {
1750   case dwarf::DW_CC_normal:             return CallingConvention::NearC;
1751   case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1752   case dwarf::DW_CC_BORLAND_thiscall:   return CallingConvention::ThisCall;
1753   case dwarf::DW_CC_BORLAND_stdcall:    return CallingConvention::NearStdCall;
1754   case dwarf::DW_CC_BORLAND_pascal:     return CallingConvention::NearPascal;
1755   case dwarf::DW_CC_LLVM_vectorcall:    return CallingConvention::NearVector;
1756   }
1757   return CallingConvention::NearC;
1758 }
1759 
1760 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1761   ModifierOptions Mods = ModifierOptions::None;
1762   PointerOptions PO = PointerOptions::None;
1763   bool IsModifier = true;
1764   const DIType *BaseTy = Ty;
1765   while (IsModifier && BaseTy) {
1766     // FIXME: Need to add DWARF tags for __unaligned and _Atomic
1767     switch (BaseTy->getTag()) {
1768     case dwarf::DW_TAG_const_type:
1769       Mods |= ModifierOptions::Const;
1770       PO |= PointerOptions::Const;
1771       break;
1772     case dwarf::DW_TAG_volatile_type:
1773       Mods |= ModifierOptions::Volatile;
1774       PO |= PointerOptions::Volatile;
1775       break;
1776     case dwarf::DW_TAG_restrict_type:
1777       // Only pointer types be marked with __restrict. There is no known flag
1778       // for __restrict in LF_MODIFIER records.
1779       PO |= PointerOptions::Restrict;
1780       break;
1781     default:
1782       IsModifier = false;
1783       break;
1784     }
1785     if (IsModifier)
1786       BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType();
1787   }
1788 
1789   // Check if the inner type will use an LF_POINTER record. If so, the
1790   // qualifiers will go in the LF_POINTER record. This comes up for types like
1791   // 'int *const' and 'int *__restrict', not the more common cases like 'const
1792   // char *'.
1793   if (BaseTy) {
1794     switch (BaseTy->getTag()) {
1795     case dwarf::DW_TAG_pointer_type:
1796     case dwarf::DW_TAG_reference_type:
1797     case dwarf::DW_TAG_rvalue_reference_type:
1798       return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
1799     case dwarf::DW_TAG_ptr_to_member_type:
1800       return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
1801     default:
1802       break;
1803     }
1804   }
1805 
1806   TypeIndex ModifiedTI = getTypeIndex(BaseTy);
1807 
1808   // Return the base type index if there aren't any modifiers. For example, the
1809   // metadata could contain restrict wrappers around non-pointer types.
1810   if (Mods == ModifierOptions::None)
1811     return ModifiedTI;
1812 
1813   ModifierRecord MR(ModifiedTI, Mods);
1814   return TypeTable.writeLeafType(MR);
1815 }
1816 
1817 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1818   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1819   for (const DIType *ArgType : Ty->getTypeArray())
1820     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgType));
1821 
1822   // MSVC uses type none for variadic argument.
1823   if (ReturnAndArgTypeIndices.size() > 1 &&
1824       ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1825     ReturnAndArgTypeIndices.back() = TypeIndex::None();
1826   }
1827   TypeIndex ReturnTypeIndex = TypeIndex::Void();
1828   ArrayRef<TypeIndex> ArgTypeIndices = None;
1829   if (!ReturnAndArgTypeIndices.empty()) {
1830     auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1831     ReturnTypeIndex = ReturnAndArgTypesRef.front();
1832     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1833   }
1834 
1835   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1836   TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
1837 
1838   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1839 
1840   FunctionOptions FO = getFunctionOptions(Ty);
1841   ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
1842                             ArgListIndex);
1843   return TypeTable.writeLeafType(Procedure);
1844 }
1845 
1846 TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
1847                                                  const DIType *ClassTy,
1848                                                  int ThisAdjustment,
1849                                                  bool IsStaticMethod,
1850                                                  FunctionOptions FO) {
1851   // Lower the containing class type.
1852   TypeIndex ClassType = getTypeIndex(ClassTy);
1853 
1854   DITypeRefArray ReturnAndArgs = Ty->getTypeArray();
1855 
1856   unsigned Index = 0;
1857   SmallVector<TypeIndex, 8> ArgTypeIndices;
1858   TypeIndex ReturnTypeIndex = TypeIndex::Void();
1859   if (ReturnAndArgs.size() > Index) {
1860     ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]);
1861   }
1862 
1863   // If the first argument is a pointer type and this isn't a static method,
1864   // treat it as the special 'this' parameter, which is encoded separately from
1865   // the arguments.
1866   TypeIndex ThisTypeIndex;
1867   if (!IsStaticMethod && ReturnAndArgs.size() > Index) {
1868     if (const DIDerivedType *PtrTy =
1869             dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index])) {
1870       if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) {
1871         ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty);
1872         Index++;
1873       }
1874     }
1875   }
1876 
1877   while (Index < ReturnAndArgs.size())
1878     ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++]));
1879 
1880   // MSVC uses type none for variadic argument.
1881   if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void())
1882     ArgTypeIndices.back() = TypeIndex::None();
1883 
1884   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1885   TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
1886 
1887   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1888 
1889   MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
1890                            ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
1891   return TypeTable.writeLeafType(MFR);
1892 }
1893 
1894 TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
1895   unsigned VSlotCount =
1896       Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
1897   SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
1898 
1899   VFTableShapeRecord VFTSR(Slots);
1900   return TypeTable.writeLeafType(VFTSR);
1901 }
1902 
1903 static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1904   switch (Flags & DINode::FlagAccessibility) {
1905   case DINode::FlagPrivate:   return MemberAccess::Private;
1906   case DINode::FlagPublic:    return MemberAccess::Public;
1907   case DINode::FlagProtected: return MemberAccess::Protected;
1908   case 0:
1909     // If there was no explicit access control, provide the default for the tag.
1910     return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1911                                                  : MemberAccess::Public;
1912   }
1913   llvm_unreachable("access flags are exclusive");
1914 }
1915 
1916 static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1917   if (SP->isArtificial())
1918     return MethodOptions::CompilerGenerated;
1919 
1920   // FIXME: Handle other MethodOptions.
1921 
1922   return MethodOptions::None;
1923 }
1924 
1925 static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1926                                            bool Introduced) {
1927   if (SP->getFlags() & DINode::FlagStaticMember)
1928     return MethodKind::Static;
1929 
1930   switch (SP->getVirtuality()) {
1931   case dwarf::DW_VIRTUALITY_none:
1932     break;
1933   case dwarf::DW_VIRTUALITY_virtual:
1934     return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1935   case dwarf::DW_VIRTUALITY_pure_virtual:
1936     return Introduced ? MethodKind::PureIntroducingVirtual
1937                       : MethodKind::PureVirtual;
1938   default:
1939     llvm_unreachable("unhandled virtuality case");
1940   }
1941 
1942   return MethodKind::Vanilla;
1943 }
1944 
1945 static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1946   switch (Ty->getTag()) {
1947   case dwarf::DW_TAG_class_type:     return TypeRecordKind::Class;
1948   case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1949   }
1950   llvm_unreachable("unexpected tag");
1951 }
1952 
1953 /// Return ClassOptions that should be present on both the forward declaration
1954 /// and the defintion of a tag type.
1955 static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1956   ClassOptions CO = ClassOptions::None;
1957 
1958   // MSVC always sets this flag, even for local types. Clang doesn't always
1959   // appear to give every type a linkage name, which may be problematic for us.
1960   // FIXME: Investigate the consequences of not following them here.
1961   if (!Ty->getIdentifier().empty())
1962     CO |= ClassOptions::HasUniqueName;
1963 
1964   // Put the Nested flag on a type if it appears immediately inside a tag type.
1965   // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1966   // here. That flag is only set on definitions, and not forward declarations.
1967   const DIScope *ImmediateScope = Ty->getScope();
1968   if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1969     CO |= ClassOptions::Nested;
1970 
1971   // Put the Scoped flag on function-local types. MSVC puts this flag for enum
1972   // type only when it has an immediate function scope. Clang never puts enums
1973   // inside DILexicalBlock scopes. Enum types, as generated by clang, are
1974   // always in function, class, or file scopes.
1975   if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
1976     if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
1977       CO |= ClassOptions::Scoped;
1978   } else {
1979     for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1980          Scope = Scope->getScope()) {
1981       if (isa<DISubprogram>(Scope)) {
1982         CO |= ClassOptions::Scoped;
1983         break;
1984       }
1985     }
1986   }
1987 
1988   return CO;
1989 }
1990 
1991 void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
1992   switch (Ty->getTag()) {
1993   case dwarf::DW_TAG_class_type:
1994   case dwarf::DW_TAG_structure_type:
1995   case dwarf::DW_TAG_union_type:
1996   case dwarf::DW_TAG_enumeration_type:
1997     break;
1998   default:
1999     return;
2000   }
2001 
2002   if (const auto *File = Ty->getFile()) {
2003     StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
2004     TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
2005 
2006     UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
2007     TypeTable.writeLeafType(USLR);
2008   }
2009 }
2010 
2011 TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
2012   ClassOptions CO = getCommonClassOptions(Ty);
2013   TypeIndex FTI;
2014   unsigned EnumeratorCount = 0;
2015 
2016   if (Ty->isForwardDecl()) {
2017     CO |= ClassOptions::ForwardReference;
2018   } else {
2019     ContinuationRecordBuilder ContinuationBuilder;
2020     ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
2021     for (const DINode *Element : Ty->getElements()) {
2022       // We assume that the frontend provides all members in source declaration
2023       // order, which is what MSVC does.
2024       if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
2025         EnumeratorRecord ER(MemberAccess::Public,
2026                             APSInt::getUnsigned(Enumerator->getValue()),
2027                             Enumerator->getName());
2028         ContinuationBuilder.writeMemberType(ER);
2029         EnumeratorCount++;
2030       }
2031     }
2032     FTI = TypeTable.insertRecord(ContinuationBuilder);
2033   }
2034 
2035   std::string FullName = getFullyQualifiedName(Ty);
2036 
2037   EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
2038                 getTypeIndex(Ty->getBaseType()));
2039   TypeIndex EnumTI = TypeTable.writeLeafType(ER);
2040 
2041   addUDTSrcLine(Ty, EnumTI);
2042 
2043   return EnumTI;
2044 }
2045 
2046 //===----------------------------------------------------------------------===//
2047 // ClassInfo
2048 //===----------------------------------------------------------------------===//
2049 
2050 struct llvm::ClassInfo {
2051   struct MemberInfo {
2052     const DIDerivedType *MemberTypeNode;
2053     uint64_t BaseOffset;
2054   };
2055   // [MemberInfo]
2056   using MemberList = std::vector<MemberInfo>;
2057 
2058   using MethodsList = TinyPtrVector<const DISubprogram *>;
2059   // MethodName -> MethodsList
2060   using MethodsMap = MapVector<MDString *, MethodsList>;
2061 
2062   /// Base classes.
2063   std::vector<const DIDerivedType *> Inheritance;
2064 
2065   /// Direct members.
2066   MemberList Members;
2067   // Direct overloaded methods gathered by name.
2068   MethodsMap Methods;
2069 
2070   TypeIndex VShapeTI;
2071 
2072   std::vector<const DIType *> NestedTypes;
2073 };
2074 
2075 void CodeViewDebug::clear() {
2076   assert(CurFn == nullptr);
2077   FileIdMap.clear();
2078   FnDebugInfo.clear();
2079   FileToFilepathMap.clear();
2080   LocalUDTs.clear();
2081   GlobalUDTs.clear();
2082   TypeIndices.clear();
2083   CompleteTypeIndices.clear();
2084   ScopeGlobals.clear();
2085 }
2086 
2087 void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
2088                                       const DIDerivedType *DDTy) {
2089   if (!DDTy->getName().empty()) {
2090     Info.Members.push_back({DDTy, 0});
2091     return;
2092   }
2093 
2094   // An unnamed member may represent a nested struct or union. Attempt to
2095   // interpret the unnamed member as a DICompositeType possibly wrapped in
2096   // qualifier types. Add all the indirect fields to the current record if that
2097   // succeeds, and drop the member if that fails.
2098   assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
2099   uint64_t Offset = DDTy->getOffsetInBits();
2100   const DIType *Ty = DDTy->getBaseType();
2101   bool FullyResolved = false;
2102   while (!FullyResolved) {
2103     switch (Ty->getTag()) {
2104     case dwarf::DW_TAG_const_type:
2105     case dwarf::DW_TAG_volatile_type:
2106       // FIXME: we should apply the qualifier types to the indirect fields
2107       // rather than dropping them.
2108       Ty = cast<DIDerivedType>(Ty)->getBaseType();
2109       break;
2110     default:
2111       FullyResolved = true;
2112       break;
2113     }
2114   }
2115 
2116   const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
2117   if (!DCTy)
2118     return;
2119 
2120   ClassInfo NestedInfo = collectClassInfo(DCTy);
2121   for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
2122     Info.Members.push_back(
2123         {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
2124 }
2125 
2126 ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
2127   ClassInfo Info;
2128   // Add elements to structure type.
2129   DINodeArray Elements = Ty->getElements();
2130   for (auto *Element : Elements) {
2131     // We assume that the frontend provides all members in source declaration
2132     // order, which is what MSVC does.
2133     if (!Element)
2134       continue;
2135     if (auto *SP = dyn_cast<DISubprogram>(Element)) {
2136       Info.Methods[SP->getRawName()].push_back(SP);
2137     } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
2138       if (DDTy->getTag() == dwarf::DW_TAG_member) {
2139         collectMemberInfo(Info, DDTy);
2140       } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
2141         Info.Inheritance.push_back(DDTy);
2142       } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
2143                  DDTy->getName() == "__vtbl_ptr_type") {
2144         Info.VShapeTI = getTypeIndex(DDTy);
2145       } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
2146         Info.NestedTypes.push_back(DDTy);
2147       } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
2148         // Ignore friend members. It appears that MSVC emitted info about
2149         // friends in the past, but modern versions do not.
2150       }
2151     } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
2152       Info.NestedTypes.push_back(Composite);
2153     }
2154     // Skip other unrecognized kinds of elements.
2155   }
2156   return Info;
2157 }
2158 
2159 static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) {
2160   // This routine is used by lowerTypeClass and lowerTypeUnion to determine
2161   // if a complete type should be emitted instead of a forward reference.
2162   return Ty->getName().empty() && Ty->getIdentifier().empty() &&
2163       !Ty->isForwardDecl();
2164 }
2165 
2166 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
2167   // Emit the complete type for unnamed structs.  C++ classes with methods
2168   // which have a circular reference back to the class type are expected to
2169   // be named by the front-end and should not be "unnamed".  C unnamed
2170   // structs should not have circular references.
2171   if (shouldAlwaysEmitCompleteClassType(Ty)) {
2172     // If this unnamed complete type is already in the process of being defined
2173     // then the description of the type is malformed and cannot be emitted
2174     // into CodeView correctly so report a fatal error.
2175     auto I = CompleteTypeIndices.find(Ty);
2176     if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
2177       report_fatal_error("cannot debug circular reference to unnamed type");
2178     return getCompleteTypeIndex(Ty);
2179   }
2180 
2181   // First, construct the forward decl.  Don't look into Ty to compute the
2182   // forward decl options, since it might not be available in all TUs.
2183   TypeRecordKind Kind = getRecordKind(Ty);
2184   ClassOptions CO =
2185       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2186   std::string FullName = getFullyQualifiedName(Ty);
2187   ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
2188                  FullName, Ty->getIdentifier());
2189   TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
2190   if (!Ty->isForwardDecl())
2191     DeferredCompleteTypes.push_back(Ty);
2192   return FwdDeclTI;
2193 }
2194 
2195 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
2196   // Construct the field list and complete type record.
2197   TypeRecordKind Kind = getRecordKind(Ty);
2198   ClassOptions CO = getCommonClassOptions(Ty);
2199   TypeIndex FieldTI;
2200   TypeIndex VShapeTI;
2201   unsigned FieldCount;
2202   bool ContainsNestedClass;
2203   std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
2204       lowerRecordFieldList(Ty);
2205 
2206   if (ContainsNestedClass)
2207     CO |= ClassOptions::ContainsNestedClass;
2208 
2209   // MSVC appears to set this flag by searching any destructor or method with
2210   // FunctionOptions::Constructor among the emitted members. Clang AST has all
2211   // the members, however special member functions are not yet emitted into
2212   // debug information. For now checking a class's non-triviality seems enough.
2213   // FIXME: not true for a nested unnamed struct.
2214   if (isNonTrivial(Ty))
2215     CO |= ClassOptions::HasConstructorOrDestructor;
2216 
2217   std::string FullName = getFullyQualifiedName(Ty);
2218 
2219   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2220 
2221   ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
2222                  SizeInBytes, FullName, Ty->getIdentifier());
2223   TypeIndex ClassTI = TypeTable.writeLeafType(CR);
2224 
2225   addUDTSrcLine(Ty, ClassTI);
2226 
2227   addToUDTs(Ty);
2228 
2229   return ClassTI;
2230 }
2231 
2232 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
2233   // Emit the complete type for unnamed unions.
2234   if (shouldAlwaysEmitCompleteClassType(Ty))
2235     return getCompleteTypeIndex(Ty);
2236 
2237   ClassOptions CO =
2238       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2239   std::string FullName = getFullyQualifiedName(Ty);
2240   UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
2241   TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
2242   if (!Ty->isForwardDecl())
2243     DeferredCompleteTypes.push_back(Ty);
2244   return FwdDeclTI;
2245 }
2246 
2247 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
2248   ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
2249   TypeIndex FieldTI;
2250   unsigned FieldCount;
2251   bool ContainsNestedClass;
2252   std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
2253       lowerRecordFieldList(Ty);
2254 
2255   if (ContainsNestedClass)
2256     CO |= ClassOptions::ContainsNestedClass;
2257 
2258   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2259   std::string FullName = getFullyQualifiedName(Ty);
2260 
2261   UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
2262                  Ty->getIdentifier());
2263   TypeIndex UnionTI = TypeTable.writeLeafType(UR);
2264 
2265   addUDTSrcLine(Ty, UnionTI);
2266 
2267   addToUDTs(Ty);
2268 
2269   return UnionTI;
2270 }
2271 
2272 std::tuple<TypeIndex, TypeIndex, unsigned, bool>
2273 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
2274   // Manually count members. MSVC appears to count everything that generates a
2275   // field list record. Each individual overload in a method overload group
2276   // contributes to this count, even though the overload group is a single field
2277   // list record.
2278   unsigned MemberCount = 0;
2279   ClassInfo Info = collectClassInfo(Ty);
2280   ContinuationRecordBuilder ContinuationBuilder;
2281   ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
2282 
2283   // Create base classes.
2284   for (const DIDerivedType *I : Info.Inheritance) {
2285     if (I->getFlags() & DINode::FlagVirtual) {
2286       // Virtual base.
2287       unsigned VBPtrOffset = I->getVBPtrOffset();
2288       // FIXME: Despite the accessor name, the offset is really in bytes.
2289       unsigned VBTableIndex = I->getOffsetInBits() / 4;
2290       auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
2291                             ? TypeRecordKind::IndirectVirtualBaseClass
2292                             : TypeRecordKind::VirtualBaseClass;
2293       VirtualBaseClassRecord VBCR(
2294           RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
2295           getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
2296           VBTableIndex);
2297 
2298       ContinuationBuilder.writeMemberType(VBCR);
2299       MemberCount++;
2300     } else {
2301       assert(I->getOffsetInBits() % 8 == 0 &&
2302              "bases must be on byte boundaries");
2303       BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
2304                           getTypeIndex(I->getBaseType()),
2305                           I->getOffsetInBits() / 8);
2306       ContinuationBuilder.writeMemberType(BCR);
2307       MemberCount++;
2308     }
2309   }
2310 
2311   // Create members.
2312   for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
2313     const DIDerivedType *Member = MemberInfo.MemberTypeNode;
2314     TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
2315     StringRef MemberName = Member->getName();
2316     MemberAccess Access =
2317         translateAccessFlags(Ty->getTag(), Member->getFlags());
2318 
2319     if (Member->isStaticMember()) {
2320       StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
2321       ContinuationBuilder.writeMemberType(SDMR);
2322       MemberCount++;
2323       continue;
2324     }
2325 
2326     // Virtual function pointer member.
2327     if ((Member->getFlags() & DINode::FlagArtificial) &&
2328         Member->getName().startswith("_vptr$")) {
2329       VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
2330       ContinuationBuilder.writeMemberType(VFPR);
2331       MemberCount++;
2332       continue;
2333     }
2334 
2335     // Data member.
2336     uint64_t MemberOffsetInBits =
2337         Member->getOffsetInBits() + MemberInfo.BaseOffset;
2338     if (Member->isBitField()) {
2339       uint64_t StartBitOffset = MemberOffsetInBits;
2340       if (const auto *CI =
2341               dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
2342         MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
2343       }
2344       StartBitOffset -= MemberOffsetInBits;
2345       BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2346                          StartBitOffset);
2347       MemberBaseType = TypeTable.writeLeafType(BFR);
2348     }
2349     uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
2350     DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2351                          MemberName);
2352     ContinuationBuilder.writeMemberType(DMR);
2353     MemberCount++;
2354   }
2355 
2356   // Create methods
2357   for (auto &MethodItr : Info.Methods) {
2358     StringRef Name = MethodItr.first->getString();
2359 
2360     std::vector<OneMethodRecord> Methods;
2361     for (const DISubprogram *SP : MethodItr.second) {
2362       TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2363       bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
2364 
2365       unsigned VFTableOffset = -1;
2366       if (Introduced)
2367         VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2368 
2369       Methods.push_back(OneMethodRecord(
2370           MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
2371           translateMethodKindFlags(SP, Introduced),
2372           translateMethodOptionFlags(SP), VFTableOffset, Name));
2373       MemberCount++;
2374     }
2375     assert(!Methods.empty() && "Empty methods map entry");
2376     if (Methods.size() == 1)
2377       ContinuationBuilder.writeMemberType(Methods[0]);
2378     else {
2379       // FIXME: Make this use its own ContinuationBuilder so that
2380       // MethodOverloadList can be split correctly.
2381       MethodOverloadListRecord MOLR(Methods);
2382       TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
2383 
2384       OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
2385       ContinuationBuilder.writeMemberType(OMR);
2386     }
2387   }
2388 
2389   // Create nested classes.
2390   for (const DIType *Nested : Info.NestedTypes) {
2391     NestedTypeRecord R(getTypeIndex(Nested), Nested->getName());
2392     ContinuationBuilder.writeMemberType(R);
2393     MemberCount++;
2394   }
2395 
2396   TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
2397   return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
2398                          !Info.NestedTypes.empty());
2399 }
2400 
2401 TypeIndex CodeViewDebug::getVBPTypeIndex() {
2402   if (!VBPType.getIndex()) {
2403     // Make a 'const int *' type.
2404     ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
2405     TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
2406 
2407     PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2408                                                   : PointerKind::Near32;
2409     PointerMode PM = PointerMode::Pointer;
2410     PointerOptions PO = PointerOptions::None;
2411     PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
2412     VBPType = TypeTable.writeLeafType(PR);
2413   }
2414 
2415   return VBPType;
2416 }
2417 
2418 TypeIndex CodeViewDebug::getTypeIndex(const DIType *Ty, const DIType *ClassTy) {
2419   // The null DIType is the void type. Don't try to hash it.
2420   if (!Ty)
2421     return TypeIndex::Void();
2422 
2423   // Check if we've already translated this type. Don't try to do a
2424   // get-or-create style insertion that caches the hash lookup across the
2425   // lowerType call. It will update the TypeIndices map.
2426   auto I = TypeIndices.find({Ty, ClassTy});
2427   if (I != TypeIndices.end())
2428     return I->second;
2429 
2430   TypeLoweringScope S(*this);
2431   TypeIndex TI = lowerType(Ty, ClassTy);
2432   return recordTypeIndexForDINode(Ty, TI, ClassTy);
2433 }
2434 
2435 codeview::TypeIndex
2436 CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy,
2437                                       const DISubroutineType *SubroutineTy) {
2438   assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type &&
2439          "this type must be a pointer type");
2440 
2441   PointerOptions Options = PointerOptions::None;
2442   if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference)
2443     Options = PointerOptions::LValueRefThisPointer;
2444   else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference)
2445     Options = PointerOptions::RValueRefThisPointer;
2446 
2447   // Check if we've already translated this type.  If there is no ref qualifier
2448   // on the function then we look up this pointer type with no associated class
2449   // so that the TypeIndex for the this pointer can be shared with the type
2450   // index for other pointers to this class type.  If there is a ref qualifier
2451   // then we lookup the pointer using the subroutine as the parent type.
2452   auto I = TypeIndices.find({PtrTy, SubroutineTy});
2453   if (I != TypeIndices.end())
2454     return I->second;
2455 
2456   TypeLoweringScope S(*this);
2457   TypeIndex TI = lowerTypePointer(PtrTy, Options);
2458   return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy);
2459 }
2460 
2461 TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(const DIType *Ty) {
2462   PointerRecord PR(getTypeIndex(Ty),
2463                    getPointerSizeInBytes() == 8 ? PointerKind::Near64
2464                                                 : PointerKind::Near32,
2465                    PointerMode::LValueReference, PointerOptions::None,
2466                    Ty->getSizeInBits() / 8);
2467   return TypeTable.writeLeafType(PR);
2468 }
2469 
2470 TypeIndex CodeViewDebug::getCompleteTypeIndex(const DIType *Ty) {
2471   // The null DIType is the void type. Don't try to hash it.
2472   if (!Ty)
2473     return TypeIndex::Void();
2474 
2475   // Look through typedefs when getting the complete type index. Call
2476   // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are
2477   // emitted only once.
2478   if (Ty->getTag() == dwarf::DW_TAG_typedef)
2479     (void)getTypeIndex(Ty);
2480   while (Ty->getTag() == dwarf::DW_TAG_typedef)
2481     Ty = cast<DIDerivedType>(Ty)->getBaseType();
2482 
2483   // If this is a non-record type, the complete type index is the same as the
2484   // normal type index. Just call getTypeIndex.
2485   switch (Ty->getTag()) {
2486   case dwarf::DW_TAG_class_type:
2487   case dwarf::DW_TAG_structure_type:
2488   case dwarf::DW_TAG_union_type:
2489     break;
2490   default:
2491     return getTypeIndex(Ty);
2492   }
2493 
2494   const auto *CTy = cast<DICompositeType>(Ty);
2495 
2496   TypeLoweringScope S(*this);
2497 
2498   // Make sure the forward declaration is emitted first. It's unclear if this
2499   // is necessary, but MSVC does it, and we should follow suit until we can show
2500   // otherwise.
2501   // We only emit a forward declaration for named types.
2502   if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
2503     TypeIndex FwdDeclTI = getTypeIndex(CTy);
2504 
2505     // Just use the forward decl if we don't have complete type info. This
2506     // might happen if the frontend is using modules and expects the complete
2507     // definition to be emitted elsewhere.
2508     if (CTy->isForwardDecl())
2509       return FwdDeclTI;
2510   }
2511 
2512   // Check if we've already translated the complete record type.
2513   // Insert the type with a null TypeIndex to signify that the type is currently
2514   // being lowered.
2515   auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
2516   if (!InsertResult.second)
2517     return InsertResult.first->second;
2518 
2519   TypeIndex TI;
2520   switch (CTy->getTag()) {
2521   case dwarf::DW_TAG_class_type:
2522   case dwarf::DW_TAG_structure_type:
2523     TI = lowerCompleteTypeClass(CTy);
2524     break;
2525   case dwarf::DW_TAG_union_type:
2526     TI = lowerCompleteTypeUnion(CTy);
2527     break;
2528   default:
2529     llvm_unreachable("not a record");
2530   }
2531 
2532   // Update the type index associated with this CompositeType.  This cannot
2533   // use the 'InsertResult' iterator above because it is potentially
2534   // invalidated by map insertions which can occur while lowering the class
2535   // type above.
2536   CompleteTypeIndices[CTy] = TI;
2537   return TI;
2538 }
2539 
2540 /// Emit all the deferred complete record types. Try to do this in FIFO order,
2541 /// and do this until fixpoint, as each complete record type typically
2542 /// references
2543 /// many other record types.
2544 void CodeViewDebug::emitDeferredCompleteTypes() {
2545   SmallVector<const DICompositeType *, 4> TypesToEmit;
2546   while (!DeferredCompleteTypes.empty()) {
2547     std::swap(DeferredCompleteTypes, TypesToEmit);
2548     for (const DICompositeType *RecordTy : TypesToEmit)
2549       getCompleteTypeIndex(RecordTy);
2550     TypesToEmit.clear();
2551   }
2552 }
2553 
2554 void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
2555                                           ArrayRef<LocalVariable> Locals) {
2556   // Get the sorted list of parameters and emit them first.
2557   SmallVector<const LocalVariable *, 6> Params;
2558   for (const LocalVariable &L : Locals)
2559     if (L.DIVar->isParameter())
2560       Params.push_back(&L);
2561   llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
2562     return L->DIVar->getArg() < R->DIVar->getArg();
2563   });
2564   for (const LocalVariable *L : Params)
2565     emitLocalVariable(FI, *L);
2566 
2567   // Next emit all non-parameters in the order that we found them.
2568   for (const LocalVariable &L : Locals)
2569     if (!L.DIVar->isParameter())
2570       emitLocalVariable(FI, L);
2571 }
2572 
2573 /// Only call this on endian-specific types like ulittle16_t and little32_t, or
2574 /// structs composed of them.
2575 template <typename T>
2576 static void copyBytesForDefRange(SmallString<20> &BytePrefix,
2577                                  SymbolKind SymKind, const T &DefRangeHeader) {
2578   BytePrefix.resize(2 + sizeof(T));
2579   ulittle16_t SymKindLE = ulittle16_t(SymKind);
2580   memcpy(&BytePrefix[0], &SymKindLE, 2);
2581   memcpy(&BytePrefix[2], &DefRangeHeader, sizeof(T));
2582 }
2583 
2584 void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
2585                                       const LocalVariable &Var) {
2586   // LocalSym record, see SymbolRecord.h for more info.
2587   MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL);
2588 
2589   LocalSymFlags Flags = LocalSymFlags::None;
2590   if (Var.DIVar->isParameter())
2591     Flags |= LocalSymFlags::IsParameter;
2592   if (Var.DefRanges.empty())
2593     Flags |= LocalSymFlags::IsOptimizedOut;
2594 
2595   OS.AddComment("TypeIndex");
2596   TypeIndex TI = Var.UseReferenceType
2597                      ? getTypeIndexForReferenceTo(Var.DIVar->getType())
2598                      : getCompleteTypeIndex(Var.DIVar->getType());
2599   OS.EmitIntValue(TI.getIndex(), 4);
2600   OS.AddComment("Flags");
2601   OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
2602   // Truncate the name so we won't overflow the record length field.
2603   emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
2604   endSymbolRecord(LocalEnd);
2605 
2606   // Calculate the on disk prefix of the appropriate def range record. The
2607   // records and on disk formats are described in SymbolRecords.h. BytePrefix
2608   // should be big enough to hold all forms without memory allocation.
2609   SmallString<20> BytePrefix;
2610   for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2611     BytePrefix.clear();
2612     if (DefRange.InMemory) {
2613       int Offset = DefRange.DataOffset;
2614       unsigned Reg = DefRange.CVRegister;
2615 
2616       // 32-bit x86 call sequences often use PUSH instructions, which disrupt
2617       // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
2618       // instead. In frames without stack realignment, $T0 will be the CFA.
2619       if (RegisterId(Reg) == RegisterId::ESP) {
2620         Reg = unsigned(RegisterId::VFRAME);
2621         Offset += FI.OffsetAdjustment;
2622       }
2623 
2624       // If we can use the chosen frame pointer for the frame and this isn't a
2625       // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
2626       // Otherwise, use S_DEFRANGE_REGISTER_REL.
2627       EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU);
2628       if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
2629           (bool(Flags & LocalSymFlags::IsParameter)
2630                ? (EncFP == FI.EncodedParamFramePtrReg)
2631                : (EncFP == FI.EncodedLocalFramePtrReg))) {
2632         little32_t FPOffset = little32_t(Offset);
2633         copyBytesForDefRange(BytePrefix, S_DEFRANGE_FRAMEPOINTER_REL, FPOffset);
2634       } else {
2635         uint16_t RegRelFlags = 0;
2636         if (DefRange.IsSubfield) {
2637           RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2638                         (DefRange.StructOffset
2639                          << DefRangeRegisterRelSym::OffsetInParentShift);
2640         }
2641         DefRangeRegisterRelSym::Header DRHdr;
2642         DRHdr.Register = Reg;
2643         DRHdr.Flags = RegRelFlags;
2644         DRHdr.BasePointerOffset = Offset;
2645         copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER_REL, DRHdr);
2646       }
2647     } else {
2648       assert(DefRange.DataOffset == 0 && "unexpected offset into register");
2649       if (DefRange.IsSubfield) {
2650         DefRangeSubfieldRegisterSym::Header DRHdr;
2651         DRHdr.Register = DefRange.CVRegister;
2652         DRHdr.MayHaveNoName = 0;
2653         DRHdr.OffsetInParent = DefRange.StructOffset;
2654         copyBytesForDefRange(BytePrefix, S_DEFRANGE_SUBFIELD_REGISTER, DRHdr);
2655       } else {
2656         DefRangeRegisterSym::Header DRHdr;
2657         DRHdr.Register = DefRange.CVRegister;
2658         DRHdr.MayHaveNoName = 0;
2659         copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER, DRHdr);
2660       }
2661     }
2662     OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2663   }
2664 }
2665 
2666 void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
2667                                          const FunctionInfo& FI) {
2668   for (LexicalBlock *Block : Blocks)
2669     emitLexicalBlock(*Block, FI);
2670 }
2671 
2672 /// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
2673 /// lexical block scope.
2674 void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
2675                                      const FunctionInfo& FI) {
2676   MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32);
2677   OS.AddComment("PtrParent");
2678   OS.EmitIntValue(0, 4);                                  // PtrParent
2679   OS.AddComment("PtrEnd");
2680   OS.EmitIntValue(0, 4);                                  // PtrEnd
2681   OS.AddComment("Code size");
2682   OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4);   // Code Size
2683   OS.AddComment("Function section relative address");
2684   OS.EmitCOFFSecRel32(Block.Begin, /*Offset=*/0);         // Func Offset
2685   OS.AddComment("Function section index");
2686   OS.EmitCOFFSectionIndex(FI.Begin);                      // Func Symbol
2687   OS.AddComment("Lexical block name");
2688   emitNullTerminatedSymbolName(OS, Block.Name);           // Name
2689   endSymbolRecord(RecordEnd);
2690 
2691   // Emit variables local to this lexical block.
2692   emitLocalVariableList(FI, Block.Locals);
2693   emitGlobalVariableList(Block.Globals);
2694 
2695   // Emit lexical blocks contained within this block.
2696   emitLexicalBlockList(Block.Children, FI);
2697 
2698   // Close the lexical block scope.
2699   emitEndSymbolRecord(SymbolKind::S_END);
2700 }
2701 
2702 /// Convenience routine for collecting lexical block information for a list
2703 /// of lexical scopes.
2704 void CodeViewDebug::collectLexicalBlockInfo(
2705         SmallVectorImpl<LexicalScope *> &Scopes,
2706         SmallVectorImpl<LexicalBlock *> &Blocks,
2707         SmallVectorImpl<LocalVariable> &Locals,
2708         SmallVectorImpl<CVGlobalVariable> &Globals) {
2709   for (LexicalScope *Scope : Scopes)
2710     collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals);
2711 }
2712 
2713 /// Populate the lexical blocks and local variable lists of the parent with
2714 /// information about the specified lexical scope.
2715 void CodeViewDebug::collectLexicalBlockInfo(
2716     LexicalScope &Scope,
2717     SmallVectorImpl<LexicalBlock *> &ParentBlocks,
2718     SmallVectorImpl<LocalVariable> &ParentLocals,
2719     SmallVectorImpl<CVGlobalVariable> &ParentGlobals) {
2720   if (Scope.isAbstractScope())
2721     return;
2722 
2723   // Gather information about the lexical scope including local variables,
2724   // global variables, and address ranges.
2725   bool IgnoreScope = false;
2726   auto LI = ScopeVariables.find(&Scope);
2727   SmallVectorImpl<LocalVariable> *Locals =
2728       LI != ScopeVariables.end() ? &LI->second : nullptr;
2729   auto GI = ScopeGlobals.find(Scope.getScopeNode());
2730   SmallVectorImpl<CVGlobalVariable> *Globals =
2731       GI != ScopeGlobals.end() ? GI->second.get() : nullptr;
2732   const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
2733   const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
2734 
2735   // Ignore lexical scopes which do not contain variables.
2736   if (!Locals && !Globals)
2737     IgnoreScope = true;
2738 
2739   // Ignore lexical scopes which are not lexical blocks.
2740   if (!DILB)
2741     IgnoreScope = true;
2742 
2743   // Ignore scopes which have too many address ranges to represent in the
2744   // current CodeView format or do not have a valid address range.
2745   //
2746   // For lexical scopes with multiple address ranges you may be tempted to
2747   // construct a single range covering every instruction where the block is
2748   // live and everything in between.  Unfortunately, Visual Studio only
2749   // displays variables from the first matching lexical block scope.  If the
2750   // first lexical block contains exception handling code or cold code which
2751   // is moved to the bottom of the routine creating a single range covering
2752   // nearly the entire routine, then it will hide all other lexical blocks
2753   // and the variables they contain.
2754   if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second))
2755     IgnoreScope = true;
2756 
2757   if (IgnoreScope) {
2758     // This scope can be safely ignored and eliminating it will reduce the
2759     // size of the debug information. Be sure to collect any variable and scope
2760     // information from the this scope or any of its children and collapse them
2761     // into the parent scope.
2762     if (Locals)
2763       ParentLocals.append(Locals->begin(), Locals->end());
2764     if (Globals)
2765       ParentGlobals.append(Globals->begin(), Globals->end());
2766     collectLexicalBlockInfo(Scope.getChildren(),
2767                             ParentBlocks,
2768                             ParentLocals,
2769                             ParentGlobals);
2770     return;
2771   }
2772 
2773   // Create a new CodeView lexical block for this lexical scope.  If we've
2774   // seen this DILexicalBlock before then the scope tree is malformed and
2775   // we can handle this gracefully by not processing it a second time.
2776   auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
2777   if (!BlockInsertion.second)
2778     return;
2779 
2780   // Create a lexical block containing the variables and collect the the
2781   // lexical block information for the children.
2782   const InsnRange &Range = Ranges.front();
2783   assert(Range.first && Range.second);
2784   LexicalBlock &Block = BlockInsertion.first->second;
2785   Block.Begin = getLabelBeforeInsn(Range.first);
2786   Block.End = getLabelAfterInsn(Range.second);
2787   assert(Block.Begin && "missing label for scope begin");
2788   assert(Block.End && "missing label for scope end");
2789   Block.Name = DILB->getName();
2790   if (Locals)
2791     Block.Locals = std::move(*Locals);
2792   if (Globals)
2793     Block.Globals = std::move(*Globals);
2794   ParentBlocks.push_back(&Block);
2795   collectLexicalBlockInfo(Scope.getChildren(),
2796                           Block.Children,
2797                           Block.Locals,
2798                           Block.Globals);
2799 }
2800 
2801 void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
2802   const Function &GV = MF->getFunction();
2803   assert(FnDebugInfo.count(&GV));
2804   assert(CurFn == FnDebugInfo[&GV].get());
2805 
2806   collectVariableInfo(GV.getSubprogram());
2807 
2808   // Build the lexical block structure to emit for this routine.
2809   if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
2810     collectLexicalBlockInfo(*CFS,
2811                             CurFn->ChildBlocks,
2812                             CurFn->Locals,
2813                             CurFn->Globals);
2814 
2815   // Clear the scope and variable information from the map which will not be
2816   // valid after we have finished processing this routine.  This also prepares
2817   // the map for the subsequent routine.
2818   ScopeVariables.clear();
2819 
2820   // Don't emit anything if we don't have any line tables.
2821   // Thunks are compiler-generated and probably won't have source correlation.
2822   if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
2823     FnDebugInfo.erase(&GV);
2824     CurFn = nullptr;
2825     return;
2826   }
2827 
2828   CurFn->Annotations = MF->getCodeViewAnnotations();
2829   CurFn->HeapAllocSites = MF->getCodeViewHeapAllocSites();
2830 
2831   CurFn->End = Asm->getFunctionEnd();
2832 
2833   CurFn = nullptr;
2834 }
2835 
2836 void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
2837   DebugHandlerBase::beginInstruction(MI);
2838 
2839   // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
2840   if (!Asm || !CurFn || MI->isDebugInstr() ||
2841       MI->getFlag(MachineInstr::FrameSetup))
2842     return;
2843 
2844   // If the first instruction of a new MBB has no location, find the first
2845   // instruction with a location and use that.
2846   DebugLoc DL = MI->getDebugLoc();
2847   if (!DL && MI->getParent() != PrevInstBB) {
2848     for (const auto &NextMI : *MI->getParent()) {
2849       if (NextMI.isDebugInstr())
2850         continue;
2851       DL = NextMI.getDebugLoc();
2852       if (DL)
2853         break;
2854     }
2855   }
2856   PrevInstBB = MI->getParent();
2857 
2858   // If we still don't have a debug location, don't record a location.
2859   if (!DL)
2860     return;
2861 
2862   maybeRecordLocation(DL, Asm->MF);
2863 }
2864 
2865 MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
2866   MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2867            *EndLabel = MMI->getContext().createTempSymbol();
2868   OS.EmitIntValue(unsigned(Kind), 4);
2869   OS.AddComment("Subsection size");
2870   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2871   OS.EmitLabel(BeginLabel);
2872   return EndLabel;
2873 }
2874 
2875 void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2876   OS.EmitLabel(EndLabel);
2877   // Every subsection must be aligned to a 4-byte boundary.
2878   OS.EmitValueToAlignment(4);
2879 }
2880 
2881 static StringRef getSymbolName(SymbolKind SymKind) {
2882   for (const EnumEntry<SymbolKind> &EE : getSymbolTypeNames())
2883     if (EE.Value == SymKind)
2884       return EE.Name;
2885   return "";
2886 }
2887 
2888 MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) {
2889   MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2890            *EndLabel = MMI->getContext().createTempSymbol();
2891   OS.AddComment("Record length");
2892   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
2893   OS.EmitLabel(BeginLabel);
2894   if (OS.isVerboseAsm())
2895     OS.AddComment("Record kind: " + getSymbolName(SymKind));
2896   OS.EmitIntValue(unsigned(SymKind), 2);
2897   return EndLabel;
2898 }
2899 
2900 void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) {
2901   // MSVC does not pad out symbol records to four bytes, but LLVM does to avoid
2902   // an extra copy of every symbol record in LLD. This increases object file
2903   // size by less than 1% in the clang build, and is compatible with the Visual
2904   // C++ linker.
2905   OS.EmitValueToAlignment(4);
2906   OS.EmitLabel(SymEnd);
2907 }
2908 
2909 void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) {
2910   OS.AddComment("Record length");
2911   OS.EmitIntValue(2, 2);
2912   if (OS.isVerboseAsm())
2913     OS.AddComment("Record kind: " + getSymbolName(EndKind));
2914   OS.EmitIntValue(unsigned(EndKind), 2); // Record Kind
2915 }
2916 
2917 void CodeViewDebug::emitDebugInfoForUDTs(
2918     ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
2919   for (const auto &UDT : UDTs) {
2920     const DIType *T = UDT.second;
2921     assert(shouldEmitUdt(T));
2922 
2923     MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT);
2924     OS.AddComment("Type");
2925     OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
2926     emitNullTerminatedSymbolName(OS, UDT.first);
2927     endSymbolRecord(UDTRecordEnd);
2928   }
2929 }
2930 
2931 void CodeViewDebug::collectGlobalVariableInfo() {
2932   DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2933       GlobalMap;
2934   for (const GlobalVariable &GV : MMI->getModule()->globals()) {
2935     SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2936     GV.getDebugInfo(GVEs);
2937     for (const auto *GVE : GVEs)
2938       GlobalMap[GVE] = &GV;
2939   }
2940 
2941   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2942   for (const MDNode *Node : CUs->operands()) {
2943     const auto *CU = cast<DICompileUnit>(Node);
2944     for (const auto *GVE : CU->getGlobalVariables()) {
2945       const DIGlobalVariable *DIGV = GVE->getVariable();
2946       const DIExpression *DIE = GVE->getExpression();
2947 
2948       // Emit constant global variables in a global symbol section.
2949       if (GlobalMap.count(GVE) == 0 && DIE->isConstant()) {
2950         CVGlobalVariable CVGV = {DIGV, DIE};
2951         GlobalVariables.emplace_back(std::move(CVGV));
2952       }
2953 
2954       const auto *GV = GlobalMap.lookup(GVE);
2955       if (!GV || GV->isDeclarationForLinker())
2956         continue;
2957 
2958       DIScope *Scope = DIGV->getScope();
2959       SmallVector<CVGlobalVariable, 1> *VariableList;
2960       if (Scope && isa<DILocalScope>(Scope)) {
2961         // Locate a global variable list for this scope, creating one if
2962         // necessary.
2963         auto Insertion = ScopeGlobals.insert(
2964             {Scope, std::unique_ptr<GlobalVariableList>()});
2965         if (Insertion.second)
2966           Insertion.first->second = llvm::make_unique<GlobalVariableList>();
2967         VariableList = Insertion.first->second.get();
2968       } else if (GV->hasComdat())
2969         // Emit this global variable into a COMDAT section.
2970         VariableList = &ComdatVariables;
2971       else
2972         // Emit this global variable in a single global symbol section.
2973         VariableList = &GlobalVariables;
2974       CVGlobalVariable CVGV = {DIGV, GV};
2975       VariableList->emplace_back(std::move(CVGV));
2976     }
2977   }
2978 }
2979 
2980 void CodeViewDebug::emitDebugInfoForGlobals() {
2981   // First, emit all globals that are not in a comdat in a single symbol
2982   // substream. MSVC doesn't like it if the substream is empty, so only open
2983   // it if we have at least one global to emit.
2984   switchToDebugSectionForSymbol(nullptr);
2985   if (!GlobalVariables.empty()) {
2986     OS.AddComment("Symbol subsection for globals");
2987     MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
2988     emitGlobalVariableList(GlobalVariables);
2989     endCVSubsection(EndLabel);
2990   }
2991 
2992   // Second, emit each global that is in a comdat into its own .debug$S
2993   // section along with its own symbol substream.
2994   for (const CVGlobalVariable &CVGV : ComdatVariables) {
2995     const GlobalVariable *GV = CVGV.GVInfo.get<const GlobalVariable *>();
2996     MCSymbol *GVSym = Asm->getSymbol(GV);
2997     OS.AddComment("Symbol subsection for " +
2998                   Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
2999     switchToDebugSectionForSymbol(GVSym);
3000     MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
3001     // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3002     emitDebugInfoForGlobal(CVGV);
3003     endCVSubsection(EndLabel);
3004   }
3005 }
3006 
3007 void CodeViewDebug::emitDebugInfoForRetainedTypes() {
3008   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
3009   for (const MDNode *Node : CUs->operands()) {
3010     for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
3011       if (DIType *RT = dyn_cast<DIType>(Ty)) {
3012         getTypeIndex(RT);
3013         // FIXME: Add to global/local DTU list.
3014       }
3015     }
3016   }
3017 }
3018 
3019 // Emit each global variable in the specified array.
3020 void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) {
3021   for (const CVGlobalVariable &CVGV : Globals) {
3022     // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3023     emitDebugInfoForGlobal(CVGV);
3024   }
3025 }
3026 
3027 void CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable &CVGV) {
3028   const DIGlobalVariable *DIGV = CVGV.DIGV;
3029   if (const GlobalVariable *GV =
3030           CVGV.GVInfo.dyn_cast<const GlobalVariable *>()) {
3031     // DataSym record, see SymbolRecord.h for more info. Thread local data
3032     // happens to have the same format as global data.
3033     MCSymbol *GVSym = Asm->getSymbol(GV);
3034     SymbolKind DataSym = GV->isThreadLocal()
3035                              ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32
3036                                                       : SymbolKind::S_GTHREAD32)
3037                              : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32
3038                                                       : SymbolKind::S_GDATA32);
3039     MCSymbol *DataEnd = beginSymbolRecord(DataSym);
3040     OS.AddComment("Type");
3041     OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
3042     OS.AddComment("DataOffset");
3043     OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
3044     OS.AddComment("Segment");
3045     OS.EmitCOFFSectionIndex(GVSym);
3046     OS.AddComment("Name");
3047     const unsigned LengthOfDataRecord = 12;
3048     emitNullTerminatedSymbolName(OS, DIGV->getName(), LengthOfDataRecord);
3049     endSymbolRecord(DataEnd);
3050   } else {
3051     // FIXME: Currently this only emits the global variables in the IR metadata.
3052     // This should also emit enums and static data members.
3053     const DIExpression *DIE = CVGV.GVInfo.get<const DIExpression *>();
3054     assert(DIE->isConstant() &&
3055            "Global constant variables must contain a constant expression.");
3056     uint64_t Val = DIE->getElement(1);
3057 
3058     MCSymbol *SConstantEnd = beginSymbolRecord(SymbolKind::S_CONSTANT);
3059     OS.AddComment("Type");
3060     OS.EmitIntValue(getTypeIndex(DIGV->getType()).getIndex(), 4);
3061     OS.AddComment("Value");
3062 
3063     // Encoded integers shouldn't need more than 10 bytes.
3064     uint8_t data[10];
3065     BinaryStreamWriter Writer(data, llvm::support::endianness::little);
3066     CodeViewRecordIO IO(Writer);
3067     cantFail(IO.mapEncodedInteger(Val));
3068     StringRef SRef((char *)data, Writer.getOffset());
3069     OS.EmitBinaryData(SRef);
3070 
3071     OS.AddComment("Name");
3072     emitNullTerminatedSymbolName(OS, DIGV->getDisplayName());
3073     endSymbolRecord(SConstantEnd);
3074   }
3075 }
3076