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