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