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