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