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