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