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