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