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