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 = TypeIndex::simpleTypeName(TI);
123       else
124         TypeName = 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 = 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 = 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:  CSKind = FileChecksumKind::MD5; break;
254       case DIFile::CSK_SHA1: CSKind = FileChecksumKind::SHA1; break;
255       }
256     }
257     bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
258                                           static_cast<unsigned>(CSKind));
259     (void)Success;
260     assert(Success && ".cv_file directive failed");
261   }
262   return Insertion.first->second;
263 }
264 
265 CodeViewDebug::InlineSite &
266 CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
267                              const DISubprogram *Inlinee) {
268   auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
269   InlineSite *Site = &SiteInsertion.first->second;
270   if (SiteInsertion.second) {
271     unsigned ParentFuncId = CurFn->FuncId;
272     if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
273       ParentFuncId =
274           getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
275               .SiteFuncId;
276 
277     Site->SiteFuncId = NextFuncId++;
278     OS.EmitCVInlineSiteIdDirective(
279         Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
280         InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
281     Site->Inlinee = Inlinee;
282     InlinedSubprograms.insert(Inlinee);
283     getFuncIdForSubprogram(Inlinee);
284   }
285   return *Site;
286 }
287 
288 static StringRef getPrettyScopeName(const DIScope *Scope) {
289   StringRef ScopeName = Scope->getName();
290   if (!ScopeName.empty())
291     return ScopeName;
292 
293   switch (Scope->getTag()) {
294   case dwarf::DW_TAG_enumeration_type:
295   case dwarf::DW_TAG_class_type:
296   case dwarf::DW_TAG_structure_type:
297   case dwarf::DW_TAG_union_type:
298     return "<unnamed-tag>";
299   case dwarf::DW_TAG_namespace:
300     return "`anonymous namespace'";
301   }
302 
303   return StringRef();
304 }
305 
306 const DISubprogram *CodeViewDebug::collectParentScopeNames(
307     const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
308   const DISubprogram *ClosestSubprogram = nullptr;
309   while (Scope != nullptr) {
310     if (ClosestSubprogram == nullptr)
311       ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
312 
313     // If a type appears in a scope chain, make sure it gets emitted. The
314     // frontend will be responsible for deciding if this should be a forward
315     // declaration or a complete type.
316     if (const auto *Ty = dyn_cast<DIType>(Scope))
317       (void)getTypeIndex(Ty);
318 
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 std::string
328 CodeViewDebug::formatNestedName(ArrayRef<StringRef> QualifiedNameComponents,
329                                 StringRef TypeName) {
330   std::string FullyQualifiedName;
331   for (StringRef QualifiedNameComponent :
332        llvm::reverse(QualifiedNameComponents)) {
333     FullyQualifiedName.append(QualifiedNameComponent);
334     FullyQualifiedName.append("::");
335   }
336   FullyQualifiedName.append(TypeName);
337   return FullyQualifiedName;
338 }
339 
340 std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
341   SmallVector<StringRef, 5> QualifiedNameComponents;
342   collectParentScopeNames(Scope, QualifiedNameComponents);
343   return formatNestedName(QualifiedNameComponents, Name);
344 }
345 
346 std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Ty) {
347   const DIScope *Scope = Ty->getScope();
348   return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
349 }
350 
351 struct CodeViewDebug::TypeLoweringScope {
352   TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
353   ~TypeLoweringScope() {
354     // Don't decrement TypeEmissionLevel until after emitting deferred types, so
355     // inner TypeLoweringScopes don't attempt to emit deferred types.
356     if (CVD.TypeEmissionLevel == 1)
357       CVD.emitDeferredCompleteTypes();
358     --CVD.TypeEmissionLevel;
359   }
360   CodeViewDebug &CVD;
361 };
362 
363 TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
364   // No scope means global scope and that uses the zero index.
365   if (!Scope || isa<DIFile>(Scope))
366     return TypeIndex();
367 
368   assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
369 
370   // Check if we've already translated this scope.
371   auto I = TypeIndices.find({Scope, nullptr});
372   if (I != TypeIndices.end())
373     return I->second;
374 
375   // Build the fully qualified name of the scope.
376   std::string ScopeName = getFullyQualifiedName(Scope);
377   StringIdRecord SID(TypeIndex(), ScopeName);
378   auto TI = TypeTable.writeLeafType(SID);
379   return recordTypeIndexForDINode(Scope, TI);
380 }
381 
382 TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
383   assert(SP);
384 
385   // Check if we've already translated this subprogram.
386   auto I = TypeIndices.find({SP, nullptr});
387   if (I != TypeIndices.end())
388     return I->second;
389 
390   // The display name includes function template arguments. Drop them to match
391   // MSVC.
392   StringRef DisplayName = SP->getName().split('<').first;
393 
394   const DIScope *Scope = SP->getScope();
395   TypeIndex TI;
396   if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
397     // If the scope is a DICompositeType, then this must be a method. Member
398     // function types take some special handling, and require access to the
399     // subprogram.
400     TypeIndex ClassType = getTypeIndex(Class);
401     MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
402                                DisplayName);
403     TI = TypeTable.writeLeafType(MFuncId);
404   } else {
405     // Otherwise, this must be a free function.
406     TypeIndex ParentScope = getScopeIndex(Scope);
407     FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
408     TI = TypeTable.writeLeafType(FuncId);
409   }
410 
411   return recordTypeIndexForDINode(SP, TI);
412 }
413 
414 static bool isNonTrivial(const DICompositeType *DCTy) {
415   return ((DCTy->getFlags() & DINode::FlagNonTrivial) == DINode::FlagNonTrivial);
416 }
417 
418 static FunctionOptions
419 getFunctionOptions(const DISubroutineType *Ty,
420                    const DICompositeType *ClassTy = nullptr,
421                    StringRef SPName = StringRef("")) {
422   FunctionOptions FO = FunctionOptions::None;
423   const DIType *ReturnTy = nullptr;
424   if (auto TypeArray = Ty->getTypeArray()) {
425     if (TypeArray.size())
426       ReturnTy = TypeArray[0];
427   }
428 
429   if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy)) {
430     if (isNonTrivial(ReturnDCTy))
431       FO |= FunctionOptions::CxxReturnUdt;
432   }
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.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
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.EmitIntValue(COFF::DEBUG_HASHES_SECTION_MAGIC, 4);
688   OS.AddComment("Section Version");
689   OS.EmitIntValue(0, 2);
690   OS.AddComment("Hash Algorithm");
691   OS.EmitIntValue(uint16_t(GlobalTypeHashAlg::SHA1_8), 2);
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.EmitIntValue(Flags, 4);
787 
788   OS.AddComment("CPUType");
789   OS.EmitIntValue(static_cast<uint64_t>(TheCPU), 2);
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.EmitIntValue(FrontVer.Part[N], 2);
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.EmitIntValue(BackVer.Part[N], 2);
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.EmitIntValue(BuildInfoIndex.getIndex(), 4);
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.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
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.EmitIntValue(InlineeIdx.getIndex(), 4);
882     OS.AddComment("Offset into filechecksum table");
883     OS.EmitCVFileChecksumOffsetDirective(FileId);
884     OS.AddComment("Starting line number");
885     OS.EmitIntValue(SP->getLine(), 4);
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.EmitIntValue(0, 4);
902   OS.AddComment("PtrEnd");
903   OS.EmitIntValue(0, 4);
904   OS.AddComment("Inlinee type index");
905   OS.EmitIntValue(InlineeIdx.getIndex(), 4);
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 = GlobalValue::dropLLVMManglingEscape(GV->getName());
955   const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
956 
957   OS.AddComment("Symbol subsection for " + Twine(FuncName));
958   MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
959 
960   // Emit S_THUNK32
961   MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32);
962   OS.AddComment("PtrParent");
963   OS.EmitIntValue(0, 4);
964   OS.AddComment("PtrEnd");
965   OS.EmitIntValue(0, 4);
966   OS.AddComment("PtrNext");
967   OS.EmitIntValue(0, 4);
968   OS.AddComment("Thunk section relative address");
969   OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
970   OS.AddComment("Thunk section index");
971   OS.EmitCOFFSectionIndex(Fn);
972   OS.AddComment("Code size");
973   OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
974   OS.AddComment("Ordinal");
975   OS.EmitIntValue(unsigned(ordinal), 1);
976   OS.AddComment("Function name");
977   emitNullTerminatedSymbolName(OS, FuncName);
978   // Additional fields specific to the thunk ordinal would go here.
979   endSymbolRecord(ThunkRecordEnd);
980 
981   // Local variables/inlined routines are purposely omitted here.  The point of
982   // marking this as a thunk is so Visual Studio will NOT stop in this routine.
983 
984   // Emit S_PROC_ID_END
985   emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
986 
987   endCVSubsection(SymbolsEnd);
988 }
989 
990 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
991                                              FunctionInfo &FI) {
992   // For each function there is a separate subsection which holds the PC to
993   // file:line table.
994   const MCSymbol *Fn = Asm->getSymbol(GV);
995   assert(Fn);
996 
997   // Switch to the to a comdat section, if appropriate.
998   switchToDebugSectionForSymbol(Fn);
999 
1000   std::string FuncName;
1001   auto *SP = GV->getSubprogram();
1002   assert(SP);
1003   setCurrentSubprogram(SP);
1004 
1005   if (SP->isThunk()) {
1006     emitDebugInfoForThunk(GV, FI, Fn);
1007     return;
1008   }
1009 
1010   // If we have a display name, build the fully qualified name by walking the
1011   // chain of scopes.
1012   if (!SP->getName().empty())
1013     FuncName = getFullyQualifiedName(SP->getScope(), SP->getName());
1014 
1015   // If our DISubprogram name is empty, use the mangled name.
1016   if (FuncName.empty())
1017     FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
1018 
1019   // Emit FPO data, but only on 32-bit x86. No other platforms use it.
1020   if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
1021     OS.EmitCVFPOData(Fn);
1022 
1023   // Emit a symbol subsection, required by VS2012+ to find function boundaries.
1024   OS.AddComment("Symbol subsection for " + Twine(FuncName));
1025   MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
1026   {
1027     SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID
1028                                                 : SymbolKind::S_GPROC32_ID;
1029     MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind);
1030 
1031     // These fields are filled in by tools like CVPACK which run after the fact.
1032     OS.AddComment("PtrParent");
1033     OS.EmitIntValue(0, 4);
1034     OS.AddComment("PtrEnd");
1035     OS.EmitIntValue(0, 4);
1036     OS.AddComment("PtrNext");
1037     OS.EmitIntValue(0, 4);
1038     // This is the important bit that tells the debugger where the function
1039     // code is located and what's its size:
1040     OS.AddComment("Code size");
1041     OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
1042     OS.AddComment("Offset after prologue");
1043     OS.EmitIntValue(0, 4);
1044     OS.AddComment("Offset before epilogue");
1045     OS.EmitIntValue(0, 4);
1046     OS.AddComment("Function type index");
1047     OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
1048     OS.AddComment("Function section relative address");
1049     OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
1050     OS.AddComment("Function section index");
1051     OS.EmitCOFFSectionIndex(Fn);
1052     OS.AddComment("Flags");
1053     OS.EmitIntValue(0, 1);
1054     // Emit the function display name as a null-terminated string.
1055     OS.AddComment("Function name");
1056     // Truncate the name so we won't overflow the record length field.
1057     emitNullTerminatedSymbolName(OS, FuncName);
1058     endSymbolRecord(ProcRecordEnd);
1059 
1060     MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC);
1061     // Subtract out the CSR size since MSVC excludes that and we include it.
1062     OS.AddComment("FrameSize");
1063     OS.EmitIntValue(FI.FrameSize - FI.CSRSize, 4);
1064     OS.AddComment("Padding");
1065     OS.EmitIntValue(0, 4);
1066     OS.AddComment("Offset of padding");
1067     OS.EmitIntValue(0, 4);
1068     OS.AddComment("Bytes of callee saved registers");
1069     OS.EmitIntValue(FI.CSRSize, 4);
1070     OS.AddComment("Exception handler offset");
1071     OS.EmitIntValue(0, 4);
1072     OS.AddComment("Exception handler section");
1073     OS.EmitIntValue(0, 2);
1074     OS.AddComment("Flags (defines frame register)");
1075     OS.EmitIntValue(uint32_t(FI.FrameProcOpts), 4);
1076     endSymbolRecord(FrameProcEnd);
1077 
1078     emitLocalVariableList(FI, FI.Locals);
1079     emitGlobalVariableList(FI.Globals);
1080     emitLexicalBlockList(FI.ChildBlocks, FI);
1081 
1082     // Emit inlined call site information. Only emit functions inlined directly
1083     // into the parent function. We'll emit the other sites recursively as part
1084     // of their parent inline site.
1085     for (const DILocation *InlinedAt : FI.ChildSites) {
1086       auto I = FI.InlineSites.find(InlinedAt);
1087       assert(I != FI.InlineSites.end() &&
1088              "child site not in function inline site map");
1089       emitInlinedCallSite(FI, InlinedAt, I->second);
1090     }
1091 
1092     for (auto Annot : FI.Annotations) {
1093       MCSymbol *Label = Annot.first;
1094       MDTuple *Strs = cast<MDTuple>(Annot.second);
1095       MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION);
1096       OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
1097       // FIXME: Make sure we don't overflow the max record size.
1098       OS.EmitCOFFSectionIndex(Label);
1099       OS.EmitIntValue(Strs->getNumOperands(), 2);
1100       for (Metadata *MD : Strs->operands()) {
1101         // MDStrings are null terminated, so we can do EmitBytes and get the
1102         // nice .asciz directive.
1103         StringRef Str = cast<MDString>(MD)->getString();
1104         assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
1105         OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
1106       }
1107       endSymbolRecord(AnnotEnd);
1108     }
1109 
1110     for (auto HeapAllocSite : FI.HeapAllocSites) {
1111       const MCSymbol *BeginLabel = std::get<0>(HeapAllocSite);
1112       const MCSymbol *EndLabel = std::get<1>(HeapAllocSite);
1113       const DIType *DITy = std::get<2>(HeapAllocSite);
1114       MCSymbol *HeapAllocEnd = beginSymbolRecord(SymbolKind::S_HEAPALLOCSITE);
1115       OS.AddComment("Call site offset");
1116       OS.EmitCOFFSecRel32(BeginLabel, /*Offset=*/0);
1117       OS.AddComment("Call site section index");
1118       OS.EmitCOFFSectionIndex(BeginLabel);
1119       OS.AddComment("Call instruction length");
1120       OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
1121       OS.AddComment("Type index");
1122       OS.EmitIntValue(getCompleteTypeIndex(DITy).getIndex(), 4);
1123       endSymbolRecord(HeapAllocEnd);
1124     }
1125 
1126     if (SP != nullptr)
1127       emitDebugInfoForUDTs(LocalUDTs);
1128 
1129     // We're done with this function.
1130     emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
1131   }
1132   endCVSubsection(SymbolsEnd);
1133 
1134   // We have an assembler directive that takes care of the whole line table.
1135   OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
1136 }
1137 
1138 CodeViewDebug::LocalVarDefRange
1139 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
1140   LocalVarDefRange DR;
1141   DR.InMemory = -1;
1142   DR.DataOffset = Offset;
1143   assert(DR.DataOffset == Offset && "truncation");
1144   DR.IsSubfield = 0;
1145   DR.StructOffset = 0;
1146   DR.CVRegister = CVRegister;
1147   return DR;
1148 }
1149 
1150 void CodeViewDebug::collectVariableInfoFromMFTable(
1151     DenseSet<InlinedEntity> &Processed) {
1152   const MachineFunction &MF = *Asm->MF;
1153   const TargetSubtargetInfo &TSI = MF.getSubtarget();
1154   const TargetFrameLowering *TFI = TSI.getFrameLowering();
1155   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1156 
1157   for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
1158     if (!VI.Var)
1159       continue;
1160     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1161            "Expected inlined-at fields to agree");
1162 
1163     Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
1164     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1165 
1166     // If variable scope is not found then skip this variable.
1167     if (!Scope)
1168       continue;
1169 
1170     // If the variable has an attached offset expression, extract it.
1171     // FIXME: Try to handle DW_OP_deref as well.
1172     int64_t ExprOffset = 0;
1173     bool Deref = false;
1174     if (VI.Expr) {
1175       // If there is one DW_OP_deref element, use offset of 0 and keep going.
1176       if (VI.Expr->getNumElements() == 1 &&
1177           VI.Expr->getElement(0) == llvm::dwarf::DW_OP_deref)
1178         Deref = true;
1179       else if (!VI.Expr->extractIfOffset(ExprOffset))
1180         continue;
1181     }
1182 
1183     // Get the frame register used and the offset.
1184     unsigned FrameReg = 0;
1185     int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
1186     uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
1187 
1188     // Calculate the label ranges.
1189     LocalVarDefRange DefRange =
1190         createDefRangeMem(CVReg, FrameOffset + ExprOffset);
1191 
1192     for (const InsnRange &Range : Scope->getRanges()) {
1193       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1194       const MCSymbol *End = getLabelAfterInsn(Range.second);
1195       End = End ? End : Asm->getFunctionEnd();
1196       DefRange.Ranges.emplace_back(Begin, End);
1197     }
1198 
1199     LocalVariable Var;
1200     Var.DIVar = VI.Var;
1201     Var.DefRanges.emplace_back(std::move(DefRange));
1202     if (Deref)
1203       Var.UseReferenceType = true;
1204 
1205     recordLocalVariable(std::move(Var), Scope);
1206   }
1207 }
1208 
1209 static bool canUseReferenceType(const DbgVariableLocation &Loc) {
1210   return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
1211 }
1212 
1213 static bool needsReferenceType(const DbgVariableLocation &Loc) {
1214   return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
1215 }
1216 
1217 void CodeViewDebug::calculateRanges(
1218     LocalVariable &Var, const DbgValueHistoryMap::Entries &Entries) {
1219   const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1220 
1221   // Calculate the definition ranges.
1222   for (auto I = Entries.begin(), E = Entries.end(); I != E; ++I) {
1223     const auto &Entry = *I;
1224     if (!Entry.isDbgValue())
1225       continue;
1226     const MachineInstr *DVInst = Entry.getInstr();
1227     assert(DVInst->isDebugValue() && "Invalid History entry");
1228     // FIXME: Find a way to represent constant variables, since they are
1229     // relatively common.
1230     Optional<DbgVariableLocation> Location =
1231         DbgVariableLocation::extractFromMachineInstruction(*DVInst);
1232     if (!Location)
1233       continue;
1234 
1235     // CodeView can only express variables in register and variables in memory
1236     // at a constant offset from a register. However, for variables passed
1237     // indirectly by pointer, it is common for that pointer to be spilled to a
1238     // stack location. For the special case of one offseted load followed by a
1239     // zero offset load (a pointer spilled to the stack), we change the type of
1240     // the local variable from a value type to a reference type. This tricks the
1241     // debugger into doing the load for us.
1242     if (Var.UseReferenceType) {
1243       // We're using a reference type. Drop the last zero offset load.
1244       if (canUseReferenceType(*Location))
1245         Location->LoadChain.pop_back();
1246       else
1247         continue;
1248     } else if (needsReferenceType(*Location)) {
1249       // This location can't be expressed without switching to a reference type.
1250       // Start over using that.
1251       Var.UseReferenceType = true;
1252       Var.DefRanges.clear();
1253       calculateRanges(Var, Entries);
1254       return;
1255     }
1256 
1257     // We can only handle a register or an offseted load of a register.
1258     if (Location->Register == 0 || Location->LoadChain.size() > 1)
1259       continue;
1260     {
1261       LocalVarDefRange DR;
1262       DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
1263       DR.InMemory = !Location->LoadChain.empty();
1264       DR.DataOffset =
1265           !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
1266       if (Location->FragmentInfo) {
1267         DR.IsSubfield = true;
1268         DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
1269       } else {
1270         DR.IsSubfield = false;
1271         DR.StructOffset = 0;
1272       }
1273 
1274       if (Var.DefRanges.empty() ||
1275           Var.DefRanges.back().isDifferentLocation(DR)) {
1276         Var.DefRanges.emplace_back(std::move(DR));
1277       }
1278     }
1279 
1280     // Compute the label range.
1281     const MCSymbol *Begin = getLabelBeforeInsn(Entry.getInstr());
1282     const MCSymbol *End;
1283     if (Entry.getEndIndex() != DbgValueHistoryMap::NoEntry) {
1284       auto &EndingEntry = Entries[Entry.getEndIndex()];
1285       End = EndingEntry.isDbgValue()
1286                 ? getLabelBeforeInsn(EndingEntry.getInstr())
1287                 : getLabelAfterInsn(EndingEntry.getInstr());
1288     } else
1289       End = Asm->getFunctionEnd();
1290 
1291     // If the last range end is our begin, just extend the last range.
1292     // Otherwise make a new range.
1293     SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1294         Var.DefRanges.back().Ranges;
1295     if (!R.empty() && R.back().second == Begin)
1296       R.back().second = End;
1297     else
1298       R.emplace_back(Begin, End);
1299 
1300     // FIXME: Do more range combining.
1301   }
1302 }
1303 
1304 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
1305   DenseSet<InlinedEntity> Processed;
1306   // Grab the variable info that was squirreled away in the MMI side-table.
1307   collectVariableInfoFromMFTable(Processed);
1308 
1309   for (const auto &I : DbgValues) {
1310     InlinedEntity IV = I.first;
1311     if (Processed.count(IV))
1312       continue;
1313     const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
1314     const DILocation *InlinedAt = IV.second;
1315 
1316     // Instruction ranges, specifying where IV is accessible.
1317     const auto &Entries = I.second;
1318 
1319     LexicalScope *Scope = nullptr;
1320     if (InlinedAt)
1321       Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1322     else
1323       Scope = LScopes.findLexicalScope(DIVar->getScope());
1324     // If variable scope is not found then skip this variable.
1325     if (!Scope)
1326       continue;
1327 
1328     LocalVariable Var;
1329     Var.DIVar = DIVar;
1330 
1331     calculateRanges(Var, Entries);
1332     recordLocalVariable(std::move(Var), Scope);
1333   }
1334 }
1335 
1336 void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
1337   const TargetSubtargetInfo &TSI = MF->getSubtarget();
1338   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1339   const MachineFrameInfo &MFI = MF->getFrameInfo();
1340   const Function &GV = MF->getFunction();
1341   auto Insertion = FnDebugInfo.insert({&GV, std::make_unique<FunctionInfo>()});
1342   assert(Insertion.second && "function already has info");
1343   CurFn = Insertion.first->second.get();
1344   CurFn->FuncId = NextFuncId++;
1345   CurFn->Begin = Asm->getFunctionBegin();
1346 
1347   // The S_FRAMEPROC record reports the stack size, and how many bytes of
1348   // callee-saved registers were used. For targets that don't use a PUSH
1349   // instruction (AArch64), this will be zero.
1350   CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
1351   CurFn->FrameSize = MFI.getStackSize();
1352   CurFn->OffsetAdjustment = MFI.getOffsetAdjustment();
1353   CurFn->HasStackRealignment = TRI->needsStackRealignment(*MF);
1354 
1355   // For this function S_FRAMEPROC record, figure out which codeview register
1356   // will be the frame pointer.
1357   CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
1358   CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
1359   if (CurFn->FrameSize > 0) {
1360     if (!TSI.getFrameLowering()->hasFP(*MF)) {
1361       CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1362       CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
1363     } else {
1364       // If there is an FP, parameters are always relative to it.
1365       CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
1366       if (CurFn->HasStackRealignment) {
1367         // If the stack needs realignment, locals are relative to SP or VFRAME.
1368         CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1369       } else {
1370         // Otherwise, locals are relative to EBP, and we probably have VLAs or
1371         // other stack adjustments.
1372         CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
1373       }
1374     }
1375   }
1376 
1377   // Compute other frame procedure options.
1378   FrameProcedureOptions FPO = FrameProcedureOptions::None;
1379   if (MFI.hasVarSizedObjects())
1380     FPO |= FrameProcedureOptions::HasAlloca;
1381   if (MF->exposesReturnsTwice())
1382     FPO |= FrameProcedureOptions::HasSetJmp;
1383   // FIXME: Set HasLongJmp if we ever track that info.
1384   if (MF->hasInlineAsm())
1385     FPO |= FrameProcedureOptions::HasInlineAssembly;
1386   if (GV.hasPersonalityFn()) {
1387     if (isAsynchronousEHPersonality(
1388             classifyEHPersonality(GV.getPersonalityFn())))
1389       FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
1390     else
1391       FPO |= FrameProcedureOptions::HasExceptionHandling;
1392   }
1393   if (GV.hasFnAttribute(Attribute::InlineHint))
1394     FPO |= FrameProcedureOptions::MarkedInline;
1395   if (GV.hasFnAttribute(Attribute::Naked))
1396     FPO |= FrameProcedureOptions::Naked;
1397   if (MFI.hasStackProtectorIndex())
1398     FPO |= FrameProcedureOptions::SecurityChecks;
1399   FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
1400   FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
1401   if (Asm->TM.getOptLevel() != CodeGenOpt::None &&
1402       !GV.hasOptSize() && !GV.hasOptNone())
1403     FPO |= FrameProcedureOptions::OptimizedForSpeed;
1404   // FIXME: Set GuardCfg when it is implemented.
1405   CurFn->FrameProcOpts = FPO;
1406 
1407   OS.EmitCVFuncIdDirective(CurFn->FuncId);
1408 
1409   // Find the end of the function prolog.  First known non-DBG_VALUE and
1410   // non-frame setup location marks the beginning of the function body.
1411   // FIXME: is there a simpler a way to do this? Can we just search
1412   // for the first instruction of the function, not the last of the prolog?
1413   DebugLoc PrologEndLoc;
1414   bool EmptyPrologue = true;
1415   for (const auto &MBB : *MF) {
1416     for (const auto &MI : MBB) {
1417       if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1418           MI.getDebugLoc()) {
1419         PrologEndLoc = MI.getDebugLoc();
1420         break;
1421       } else if (!MI.isMetaInstruction()) {
1422         EmptyPrologue = false;
1423       }
1424     }
1425   }
1426 
1427   // Record beginning of function if we have a non-empty prologue.
1428   if (PrologEndLoc && !EmptyPrologue) {
1429     DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
1430     maybeRecordLocation(FnStartDL, MF);
1431   }
1432 
1433   // Find heap alloc sites and emit labels around them.
1434   for (const auto &MBB : *MF) {
1435     for (const auto &MI : MBB) {
1436       if (MI.getHeapAllocMarker()) {
1437         requestLabelBeforeInsn(&MI);
1438         requestLabelAfterInsn(&MI);
1439       }
1440     }
1441   }
1442 }
1443 
1444 static bool shouldEmitUdt(const DIType *T) {
1445   if (!T)
1446     return false;
1447 
1448   // MSVC does not emit UDTs for typedefs that are scoped to classes.
1449   if (T->getTag() == dwarf::DW_TAG_typedef) {
1450     if (DIScope *Scope = T->getScope()) {
1451       switch (Scope->getTag()) {
1452       case dwarf::DW_TAG_structure_type:
1453       case dwarf::DW_TAG_class_type:
1454       case dwarf::DW_TAG_union_type:
1455         return false;
1456       }
1457     }
1458   }
1459 
1460   while (true) {
1461     if (!T || T->isForwardDecl())
1462       return false;
1463 
1464     const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
1465     if (!DT)
1466       return true;
1467     T = DT->getBaseType();
1468   }
1469   return true;
1470 }
1471 
1472 void CodeViewDebug::addToUDTs(const DIType *Ty) {
1473   // Don't record empty UDTs.
1474   if (Ty->getName().empty())
1475     return;
1476   if (!shouldEmitUdt(Ty))
1477     return;
1478 
1479   SmallVector<StringRef, 5> ParentScopeNames;
1480   const DISubprogram *ClosestSubprogram =
1481       collectParentScopeNames(Ty->getScope(), ParentScopeNames);
1482 
1483   std::string FullyQualifiedName =
1484       formatNestedName(ParentScopeNames, getPrettyScopeName(Ty));
1485 
1486   if (ClosestSubprogram == nullptr) {
1487     GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1488   } else if (ClosestSubprogram == CurrentSubprogram) {
1489     LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1490   }
1491 
1492   // TODO: What if the ClosestSubprogram is neither null or the current
1493   // subprogram?  Currently, the UDT just gets dropped on the floor.
1494   //
1495   // The current behavior is not desirable.  To get maximal fidelity, we would
1496   // need to perform all type translation before beginning emission of .debug$S
1497   // and then make LocalUDTs a member of FunctionInfo
1498 }
1499 
1500 TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
1501   // Generic dispatch for lowering an unknown type.
1502   switch (Ty->getTag()) {
1503   case dwarf::DW_TAG_array_type:
1504     return lowerTypeArray(cast<DICompositeType>(Ty));
1505   case dwarf::DW_TAG_typedef:
1506     return lowerTypeAlias(cast<DIDerivedType>(Ty));
1507   case dwarf::DW_TAG_base_type:
1508     return lowerTypeBasic(cast<DIBasicType>(Ty));
1509   case dwarf::DW_TAG_pointer_type:
1510     if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1511       return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1512     LLVM_FALLTHROUGH;
1513   case dwarf::DW_TAG_reference_type:
1514   case dwarf::DW_TAG_rvalue_reference_type:
1515     return lowerTypePointer(cast<DIDerivedType>(Ty));
1516   case dwarf::DW_TAG_ptr_to_member_type:
1517     return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1518   case dwarf::DW_TAG_restrict_type:
1519   case dwarf::DW_TAG_const_type:
1520   case dwarf::DW_TAG_volatile_type:
1521   // TODO: add support for DW_TAG_atomic_type here
1522     return lowerTypeModifier(cast<DIDerivedType>(Ty));
1523   case dwarf::DW_TAG_subroutine_type:
1524     if (ClassTy) {
1525       // The member function type of a member function pointer has no
1526       // ThisAdjustment.
1527       return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1528                                      /*ThisAdjustment=*/0,
1529                                      /*IsStaticMethod=*/false);
1530     }
1531     return lowerTypeFunction(cast<DISubroutineType>(Ty));
1532   case dwarf::DW_TAG_enumeration_type:
1533     return lowerTypeEnum(cast<DICompositeType>(Ty));
1534   case dwarf::DW_TAG_class_type:
1535   case dwarf::DW_TAG_structure_type:
1536     return lowerTypeClass(cast<DICompositeType>(Ty));
1537   case dwarf::DW_TAG_union_type:
1538     return lowerTypeUnion(cast<DICompositeType>(Ty));
1539   case dwarf::DW_TAG_unspecified_type:
1540     if (Ty->getName() == "decltype(nullptr)")
1541       return TypeIndex::NullptrT();
1542     return TypeIndex::None();
1543   default:
1544     // Use the null type index.
1545     return TypeIndex();
1546   }
1547 }
1548 
1549 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
1550   TypeIndex UnderlyingTypeIndex = getTypeIndex(Ty->getBaseType());
1551   StringRef TypeName = Ty->getName();
1552 
1553   addToUDTs(Ty);
1554 
1555   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
1556       TypeName == "HRESULT")
1557     return TypeIndex(SimpleTypeKind::HResult);
1558   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
1559       TypeName == "wchar_t")
1560     return TypeIndex(SimpleTypeKind::WideCharacter);
1561 
1562   return UnderlyingTypeIndex;
1563 }
1564 
1565 TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1566   const DIType *ElementType = Ty->getBaseType();
1567   TypeIndex ElementTypeIndex = getTypeIndex(ElementType);
1568   // IndexType is size_t, which depends on the bitness of the target.
1569   TypeIndex IndexType = getPointerSizeInBytes() == 8
1570                             ? TypeIndex(SimpleTypeKind::UInt64Quad)
1571                             : TypeIndex(SimpleTypeKind::UInt32Long);
1572 
1573   uint64_t ElementSize = getBaseTypeSize(ElementType) / 8;
1574 
1575   // Add subranges to array type.
1576   DINodeArray Elements = Ty->getElements();
1577   for (int i = Elements.size() - 1; i >= 0; --i) {
1578     const DINode *Element = Elements[i];
1579     assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1580 
1581     const DISubrange *Subrange = cast<DISubrange>(Element);
1582     assert(Subrange->getLowerBound() == 0 &&
1583            "codeview doesn't support subranges with lower bounds");
1584     int64_t Count = -1;
1585     if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>())
1586       Count = CI->getSExtValue();
1587 
1588     // Forward declarations of arrays without a size and VLAs use a count of -1.
1589     // Emit a count of zero in these cases to match what MSVC does for arrays
1590     // without a size. MSVC doesn't support VLAs, so it's not clear what we
1591     // should do for them even if we could distinguish them.
1592     if (Count == -1)
1593       Count = 0;
1594 
1595     // Update the element size and element type index for subsequent subranges.
1596     ElementSize *= Count;
1597 
1598     // If this is the outermost array, use the size from the array. It will be
1599     // more accurate if we had a VLA or an incomplete element type size.
1600     uint64_t ArraySize =
1601         (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1602 
1603     StringRef Name = (i == 0) ? Ty->getName() : "";
1604     ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1605     ElementTypeIndex = TypeTable.writeLeafType(AR);
1606   }
1607 
1608   return ElementTypeIndex;
1609 }
1610 
1611 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1612   TypeIndex Index;
1613   dwarf::TypeKind Kind;
1614   uint32_t ByteSize;
1615 
1616   Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
1617   ByteSize = Ty->getSizeInBits() / 8;
1618 
1619   SimpleTypeKind STK = SimpleTypeKind::None;
1620   switch (Kind) {
1621   case dwarf::DW_ATE_address:
1622     // FIXME: Translate
1623     break;
1624   case dwarf::DW_ATE_boolean:
1625     switch (ByteSize) {
1626     case 1:  STK = SimpleTypeKind::Boolean8;   break;
1627     case 2:  STK = SimpleTypeKind::Boolean16;  break;
1628     case 4:  STK = SimpleTypeKind::Boolean32;  break;
1629     case 8:  STK = SimpleTypeKind::Boolean64;  break;
1630     case 16: STK = SimpleTypeKind::Boolean128; break;
1631     }
1632     break;
1633   case dwarf::DW_ATE_complex_float:
1634     switch (ByteSize) {
1635     case 2:  STK = SimpleTypeKind::Complex16;  break;
1636     case 4:  STK = SimpleTypeKind::Complex32;  break;
1637     case 8:  STK = SimpleTypeKind::Complex64;  break;
1638     case 10: STK = SimpleTypeKind::Complex80;  break;
1639     case 16: STK = SimpleTypeKind::Complex128; break;
1640     }
1641     break;
1642   case dwarf::DW_ATE_float:
1643     switch (ByteSize) {
1644     case 2:  STK = SimpleTypeKind::Float16;  break;
1645     case 4:  STK = SimpleTypeKind::Float32;  break;
1646     case 6:  STK = SimpleTypeKind::Float48;  break;
1647     case 8:  STK = SimpleTypeKind::Float64;  break;
1648     case 10: STK = SimpleTypeKind::Float80;  break;
1649     case 16: STK = SimpleTypeKind::Float128; break;
1650     }
1651     break;
1652   case dwarf::DW_ATE_signed:
1653     switch (ByteSize) {
1654     case 1:  STK = SimpleTypeKind::SignedCharacter; break;
1655     case 2:  STK = SimpleTypeKind::Int16Short;      break;
1656     case 4:  STK = SimpleTypeKind::Int32;           break;
1657     case 8:  STK = SimpleTypeKind::Int64Quad;       break;
1658     case 16: STK = SimpleTypeKind::Int128Oct;       break;
1659     }
1660     break;
1661   case dwarf::DW_ATE_unsigned:
1662     switch (ByteSize) {
1663     case 1:  STK = SimpleTypeKind::UnsignedCharacter; break;
1664     case 2:  STK = SimpleTypeKind::UInt16Short;       break;
1665     case 4:  STK = SimpleTypeKind::UInt32;            break;
1666     case 8:  STK = SimpleTypeKind::UInt64Quad;        break;
1667     case 16: STK = SimpleTypeKind::UInt128Oct;        break;
1668     }
1669     break;
1670   case dwarf::DW_ATE_UTF:
1671     switch (ByteSize) {
1672     case 2: STK = SimpleTypeKind::Character16; break;
1673     case 4: STK = SimpleTypeKind::Character32; break;
1674     }
1675     break;
1676   case dwarf::DW_ATE_signed_char:
1677     if (ByteSize == 1)
1678       STK = SimpleTypeKind::SignedCharacter;
1679     break;
1680   case dwarf::DW_ATE_unsigned_char:
1681     if (ByteSize == 1)
1682       STK = SimpleTypeKind::UnsignedCharacter;
1683     break;
1684   default:
1685     break;
1686   }
1687 
1688   // Apply some fixups based on the source-level type name.
1689   if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1690     STK = SimpleTypeKind::Int32Long;
1691   if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1692     STK = SimpleTypeKind::UInt32Long;
1693   if (STK == SimpleTypeKind::UInt16Short &&
1694       (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
1695     STK = SimpleTypeKind::WideCharacter;
1696   if ((STK == SimpleTypeKind::SignedCharacter ||
1697        STK == SimpleTypeKind::UnsignedCharacter) &&
1698       Ty->getName() == "char")
1699     STK = SimpleTypeKind::NarrowCharacter;
1700 
1701   return TypeIndex(STK);
1702 }
1703 
1704 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
1705                                           PointerOptions PO) {
1706   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1707 
1708   // Pointers to simple types without any options can use SimpleTypeMode, rather
1709   // than having a dedicated pointer type record.
1710   if (PointeeTI.isSimple() && PO == PointerOptions::None &&
1711       PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1712       Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1713     SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1714                               ? SimpleTypeMode::NearPointer64
1715                               : SimpleTypeMode::NearPointer32;
1716     return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1717   }
1718 
1719   PointerKind PK =
1720       Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1721   PointerMode PM = PointerMode::Pointer;
1722   switch (Ty->getTag()) {
1723   default: llvm_unreachable("not a pointer tag type");
1724   case dwarf::DW_TAG_pointer_type:
1725     PM = PointerMode::Pointer;
1726     break;
1727   case dwarf::DW_TAG_reference_type:
1728     PM = PointerMode::LValueReference;
1729     break;
1730   case dwarf::DW_TAG_rvalue_reference_type:
1731     PM = PointerMode::RValueReference;
1732     break;
1733   }
1734 
1735   if (Ty->isObjectPointer())
1736     PO |= PointerOptions::Const;
1737 
1738   PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1739   return TypeTable.writeLeafType(PR);
1740 }
1741 
1742 static PointerToMemberRepresentation
1743 translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1744   // SizeInBytes being zero generally implies that the member pointer type was
1745   // incomplete, which can happen if it is part of a function prototype. In this
1746   // case, use the unknown model instead of the general model.
1747   if (IsPMF) {
1748     switch (Flags & DINode::FlagPtrToMemberRep) {
1749     case 0:
1750       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1751                               : PointerToMemberRepresentation::GeneralFunction;
1752     case DINode::FlagSingleInheritance:
1753       return PointerToMemberRepresentation::SingleInheritanceFunction;
1754     case DINode::FlagMultipleInheritance:
1755       return PointerToMemberRepresentation::MultipleInheritanceFunction;
1756     case DINode::FlagVirtualInheritance:
1757       return PointerToMemberRepresentation::VirtualInheritanceFunction;
1758     }
1759   } else {
1760     switch (Flags & DINode::FlagPtrToMemberRep) {
1761     case 0:
1762       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1763                               : PointerToMemberRepresentation::GeneralData;
1764     case DINode::FlagSingleInheritance:
1765       return PointerToMemberRepresentation::SingleInheritanceData;
1766     case DINode::FlagMultipleInheritance:
1767       return PointerToMemberRepresentation::MultipleInheritanceData;
1768     case DINode::FlagVirtualInheritance:
1769       return PointerToMemberRepresentation::VirtualInheritanceData;
1770     }
1771   }
1772   llvm_unreachable("invalid ptr to member representation");
1773 }
1774 
1775 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
1776                                                 PointerOptions PO) {
1777   assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1778   TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
1779   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
1780   PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1781                                                 : PointerKind::Near32;
1782   bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1783   PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1784                          : PointerMode::PointerToDataMember;
1785 
1786   assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1787   uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1788   MemberPointerInfo MPI(
1789       ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
1790   PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
1791   return TypeTable.writeLeafType(PR);
1792 }
1793 
1794 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1795 /// have a translation, use the NearC convention.
1796 static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1797   switch (DwarfCC) {
1798   case dwarf::DW_CC_normal:             return CallingConvention::NearC;
1799   case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1800   case dwarf::DW_CC_BORLAND_thiscall:   return CallingConvention::ThisCall;
1801   case dwarf::DW_CC_BORLAND_stdcall:    return CallingConvention::NearStdCall;
1802   case dwarf::DW_CC_BORLAND_pascal:     return CallingConvention::NearPascal;
1803   case dwarf::DW_CC_LLVM_vectorcall:    return CallingConvention::NearVector;
1804   }
1805   return CallingConvention::NearC;
1806 }
1807 
1808 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1809   ModifierOptions Mods = ModifierOptions::None;
1810   PointerOptions PO = PointerOptions::None;
1811   bool IsModifier = true;
1812   const DIType *BaseTy = Ty;
1813   while (IsModifier && BaseTy) {
1814     // FIXME: Need to add DWARF tags for __unaligned and _Atomic
1815     switch (BaseTy->getTag()) {
1816     case dwarf::DW_TAG_const_type:
1817       Mods |= ModifierOptions::Const;
1818       PO |= PointerOptions::Const;
1819       break;
1820     case dwarf::DW_TAG_volatile_type:
1821       Mods |= ModifierOptions::Volatile;
1822       PO |= PointerOptions::Volatile;
1823       break;
1824     case dwarf::DW_TAG_restrict_type:
1825       // Only pointer types be marked with __restrict. There is no known flag
1826       // for __restrict in LF_MODIFIER records.
1827       PO |= PointerOptions::Restrict;
1828       break;
1829     default:
1830       IsModifier = false;
1831       break;
1832     }
1833     if (IsModifier)
1834       BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType();
1835   }
1836 
1837   // Check if the inner type will use an LF_POINTER record. If so, the
1838   // qualifiers will go in the LF_POINTER record. This comes up for types like
1839   // 'int *const' and 'int *__restrict', not the more common cases like 'const
1840   // char *'.
1841   if (BaseTy) {
1842     switch (BaseTy->getTag()) {
1843     case dwarf::DW_TAG_pointer_type:
1844     case dwarf::DW_TAG_reference_type:
1845     case dwarf::DW_TAG_rvalue_reference_type:
1846       return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
1847     case dwarf::DW_TAG_ptr_to_member_type:
1848       return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
1849     default:
1850       break;
1851     }
1852   }
1853 
1854   TypeIndex ModifiedTI = getTypeIndex(BaseTy);
1855 
1856   // Return the base type index if there aren't any modifiers. For example, the
1857   // metadata could contain restrict wrappers around non-pointer types.
1858   if (Mods == ModifierOptions::None)
1859     return ModifiedTI;
1860 
1861   ModifierRecord MR(ModifiedTI, Mods);
1862   return TypeTable.writeLeafType(MR);
1863 }
1864 
1865 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1866   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1867   for (const DIType *ArgType : Ty->getTypeArray())
1868     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgType));
1869 
1870   // MSVC uses type none for variadic argument.
1871   if (ReturnAndArgTypeIndices.size() > 1 &&
1872       ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1873     ReturnAndArgTypeIndices.back() = TypeIndex::None();
1874   }
1875   TypeIndex ReturnTypeIndex = TypeIndex::Void();
1876   ArrayRef<TypeIndex> ArgTypeIndices = None;
1877   if (!ReturnAndArgTypeIndices.empty()) {
1878     auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1879     ReturnTypeIndex = ReturnAndArgTypesRef.front();
1880     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1881   }
1882 
1883   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1884   TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
1885 
1886   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1887 
1888   FunctionOptions FO = getFunctionOptions(Ty);
1889   ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
1890                             ArgListIndex);
1891   return TypeTable.writeLeafType(Procedure);
1892 }
1893 
1894 TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
1895                                                  const DIType *ClassTy,
1896                                                  int ThisAdjustment,
1897                                                  bool IsStaticMethod,
1898                                                  FunctionOptions FO) {
1899   // Lower the containing class type.
1900   TypeIndex ClassType = getTypeIndex(ClassTy);
1901 
1902   DITypeRefArray ReturnAndArgs = Ty->getTypeArray();
1903 
1904   unsigned Index = 0;
1905   SmallVector<TypeIndex, 8> ArgTypeIndices;
1906   TypeIndex ReturnTypeIndex = TypeIndex::Void();
1907   if (ReturnAndArgs.size() > Index) {
1908     ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]);
1909   }
1910 
1911   // If the first argument is a pointer type and this isn't a static method,
1912   // treat it as the special 'this' parameter, which is encoded separately from
1913   // the arguments.
1914   TypeIndex ThisTypeIndex;
1915   if (!IsStaticMethod && ReturnAndArgs.size() > Index) {
1916     if (const DIDerivedType *PtrTy =
1917             dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index])) {
1918       if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) {
1919         ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty);
1920         Index++;
1921       }
1922     }
1923   }
1924 
1925   while (Index < ReturnAndArgs.size())
1926     ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++]));
1927 
1928   // MSVC uses type none for variadic argument.
1929   if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void())
1930     ArgTypeIndices.back() = TypeIndex::None();
1931 
1932   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1933   TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
1934 
1935   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1936 
1937   MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
1938                            ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
1939   return TypeTable.writeLeafType(MFR);
1940 }
1941 
1942 TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
1943   unsigned VSlotCount =
1944       Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
1945   SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
1946 
1947   VFTableShapeRecord VFTSR(Slots);
1948   return TypeTable.writeLeafType(VFTSR);
1949 }
1950 
1951 static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1952   switch (Flags & DINode::FlagAccessibility) {
1953   case DINode::FlagPrivate:   return MemberAccess::Private;
1954   case DINode::FlagPublic:    return MemberAccess::Public;
1955   case DINode::FlagProtected: return MemberAccess::Protected;
1956   case 0:
1957     // If there was no explicit access control, provide the default for the tag.
1958     return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1959                                                  : MemberAccess::Public;
1960   }
1961   llvm_unreachable("access flags are exclusive");
1962 }
1963 
1964 static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1965   if (SP->isArtificial())
1966     return MethodOptions::CompilerGenerated;
1967 
1968   // FIXME: Handle other MethodOptions.
1969 
1970   return MethodOptions::None;
1971 }
1972 
1973 static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1974                                            bool Introduced) {
1975   if (SP->getFlags() & DINode::FlagStaticMember)
1976     return MethodKind::Static;
1977 
1978   switch (SP->getVirtuality()) {
1979   case dwarf::DW_VIRTUALITY_none:
1980     break;
1981   case dwarf::DW_VIRTUALITY_virtual:
1982     return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1983   case dwarf::DW_VIRTUALITY_pure_virtual:
1984     return Introduced ? MethodKind::PureIntroducingVirtual
1985                       : MethodKind::PureVirtual;
1986   default:
1987     llvm_unreachable("unhandled virtuality case");
1988   }
1989 
1990   return MethodKind::Vanilla;
1991 }
1992 
1993 static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1994   switch (Ty->getTag()) {
1995   case dwarf::DW_TAG_class_type:     return TypeRecordKind::Class;
1996   case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1997   }
1998   llvm_unreachable("unexpected tag");
1999 }
2000 
2001 /// Return ClassOptions that should be present on both the forward declaration
2002 /// and the defintion of a tag type.
2003 static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
2004   ClassOptions CO = ClassOptions::None;
2005 
2006   // MSVC always sets this flag, even for local types. Clang doesn't always
2007   // appear to give every type a linkage name, which may be problematic for us.
2008   // FIXME: Investigate the consequences of not following them here.
2009   if (!Ty->getIdentifier().empty())
2010     CO |= ClassOptions::HasUniqueName;
2011 
2012   // Put the Nested flag on a type if it appears immediately inside a tag type.
2013   // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
2014   // here. That flag is only set on definitions, and not forward declarations.
2015   const DIScope *ImmediateScope = Ty->getScope();
2016   if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
2017     CO |= ClassOptions::Nested;
2018 
2019   // Put the Scoped flag on function-local types. MSVC puts this flag for enum
2020   // type only when it has an immediate function scope. Clang never puts enums
2021   // inside DILexicalBlock scopes. Enum types, as generated by clang, are
2022   // always in function, class, or file scopes.
2023   if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
2024     if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
2025       CO |= ClassOptions::Scoped;
2026   } else {
2027     for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
2028          Scope = Scope->getScope()) {
2029       if (isa<DISubprogram>(Scope)) {
2030         CO |= ClassOptions::Scoped;
2031         break;
2032       }
2033     }
2034   }
2035 
2036   return CO;
2037 }
2038 
2039 void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
2040   switch (Ty->getTag()) {
2041   case dwarf::DW_TAG_class_type:
2042   case dwarf::DW_TAG_structure_type:
2043   case dwarf::DW_TAG_union_type:
2044   case dwarf::DW_TAG_enumeration_type:
2045     break;
2046   default:
2047     return;
2048   }
2049 
2050   if (const auto *File = Ty->getFile()) {
2051     StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
2052     TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
2053 
2054     UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
2055     TypeTable.writeLeafType(USLR);
2056   }
2057 }
2058 
2059 TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
2060   ClassOptions CO = getCommonClassOptions(Ty);
2061   TypeIndex FTI;
2062   unsigned EnumeratorCount = 0;
2063 
2064   if (Ty->isForwardDecl()) {
2065     CO |= ClassOptions::ForwardReference;
2066   } else {
2067     ContinuationRecordBuilder ContinuationBuilder;
2068     ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
2069     for (const DINode *Element : Ty->getElements()) {
2070       // We assume that the frontend provides all members in source declaration
2071       // order, which is what MSVC does.
2072       if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
2073         EnumeratorRecord ER(MemberAccess::Public,
2074                             APSInt::getUnsigned(Enumerator->getValue()),
2075                             Enumerator->getName());
2076         ContinuationBuilder.writeMemberType(ER);
2077         EnumeratorCount++;
2078       }
2079     }
2080     FTI = TypeTable.insertRecord(ContinuationBuilder);
2081   }
2082 
2083   std::string FullName = getFullyQualifiedName(Ty);
2084 
2085   EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
2086                 getTypeIndex(Ty->getBaseType()));
2087   TypeIndex EnumTI = TypeTable.writeLeafType(ER);
2088 
2089   addUDTSrcLine(Ty, EnumTI);
2090 
2091   return EnumTI;
2092 }
2093 
2094 //===----------------------------------------------------------------------===//
2095 // ClassInfo
2096 //===----------------------------------------------------------------------===//
2097 
2098 struct llvm::ClassInfo {
2099   struct MemberInfo {
2100     const DIDerivedType *MemberTypeNode;
2101     uint64_t BaseOffset;
2102   };
2103   // [MemberInfo]
2104   using MemberList = std::vector<MemberInfo>;
2105 
2106   using MethodsList = TinyPtrVector<const DISubprogram *>;
2107   // MethodName -> MethodsList
2108   using MethodsMap = MapVector<MDString *, MethodsList>;
2109 
2110   /// Base classes.
2111   std::vector<const DIDerivedType *> Inheritance;
2112 
2113   /// Direct members.
2114   MemberList Members;
2115   // Direct overloaded methods gathered by name.
2116   MethodsMap Methods;
2117 
2118   TypeIndex VShapeTI;
2119 
2120   std::vector<const DIType *> NestedTypes;
2121 };
2122 
2123 void CodeViewDebug::clear() {
2124   assert(CurFn == nullptr);
2125   FileIdMap.clear();
2126   FnDebugInfo.clear();
2127   FileToFilepathMap.clear();
2128   LocalUDTs.clear();
2129   GlobalUDTs.clear();
2130   TypeIndices.clear();
2131   CompleteTypeIndices.clear();
2132   ScopeGlobals.clear();
2133 }
2134 
2135 void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
2136                                       const DIDerivedType *DDTy) {
2137   if (!DDTy->getName().empty()) {
2138     Info.Members.push_back({DDTy, 0});
2139     return;
2140   }
2141 
2142   // An unnamed member may represent a nested struct or union. Attempt to
2143   // interpret the unnamed member as a DICompositeType possibly wrapped in
2144   // qualifier types. Add all the indirect fields to the current record if that
2145   // succeeds, and drop the member if that fails.
2146   assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
2147   uint64_t Offset = DDTy->getOffsetInBits();
2148   const DIType *Ty = DDTy->getBaseType();
2149   bool FullyResolved = false;
2150   while (!FullyResolved) {
2151     switch (Ty->getTag()) {
2152     case dwarf::DW_TAG_const_type:
2153     case dwarf::DW_TAG_volatile_type:
2154       // FIXME: we should apply the qualifier types to the indirect fields
2155       // rather than dropping them.
2156       Ty = cast<DIDerivedType>(Ty)->getBaseType();
2157       break;
2158     default:
2159       FullyResolved = true;
2160       break;
2161     }
2162   }
2163 
2164   const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
2165   if (!DCTy)
2166     return;
2167 
2168   ClassInfo NestedInfo = collectClassInfo(DCTy);
2169   for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
2170     Info.Members.push_back(
2171         {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
2172 }
2173 
2174 ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
2175   ClassInfo Info;
2176   // Add elements to structure type.
2177   DINodeArray Elements = Ty->getElements();
2178   for (auto *Element : Elements) {
2179     // We assume that the frontend provides all members in source declaration
2180     // order, which is what MSVC does.
2181     if (!Element)
2182       continue;
2183     if (auto *SP = dyn_cast<DISubprogram>(Element)) {
2184       Info.Methods[SP->getRawName()].push_back(SP);
2185     } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
2186       if (DDTy->getTag() == dwarf::DW_TAG_member) {
2187         collectMemberInfo(Info, DDTy);
2188       } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
2189         Info.Inheritance.push_back(DDTy);
2190       } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
2191                  DDTy->getName() == "__vtbl_ptr_type") {
2192         Info.VShapeTI = getTypeIndex(DDTy);
2193       } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
2194         Info.NestedTypes.push_back(DDTy);
2195       } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
2196         // Ignore friend members. It appears that MSVC emitted info about
2197         // friends in the past, but modern versions do not.
2198       }
2199     } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
2200       Info.NestedTypes.push_back(Composite);
2201     }
2202     // Skip other unrecognized kinds of elements.
2203   }
2204   return Info;
2205 }
2206 
2207 static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) {
2208   // This routine is used by lowerTypeClass and lowerTypeUnion to determine
2209   // if a complete type should be emitted instead of a forward reference.
2210   return Ty->getName().empty() && Ty->getIdentifier().empty() &&
2211       !Ty->isForwardDecl();
2212 }
2213 
2214 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
2215   // Emit the complete type for unnamed structs.  C++ classes with methods
2216   // which have a circular reference back to the class type are expected to
2217   // be named by the front-end and should not be "unnamed".  C unnamed
2218   // structs should not have circular references.
2219   if (shouldAlwaysEmitCompleteClassType(Ty)) {
2220     // If this unnamed complete type is already in the process of being defined
2221     // then the description of the type is malformed and cannot be emitted
2222     // into CodeView correctly so report a fatal error.
2223     auto I = CompleteTypeIndices.find(Ty);
2224     if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
2225       report_fatal_error("cannot debug circular reference to unnamed type");
2226     return getCompleteTypeIndex(Ty);
2227   }
2228 
2229   // First, construct the forward decl.  Don't look into Ty to compute the
2230   // forward decl options, since it might not be available in all TUs.
2231   TypeRecordKind Kind = getRecordKind(Ty);
2232   ClassOptions CO =
2233       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2234   std::string FullName = getFullyQualifiedName(Ty);
2235   ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
2236                  FullName, Ty->getIdentifier());
2237   TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
2238   if (!Ty->isForwardDecl())
2239     DeferredCompleteTypes.push_back(Ty);
2240   return FwdDeclTI;
2241 }
2242 
2243 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
2244   // Construct the field list and complete type record.
2245   TypeRecordKind Kind = getRecordKind(Ty);
2246   ClassOptions CO = getCommonClassOptions(Ty);
2247   TypeIndex FieldTI;
2248   TypeIndex VShapeTI;
2249   unsigned FieldCount;
2250   bool ContainsNestedClass;
2251   std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
2252       lowerRecordFieldList(Ty);
2253 
2254   if (ContainsNestedClass)
2255     CO |= ClassOptions::ContainsNestedClass;
2256 
2257   // MSVC appears to set this flag by searching any destructor or method with
2258   // FunctionOptions::Constructor among the emitted members. Clang AST has all
2259   // the members, however special member functions are not yet emitted into
2260   // debug information. For now checking a class's non-triviality seems enough.
2261   // FIXME: not true for a nested unnamed struct.
2262   if (isNonTrivial(Ty))
2263     CO |= ClassOptions::HasConstructorOrDestructor;
2264 
2265   std::string FullName = getFullyQualifiedName(Ty);
2266 
2267   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2268 
2269   ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
2270                  SizeInBytes, FullName, Ty->getIdentifier());
2271   TypeIndex ClassTI = TypeTable.writeLeafType(CR);
2272 
2273   addUDTSrcLine(Ty, ClassTI);
2274 
2275   addToUDTs(Ty);
2276 
2277   return ClassTI;
2278 }
2279 
2280 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
2281   // Emit the complete type for unnamed unions.
2282   if (shouldAlwaysEmitCompleteClassType(Ty))
2283     return getCompleteTypeIndex(Ty);
2284 
2285   ClassOptions CO =
2286       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2287   std::string FullName = getFullyQualifiedName(Ty);
2288   UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
2289   TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
2290   if (!Ty->isForwardDecl())
2291     DeferredCompleteTypes.push_back(Ty);
2292   return FwdDeclTI;
2293 }
2294 
2295 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
2296   ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
2297   TypeIndex FieldTI;
2298   unsigned FieldCount;
2299   bool ContainsNestedClass;
2300   std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
2301       lowerRecordFieldList(Ty);
2302 
2303   if (ContainsNestedClass)
2304     CO |= ClassOptions::ContainsNestedClass;
2305 
2306   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2307   std::string FullName = getFullyQualifiedName(Ty);
2308 
2309   UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
2310                  Ty->getIdentifier());
2311   TypeIndex UnionTI = TypeTable.writeLeafType(UR);
2312 
2313   addUDTSrcLine(Ty, UnionTI);
2314 
2315   addToUDTs(Ty);
2316 
2317   return UnionTI;
2318 }
2319 
2320 std::tuple<TypeIndex, TypeIndex, unsigned, bool>
2321 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
2322   // Manually count members. MSVC appears to count everything that generates a
2323   // field list record. Each individual overload in a method overload group
2324   // contributes to this count, even though the overload group is a single field
2325   // list record.
2326   unsigned MemberCount = 0;
2327   ClassInfo Info = collectClassInfo(Ty);
2328   ContinuationRecordBuilder ContinuationBuilder;
2329   ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
2330 
2331   // Create base classes.
2332   for (const DIDerivedType *I : Info.Inheritance) {
2333     if (I->getFlags() & DINode::FlagVirtual) {
2334       // Virtual base.
2335       unsigned VBPtrOffset = I->getVBPtrOffset();
2336       // FIXME: Despite the accessor name, the offset is really in bytes.
2337       unsigned VBTableIndex = I->getOffsetInBits() / 4;
2338       auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
2339                             ? TypeRecordKind::IndirectVirtualBaseClass
2340                             : TypeRecordKind::VirtualBaseClass;
2341       VirtualBaseClassRecord VBCR(
2342           RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
2343           getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
2344           VBTableIndex);
2345 
2346       ContinuationBuilder.writeMemberType(VBCR);
2347       MemberCount++;
2348     } else {
2349       assert(I->getOffsetInBits() % 8 == 0 &&
2350              "bases must be on byte boundaries");
2351       BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
2352                           getTypeIndex(I->getBaseType()),
2353                           I->getOffsetInBits() / 8);
2354       ContinuationBuilder.writeMemberType(BCR);
2355       MemberCount++;
2356     }
2357   }
2358 
2359   // Create members.
2360   for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
2361     const DIDerivedType *Member = MemberInfo.MemberTypeNode;
2362     TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
2363     StringRef MemberName = Member->getName();
2364     MemberAccess Access =
2365         translateAccessFlags(Ty->getTag(), Member->getFlags());
2366 
2367     if (Member->isStaticMember()) {
2368       StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
2369       ContinuationBuilder.writeMemberType(SDMR);
2370       MemberCount++;
2371       continue;
2372     }
2373 
2374     // Virtual function pointer member.
2375     if ((Member->getFlags() & DINode::FlagArtificial) &&
2376         Member->getName().startswith("_vptr$")) {
2377       VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
2378       ContinuationBuilder.writeMemberType(VFPR);
2379       MemberCount++;
2380       continue;
2381     }
2382 
2383     // Data member.
2384     uint64_t MemberOffsetInBits =
2385         Member->getOffsetInBits() + MemberInfo.BaseOffset;
2386     if (Member->isBitField()) {
2387       uint64_t StartBitOffset = MemberOffsetInBits;
2388       if (const auto *CI =
2389               dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
2390         MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
2391       }
2392       StartBitOffset -= MemberOffsetInBits;
2393       BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2394                          StartBitOffset);
2395       MemberBaseType = TypeTable.writeLeafType(BFR);
2396     }
2397     uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
2398     DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2399                          MemberName);
2400     ContinuationBuilder.writeMemberType(DMR);
2401     MemberCount++;
2402   }
2403 
2404   // Create methods
2405   for (auto &MethodItr : Info.Methods) {
2406     StringRef Name = MethodItr.first->getString();
2407 
2408     std::vector<OneMethodRecord> Methods;
2409     for (const DISubprogram *SP : MethodItr.second) {
2410       TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2411       bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
2412 
2413       unsigned VFTableOffset = -1;
2414       if (Introduced)
2415         VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2416 
2417       Methods.push_back(OneMethodRecord(
2418           MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
2419           translateMethodKindFlags(SP, Introduced),
2420           translateMethodOptionFlags(SP), VFTableOffset, Name));
2421       MemberCount++;
2422     }
2423     assert(!Methods.empty() && "Empty methods map entry");
2424     if (Methods.size() == 1)
2425       ContinuationBuilder.writeMemberType(Methods[0]);
2426     else {
2427       // FIXME: Make this use its own ContinuationBuilder so that
2428       // MethodOverloadList can be split correctly.
2429       MethodOverloadListRecord MOLR(Methods);
2430       TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
2431 
2432       OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
2433       ContinuationBuilder.writeMemberType(OMR);
2434     }
2435   }
2436 
2437   // Create nested classes.
2438   for (const DIType *Nested : Info.NestedTypes) {
2439     NestedTypeRecord R(getTypeIndex(Nested), Nested->getName());
2440     ContinuationBuilder.writeMemberType(R);
2441     MemberCount++;
2442   }
2443 
2444   TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
2445   return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
2446                          !Info.NestedTypes.empty());
2447 }
2448 
2449 TypeIndex CodeViewDebug::getVBPTypeIndex() {
2450   if (!VBPType.getIndex()) {
2451     // Make a 'const int *' type.
2452     ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
2453     TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
2454 
2455     PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2456                                                   : PointerKind::Near32;
2457     PointerMode PM = PointerMode::Pointer;
2458     PointerOptions PO = PointerOptions::None;
2459     PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
2460     VBPType = TypeTable.writeLeafType(PR);
2461   }
2462 
2463   return VBPType;
2464 }
2465 
2466 TypeIndex CodeViewDebug::getTypeIndex(const DIType *Ty, const DIType *ClassTy) {
2467   // The null DIType is the void type. Don't try to hash it.
2468   if (!Ty)
2469     return TypeIndex::Void();
2470 
2471   // Check if we've already translated this type. Don't try to do a
2472   // get-or-create style insertion that caches the hash lookup across the
2473   // lowerType call. It will update the TypeIndices map.
2474   auto I = TypeIndices.find({Ty, ClassTy});
2475   if (I != TypeIndices.end())
2476     return I->second;
2477 
2478   TypeLoweringScope S(*this);
2479   TypeIndex TI = lowerType(Ty, ClassTy);
2480   return recordTypeIndexForDINode(Ty, TI, ClassTy);
2481 }
2482 
2483 codeview::TypeIndex
2484 CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy,
2485                                       const DISubroutineType *SubroutineTy) {
2486   assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type &&
2487          "this type must be a pointer type");
2488 
2489   PointerOptions Options = PointerOptions::None;
2490   if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference)
2491     Options = PointerOptions::LValueRefThisPointer;
2492   else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference)
2493     Options = PointerOptions::RValueRefThisPointer;
2494 
2495   // Check if we've already translated this type.  If there is no ref qualifier
2496   // on the function then we look up this pointer type with no associated class
2497   // so that the TypeIndex for the this pointer can be shared with the type
2498   // index for other pointers to this class type.  If there is a ref qualifier
2499   // then we lookup the pointer using the subroutine as the parent type.
2500   auto I = TypeIndices.find({PtrTy, SubroutineTy});
2501   if (I != TypeIndices.end())
2502     return I->second;
2503 
2504   TypeLoweringScope S(*this);
2505   TypeIndex TI = lowerTypePointer(PtrTy, Options);
2506   return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy);
2507 }
2508 
2509 TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(const DIType *Ty) {
2510   PointerRecord PR(getTypeIndex(Ty),
2511                    getPointerSizeInBytes() == 8 ? PointerKind::Near64
2512                                                 : PointerKind::Near32,
2513                    PointerMode::LValueReference, PointerOptions::None,
2514                    Ty->getSizeInBits() / 8);
2515   return TypeTable.writeLeafType(PR);
2516 }
2517 
2518 TypeIndex CodeViewDebug::getCompleteTypeIndex(const DIType *Ty) {
2519   // The null DIType is the void type. Don't try to hash it.
2520   if (!Ty)
2521     return TypeIndex::Void();
2522 
2523   // Look through typedefs when getting the complete type index. Call
2524   // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are
2525   // emitted only once.
2526   if (Ty->getTag() == dwarf::DW_TAG_typedef)
2527     (void)getTypeIndex(Ty);
2528   while (Ty->getTag() == dwarf::DW_TAG_typedef)
2529     Ty = cast<DIDerivedType>(Ty)->getBaseType();
2530 
2531   // If this is a non-record type, the complete type index is the same as the
2532   // normal type index. Just call getTypeIndex.
2533   switch (Ty->getTag()) {
2534   case dwarf::DW_TAG_class_type:
2535   case dwarf::DW_TAG_structure_type:
2536   case dwarf::DW_TAG_union_type:
2537     break;
2538   default:
2539     return getTypeIndex(Ty);
2540   }
2541 
2542   const auto *CTy = cast<DICompositeType>(Ty);
2543 
2544   TypeLoweringScope S(*this);
2545 
2546   // Make sure the forward declaration is emitted first. It's unclear if this
2547   // is necessary, but MSVC does it, and we should follow suit until we can show
2548   // otherwise.
2549   // We only emit a forward declaration for named types.
2550   if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
2551     TypeIndex FwdDeclTI = getTypeIndex(CTy);
2552 
2553     // Just use the forward decl if we don't have complete type info. This
2554     // might happen if the frontend is using modules and expects the complete
2555     // definition to be emitted elsewhere.
2556     if (CTy->isForwardDecl())
2557       return FwdDeclTI;
2558   }
2559 
2560   // Check if we've already translated the complete record type.
2561   // Insert the type with a null TypeIndex to signify that the type is currently
2562   // being lowered.
2563   auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
2564   if (!InsertResult.second)
2565     return InsertResult.first->second;
2566 
2567   TypeIndex TI;
2568   switch (CTy->getTag()) {
2569   case dwarf::DW_TAG_class_type:
2570   case dwarf::DW_TAG_structure_type:
2571     TI = lowerCompleteTypeClass(CTy);
2572     break;
2573   case dwarf::DW_TAG_union_type:
2574     TI = lowerCompleteTypeUnion(CTy);
2575     break;
2576   default:
2577     llvm_unreachable("not a record");
2578   }
2579 
2580   // Update the type index associated with this CompositeType.  This cannot
2581   // use the 'InsertResult' iterator above because it is potentially
2582   // invalidated by map insertions which can occur while lowering the class
2583   // type above.
2584   CompleteTypeIndices[CTy] = TI;
2585   return TI;
2586 }
2587 
2588 /// Emit all the deferred complete record types. Try to do this in FIFO order,
2589 /// and do this until fixpoint, as each complete record type typically
2590 /// references
2591 /// many other record types.
2592 void CodeViewDebug::emitDeferredCompleteTypes() {
2593   SmallVector<const DICompositeType *, 4> TypesToEmit;
2594   while (!DeferredCompleteTypes.empty()) {
2595     std::swap(DeferredCompleteTypes, TypesToEmit);
2596     for (const DICompositeType *RecordTy : TypesToEmit)
2597       getCompleteTypeIndex(RecordTy);
2598     TypesToEmit.clear();
2599   }
2600 }
2601 
2602 void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
2603                                           ArrayRef<LocalVariable> Locals) {
2604   // Get the sorted list of parameters and emit them first.
2605   SmallVector<const LocalVariable *, 6> Params;
2606   for (const LocalVariable &L : Locals)
2607     if (L.DIVar->isParameter())
2608       Params.push_back(&L);
2609   llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
2610     return L->DIVar->getArg() < R->DIVar->getArg();
2611   });
2612   for (const LocalVariable *L : Params)
2613     emitLocalVariable(FI, *L);
2614 
2615   // Next emit all non-parameters in the order that we found them.
2616   for (const LocalVariable &L : Locals)
2617     if (!L.DIVar->isParameter())
2618       emitLocalVariable(FI, L);
2619 }
2620 
2621 void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
2622                                       const LocalVariable &Var) {
2623   // LocalSym record, see SymbolRecord.h for more info.
2624   MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL);
2625 
2626   LocalSymFlags Flags = LocalSymFlags::None;
2627   if (Var.DIVar->isParameter())
2628     Flags |= LocalSymFlags::IsParameter;
2629   if (Var.DefRanges.empty())
2630     Flags |= LocalSymFlags::IsOptimizedOut;
2631 
2632   OS.AddComment("TypeIndex");
2633   TypeIndex TI = Var.UseReferenceType
2634                      ? getTypeIndexForReferenceTo(Var.DIVar->getType())
2635                      : getCompleteTypeIndex(Var.DIVar->getType());
2636   OS.EmitIntValue(TI.getIndex(), 4);
2637   OS.AddComment("Flags");
2638   OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
2639   // Truncate the name so we won't overflow the record length field.
2640   emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
2641   endSymbolRecord(LocalEnd);
2642 
2643   // Calculate the on disk prefix of the appropriate def range record. The
2644   // records and on disk formats are described in SymbolRecords.h. BytePrefix
2645   // should be big enough to hold all forms without memory allocation.
2646   SmallString<20> BytePrefix;
2647   for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2648     BytePrefix.clear();
2649     if (DefRange.InMemory) {
2650       int Offset = DefRange.DataOffset;
2651       unsigned Reg = DefRange.CVRegister;
2652 
2653       // 32-bit x86 call sequences often use PUSH instructions, which disrupt
2654       // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
2655       // instead. In frames without stack realignment, $T0 will be the CFA.
2656       if (RegisterId(Reg) == RegisterId::ESP) {
2657         Reg = unsigned(RegisterId::VFRAME);
2658         Offset += FI.OffsetAdjustment;
2659       }
2660 
2661       // If we can use the chosen frame pointer for the frame and this isn't a
2662       // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
2663       // Otherwise, use S_DEFRANGE_REGISTER_REL.
2664       EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU);
2665       if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
2666           (bool(Flags & LocalSymFlags::IsParameter)
2667                ? (EncFP == FI.EncodedParamFramePtrReg)
2668                : (EncFP == FI.EncodedLocalFramePtrReg))) {
2669         DefRangeFramePointerRelHeader DRHdr;
2670         DRHdr.Offset = Offset;
2671         OS.EmitCVDefRangeDirective(DefRange.Ranges, DRHdr);
2672       } else {
2673         uint16_t RegRelFlags = 0;
2674         if (DefRange.IsSubfield) {
2675           RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2676                         (DefRange.StructOffset
2677                          << DefRangeRegisterRelSym::OffsetInParentShift);
2678         }
2679         DefRangeRegisterRelHeader DRHdr;
2680         DRHdr.Register = Reg;
2681         DRHdr.Flags = RegRelFlags;
2682         DRHdr.BasePointerOffset = Offset;
2683         OS.EmitCVDefRangeDirective(DefRange.Ranges, DRHdr);
2684       }
2685     } else {
2686       assert(DefRange.DataOffset == 0 && "unexpected offset into register");
2687       if (DefRange.IsSubfield) {
2688         DefRangeSubfieldRegisterHeader DRHdr;
2689         DRHdr.Register = DefRange.CVRegister;
2690         DRHdr.MayHaveNoName = 0;
2691         DRHdr.OffsetInParent = DefRange.StructOffset;
2692         OS.EmitCVDefRangeDirective(DefRange.Ranges, DRHdr);
2693       } else {
2694         DefRangeRegisterHeader DRHdr;
2695         DRHdr.Register = DefRange.CVRegister;
2696         DRHdr.MayHaveNoName = 0;
2697         OS.EmitCVDefRangeDirective(DefRange.Ranges, DRHdr);
2698       }
2699     }
2700   }
2701 }
2702 
2703 void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
2704                                          const FunctionInfo& FI) {
2705   for (LexicalBlock *Block : Blocks)
2706     emitLexicalBlock(*Block, FI);
2707 }
2708 
2709 /// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
2710 /// lexical block scope.
2711 void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
2712                                      const FunctionInfo& FI) {
2713   MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32);
2714   OS.AddComment("PtrParent");
2715   OS.EmitIntValue(0, 4);                                  // PtrParent
2716   OS.AddComment("PtrEnd");
2717   OS.EmitIntValue(0, 4);                                  // PtrEnd
2718   OS.AddComment("Code size");
2719   OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4);   // Code Size
2720   OS.AddComment("Function section relative address");
2721   OS.EmitCOFFSecRel32(Block.Begin, /*Offset=*/0);         // Func Offset
2722   OS.AddComment("Function section index");
2723   OS.EmitCOFFSectionIndex(FI.Begin);                      // Func Symbol
2724   OS.AddComment("Lexical block name");
2725   emitNullTerminatedSymbolName(OS, Block.Name);           // Name
2726   endSymbolRecord(RecordEnd);
2727 
2728   // Emit variables local to this lexical block.
2729   emitLocalVariableList(FI, Block.Locals);
2730   emitGlobalVariableList(Block.Globals);
2731 
2732   // Emit lexical blocks contained within this block.
2733   emitLexicalBlockList(Block.Children, FI);
2734 
2735   // Close the lexical block scope.
2736   emitEndSymbolRecord(SymbolKind::S_END);
2737 }
2738 
2739 /// Convenience routine for collecting lexical block information for a list
2740 /// of lexical scopes.
2741 void CodeViewDebug::collectLexicalBlockInfo(
2742         SmallVectorImpl<LexicalScope *> &Scopes,
2743         SmallVectorImpl<LexicalBlock *> &Blocks,
2744         SmallVectorImpl<LocalVariable> &Locals,
2745         SmallVectorImpl<CVGlobalVariable> &Globals) {
2746   for (LexicalScope *Scope : Scopes)
2747     collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals);
2748 }
2749 
2750 /// Populate the lexical blocks and local variable lists of the parent with
2751 /// information about the specified lexical scope.
2752 void CodeViewDebug::collectLexicalBlockInfo(
2753     LexicalScope &Scope,
2754     SmallVectorImpl<LexicalBlock *> &ParentBlocks,
2755     SmallVectorImpl<LocalVariable> &ParentLocals,
2756     SmallVectorImpl<CVGlobalVariable> &ParentGlobals) {
2757   if (Scope.isAbstractScope())
2758     return;
2759 
2760   // Gather information about the lexical scope including local variables,
2761   // global variables, and address ranges.
2762   bool IgnoreScope = false;
2763   auto LI = ScopeVariables.find(&Scope);
2764   SmallVectorImpl<LocalVariable> *Locals =
2765       LI != ScopeVariables.end() ? &LI->second : nullptr;
2766   auto GI = ScopeGlobals.find(Scope.getScopeNode());
2767   SmallVectorImpl<CVGlobalVariable> *Globals =
2768       GI != ScopeGlobals.end() ? GI->second.get() : nullptr;
2769   const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
2770   const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
2771 
2772   // Ignore lexical scopes which do not contain variables.
2773   if (!Locals && !Globals)
2774     IgnoreScope = true;
2775 
2776   // Ignore lexical scopes which are not lexical blocks.
2777   if (!DILB)
2778     IgnoreScope = true;
2779 
2780   // Ignore scopes which have too many address ranges to represent in the
2781   // current CodeView format or do not have a valid address range.
2782   //
2783   // For lexical scopes with multiple address ranges you may be tempted to
2784   // construct a single range covering every instruction where the block is
2785   // live and everything in between.  Unfortunately, Visual Studio only
2786   // displays variables from the first matching lexical block scope.  If the
2787   // first lexical block contains exception handling code or cold code which
2788   // is moved to the bottom of the routine creating a single range covering
2789   // nearly the entire routine, then it will hide all other lexical blocks
2790   // and the variables they contain.
2791   if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second))
2792     IgnoreScope = true;
2793 
2794   if (IgnoreScope) {
2795     // This scope can be safely ignored and eliminating it will reduce the
2796     // size of the debug information. Be sure to collect any variable and scope
2797     // information from the this scope or any of its children and collapse them
2798     // into the parent scope.
2799     if (Locals)
2800       ParentLocals.append(Locals->begin(), Locals->end());
2801     if (Globals)
2802       ParentGlobals.append(Globals->begin(), Globals->end());
2803     collectLexicalBlockInfo(Scope.getChildren(),
2804                             ParentBlocks,
2805                             ParentLocals,
2806                             ParentGlobals);
2807     return;
2808   }
2809 
2810   // Create a new CodeView lexical block for this lexical scope.  If we've
2811   // seen this DILexicalBlock before then the scope tree is malformed and
2812   // we can handle this gracefully by not processing it a second time.
2813   auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
2814   if (!BlockInsertion.second)
2815     return;
2816 
2817   // Create a lexical block containing the variables and collect the the
2818   // lexical block information for the children.
2819   const InsnRange &Range = Ranges.front();
2820   assert(Range.first && Range.second);
2821   LexicalBlock &Block = BlockInsertion.first->second;
2822   Block.Begin = getLabelBeforeInsn(Range.first);
2823   Block.End = getLabelAfterInsn(Range.second);
2824   assert(Block.Begin && "missing label for scope begin");
2825   assert(Block.End && "missing label for scope end");
2826   Block.Name = DILB->getName();
2827   if (Locals)
2828     Block.Locals = std::move(*Locals);
2829   if (Globals)
2830     Block.Globals = std::move(*Globals);
2831   ParentBlocks.push_back(&Block);
2832   collectLexicalBlockInfo(Scope.getChildren(),
2833                           Block.Children,
2834                           Block.Locals,
2835                           Block.Globals);
2836 }
2837 
2838 void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
2839   const Function &GV = MF->getFunction();
2840   assert(FnDebugInfo.count(&GV));
2841   assert(CurFn == FnDebugInfo[&GV].get());
2842 
2843   collectVariableInfo(GV.getSubprogram());
2844 
2845   // Build the lexical block structure to emit for this routine.
2846   if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
2847     collectLexicalBlockInfo(*CFS,
2848                             CurFn->ChildBlocks,
2849                             CurFn->Locals,
2850                             CurFn->Globals);
2851 
2852   // Clear the scope and variable information from the map which will not be
2853   // valid after we have finished processing this routine.  This also prepares
2854   // the map for the subsequent routine.
2855   ScopeVariables.clear();
2856 
2857   // Don't emit anything if we don't have any line tables.
2858   // Thunks are compiler-generated and probably won't have source correlation.
2859   if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
2860     FnDebugInfo.erase(&GV);
2861     CurFn = nullptr;
2862     return;
2863   }
2864 
2865   // Find heap alloc sites and add to list.
2866   for (const auto &MBB : *MF) {
2867     for (const auto &MI : MBB) {
2868       if (MDNode *MD = MI.getHeapAllocMarker()) {
2869         CurFn->HeapAllocSites.push_back(std::make_tuple(getLabelBeforeInsn(&MI),
2870                                                         getLabelAfterInsn(&MI),
2871                                                         dyn_cast<DIType>(MD)));
2872       }
2873     }
2874   }
2875 
2876   CurFn->Annotations = MF->getCodeViewAnnotations();
2877 
2878   CurFn->End = Asm->getFunctionEnd();
2879 
2880   CurFn = nullptr;
2881 }
2882 
2883 // Usable locations are valid with non-zero line numbers. A line number of zero
2884 // corresponds to optimized code that doesn't have a distinct source location.
2885 // In this case, we try to use the previous or next source location depending on
2886 // the context.
2887 static bool isUsableDebugLoc(DebugLoc DL) {
2888   return DL && DL.getLine() != 0;
2889 }
2890 
2891 void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
2892   DebugHandlerBase::beginInstruction(MI);
2893 
2894   // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
2895   if (!Asm || !CurFn || MI->isDebugInstr() ||
2896       MI->getFlag(MachineInstr::FrameSetup))
2897     return;
2898 
2899   // If the first instruction of a new MBB has no location, find the first
2900   // instruction with a location and use that.
2901   DebugLoc DL = MI->getDebugLoc();
2902   if (!isUsableDebugLoc(DL) && MI->getParent() != PrevInstBB) {
2903     for (const auto &NextMI : *MI->getParent()) {
2904       if (NextMI.isDebugInstr())
2905         continue;
2906       DL = NextMI.getDebugLoc();
2907       if (isUsableDebugLoc(DL))
2908         break;
2909     }
2910     // FIXME: Handle the case where the BB has no valid locations. This would
2911     // probably require doing a real dataflow analysis.
2912   }
2913   PrevInstBB = MI->getParent();
2914 
2915   // If we still don't have a debug location, don't record a location.
2916   if (!isUsableDebugLoc(DL))
2917     return;
2918 
2919   maybeRecordLocation(DL, Asm->MF);
2920 }
2921 
2922 MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
2923   MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2924            *EndLabel = MMI->getContext().createTempSymbol();
2925   OS.EmitIntValue(unsigned(Kind), 4);
2926   OS.AddComment("Subsection size");
2927   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2928   OS.EmitLabel(BeginLabel);
2929   return EndLabel;
2930 }
2931 
2932 void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2933   OS.EmitLabel(EndLabel);
2934   // Every subsection must be aligned to a 4-byte boundary.
2935   OS.EmitValueToAlignment(4);
2936 }
2937 
2938 static StringRef getSymbolName(SymbolKind SymKind) {
2939   for (const EnumEntry<SymbolKind> &EE : getSymbolTypeNames())
2940     if (EE.Value == SymKind)
2941       return EE.Name;
2942   return "";
2943 }
2944 
2945 MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) {
2946   MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2947            *EndLabel = MMI->getContext().createTempSymbol();
2948   OS.AddComment("Record length");
2949   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
2950   OS.EmitLabel(BeginLabel);
2951   if (OS.isVerboseAsm())
2952     OS.AddComment("Record kind: " + getSymbolName(SymKind));
2953   OS.EmitIntValue(unsigned(SymKind), 2);
2954   return EndLabel;
2955 }
2956 
2957 void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) {
2958   // MSVC does not pad out symbol records to four bytes, but LLVM does to avoid
2959   // an extra copy of every symbol record in LLD. This increases object file
2960   // size by less than 1% in the clang build, and is compatible with the Visual
2961   // C++ linker.
2962   OS.EmitValueToAlignment(4);
2963   OS.EmitLabel(SymEnd);
2964 }
2965 
2966 void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) {
2967   OS.AddComment("Record length");
2968   OS.EmitIntValue(2, 2);
2969   if (OS.isVerboseAsm())
2970     OS.AddComment("Record kind: " + getSymbolName(EndKind));
2971   OS.EmitIntValue(unsigned(EndKind), 2); // Record Kind
2972 }
2973 
2974 void CodeViewDebug::emitDebugInfoForUDTs(
2975     ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
2976   for (const auto &UDT : UDTs) {
2977     const DIType *T = UDT.second;
2978     assert(shouldEmitUdt(T));
2979 
2980     MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT);
2981     OS.AddComment("Type");
2982     OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
2983     emitNullTerminatedSymbolName(OS, UDT.first);
2984     endSymbolRecord(UDTRecordEnd);
2985   }
2986 }
2987 
2988 void CodeViewDebug::collectGlobalVariableInfo() {
2989   DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2990       GlobalMap;
2991   for (const GlobalVariable &GV : MMI->getModule()->globals()) {
2992     SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2993     GV.getDebugInfo(GVEs);
2994     for (const auto *GVE : GVEs)
2995       GlobalMap[GVE] = &GV;
2996   }
2997 
2998   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2999   for (const MDNode *Node : CUs->operands()) {
3000     const auto *CU = cast<DICompileUnit>(Node);
3001     for (const auto *GVE : CU->getGlobalVariables()) {
3002       const DIGlobalVariable *DIGV = GVE->getVariable();
3003       const DIExpression *DIE = GVE->getExpression();
3004 
3005       // Emit constant global variables in a global symbol section.
3006       if (GlobalMap.count(GVE) == 0 && DIE->isConstant()) {
3007         CVGlobalVariable CVGV = {DIGV, DIE};
3008         GlobalVariables.emplace_back(std::move(CVGV));
3009       }
3010 
3011       const auto *GV = GlobalMap.lookup(GVE);
3012       if (!GV || GV->isDeclarationForLinker())
3013         continue;
3014 
3015       DIScope *Scope = DIGV->getScope();
3016       SmallVector<CVGlobalVariable, 1> *VariableList;
3017       if (Scope && isa<DILocalScope>(Scope)) {
3018         // Locate a global variable list for this scope, creating one if
3019         // necessary.
3020         auto Insertion = ScopeGlobals.insert(
3021             {Scope, std::unique_ptr<GlobalVariableList>()});
3022         if (Insertion.second)
3023           Insertion.first->second = std::make_unique<GlobalVariableList>();
3024         VariableList = Insertion.first->second.get();
3025       } else if (GV->hasComdat())
3026         // Emit this global variable into a COMDAT section.
3027         VariableList = &ComdatVariables;
3028       else
3029         // Emit this global variable in a single global symbol section.
3030         VariableList = &GlobalVariables;
3031       CVGlobalVariable CVGV = {DIGV, GV};
3032       VariableList->emplace_back(std::move(CVGV));
3033     }
3034   }
3035 }
3036 
3037 void CodeViewDebug::emitDebugInfoForGlobals() {
3038   // First, emit all globals that are not in a comdat in a single symbol
3039   // substream. MSVC doesn't like it if the substream is empty, so only open
3040   // it if we have at least one global to emit.
3041   switchToDebugSectionForSymbol(nullptr);
3042   if (!GlobalVariables.empty()) {
3043     OS.AddComment("Symbol subsection for globals");
3044     MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
3045     emitGlobalVariableList(GlobalVariables);
3046     endCVSubsection(EndLabel);
3047   }
3048 
3049   // Second, emit each global that is in a comdat into its own .debug$S
3050   // section along with its own symbol substream.
3051   for (const CVGlobalVariable &CVGV : ComdatVariables) {
3052     const GlobalVariable *GV = CVGV.GVInfo.get<const GlobalVariable *>();
3053     MCSymbol *GVSym = Asm->getSymbol(GV);
3054     OS.AddComment("Symbol subsection for " +
3055                   Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
3056     switchToDebugSectionForSymbol(GVSym);
3057     MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
3058     // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3059     emitDebugInfoForGlobal(CVGV);
3060     endCVSubsection(EndLabel);
3061   }
3062 }
3063 
3064 void CodeViewDebug::emitDebugInfoForRetainedTypes() {
3065   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
3066   for (const MDNode *Node : CUs->operands()) {
3067     for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
3068       if (DIType *RT = dyn_cast<DIType>(Ty)) {
3069         getTypeIndex(RT);
3070         // FIXME: Add to global/local DTU list.
3071       }
3072     }
3073   }
3074 }
3075 
3076 // Emit each global variable in the specified array.
3077 void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) {
3078   for (const CVGlobalVariable &CVGV : Globals) {
3079     // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3080     emitDebugInfoForGlobal(CVGV);
3081   }
3082 }
3083 
3084 void CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable &CVGV) {
3085   const DIGlobalVariable *DIGV = CVGV.DIGV;
3086   if (const GlobalVariable *GV =
3087           CVGV.GVInfo.dyn_cast<const GlobalVariable *>()) {
3088     // DataSym record, see SymbolRecord.h for more info. Thread local data
3089     // happens to have the same format as global data.
3090     MCSymbol *GVSym = Asm->getSymbol(GV);
3091     SymbolKind DataSym = GV->isThreadLocal()
3092                              ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32
3093                                                       : SymbolKind::S_GTHREAD32)
3094                              : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32
3095                                                       : SymbolKind::S_GDATA32);
3096     MCSymbol *DataEnd = beginSymbolRecord(DataSym);
3097     OS.AddComment("Type");
3098     OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
3099     OS.AddComment("DataOffset");
3100     OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
3101     OS.AddComment("Segment");
3102     OS.EmitCOFFSectionIndex(GVSym);
3103     OS.AddComment("Name");
3104     const unsigned LengthOfDataRecord = 12;
3105     emitNullTerminatedSymbolName(OS, DIGV->getName(), LengthOfDataRecord);
3106     endSymbolRecord(DataEnd);
3107   } else {
3108     // FIXME: Currently this only emits the global variables in the IR metadata.
3109     // This should also emit enums and static data members.
3110     const DIExpression *DIE = CVGV.GVInfo.get<const DIExpression *>();
3111     assert(DIE->isConstant() &&
3112            "Global constant variables must contain a constant expression.");
3113     uint64_t Val = DIE->getElement(1);
3114 
3115     MCSymbol *SConstantEnd = beginSymbolRecord(SymbolKind::S_CONSTANT);
3116     OS.AddComment("Type");
3117     OS.EmitIntValue(getTypeIndex(DIGV->getType()).getIndex(), 4);
3118     OS.AddComment("Value");
3119 
3120     // Encoded integers shouldn't need more than 10 bytes.
3121     uint8_t data[10];
3122     BinaryStreamWriter Writer(data, llvm::support::endianness::little);
3123     CodeViewRecordIO IO(Writer);
3124     cantFail(IO.mapEncodedInteger(Val));
3125     StringRef SRef((char *)data, Writer.getOffset());
3126     OS.EmitBinaryData(SRef);
3127 
3128     OS.AddComment("Name");
3129     const DIScope *Scope = DIGV->getScope();
3130     // For static data members, get the scope from the declaration.
3131     if (const auto *MemberDecl = dyn_cast_or_null<DIDerivedType>(
3132             DIGV->getRawStaticDataMemberDeclaration()))
3133       Scope = MemberDecl->getScope();
3134     emitNullTerminatedSymbolName(OS,
3135                                  getFullyQualifiedName(Scope, DIGV->getName()));
3136     endSymbolRecord(SConstantEnd);
3137   }
3138 }
3139