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