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