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