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