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