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