1 //===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing Microsoft CodeView debug info.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeViewDebug.h"
15 #include "DwarfExpression.h"
16 #include "llvm/ADT/APSInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/MapVector.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/TinyPtrVector.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/BinaryFormat/COFF.h"
31 #include "llvm/BinaryFormat/Dwarf.h"
32 #include "llvm/CodeGen/AsmPrinter.h"
33 #include "llvm/CodeGen/LexicalScopes.h"
34 #include "llvm/CodeGen/MachineFunction.h"
35 #include "llvm/CodeGen/MachineInstr.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineOperand.h"
38 #include "llvm/CodeGen/TargetFrameLowering.h"
39 #include "llvm/CodeGen/TargetLoweringObjectFile.h"
40 #include "llvm/CodeGen/TargetRegisterInfo.h"
41 #include "llvm/CodeGen/TargetSubtargetInfo.h"
42 #include "llvm/Config/llvm-config.h"
43 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
44 #include "llvm/DebugInfo/CodeView/CodeView.h"
45 #include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h"
46 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
47 #include "llvm/DebugInfo/CodeView/Line.h"
48 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
49 #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
50 #include "llvm/DebugInfo/CodeView/TypeIndex.h"
51 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
52 #include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
53 #include "llvm/IR/Constants.h"
54 #include "llvm/IR/DataLayout.h"
55 #include "llvm/IR/DebugInfoMetadata.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/Function.h"
58 #include "llvm/IR/GlobalValue.h"
59 #include "llvm/IR/GlobalVariable.h"
60 #include "llvm/IR/Metadata.h"
61 #include "llvm/IR/Module.h"
62 #include "llvm/MC/MCAsmInfo.h"
63 #include "llvm/MC/MCContext.h"
64 #include "llvm/MC/MCSectionCOFF.h"
65 #include "llvm/MC/MCStreamer.h"
66 #include "llvm/MC/MCSymbol.h"
67 #include "llvm/Support/BinaryByteStream.h"
68 #include "llvm/Support/BinaryStreamReader.h"
69 #include "llvm/Support/Casting.h"
70 #include "llvm/Support/CommandLine.h"
71 #include "llvm/Support/Compiler.h"
72 #include "llvm/Support/Endian.h"
73 #include "llvm/Support/Error.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/FormatVariadic.h"
76 #include "llvm/Support/SMLoc.h"
77 #include "llvm/Support/ScopedPrinter.h"
78 #include "llvm/Target/TargetMachine.h"
79 #include <algorithm>
80 #include <cassert>
81 #include <cctype>
82 #include <cstddef>
83 #include <cstdint>
84 #include <iterator>
85 #include <limits>
86 #include <string>
87 #include <utility>
88 #include <vector>
89 
90 using namespace llvm;
91 using namespace llvm::codeview;
92 
93 static cl::opt<bool> EmitDebugGlobalHashes("emit-codeview-ghash-section",
94                                            cl::ReallyHidden, cl::init(false));
95 
96 CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
97     : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {
98   // If module doesn't have named metadata anchors or COFF debug section
99   // is not available, skip any debug info related stuff.
100   if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
101       !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
102     Asm = nullptr;
103     return;
104   }
105 
106   // Tell MMI that we have debug info.
107   MMI->setDebugInfoAvailability(true);
108 }
109 
110 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
111   std::string &Filepath = FileToFilepathMap[File];
112   if (!Filepath.empty())
113     return Filepath;
114 
115   StringRef Dir = File->getDirectory(), Filename = File->getFilename();
116 
117   // Clang emits directory and relative filename info into the IR, but CodeView
118   // operates on full paths.  We could change Clang to emit full paths too, but
119   // that would increase the IR size and probably not needed for other users.
120   // For now, just concatenate and canonicalize the path here.
121   if (Filename.find(':') == 1)
122     Filepath = Filename;
123   else
124     Filepath = (Dir + "\\" + Filename).str();
125 
126   // Canonicalize the path.  We have to do it textually because we may no longer
127   // have access the file in the filesystem.
128   // First, replace all slashes with backslashes.
129   std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
130 
131   // Remove all "\.\" with "\".
132   size_t Cursor = 0;
133   while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
134     Filepath.erase(Cursor, 2);
135 
136   // Replace all "\XXX\..\" with "\".  Don't try too hard though as the original
137   // path should be well-formatted, e.g. start with a drive letter, etc.
138   Cursor = 0;
139   while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
140     // Something's wrong if the path starts with "\..\", abort.
141     if (Cursor == 0)
142       break;
143 
144     size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
145     if (PrevSlash == std::string::npos)
146       // Something's wrong, abort.
147       break;
148 
149     Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
150     // The next ".." might be following the one we've just erased.
151     Cursor = PrevSlash;
152   }
153 
154   // Remove all duplicate backslashes.
155   Cursor = 0;
156   while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
157     Filepath.erase(Cursor, 1);
158 
159   return Filepath;
160 }
161 
162 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
163   StringRef FullPath = getFullFilepath(F);
164   unsigned NextId = FileIdMap.size() + 1;
165   auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
166   if (Insertion.second) {
167     // We have to compute the full filepath and emit a .cv_file directive.
168     ArrayRef<uint8_t> ChecksumAsBytes;
169     FileChecksumKind CSKind = FileChecksumKind::None;
170     if (F->getChecksum()) {
171       std::string Checksum = fromHex(F->getChecksum()->Value);
172       void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
173       memcpy(CKMem, Checksum.data(), Checksum.size());
174       ChecksumAsBytes = ArrayRef<uint8_t>(
175           reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
176       switch (F->getChecksum()->Kind) {
177       case DIFile::CSK_MD5:  CSKind = FileChecksumKind::MD5; break;
178       case DIFile::CSK_SHA1: CSKind = FileChecksumKind::SHA1; break;
179       }
180     }
181     bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
182                                           static_cast<unsigned>(CSKind));
183     (void)Success;
184     assert(Success && ".cv_file directive failed");
185   }
186   return Insertion.first->second;
187 }
188 
189 CodeViewDebug::InlineSite &
190 CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
191                              const DISubprogram *Inlinee) {
192   auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
193   InlineSite *Site = &SiteInsertion.first->second;
194   if (SiteInsertion.second) {
195     unsigned ParentFuncId = CurFn->FuncId;
196     if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
197       ParentFuncId =
198           getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
199               .SiteFuncId;
200 
201     Site->SiteFuncId = NextFuncId++;
202     OS.EmitCVInlineSiteIdDirective(
203         Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
204         InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
205     Site->Inlinee = Inlinee;
206     InlinedSubprograms.insert(Inlinee);
207     getFuncIdForSubprogram(Inlinee);
208   }
209   return *Site;
210 }
211 
212 static StringRef getPrettyScopeName(const DIScope *Scope) {
213   StringRef ScopeName = Scope->getName();
214   if (!ScopeName.empty())
215     return ScopeName;
216 
217   switch (Scope->getTag()) {
218   case dwarf::DW_TAG_enumeration_type:
219   case dwarf::DW_TAG_class_type:
220   case dwarf::DW_TAG_structure_type:
221   case dwarf::DW_TAG_union_type:
222     return "<unnamed-tag>";
223   case dwarf::DW_TAG_namespace:
224     return "`anonymous namespace'";
225   }
226 
227   return StringRef();
228 }
229 
230 static const DISubprogram *getQualifiedNameComponents(
231     const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
232   const DISubprogram *ClosestSubprogram = nullptr;
233   while (Scope != nullptr) {
234     if (ClosestSubprogram == nullptr)
235       ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
236     StringRef ScopeName = getPrettyScopeName(Scope);
237     if (!ScopeName.empty())
238       QualifiedNameComponents.push_back(ScopeName);
239     Scope = Scope->getScope().resolve();
240   }
241   return ClosestSubprogram;
242 }
243 
244 static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
245                                     StringRef TypeName) {
246   std::string FullyQualifiedName;
247   for (StringRef QualifiedNameComponent :
248        llvm::reverse(QualifiedNameComponents)) {
249     FullyQualifiedName.append(QualifiedNameComponent);
250     FullyQualifiedName.append("::");
251   }
252   FullyQualifiedName.append(TypeName);
253   return FullyQualifiedName;
254 }
255 
256 static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
257   SmallVector<StringRef, 5> QualifiedNameComponents;
258   getQualifiedNameComponents(Scope, QualifiedNameComponents);
259   return getQualifiedName(QualifiedNameComponents, Name);
260 }
261 
262 struct CodeViewDebug::TypeLoweringScope {
263   TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
264   ~TypeLoweringScope() {
265     // Don't decrement TypeEmissionLevel until after emitting deferred types, so
266     // inner TypeLoweringScopes don't attempt to emit deferred types.
267     if (CVD.TypeEmissionLevel == 1)
268       CVD.emitDeferredCompleteTypes();
269     --CVD.TypeEmissionLevel;
270   }
271   CodeViewDebug &CVD;
272 };
273 
274 static std::string getFullyQualifiedName(const DIScope *Ty) {
275   const DIScope *Scope = Ty->getScope().resolve();
276   return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
277 }
278 
279 TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
280   // No scope means global scope and that uses the zero index.
281   if (!Scope || isa<DIFile>(Scope))
282     return TypeIndex();
283 
284   assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
285 
286   // Check if we've already translated this scope.
287   auto I = TypeIndices.find({Scope, nullptr});
288   if (I != TypeIndices.end())
289     return I->second;
290 
291   // Build the fully qualified name of the scope.
292   std::string ScopeName = getFullyQualifiedName(Scope);
293   StringIdRecord SID(TypeIndex(), ScopeName);
294   auto TI = TypeTable.writeLeafType(SID);
295   return recordTypeIndexForDINode(Scope, TI);
296 }
297 
298 TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
299   assert(SP);
300 
301   // Check if we've already translated this subprogram.
302   auto I = TypeIndices.find({SP, nullptr});
303   if (I != TypeIndices.end())
304     return I->second;
305 
306   // The display name includes function template arguments. Drop them to match
307   // MSVC.
308   StringRef DisplayName = SP->getName().split('<').first;
309 
310   const DIScope *Scope = SP->getScope().resolve();
311   TypeIndex TI;
312   if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
313     // If the scope is a DICompositeType, then this must be a method. Member
314     // function types take some special handling, and require access to the
315     // subprogram.
316     TypeIndex ClassType = getTypeIndex(Class);
317     MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
318                                DisplayName);
319     TI = TypeTable.writeLeafType(MFuncId);
320   } else {
321     // Otherwise, this must be a free function.
322     TypeIndex ParentScope = getScopeIndex(Scope);
323     FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
324     TI = TypeTable.writeLeafType(FuncId);
325   }
326 
327   return recordTypeIndexForDINode(SP, TI);
328 }
329 
330 TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
331                                                const DICompositeType *Class) {
332   // Always use the method declaration as the key for the function type. The
333   // method declaration contains the this adjustment.
334   if (SP->getDeclaration())
335     SP = SP->getDeclaration();
336   assert(!SP->getDeclaration() && "should use declaration as key");
337 
338   // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
339   // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
340   auto I = TypeIndices.find({SP, Class});
341   if (I != TypeIndices.end())
342     return I->second;
343 
344   // Make sure complete type info for the class is emitted *after* the member
345   // function type, as the complete class type is likely to reference this
346   // member function type.
347   TypeLoweringScope S(*this);
348   const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
349   TypeIndex TI = lowerTypeMemberFunction(
350       SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod);
351   return recordTypeIndexForDINode(SP, TI, Class);
352 }
353 
354 TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
355                                                   TypeIndex TI,
356                                                   const DIType *ClassTy) {
357   auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
358   (void)InsertResult;
359   assert(InsertResult.second && "DINode was already assigned a type index");
360   return TI;
361 }
362 
363 unsigned CodeViewDebug::getPointerSizeInBytes() {
364   return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
365 }
366 
367 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
368                                         const DILocation *InlinedAt) {
369   if (InlinedAt) {
370     // This variable was inlined. Associate it with the InlineSite.
371     const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
372     InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
373     Site.InlinedLocals.emplace_back(Var);
374   } else {
375     // This variable goes in the main ProcSym.
376     CurFn->Locals.emplace_back(Var);
377   }
378 }
379 
380 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
381                                const DILocation *Loc) {
382   auto B = Locs.begin(), E = Locs.end();
383   if (std::find(B, E, Loc) == E)
384     Locs.push_back(Loc);
385 }
386 
387 void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
388                                         const MachineFunction *MF) {
389   // Skip this instruction if it has the same location as the previous one.
390   if (!DL || DL == PrevInstLoc)
391     return;
392 
393   const DIScope *Scope = DL.get()->getScope();
394   if (!Scope)
395     return;
396 
397   // Skip this line if it is longer than the maximum we can record.
398   LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
399   if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
400       LI.isNeverStepInto())
401     return;
402 
403   ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
404   if (CI.getStartColumn() != DL.getCol())
405     return;
406 
407   if (!CurFn->HaveLineInfo)
408     CurFn->HaveLineInfo = true;
409   unsigned FileId = 0;
410   if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
411     FileId = CurFn->LastFileId;
412   else
413     FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
414   PrevInstLoc = DL;
415 
416   unsigned FuncId = CurFn->FuncId;
417   if (const DILocation *SiteLoc = DL->getInlinedAt()) {
418     const DILocation *Loc = DL.get();
419 
420     // If this location was actually inlined from somewhere else, give it the ID
421     // of the inline call site.
422     FuncId =
423         getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
424 
425     // Ensure we have links in the tree of inline call sites.
426     bool FirstLoc = true;
427     while ((SiteLoc = Loc->getInlinedAt())) {
428       InlineSite &Site =
429           getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
430       if (!FirstLoc)
431         addLocIfNotPresent(Site.ChildSites, Loc);
432       FirstLoc = false;
433       Loc = SiteLoc;
434     }
435     addLocIfNotPresent(CurFn->ChildSites, Loc);
436   }
437 
438   OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
439                         /*PrologueEnd=*/false, /*IsStmt=*/false,
440                         DL->getFilename(), SMLoc());
441 }
442 
443 void CodeViewDebug::emitCodeViewMagicVersion() {
444   OS.EmitValueToAlignment(4);
445   OS.AddComment("Debug section magic");
446   OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
447 }
448 
449 void CodeViewDebug::endModule() {
450   if (!Asm || !MMI->hasDebugInfo())
451     return;
452 
453   assert(Asm != nullptr);
454 
455   // The COFF .debug$S section consists of several subsections, each starting
456   // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
457   // of the payload followed by the payload itself.  The subsections are 4-byte
458   // aligned.
459 
460   // Use the generic .debug$S section, and make a subsection for all the inlined
461   // subprograms.
462   switchToDebugSectionForSymbol(nullptr);
463 
464   MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
465   emitCompilerInformation();
466   endCVSubsection(CompilerInfo);
467 
468   emitInlineeLinesSubsection();
469 
470   // Emit per-function debug information.
471   for (auto &P : FnDebugInfo)
472     if (!P.first->isDeclarationForLinker())
473       emitDebugInfoForFunction(P.first, P.second);
474 
475   // Emit global variable debug information.
476   setCurrentSubprogram(nullptr);
477   emitDebugInfoForGlobals();
478 
479   // Emit retained types.
480   emitDebugInfoForRetainedTypes();
481 
482   // Switch back to the generic .debug$S section after potentially processing
483   // comdat symbol sections.
484   switchToDebugSectionForSymbol(nullptr);
485 
486   // Emit UDT records for any types used by global variables.
487   if (!GlobalUDTs.empty()) {
488     MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
489     emitDebugInfoForUDTs(GlobalUDTs);
490     endCVSubsection(SymbolsEnd);
491   }
492 
493   // This subsection holds a file index to offset in string table table.
494   OS.AddComment("File index to string table offset subsection");
495   OS.EmitCVFileChecksumsDirective();
496 
497   // This subsection holds the string table.
498   OS.AddComment("String table");
499   OS.EmitCVStringTableDirective();
500 
501   // Emit type information and hashes last, so that any types we translate while
502   // emitting function info are included.
503   emitTypeInformation();
504 
505   if (EmitDebugGlobalHashes)
506     emitTypeGlobalHashes();
507 
508   clear();
509 }
510 
511 static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S,
512     unsigned MaxFixedRecordLength = 0xF00) {
513   // The maximum CV record length is 0xFF00. Most of the strings we emit appear
514   // after a fixed length portion of the record. The fixed length portion should
515   // always be less than 0xF00 (3840) bytes, so truncate the string so that the
516   // overall record size is less than the maximum allowed.
517   SmallString<32> NullTerminatedString(
518       S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
519   NullTerminatedString.push_back('\0');
520   OS.EmitBytes(NullTerminatedString);
521 }
522 
523 void CodeViewDebug::emitTypeInformation() {
524   if (TypeTable.empty())
525     return;
526 
527   // Start the .debug$T section with 0x4.
528   OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
529   emitCodeViewMagicVersion();
530 
531   SmallString<8> CommentPrefix;
532   if (OS.isVerboseAsm()) {
533     CommentPrefix += '\t';
534     CommentPrefix += Asm->MAI->getCommentString();
535     CommentPrefix += ' ';
536   }
537 
538   TypeTableCollection Table(TypeTable.records());
539   Optional<TypeIndex> B = Table.getFirst();
540   while (B) {
541     // This will fail if the record data is invalid.
542     CVType Record = Table.getType(*B);
543 
544     if (OS.isVerboseAsm()) {
545       // Emit a block comment describing the type record for readability.
546       SmallString<512> CommentBlock;
547       raw_svector_ostream CommentOS(CommentBlock);
548       ScopedPrinter SP(CommentOS);
549       SP.setPrefix(CommentPrefix);
550       TypeDumpVisitor TDV(Table, &SP, false);
551 
552       Error E = codeview::visitTypeRecord(Record, *B, TDV);
553       if (E) {
554         logAllUnhandledErrors(std::move(E), errs(), "error: ");
555         llvm_unreachable("produced malformed type record");
556       }
557       // emitRawComment will insert its own tab and comment string before
558       // the first line, so strip off our first one. It also prints its own
559       // newline.
560       OS.emitRawComment(
561           CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
562     }
563     OS.EmitBinaryData(Record.str_data());
564     B = Table.getNext(*B);
565   }
566 }
567 
568 void CodeViewDebug::emitTypeGlobalHashes() {
569   if (TypeTable.empty())
570     return;
571 
572   // Start the .debug$H section with the version and hash algorithm, currently
573   // hardcoded to version 0, SHA1.
574   OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
575 
576   OS.EmitValueToAlignment(4);
577   OS.AddComment("Magic");
578   OS.EmitIntValue(COFF::DEBUG_HASHES_SECTION_MAGIC, 4);
579   OS.AddComment("Section Version");
580   OS.EmitIntValue(0, 2);
581   OS.AddComment("Hash Algorithm");
582   OS.EmitIntValue(uint16_t(GlobalTypeHashAlg::SHA1), 2);
583 
584   TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
585   for (const auto &GHR : TypeTable.hashes()) {
586     if (OS.isVerboseAsm()) {
587       // Emit an EOL-comment describing which TypeIndex this hash corresponds
588       // to, as well as the stringified SHA1 hash.
589       SmallString<32> Comment;
590       raw_svector_ostream CommentOS(Comment);
591       CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
592       OS.AddComment(Comment);
593       ++TI;
594     }
595     assert(GHR.Hash.size() % 20 == 0);
596     StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
597                 GHR.Hash.size());
598     OS.EmitBinaryData(S);
599   }
600 }
601 
602 static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
603   switch (DWLang) {
604   case dwarf::DW_LANG_C:
605   case dwarf::DW_LANG_C89:
606   case dwarf::DW_LANG_C99:
607   case dwarf::DW_LANG_C11:
608   case dwarf::DW_LANG_ObjC:
609     return SourceLanguage::C;
610   case dwarf::DW_LANG_C_plus_plus:
611   case dwarf::DW_LANG_C_plus_plus_03:
612   case dwarf::DW_LANG_C_plus_plus_11:
613   case dwarf::DW_LANG_C_plus_plus_14:
614     return SourceLanguage::Cpp;
615   case dwarf::DW_LANG_Fortran77:
616   case dwarf::DW_LANG_Fortran90:
617   case dwarf::DW_LANG_Fortran03:
618   case dwarf::DW_LANG_Fortran08:
619     return SourceLanguage::Fortran;
620   case dwarf::DW_LANG_Pascal83:
621     return SourceLanguage::Pascal;
622   case dwarf::DW_LANG_Cobol74:
623   case dwarf::DW_LANG_Cobol85:
624     return SourceLanguage::Cobol;
625   case dwarf::DW_LANG_Java:
626     return SourceLanguage::Java;
627   case dwarf::DW_LANG_D:
628     return SourceLanguage::D;
629   default:
630     // There's no CodeView representation for this language, and CV doesn't
631     // have an "unknown" option for the language field, so we'll use MASM,
632     // as it's very low level.
633     return SourceLanguage::Masm;
634   }
635 }
636 
637 namespace {
638 struct Version {
639   int Part[4];
640 };
641 } // end anonymous namespace
642 
643 // Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
644 // the version number.
645 static Version parseVersion(StringRef Name) {
646   Version V = {{0}};
647   int N = 0;
648   for (const char C : Name) {
649     if (isdigit(C)) {
650       V.Part[N] *= 10;
651       V.Part[N] += C - '0';
652     } else if (C == '.') {
653       ++N;
654       if (N >= 4)
655         return V;
656     } else if (N > 0)
657       return V;
658   }
659   return V;
660 }
661 
662 static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
663   switch (Type) {
664   case Triple::ArchType::x86:
665     return CPUType::Pentium3;
666   case Triple::ArchType::x86_64:
667     return CPUType::X64;
668   case Triple::ArchType::thumb:
669     return CPUType::Thumb;
670   case Triple::ArchType::aarch64:
671     return CPUType::ARM64;
672   default:
673     report_fatal_error("target architecture doesn't map to a CodeView CPUType");
674   }
675 }
676 
677 void CodeViewDebug::emitCompilerInformation() {
678   MCContext &Context = MMI->getContext();
679   MCSymbol *CompilerBegin = Context.createTempSymbol(),
680            *CompilerEnd = Context.createTempSymbol();
681   OS.AddComment("Record length");
682   OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
683   OS.EmitLabel(CompilerBegin);
684   OS.AddComment("Record kind: S_COMPILE3");
685   OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
686   uint32_t Flags = 0;
687 
688   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
689   const MDNode *Node = *CUs->operands().begin();
690   const auto *CU = cast<DICompileUnit>(Node);
691 
692   // The low byte of the flags indicates the source language.
693   Flags = MapDWLangToCVLang(CU->getSourceLanguage());
694   // TODO:  Figure out which other flags need to be set.
695 
696   OS.AddComment("Flags and language");
697   OS.EmitIntValue(Flags, 4);
698 
699   OS.AddComment("CPUType");
700   CPUType CPU =
701       mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
702   OS.EmitIntValue(static_cast<uint64_t>(CPU), 2);
703 
704   StringRef CompilerVersion = CU->getProducer();
705   Version FrontVer = parseVersion(CompilerVersion);
706   OS.AddComment("Frontend version");
707   for (int N = 0; N < 4; ++N)
708     OS.EmitIntValue(FrontVer.Part[N], 2);
709 
710   // Some Microsoft tools, like Binscope, expect a backend version number of at
711   // least 8.something, so we'll coerce the LLVM version into a form that
712   // guarantees it'll be big enough without really lying about the version.
713   int Major = 1000 * LLVM_VERSION_MAJOR +
714               10 * LLVM_VERSION_MINOR +
715               LLVM_VERSION_PATCH;
716   // Clamp it for builds that use unusually large version numbers.
717   Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
718   Version BackVer = {{ Major, 0, 0, 0 }};
719   OS.AddComment("Backend version");
720   for (int N = 0; N < 4; ++N)
721     OS.EmitIntValue(BackVer.Part[N], 2);
722 
723   OS.AddComment("Null-terminated compiler version string");
724   emitNullTerminatedSymbolName(OS, CompilerVersion);
725 
726   OS.EmitLabel(CompilerEnd);
727 }
728 
729 void CodeViewDebug::emitInlineeLinesSubsection() {
730   if (InlinedSubprograms.empty())
731     return;
732 
733   OS.AddComment("Inlinee lines subsection");
734   MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
735 
736   // We emit the checksum info for files.  This is used by debuggers to
737   // determine if a pdb matches the source before loading it.  Visual Studio,
738   // for instance, will display a warning that the breakpoints are not valid if
739   // the pdb does not match the source.
740   OS.AddComment("Inlinee lines signature");
741   OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
742 
743   for (const DISubprogram *SP : InlinedSubprograms) {
744     assert(TypeIndices.count({SP, nullptr}));
745     TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
746 
747     OS.AddBlankLine();
748     unsigned FileId = maybeRecordFile(SP->getFile());
749     OS.AddComment("Inlined function " + SP->getName() + " starts at " +
750                   SP->getFilename() + Twine(':') + Twine(SP->getLine()));
751     OS.AddBlankLine();
752     OS.AddComment("Type index of inlined function");
753     OS.EmitIntValue(InlineeIdx.getIndex(), 4);
754     OS.AddComment("Offset into filechecksum table");
755     OS.EmitCVFileChecksumOffsetDirective(FileId);
756     OS.AddComment("Starting line number");
757     OS.EmitIntValue(SP->getLine(), 4);
758   }
759 
760   endCVSubsection(InlineEnd);
761 }
762 
763 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
764                                         const DILocation *InlinedAt,
765                                         const InlineSite &Site) {
766   MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
767            *InlineEnd = MMI->getContext().createTempSymbol();
768 
769   assert(TypeIndices.count({Site.Inlinee, nullptr}));
770   TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
771 
772   // SymbolRecord
773   OS.AddComment("Record length");
774   OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2);   // RecordLength
775   OS.EmitLabel(InlineBegin);
776   OS.AddComment("Record kind: S_INLINESITE");
777   OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
778 
779   OS.AddComment("PtrParent");
780   OS.EmitIntValue(0, 4);
781   OS.AddComment("PtrEnd");
782   OS.EmitIntValue(0, 4);
783   OS.AddComment("Inlinee type index");
784   OS.EmitIntValue(InlineeIdx.getIndex(), 4);
785 
786   unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
787   unsigned StartLineNum = Site.Inlinee->getLine();
788 
789   OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
790                                     FI.Begin, FI.End);
791 
792   OS.EmitLabel(InlineEnd);
793 
794   emitLocalVariableList(Site.InlinedLocals);
795 
796   // Recurse on child inlined call sites before closing the scope.
797   for (const DILocation *ChildSite : Site.ChildSites) {
798     auto I = FI.InlineSites.find(ChildSite);
799     assert(I != FI.InlineSites.end() &&
800            "child site not in function inline site map");
801     emitInlinedCallSite(FI, ChildSite, I->second);
802   }
803 
804   // Close the scope.
805   OS.AddComment("Record length");
806   OS.EmitIntValue(2, 2);                                  // RecordLength
807   OS.AddComment("Record kind: S_INLINESITE_END");
808   OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
809 }
810 
811 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
812   // If we have a symbol, it may be in a section that is COMDAT. If so, find the
813   // comdat key. A section may be comdat because of -ffunction-sections or
814   // because it is comdat in the IR.
815   MCSectionCOFF *GVSec =
816       GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
817   const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
818 
819   MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
820       Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
821   DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
822 
823   OS.SwitchSection(DebugSec);
824 
825   // Emit the magic version number if this is the first time we've switched to
826   // this section.
827   if (ComdatDebugSections.insert(DebugSec).second)
828     emitCodeViewMagicVersion();
829 }
830 
831 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
832                                              FunctionInfo &FI) {
833   // For each function there is a separate subsection which holds the PC to
834   // file:line table.
835   const MCSymbol *Fn = Asm->getSymbol(GV);
836   assert(Fn);
837 
838   // Switch to the to a comdat section, if appropriate.
839   switchToDebugSectionForSymbol(Fn);
840 
841   std::string FuncName;
842   auto *SP = GV->getSubprogram();
843   assert(SP);
844   setCurrentSubprogram(SP);
845 
846   // If we have a display name, build the fully qualified name by walking the
847   // chain of scopes.
848   if (!SP->getName().empty())
849     FuncName =
850         getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
851 
852   // If our DISubprogram name is empty, use the mangled name.
853   if (FuncName.empty())
854     FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
855 
856   // Emit FPO data, but only on 32-bit x86. No other platforms use it.
857   if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
858     OS.EmitCVFPOData(Fn);
859 
860   // Emit a symbol subsection, required by VS2012+ to find function boundaries.
861   OS.AddComment("Symbol subsection for " + Twine(FuncName));
862   MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
863   {
864     MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
865              *ProcRecordEnd = MMI->getContext().createTempSymbol();
866     OS.AddComment("Record length");
867     OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
868     OS.EmitLabel(ProcRecordBegin);
869 
870     if (GV->hasLocalLinkage()) {
871       OS.AddComment("Record kind: S_LPROC32_ID");
872       OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
873     } else {
874       OS.AddComment("Record kind: S_GPROC32_ID");
875       OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
876     }
877 
878     // These fields are filled in by tools like CVPACK which run after the fact.
879     OS.AddComment("PtrParent");
880     OS.EmitIntValue(0, 4);
881     OS.AddComment("PtrEnd");
882     OS.EmitIntValue(0, 4);
883     OS.AddComment("PtrNext");
884     OS.EmitIntValue(0, 4);
885     // This is the important bit that tells the debugger where the function
886     // code is located and what's its size:
887     OS.AddComment("Code size");
888     OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
889     OS.AddComment("Offset after prologue");
890     OS.EmitIntValue(0, 4);
891     OS.AddComment("Offset before epilogue");
892     OS.EmitIntValue(0, 4);
893     OS.AddComment("Function type index");
894     OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
895     OS.AddComment("Function section relative address");
896     OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
897     OS.AddComment("Function section index");
898     OS.EmitCOFFSectionIndex(Fn);
899     OS.AddComment("Flags");
900     OS.EmitIntValue(0, 1);
901     // Emit the function display name as a null-terminated string.
902     OS.AddComment("Function name");
903     // Truncate the name so we won't overflow the record length field.
904     emitNullTerminatedSymbolName(OS, FuncName);
905     OS.EmitLabel(ProcRecordEnd);
906 
907     emitLocalVariableList(FI.Locals);
908 
909     // Emit inlined call site information. Only emit functions inlined directly
910     // into the parent function. We'll emit the other sites recursively as part
911     // of their parent inline site.
912     for (const DILocation *InlinedAt : FI.ChildSites) {
913       auto I = FI.InlineSites.find(InlinedAt);
914       assert(I != FI.InlineSites.end() &&
915              "child site not in function inline site map");
916       emitInlinedCallSite(FI, InlinedAt, I->second);
917     }
918 
919     for (auto Annot : FI.Annotations) {
920       MCSymbol *Label = Annot.first;
921       MDTuple *Strs = cast<MDTuple>(Annot.second);
922       MCSymbol *AnnotBegin = MMI->getContext().createTempSymbol(),
923                *AnnotEnd = MMI->getContext().createTempSymbol();
924       OS.AddComment("Record length");
925       OS.emitAbsoluteSymbolDiff(AnnotEnd, AnnotBegin, 2);
926       OS.EmitLabel(AnnotBegin);
927       OS.AddComment("Record kind: S_ANNOTATION");
928       OS.EmitIntValue(SymbolKind::S_ANNOTATION, 2);
929       OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
930       // FIXME: Make sure we don't overflow the max record size.
931       OS.EmitCOFFSectionIndex(Label);
932       OS.EmitIntValue(Strs->getNumOperands(), 2);
933       for (Metadata *MD : Strs->operands()) {
934         // MDStrings are null terminated, so we can do EmitBytes and get the
935         // nice .asciz directive.
936         StringRef Str = cast<MDString>(MD)->getString();
937         assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
938         OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
939       }
940       OS.EmitLabel(AnnotEnd);
941     }
942 
943     if (SP != nullptr)
944       emitDebugInfoForUDTs(LocalUDTs);
945 
946     // We're done with this function.
947     OS.AddComment("Record length");
948     OS.EmitIntValue(0x0002, 2);
949     OS.AddComment("Record kind: S_PROC_ID_END");
950     OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
951   }
952   endCVSubsection(SymbolsEnd);
953 
954   // We have an assembler directive that takes care of the whole line table.
955   OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
956 }
957 
958 CodeViewDebug::LocalVarDefRange
959 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
960   LocalVarDefRange DR;
961   DR.InMemory = -1;
962   DR.DataOffset = Offset;
963   assert(DR.DataOffset == Offset && "truncation");
964   DR.IsSubfield = 0;
965   DR.StructOffset = 0;
966   DR.CVRegister = CVRegister;
967   return DR;
968 }
969 
970 CodeViewDebug::LocalVarDefRange
971 CodeViewDebug::createDefRangeGeneral(uint16_t CVRegister, bool InMemory,
972                                      int Offset, bool IsSubfield,
973                                      uint16_t StructOffset) {
974   LocalVarDefRange DR;
975   DR.InMemory = InMemory;
976   DR.DataOffset = Offset;
977   DR.IsSubfield = IsSubfield;
978   DR.StructOffset = StructOffset;
979   DR.CVRegister = CVRegister;
980   return DR;
981 }
982 
983 void CodeViewDebug::collectVariableInfoFromMFTable(
984     DenseSet<InlinedVariable> &Processed) {
985   const MachineFunction &MF = *Asm->MF;
986   const TargetSubtargetInfo &TSI = MF.getSubtarget();
987   const TargetFrameLowering *TFI = TSI.getFrameLowering();
988   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
989 
990   for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
991     if (!VI.Var)
992       continue;
993     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
994            "Expected inlined-at fields to agree");
995 
996     Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
997     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
998 
999     // If variable scope is not found then skip this variable.
1000     if (!Scope)
1001       continue;
1002 
1003     // If the variable has an attached offset expression, extract it.
1004     // FIXME: Try to handle DW_OP_deref as well.
1005     int64_t ExprOffset = 0;
1006     if (VI.Expr)
1007       if (!VI.Expr->extractIfOffset(ExprOffset))
1008         continue;
1009 
1010     // Get the frame register used and the offset.
1011     unsigned FrameReg = 0;
1012     int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
1013     uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
1014 
1015     // Calculate the label ranges.
1016     LocalVarDefRange DefRange =
1017         createDefRangeMem(CVReg, FrameOffset + ExprOffset);
1018     for (const InsnRange &Range : Scope->getRanges()) {
1019       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1020       const MCSymbol *End = getLabelAfterInsn(Range.second);
1021       End = End ? End : Asm->getFunctionEnd();
1022       DefRange.Ranges.emplace_back(Begin, End);
1023     }
1024 
1025     LocalVariable Var;
1026     Var.DIVar = VI.Var;
1027     Var.DefRanges.emplace_back(std::move(DefRange));
1028     recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
1029   }
1030 }
1031 
1032 static bool canUseReferenceType(const DbgVariableLocation &Loc) {
1033   return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
1034 }
1035 
1036 static bool needsReferenceType(const DbgVariableLocation &Loc) {
1037   return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
1038 }
1039 
1040 void CodeViewDebug::calculateRanges(
1041     LocalVariable &Var, const DbgValueHistoryMap::InstrRanges &Ranges) {
1042   const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1043 
1044   // Calculate the definition ranges.
1045   for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1046     const InsnRange &Range = *I;
1047     const MachineInstr *DVInst = Range.first;
1048     assert(DVInst->isDebugValue() && "Invalid History entry");
1049     // FIXME: Find a way to represent constant variables, since they are
1050     // relatively common.
1051     Optional<DbgVariableLocation> Location =
1052         DbgVariableLocation::extractFromMachineInstruction(*DVInst);
1053     if (!Location)
1054       continue;
1055 
1056     // CodeView can only express variables in register and variables in memory
1057     // at a constant offset from a register. However, for variables passed
1058     // indirectly by pointer, it is common for that pointer to be spilled to a
1059     // stack location. For the special case of one offseted load followed by a
1060     // zero offset load (a pointer spilled to the stack), we change the type of
1061     // the local variable from a value type to a reference type. This tricks the
1062     // debugger into doing the load for us.
1063     if (Var.UseReferenceType) {
1064       // We're using a reference type. Drop the last zero offset load.
1065       if (canUseReferenceType(*Location))
1066         Location->LoadChain.pop_back();
1067       else
1068         continue;
1069     } else if (needsReferenceType(*Location)) {
1070       // This location can't be expressed without switching to a reference type.
1071       // Start over using that.
1072       Var.UseReferenceType = true;
1073       Var.DefRanges.clear();
1074       calculateRanges(Var, Ranges);
1075       return;
1076     }
1077 
1078     // We can only handle a register or an offseted load of a register.
1079     if (Location->Register == 0 || Location->LoadChain.size() > 1)
1080       continue;
1081     {
1082       LocalVarDefRange DR;
1083       DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
1084       DR.InMemory = !Location->LoadChain.empty();
1085       DR.DataOffset =
1086           !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
1087       if (Location->FragmentInfo) {
1088         DR.IsSubfield = true;
1089         DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
1090       } else {
1091         DR.IsSubfield = false;
1092         DR.StructOffset = 0;
1093       }
1094 
1095       if (Var.DefRanges.empty() ||
1096           Var.DefRanges.back().isDifferentLocation(DR)) {
1097         Var.DefRanges.emplace_back(std::move(DR));
1098       }
1099     }
1100 
1101     // Compute the label range.
1102     const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1103     const MCSymbol *End = getLabelAfterInsn(Range.second);
1104     if (!End) {
1105       // This range is valid until the next overlapping bitpiece. In the
1106       // common case, ranges will not be bitpieces, so they will overlap.
1107       auto J = std::next(I);
1108       const DIExpression *DIExpr = DVInst->getDebugExpression();
1109       while (J != E &&
1110              !fragmentsOverlap(DIExpr, J->first->getDebugExpression()))
1111         ++J;
1112       if (J != E)
1113         End = getLabelBeforeInsn(J->first);
1114       else
1115         End = Asm->getFunctionEnd();
1116     }
1117 
1118     // If the last range end is our begin, just extend the last range.
1119     // Otherwise make a new range.
1120     SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1121         Var.DefRanges.back().Ranges;
1122     if (!R.empty() && R.back().second == Begin)
1123       R.back().second = End;
1124     else
1125       R.emplace_back(Begin, End);
1126 
1127     // FIXME: Do more range combining.
1128   }
1129 }
1130 
1131 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
1132   DenseSet<InlinedVariable> Processed;
1133   // Grab the variable info that was squirreled away in the MMI side-table.
1134   collectVariableInfoFromMFTable(Processed);
1135 
1136   for (const auto &I : DbgValues) {
1137     InlinedVariable IV = I.first;
1138     if (Processed.count(IV))
1139       continue;
1140     const DILocalVariable *DIVar = IV.first;
1141     const DILocation *InlinedAt = IV.second;
1142 
1143     // Instruction ranges, specifying where IV is accessible.
1144     const auto &Ranges = I.second;
1145 
1146     LexicalScope *Scope = nullptr;
1147     if (InlinedAt)
1148       Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1149     else
1150       Scope = LScopes.findLexicalScope(DIVar->getScope());
1151     // If variable scope is not found then skip this variable.
1152     if (!Scope)
1153       continue;
1154 
1155     LocalVariable Var;
1156     Var.DIVar = DIVar;
1157 
1158     calculateRanges(Var, Ranges);
1159     recordLocalVariable(std::move(Var), InlinedAt);
1160   }
1161 }
1162 
1163 void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
1164   const Function &GV = MF->getFunction();
1165   assert(FnDebugInfo.count(&GV) == false);
1166   CurFn = &FnDebugInfo[&GV];
1167   CurFn->FuncId = NextFuncId++;
1168   CurFn->Begin = Asm->getFunctionBegin();
1169 
1170   OS.EmitCVFuncIdDirective(CurFn->FuncId);
1171 
1172   // Find the end of the function prolog.  First known non-DBG_VALUE and
1173   // non-frame setup location marks the beginning of the function body.
1174   // FIXME: is there a simpler a way to do this? Can we just search
1175   // for the first instruction of the function, not the last of the prolog?
1176   DebugLoc PrologEndLoc;
1177   bool EmptyPrologue = true;
1178   for (const auto &MBB : *MF) {
1179     for (const auto &MI : MBB) {
1180       if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1181           MI.getDebugLoc()) {
1182         PrologEndLoc = MI.getDebugLoc();
1183         break;
1184       } else if (!MI.isMetaInstruction()) {
1185         EmptyPrologue = false;
1186       }
1187     }
1188   }
1189 
1190   // Record beginning of function if we have a non-empty prologue.
1191   if (PrologEndLoc && !EmptyPrologue) {
1192     DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
1193     maybeRecordLocation(FnStartDL, MF);
1194   }
1195 }
1196 
1197 static bool shouldEmitUdt(const DIType *T) {
1198   if (!T)
1199     return false;
1200 
1201   // MSVC does not emit UDTs for typedefs that are scoped to classes.
1202   if (T->getTag() == dwarf::DW_TAG_typedef) {
1203     if (DIScope *Scope = T->getScope().resolve()) {
1204       switch (Scope->getTag()) {
1205       case dwarf::DW_TAG_structure_type:
1206       case dwarf::DW_TAG_class_type:
1207       case dwarf::DW_TAG_union_type:
1208         return false;
1209       }
1210     }
1211   }
1212 
1213   while (true) {
1214     if (!T || T->isForwardDecl())
1215       return false;
1216 
1217     const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
1218     if (!DT)
1219       return true;
1220     T = DT->getBaseType().resolve();
1221   }
1222   return true;
1223 }
1224 
1225 void CodeViewDebug::addToUDTs(const DIType *Ty) {
1226   // Don't record empty UDTs.
1227   if (Ty->getName().empty())
1228     return;
1229   if (!shouldEmitUdt(Ty))
1230     return;
1231 
1232   SmallVector<StringRef, 5> QualifiedNameComponents;
1233   const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1234       Ty->getScope().resolve(), QualifiedNameComponents);
1235 
1236   std::string FullyQualifiedName =
1237       getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
1238 
1239   if (ClosestSubprogram == nullptr) {
1240     GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1241   } else if (ClosestSubprogram == CurrentSubprogram) {
1242     LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1243   }
1244 
1245   // TODO: What if the ClosestSubprogram is neither null or the current
1246   // subprogram?  Currently, the UDT just gets dropped on the floor.
1247   //
1248   // The current behavior is not desirable.  To get maximal fidelity, we would
1249   // need to perform all type translation before beginning emission of .debug$S
1250   // and then make LocalUDTs a member of FunctionInfo
1251 }
1252 
1253 TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
1254   // Generic dispatch for lowering an unknown type.
1255   switch (Ty->getTag()) {
1256   case dwarf::DW_TAG_array_type:
1257     return lowerTypeArray(cast<DICompositeType>(Ty));
1258   case dwarf::DW_TAG_typedef:
1259     return lowerTypeAlias(cast<DIDerivedType>(Ty));
1260   case dwarf::DW_TAG_base_type:
1261     return lowerTypeBasic(cast<DIBasicType>(Ty));
1262   case dwarf::DW_TAG_pointer_type:
1263     if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1264       return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1265     LLVM_FALLTHROUGH;
1266   case dwarf::DW_TAG_reference_type:
1267   case dwarf::DW_TAG_rvalue_reference_type:
1268     return lowerTypePointer(cast<DIDerivedType>(Ty));
1269   case dwarf::DW_TAG_ptr_to_member_type:
1270     return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1271   case dwarf::DW_TAG_const_type:
1272   case dwarf::DW_TAG_volatile_type:
1273   // TODO: add support for DW_TAG_atomic_type here
1274     return lowerTypeModifier(cast<DIDerivedType>(Ty));
1275   case dwarf::DW_TAG_subroutine_type:
1276     if (ClassTy) {
1277       // The member function type of a member function pointer has no
1278       // ThisAdjustment.
1279       return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1280                                      /*ThisAdjustment=*/0,
1281                                      /*IsStaticMethod=*/false);
1282     }
1283     return lowerTypeFunction(cast<DISubroutineType>(Ty));
1284   case dwarf::DW_TAG_enumeration_type:
1285     return lowerTypeEnum(cast<DICompositeType>(Ty));
1286   case dwarf::DW_TAG_class_type:
1287   case dwarf::DW_TAG_structure_type:
1288     return lowerTypeClass(cast<DICompositeType>(Ty));
1289   case dwarf::DW_TAG_union_type:
1290     return lowerTypeUnion(cast<DICompositeType>(Ty));
1291   case dwarf::DW_TAG_unspecified_type:
1292     return TypeIndex::None();
1293   default:
1294     // Use the null type index.
1295     return TypeIndex();
1296   }
1297 }
1298 
1299 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
1300   DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1301   TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
1302   StringRef TypeName = Ty->getName();
1303 
1304   addToUDTs(Ty);
1305 
1306   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
1307       TypeName == "HRESULT")
1308     return TypeIndex(SimpleTypeKind::HResult);
1309   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
1310       TypeName == "wchar_t")
1311     return TypeIndex(SimpleTypeKind::WideCharacter);
1312 
1313   return UnderlyingTypeIndex;
1314 }
1315 
1316 TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1317   DITypeRef ElementTypeRef = Ty->getBaseType();
1318   TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1319   // IndexType is size_t, which depends on the bitness of the target.
1320   TypeIndex IndexType = Asm->TM.getPointerSize() == 8
1321                             ? TypeIndex(SimpleTypeKind::UInt64Quad)
1322                             : TypeIndex(SimpleTypeKind::UInt32Long);
1323 
1324   uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1325 
1326   // Add subranges to array type.
1327   DINodeArray Elements = Ty->getElements();
1328   for (int i = Elements.size() - 1; i >= 0; --i) {
1329     const DINode *Element = Elements[i];
1330     assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1331 
1332     const DISubrange *Subrange = cast<DISubrange>(Element);
1333     assert(Subrange->getLowerBound() == 0 &&
1334            "codeview doesn't support subranges with lower bounds");
1335     int64_t Count = -1;
1336     if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>())
1337       Count = CI->getSExtValue();
1338 
1339     // Forward declarations of arrays without a size and VLAs use a count of -1.
1340     // Emit a count of zero in these cases to match what MSVC does for arrays
1341     // without a size. MSVC doesn't support VLAs, so it's not clear what we
1342     // should do for them even if we could distinguish them.
1343     if (Count == -1)
1344       Count = 0;
1345 
1346     // Update the element size and element type index for subsequent subranges.
1347     ElementSize *= Count;
1348 
1349     // If this is the outermost array, use the size from the array. It will be
1350     // more accurate if we had a VLA or an incomplete element type size.
1351     uint64_t ArraySize =
1352         (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1353 
1354     StringRef Name = (i == 0) ? Ty->getName() : "";
1355     ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1356     ElementTypeIndex = TypeTable.writeLeafType(AR);
1357   }
1358 
1359   return ElementTypeIndex;
1360 }
1361 
1362 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1363   TypeIndex Index;
1364   dwarf::TypeKind Kind;
1365   uint32_t ByteSize;
1366 
1367   Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
1368   ByteSize = Ty->getSizeInBits() / 8;
1369 
1370   SimpleTypeKind STK = SimpleTypeKind::None;
1371   switch (Kind) {
1372   case dwarf::DW_ATE_address:
1373     // FIXME: Translate
1374     break;
1375   case dwarf::DW_ATE_boolean:
1376     switch (ByteSize) {
1377     case 1:  STK = SimpleTypeKind::Boolean8;   break;
1378     case 2:  STK = SimpleTypeKind::Boolean16;  break;
1379     case 4:  STK = SimpleTypeKind::Boolean32;  break;
1380     case 8:  STK = SimpleTypeKind::Boolean64;  break;
1381     case 16: STK = SimpleTypeKind::Boolean128; break;
1382     }
1383     break;
1384   case dwarf::DW_ATE_complex_float:
1385     switch (ByteSize) {
1386     case 2:  STK = SimpleTypeKind::Complex16;  break;
1387     case 4:  STK = SimpleTypeKind::Complex32;  break;
1388     case 8:  STK = SimpleTypeKind::Complex64;  break;
1389     case 10: STK = SimpleTypeKind::Complex80;  break;
1390     case 16: STK = SimpleTypeKind::Complex128; break;
1391     }
1392     break;
1393   case dwarf::DW_ATE_float:
1394     switch (ByteSize) {
1395     case 2:  STK = SimpleTypeKind::Float16;  break;
1396     case 4:  STK = SimpleTypeKind::Float32;  break;
1397     case 6:  STK = SimpleTypeKind::Float48;  break;
1398     case 8:  STK = SimpleTypeKind::Float64;  break;
1399     case 10: STK = SimpleTypeKind::Float80;  break;
1400     case 16: STK = SimpleTypeKind::Float128; break;
1401     }
1402     break;
1403   case dwarf::DW_ATE_signed:
1404     switch (ByteSize) {
1405     case 1:  STK = SimpleTypeKind::SignedCharacter; break;
1406     case 2:  STK = SimpleTypeKind::Int16Short;      break;
1407     case 4:  STK = SimpleTypeKind::Int32;           break;
1408     case 8:  STK = SimpleTypeKind::Int64Quad;       break;
1409     case 16: STK = SimpleTypeKind::Int128Oct;       break;
1410     }
1411     break;
1412   case dwarf::DW_ATE_unsigned:
1413     switch (ByteSize) {
1414     case 1:  STK = SimpleTypeKind::UnsignedCharacter; break;
1415     case 2:  STK = SimpleTypeKind::UInt16Short;       break;
1416     case 4:  STK = SimpleTypeKind::UInt32;            break;
1417     case 8:  STK = SimpleTypeKind::UInt64Quad;        break;
1418     case 16: STK = SimpleTypeKind::UInt128Oct;        break;
1419     }
1420     break;
1421   case dwarf::DW_ATE_UTF:
1422     switch (ByteSize) {
1423     case 2: STK = SimpleTypeKind::Character16; break;
1424     case 4: STK = SimpleTypeKind::Character32; break;
1425     }
1426     break;
1427   case dwarf::DW_ATE_signed_char:
1428     if (ByteSize == 1)
1429       STK = SimpleTypeKind::SignedCharacter;
1430     break;
1431   case dwarf::DW_ATE_unsigned_char:
1432     if (ByteSize == 1)
1433       STK = SimpleTypeKind::UnsignedCharacter;
1434     break;
1435   default:
1436     break;
1437   }
1438 
1439   // Apply some fixups based on the source-level type name.
1440   if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1441     STK = SimpleTypeKind::Int32Long;
1442   if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1443     STK = SimpleTypeKind::UInt32Long;
1444   if (STK == SimpleTypeKind::UInt16Short &&
1445       (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
1446     STK = SimpleTypeKind::WideCharacter;
1447   if ((STK == SimpleTypeKind::SignedCharacter ||
1448        STK == SimpleTypeKind::UnsignedCharacter) &&
1449       Ty->getName() == "char")
1450     STK = SimpleTypeKind::NarrowCharacter;
1451 
1452   return TypeIndex(STK);
1453 }
1454 
1455 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1456   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1457 
1458   // Pointers to simple types can use SimpleTypeMode, rather than having a
1459   // dedicated pointer type record.
1460   if (PointeeTI.isSimple() &&
1461       PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1462       Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1463     SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1464                               ? SimpleTypeMode::NearPointer64
1465                               : SimpleTypeMode::NearPointer32;
1466     return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1467   }
1468 
1469   PointerKind PK =
1470       Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1471   PointerMode PM = PointerMode::Pointer;
1472   switch (Ty->getTag()) {
1473   default: llvm_unreachable("not a pointer tag type");
1474   case dwarf::DW_TAG_pointer_type:
1475     PM = PointerMode::Pointer;
1476     break;
1477   case dwarf::DW_TAG_reference_type:
1478     PM = PointerMode::LValueReference;
1479     break;
1480   case dwarf::DW_TAG_rvalue_reference_type:
1481     PM = PointerMode::RValueReference;
1482     break;
1483   }
1484   // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1485   // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1486   // do.
1487   PointerOptions PO = PointerOptions::None;
1488   PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1489   return TypeTable.writeLeafType(PR);
1490 }
1491 
1492 static PointerToMemberRepresentation
1493 translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1494   // SizeInBytes being zero generally implies that the member pointer type was
1495   // incomplete, which can happen if it is part of a function prototype. In this
1496   // case, use the unknown model instead of the general model.
1497   if (IsPMF) {
1498     switch (Flags & DINode::FlagPtrToMemberRep) {
1499     case 0:
1500       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1501                               : PointerToMemberRepresentation::GeneralFunction;
1502     case DINode::FlagSingleInheritance:
1503       return PointerToMemberRepresentation::SingleInheritanceFunction;
1504     case DINode::FlagMultipleInheritance:
1505       return PointerToMemberRepresentation::MultipleInheritanceFunction;
1506     case DINode::FlagVirtualInheritance:
1507       return PointerToMemberRepresentation::VirtualInheritanceFunction;
1508     }
1509   } else {
1510     switch (Flags & DINode::FlagPtrToMemberRep) {
1511     case 0:
1512       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1513                               : PointerToMemberRepresentation::GeneralData;
1514     case DINode::FlagSingleInheritance:
1515       return PointerToMemberRepresentation::SingleInheritanceData;
1516     case DINode::FlagMultipleInheritance:
1517       return PointerToMemberRepresentation::MultipleInheritanceData;
1518     case DINode::FlagVirtualInheritance:
1519       return PointerToMemberRepresentation::VirtualInheritanceData;
1520     }
1521   }
1522   llvm_unreachable("invalid ptr to member representation");
1523 }
1524 
1525 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1526   assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1527   TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
1528   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
1529   PointerKind PK = Asm->TM.getPointerSize() == 8 ? PointerKind::Near64
1530                                                  : PointerKind::Near32;
1531   bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1532   PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1533                          : PointerMode::PointerToDataMember;
1534   PointerOptions PO = PointerOptions::None; // FIXME
1535   assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1536   uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1537   MemberPointerInfo MPI(
1538       ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
1539   PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
1540   return TypeTable.writeLeafType(PR);
1541 }
1542 
1543 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1544 /// have a translation, use the NearC convention.
1545 static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1546   switch (DwarfCC) {
1547   case dwarf::DW_CC_normal:             return CallingConvention::NearC;
1548   case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1549   case dwarf::DW_CC_BORLAND_thiscall:   return CallingConvention::ThisCall;
1550   case dwarf::DW_CC_BORLAND_stdcall:    return CallingConvention::NearStdCall;
1551   case dwarf::DW_CC_BORLAND_pascal:     return CallingConvention::NearPascal;
1552   case dwarf::DW_CC_LLVM_vectorcall:    return CallingConvention::NearVector;
1553   }
1554   return CallingConvention::NearC;
1555 }
1556 
1557 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1558   ModifierOptions Mods = ModifierOptions::None;
1559   bool IsModifier = true;
1560   const DIType *BaseTy = Ty;
1561   while (IsModifier && BaseTy) {
1562     // FIXME: Need to add DWARF tags for __unaligned and _Atomic
1563     switch (BaseTy->getTag()) {
1564     case dwarf::DW_TAG_const_type:
1565       Mods |= ModifierOptions::Const;
1566       break;
1567     case dwarf::DW_TAG_volatile_type:
1568       Mods |= ModifierOptions::Volatile;
1569       break;
1570     default:
1571       IsModifier = false;
1572       break;
1573     }
1574     if (IsModifier)
1575       BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1576   }
1577   TypeIndex ModifiedTI = getTypeIndex(BaseTy);
1578   ModifierRecord MR(ModifiedTI, Mods);
1579   return TypeTable.writeLeafType(MR);
1580 }
1581 
1582 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1583   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1584   for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1585     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1586 
1587   // MSVC uses type none for variadic argument.
1588   if (ReturnAndArgTypeIndices.size() > 1 &&
1589       ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1590     ReturnAndArgTypeIndices.back() = TypeIndex::None();
1591   }
1592   TypeIndex ReturnTypeIndex = TypeIndex::Void();
1593   ArrayRef<TypeIndex> ArgTypeIndices = None;
1594   if (!ReturnAndArgTypeIndices.empty()) {
1595     auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1596     ReturnTypeIndex = ReturnAndArgTypesRef.front();
1597     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1598   }
1599 
1600   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1601   TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
1602 
1603   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1604 
1605   ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1606                             ArgTypeIndices.size(), ArgListIndex);
1607   return TypeTable.writeLeafType(Procedure);
1608 }
1609 
1610 TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
1611                                                  const DIType *ClassTy,
1612                                                  int ThisAdjustment,
1613                                                  bool IsStaticMethod) {
1614   // Lower the containing class type.
1615   TypeIndex ClassType = getTypeIndex(ClassTy);
1616 
1617   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1618   for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1619     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1620 
1621   // MSVC uses type none for variadic argument.
1622   if (ReturnAndArgTypeIndices.size() > 1 &&
1623       ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1624     ReturnAndArgTypeIndices.back() = TypeIndex::None();
1625   }
1626   TypeIndex ReturnTypeIndex = TypeIndex::Void();
1627   ArrayRef<TypeIndex> ArgTypeIndices = None;
1628   if (!ReturnAndArgTypeIndices.empty()) {
1629     auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1630     ReturnTypeIndex = ReturnAndArgTypesRef.front();
1631     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1632   }
1633   TypeIndex ThisTypeIndex;
1634   if (!IsStaticMethod && !ArgTypeIndices.empty()) {
1635     ThisTypeIndex = ArgTypeIndices.front();
1636     ArgTypeIndices = ArgTypeIndices.drop_front();
1637   }
1638 
1639   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1640   TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
1641 
1642   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1643 
1644   // TODO: Need to use the correct values for FunctionOptions.
1645   MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC,
1646                            FunctionOptions::None, ArgTypeIndices.size(),
1647                            ArgListIndex, ThisAdjustment);
1648   return TypeTable.writeLeafType(MFR);
1649 }
1650 
1651 TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
1652   unsigned VSlotCount =
1653       Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
1654   SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
1655 
1656   VFTableShapeRecord VFTSR(Slots);
1657   return TypeTable.writeLeafType(VFTSR);
1658 }
1659 
1660 static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1661   switch (Flags & DINode::FlagAccessibility) {
1662   case DINode::FlagPrivate:   return MemberAccess::Private;
1663   case DINode::FlagPublic:    return MemberAccess::Public;
1664   case DINode::FlagProtected: return MemberAccess::Protected;
1665   case 0:
1666     // If there was no explicit access control, provide the default for the tag.
1667     return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1668                                                  : MemberAccess::Public;
1669   }
1670   llvm_unreachable("access flags are exclusive");
1671 }
1672 
1673 static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1674   if (SP->isArtificial())
1675     return MethodOptions::CompilerGenerated;
1676 
1677   // FIXME: Handle other MethodOptions.
1678 
1679   return MethodOptions::None;
1680 }
1681 
1682 static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1683                                            bool Introduced) {
1684   if (SP->getFlags() & DINode::FlagStaticMember)
1685     return MethodKind::Static;
1686 
1687   switch (SP->getVirtuality()) {
1688   case dwarf::DW_VIRTUALITY_none:
1689     break;
1690   case dwarf::DW_VIRTUALITY_virtual:
1691     return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1692   case dwarf::DW_VIRTUALITY_pure_virtual:
1693     return Introduced ? MethodKind::PureIntroducingVirtual
1694                       : MethodKind::PureVirtual;
1695   default:
1696     llvm_unreachable("unhandled virtuality case");
1697   }
1698 
1699   return MethodKind::Vanilla;
1700 }
1701 
1702 static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1703   switch (Ty->getTag()) {
1704   case dwarf::DW_TAG_class_type:     return TypeRecordKind::Class;
1705   case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1706   }
1707   llvm_unreachable("unexpected tag");
1708 }
1709 
1710 /// Return ClassOptions that should be present on both the forward declaration
1711 /// and the defintion of a tag type.
1712 static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1713   ClassOptions CO = ClassOptions::None;
1714 
1715   // MSVC always sets this flag, even for local types. Clang doesn't always
1716   // appear to give every type a linkage name, which may be problematic for us.
1717   // FIXME: Investigate the consequences of not following them here.
1718   if (!Ty->getIdentifier().empty())
1719     CO |= ClassOptions::HasUniqueName;
1720 
1721   // Put the Nested flag on a type if it appears immediately inside a tag type.
1722   // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1723   // here. That flag is only set on definitions, and not forward declarations.
1724   const DIScope *ImmediateScope = Ty->getScope().resolve();
1725   if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1726     CO |= ClassOptions::Nested;
1727 
1728   // Put the Scoped flag on function-local types.
1729   for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1730        Scope = Scope->getScope().resolve()) {
1731     if (isa<DISubprogram>(Scope)) {
1732       CO |= ClassOptions::Scoped;
1733       break;
1734     }
1735   }
1736 
1737   return CO;
1738 }
1739 
1740 TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
1741   ClassOptions CO = getCommonClassOptions(Ty);
1742   TypeIndex FTI;
1743   unsigned EnumeratorCount = 0;
1744 
1745   if (Ty->isForwardDecl()) {
1746     CO |= ClassOptions::ForwardReference;
1747   } else {
1748     ContinuationRecordBuilder ContinuationBuilder;
1749     ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
1750     for (const DINode *Element : Ty->getElements()) {
1751       // We assume that the frontend provides all members in source declaration
1752       // order, which is what MSVC does.
1753       if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
1754         EnumeratorRecord ER(MemberAccess::Public,
1755                             APSInt::getUnsigned(Enumerator->getValue()),
1756                             Enumerator->getName());
1757         ContinuationBuilder.writeMemberType(ER);
1758         EnumeratorCount++;
1759       }
1760     }
1761     FTI = TypeTable.insertRecord(ContinuationBuilder);
1762   }
1763 
1764   std::string FullName = getFullyQualifiedName(Ty);
1765 
1766   EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
1767                 getTypeIndex(Ty->getBaseType()));
1768   return TypeTable.writeLeafType(ER);
1769 }
1770 
1771 //===----------------------------------------------------------------------===//
1772 // ClassInfo
1773 //===----------------------------------------------------------------------===//
1774 
1775 struct llvm::ClassInfo {
1776   struct MemberInfo {
1777     const DIDerivedType *MemberTypeNode;
1778     uint64_t BaseOffset;
1779   };
1780   // [MemberInfo]
1781   using MemberList = std::vector<MemberInfo>;
1782 
1783   using MethodsList = TinyPtrVector<const DISubprogram *>;
1784   // MethodName -> MethodsList
1785   using MethodsMap = MapVector<MDString *, MethodsList>;
1786 
1787   /// Base classes.
1788   std::vector<const DIDerivedType *> Inheritance;
1789 
1790   /// Direct members.
1791   MemberList Members;
1792   // Direct overloaded methods gathered by name.
1793   MethodsMap Methods;
1794 
1795   TypeIndex VShapeTI;
1796 
1797   std::vector<const DIType *> NestedTypes;
1798 };
1799 
1800 void CodeViewDebug::clear() {
1801   assert(CurFn == nullptr);
1802   FileIdMap.clear();
1803   FnDebugInfo.clear();
1804   FileToFilepathMap.clear();
1805   LocalUDTs.clear();
1806   GlobalUDTs.clear();
1807   TypeIndices.clear();
1808   CompleteTypeIndices.clear();
1809 }
1810 
1811 void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1812                                       const DIDerivedType *DDTy) {
1813   if (!DDTy->getName().empty()) {
1814     Info.Members.push_back({DDTy, 0});
1815     return;
1816   }
1817   // An unnamed member must represent a nested struct or union. Add all the
1818   // indirect fields to the current record.
1819   assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
1820   uint64_t Offset = DDTy->getOffsetInBits();
1821   const DIType *Ty = DDTy->getBaseType().resolve();
1822   const DICompositeType *DCTy = cast<DICompositeType>(Ty);
1823   ClassInfo NestedInfo = collectClassInfo(DCTy);
1824   for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
1825     Info.Members.push_back(
1826         {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
1827 }
1828 
1829 ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1830   ClassInfo Info;
1831   // Add elements to structure type.
1832   DINodeArray Elements = Ty->getElements();
1833   for (auto *Element : Elements) {
1834     // We assume that the frontend provides all members in source declaration
1835     // order, which is what MSVC does.
1836     if (!Element)
1837       continue;
1838     if (auto *SP = dyn_cast<DISubprogram>(Element)) {
1839       Info.Methods[SP->getRawName()].push_back(SP);
1840     } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
1841       if (DDTy->getTag() == dwarf::DW_TAG_member) {
1842         collectMemberInfo(Info, DDTy);
1843       } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1844         Info.Inheritance.push_back(DDTy);
1845       } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
1846                  DDTy->getName() == "__vtbl_ptr_type") {
1847         Info.VShapeTI = getTypeIndex(DDTy);
1848       } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
1849         Info.NestedTypes.push_back(DDTy);
1850       } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1851         // Ignore friend members. It appears that MSVC emitted info about
1852         // friends in the past, but modern versions do not.
1853       }
1854     } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
1855       Info.NestedTypes.push_back(Composite);
1856     }
1857     // Skip other unrecognized kinds of elements.
1858   }
1859   return Info;
1860 }
1861 
1862 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1863   // First, construct the forward decl.  Don't look into Ty to compute the
1864   // forward decl options, since it might not be available in all TUs.
1865   TypeRecordKind Kind = getRecordKind(Ty);
1866   ClassOptions CO =
1867       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
1868   std::string FullName = getFullyQualifiedName(Ty);
1869   ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
1870                  FullName, Ty->getIdentifier());
1871   TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
1872   if (!Ty->isForwardDecl())
1873     DeferredCompleteTypes.push_back(Ty);
1874   return FwdDeclTI;
1875 }
1876 
1877 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1878   // Construct the field list and complete type record.
1879   TypeRecordKind Kind = getRecordKind(Ty);
1880   ClassOptions CO = getCommonClassOptions(Ty);
1881   TypeIndex FieldTI;
1882   TypeIndex VShapeTI;
1883   unsigned FieldCount;
1884   bool ContainsNestedClass;
1885   std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
1886       lowerRecordFieldList(Ty);
1887 
1888   if (ContainsNestedClass)
1889     CO |= ClassOptions::ContainsNestedClass;
1890 
1891   std::string FullName = getFullyQualifiedName(Ty);
1892 
1893   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1894 
1895   ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
1896                  SizeInBytes, FullName, Ty->getIdentifier());
1897   TypeIndex ClassTI = TypeTable.writeLeafType(CR);
1898 
1899   if (const auto *File = Ty->getFile()) {
1900     StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
1901     TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
1902 
1903     UdtSourceLineRecord USLR(ClassTI, SIDI, Ty->getLine());
1904     TypeTable.writeLeafType(USLR);
1905   }
1906 
1907   addToUDTs(Ty);
1908 
1909   return ClassTI;
1910 }
1911 
1912 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1913   ClassOptions CO =
1914       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
1915   std::string FullName = getFullyQualifiedName(Ty);
1916   UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
1917   TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
1918   if (!Ty->isForwardDecl())
1919     DeferredCompleteTypes.push_back(Ty);
1920   return FwdDeclTI;
1921 }
1922 
1923 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
1924   ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
1925   TypeIndex FieldTI;
1926   unsigned FieldCount;
1927   bool ContainsNestedClass;
1928   std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
1929       lowerRecordFieldList(Ty);
1930 
1931   if (ContainsNestedClass)
1932     CO |= ClassOptions::ContainsNestedClass;
1933 
1934   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1935   std::string FullName = getFullyQualifiedName(Ty);
1936 
1937   UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
1938                  Ty->getIdentifier());
1939   TypeIndex UnionTI = TypeTable.writeLeafType(UR);
1940 
1941   StringIdRecord SIR(TypeIndex(0x0), getFullFilepath(Ty->getFile()));
1942   TypeIndex SIRI = TypeTable.writeLeafType(SIR);
1943 
1944   UdtSourceLineRecord USLR(UnionTI, SIRI, Ty->getLine());
1945   TypeTable.writeLeafType(USLR);
1946 
1947   addToUDTs(Ty);
1948 
1949   return UnionTI;
1950 }
1951 
1952 std::tuple<TypeIndex, TypeIndex, unsigned, bool>
1953 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1954   // Manually count members. MSVC appears to count everything that generates a
1955   // field list record. Each individual overload in a method overload group
1956   // contributes to this count, even though the overload group is a single field
1957   // list record.
1958   unsigned MemberCount = 0;
1959   ClassInfo Info = collectClassInfo(Ty);
1960   ContinuationRecordBuilder ContinuationBuilder;
1961   ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
1962 
1963   // Create base classes.
1964   for (const DIDerivedType *I : Info.Inheritance) {
1965     if (I->getFlags() & DINode::FlagVirtual) {
1966       // Virtual base.
1967       // FIXME: Emit VBPtrOffset when the frontend provides it.
1968       unsigned VBPtrOffset = 0;
1969       // FIXME: Despite the accessor name, the offset is really in bytes.
1970       unsigned VBTableIndex = I->getOffsetInBits() / 4;
1971       auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
1972                             ? TypeRecordKind::IndirectVirtualBaseClass
1973                             : TypeRecordKind::VirtualBaseClass;
1974       VirtualBaseClassRecord VBCR(
1975           RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
1976           getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
1977           VBTableIndex);
1978 
1979       ContinuationBuilder.writeMemberType(VBCR);
1980       MemberCount++;
1981     } else {
1982       assert(I->getOffsetInBits() % 8 == 0 &&
1983              "bases must be on byte boundaries");
1984       BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
1985                           getTypeIndex(I->getBaseType()),
1986                           I->getOffsetInBits() / 8);
1987       ContinuationBuilder.writeMemberType(BCR);
1988       MemberCount++;
1989     }
1990   }
1991 
1992   // Create members.
1993   for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1994     const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1995     TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
1996     StringRef MemberName = Member->getName();
1997     MemberAccess Access =
1998         translateAccessFlags(Ty->getTag(), Member->getFlags());
1999 
2000     if (Member->isStaticMember()) {
2001       StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
2002       ContinuationBuilder.writeMemberType(SDMR);
2003       MemberCount++;
2004       continue;
2005     }
2006 
2007     // Virtual function pointer member.
2008     if ((Member->getFlags() & DINode::FlagArtificial) &&
2009         Member->getName().startswith("_vptr$")) {
2010       VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
2011       ContinuationBuilder.writeMemberType(VFPR);
2012       MemberCount++;
2013       continue;
2014     }
2015 
2016     // Data member.
2017     uint64_t MemberOffsetInBits =
2018         Member->getOffsetInBits() + MemberInfo.BaseOffset;
2019     if (Member->isBitField()) {
2020       uint64_t StartBitOffset = MemberOffsetInBits;
2021       if (const auto *CI =
2022               dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
2023         MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
2024       }
2025       StartBitOffset -= MemberOffsetInBits;
2026       BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2027                          StartBitOffset);
2028       MemberBaseType = TypeTable.writeLeafType(BFR);
2029     }
2030     uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
2031     DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2032                          MemberName);
2033     ContinuationBuilder.writeMemberType(DMR);
2034     MemberCount++;
2035   }
2036 
2037   // Create methods
2038   for (auto &MethodItr : Info.Methods) {
2039     StringRef Name = MethodItr.first->getString();
2040 
2041     std::vector<OneMethodRecord> Methods;
2042     for (const DISubprogram *SP : MethodItr.second) {
2043       TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2044       bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
2045 
2046       unsigned VFTableOffset = -1;
2047       if (Introduced)
2048         VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2049 
2050       Methods.push_back(OneMethodRecord(
2051           MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
2052           translateMethodKindFlags(SP, Introduced),
2053           translateMethodOptionFlags(SP), VFTableOffset, Name));
2054       MemberCount++;
2055     }
2056     assert(!Methods.empty() && "Empty methods map entry");
2057     if (Methods.size() == 1)
2058       ContinuationBuilder.writeMemberType(Methods[0]);
2059     else {
2060       // FIXME: Make this use its own ContinuationBuilder so that
2061       // MethodOverloadList can be split correctly.
2062       MethodOverloadListRecord MOLR(Methods);
2063       TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
2064 
2065       OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
2066       ContinuationBuilder.writeMemberType(OMR);
2067     }
2068   }
2069 
2070   // Create nested classes.
2071   for (const DIType *Nested : Info.NestedTypes) {
2072     NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
2073     ContinuationBuilder.writeMemberType(R);
2074     MemberCount++;
2075   }
2076 
2077   TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
2078   return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
2079                          !Info.NestedTypes.empty());
2080 }
2081 
2082 TypeIndex CodeViewDebug::getVBPTypeIndex() {
2083   if (!VBPType.getIndex()) {
2084     // Make a 'const int *' type.
2085     ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
2086     TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
2087 
2088     PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2089                                                   : PointerKind::Near32;
2090     PointerMode PM = PointerMode::Pointer;
2091     PointerOptions PO = PointerOptions::None;
2092     PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
2093     VBPType = TypeTable.writeLeafType(PR);
2094   }
2095 
2096   return VBPType;
2097 }
2098 
2099 TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
2100   const DIType *Ty = TypeRef.resolve();
2101   const DIType *ClassTy = ClassTyRef.resolve();
2102 
2103   // The null DIType is the void type. Don't try to hash it.
2104   if (!Ty)
2105     return TypeIndex::Void();
2106 
2107   // Check if we've already translated this type. Don't try to do a
2108   // get-or-create style insertion that caches the hash lookup across the
2109   // lowerType call. It will update the TypeIndices map.
2110   auto I = TypeIndices.find({Ty, ClassTy});
2111   if (I != TypeIndices.end())
2112     return I->second;
2113 
2114   TypeLoweringScope S(*this);
2115   TypeIndex TI = lowerType(Ty, ClassTy);
2116   return recordTypeIndexForDINode(Ty, TI, ClassTy);
2117 }
2118 
2119 TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(DITypeRef TypeRef) {
2120   DIType *Ty = TypeRef.resolve();
2121   PointerRecord PR(getTypeIndex(Ty),
2122                    getPointerSizeInBytes() == 8 ? PointerKind::Near64
2123                                                 : PointerKind::Near32,
2124                    PointerMode::LValueReference, PointerOptions::None,
2125                    Ty->getSizeInBits() / 8);
2126   return TypeTable.writeLeafType(PR);
2127 }
2128 
2129 TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
2130   const DIType *Ty = TypeRef.resolve();
2131 
2132   // The null DIType is the void type. Don't try to hash it.
2133   if (!Ty)
2134     return TypeIndex::Void();
2135 
2136   // If this is a non-record type, the complete type index is the same as the
2137   // normal type index. Just call getTypeIndex.
2138   switch (Ty->getTag()) {
2139   case dwarf::DW_TAG_class_type:
2140   case dwarf::DW_TAG_structure_type:
2141   case dwarf::DW_TAG_union_type:
2142     break;
2143   default:
2144     return getTypeIndex(Ty);
2145   }
2146 
2147   // Check if we've already translated the complete record type.  Lowering a
2148   // complete type should never trigger lowering another complete type, so we
2149   // can reuse the hash table lookup result.
2150   const auto *CTy = cast<DICompositeType>(Ty);
2151   auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
2152   if (!InsertResult.second)
2153     return InsertResult.first->second;
2154 
2155   TypeLoweringScope S(*this);
2156 
2157   // Make sure the forward declaration is emitted first. It's unclear if this
2158   // is necessary, but MSVC does it, and we should follow suit until we can show
2159   // otherwise.
2160   TypeIndex FwdDeclTI = getTypeIndex(CTy);
2161 
2162   // Just use the forward decl if we don't have complete type info. This might
2163   // happen if the frontend is using modules and expects the complete definition
2164   // to be emitted elsewhere.
2165   if (CTy->isForwardDecl())
2166     return FwdDeclTI;
2167 
2168   TypeIndex TI;
2169   switch (CTy->getTag()) {
2170   case dwarf::DW_TAG_class_type:
2171   case dwarf::DW_TAG_structure_type:
2172     TI = lowerCompleteTypeClass(CTy);
2173     break;
2174   case dwarf::DW_TAG_union_type:
2175     TI = lowerCompleteTypeUnion(CTy);
2176     break;
2177   default:
2178     llvm_unreachable("not a record");
2179   }
2180 
2181   InsertResult.first->second = TI;
2182   return TI;
2183 }
2184 
2185 /// Emit all the deferred complete record types. Try to do this in FIFO order,
2186 /// and do this until fixpoint, as each complete record type typically
2187 /// references
2188 /// many other record types.
2189 void CodeViewDebug::emitDeferredCompleteTypes() {
2190   SmallVector<const DICompositeType *, 4> TypesToEmit;
2191   while (!DeferredCompleteTypes.empty()) {
2192     std::swap(DeferredCompleteTypes, TypesToEmit);
2193     for (const DICompositeType *RecordTy : TypesToEmit)
2194       getCompleteTypeIndex(RecordTy);
2195     TypesToEmit.clear();
2196   }
2197 }
2198 
2199 void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
2200   // Get the sorted list of parameters and emit them first.
2201   SmallVector<const LocalVariable *, 6> Params;
2202   for (const LocalVariable &L : Locals)
2203     if (L.DIVar->isParameter())
2204       Params.push_back(&L);
2205   std::sort(Params.begin(), Params.end(),
2206             [](const LocalVariable *L, const LocalVariable *R) {
2207               return L->DIVar->getArg() < R->DIVar->getArg();
2208             });
2209   for (const LocalVariable *L : Params)
2210     emitLocalVariable(*L);
2211 
2212   // Next emit all non-parameters in the order that we found them.
2213   for (const LocalVariable &L : Locals)
2214     if (!L.DIVar->isParameter())
2215       emitLocalVariable(L);
2216 }
2217 
2218 void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
2219   // LocalSym record, see SymbolRecord.h for more info.
2220   MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
2221            *LocalEnd = MMI->getContext().createTempSymbol();
2222   OS.AddComment("Record length");
2223   OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
2224   OS.EmitLabel(LocalBegin);
2225 
2226   OS.AddComment("Record kind: S_LOCAL");
2227   OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
2228 
2229   LocalSymFlags Flags = LocalSymFlags::None;
2230   if (Var.DIVar->isParameter())
2231     Flags |= LocalSymFlags::IsParameter;
2232   if (Var.DefRanges.empty())
2233     Flags |= LocalSymFlags::IsOptimizedOut;
2234 
2235   OS.AddComment("TypeIndex");
2236   TypeIndex TI = Var.UseReferenceType
2237                      ? getTypeIndexForReferenceTo(Var.DIVar->getType())
2238                      : getCompleteTypeIndex(Var.DIVar->getType());
2239   OS.EmitIntValue(TI.getIndex(), 4);
2240   OS.AddComment("Flags");
2241   OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
2242   // Truncate the name so we won't overflow the record length field.
2243   emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
2244   OS.EmitLabel(LocalEnd);
2245 
2246   // Calculate the on disk prefix of the appropriate def range record. The
2247   // records and on disk formats are described in SymbolRecords.h. BytePrefix
2248   // should be big enough to hold all forms without memory allocation.
2249   SmallString<20> BytePrefix;
2250   for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2251     BytePrefix.clear();
2252     if (DefRange.InMemory) {
2253       uint16_t RegRelFlags = 0;
2254       if (DefRange.IsSubfield) {
2255         RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2256                       (DefRange.StructOffset
2257                        << DefRangeRegisterRelSym::OffsetInParentShift);
2258       }
2259       DefRangeRegisterRelSym Sym(S_DEFRANGE_REGISTER_REL);
2260       Sym.Hdr.Register = DefRange.CVRegister;
2261       Sym.Hdr.Flags = RegRelFlags;
2262       Sym.Hdr.BasePointerOffset = DefRange.DataOffset;
2263       ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
2264       BytePrefix +=
2265           StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
2266       BytePrefix +=
2267           StringRef(reinterpret_cast<const char *>(&Sym.Hdr), sizeof(Sym.Hdr));
2268     } else {
2269       assert(DefRange.DataOffset == 0 && "unexpected offset into register");
2270       if (DefRange.IsSubfield) {
2271         // Unclear what matters here.
2272         DefRangeSubfieldRegisterSym Sym(S_DEFRANGE_SUBFIELD_REGISTER);
2273         Sym.Hdr.Register = DefRange.CVRegister;
2274         Sym.Hdr.MayHaveNoName = 0;
2275         Sym.Hdr.OffsetInParent = DefRange.StructOffset;
2276 
2277         ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_SUBFIELD_REGISTER);
2278         BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2279                                 sizeof(SymKind));
2280         BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2281                                 sizeof(Sym.Hdr));
2282       } else {
2283         // Unclear what matters here.
2284         DefRangeRegisterSym Sym(S_DEFRANGE_REGISTER);
2285         Sym.Hdr.Register = DefRange.CVRegister;
2286         Sym.Hdr.MayHaveNoName = 0;
2287         ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
2288         BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2289                                 sizeof(SymKind));
2290         BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2291                                 sizeof(Sym.Hdr));
2292       }
2293     }
2294     OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2295   }
2296 }
2297 
2298 void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
2299   const Function &GV = MF->getFunction();
2300   assert(FnDebugInfo.count(&GV));
2301   assert(CurFn == &FnDebugInfo[&GV]);
2302 
2303   collectVariableInfo(GV.getSubprogram());
2304 
2305   // Don't emit anything if we don't have any line tables.
2306   if (!CurFn->HaveLineInfo) {
2307     FnDebugInfo.erase(&GV);
2308     CurFn = nullptr;
2309     return;
2310   }
2311 
2312   CurFn->Annotations = MF->getCodeViewAnnotations();
2313 
2314   CurFn->End = Asm->getFunctionEnd();
2315 
2316   CurFn = nullptr;
2317 }
2318 
2319 void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
2320   DebugHandlerBase::beginInstruction(MI);
2321 
2322   // Ignore DBG_VALUE locations and function prologue.
2323   if (!Asm || !CurFn || MI->isDebugValue() ||
2324       MI->getFlag(MachineInstr::FrameSetup))
2325     return;
2326 
2327   // If the first instruction of a new MBB has no location, find the first
2328   // instruction with a location and use that.
2329   DebugLoc DL = MI->getDebugLoc();
2330   if (!DL && MI->getParent() != PrevInstBB) {
2331     for (const auto &NextMI : *MI->getParent()) {
2332       if (NextMI.isDebugValue())
2333         continue;
2334       DL = NextMI.getDebugLoc();
2335       if (DL)
2336         break;
2337     }
2338   }
2339   PrevInstBB = MI->getParent();
2340 
2341   // If we still don't have a debug location, don't record a location.
2342   if (!DL)
2343     return;
2344 
2345   maybeRecordLocation(DL, Asm->MF);
2346 }
2347 
2348 MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
2349   MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2350            *EndLabel = MMI->getContext().createTempSymbol();
2351   OS.EmitIntValue(unsigned(Kind), 4);
2352   OS.AddComment("Subsection size");
2353   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2354   OS.EmitLabel(BeginLabel);
2355   return EndLabel;
2356 }
2357 
2358 void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2359   OS.EmitLabel(EndLabel);
2360   // Every subsection must be aligned to a 4-byte boundary.
2361   OS.EmitValueToAlignment(4);
2362 }
2363 
2364 void CodeViewDebug::emitDebugInfoForUDTs(
2365     ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
2366   for (const auto &UDT : UDTs) {
2367     const DIType *T = UDT.second;
2368     assert(shouldEmitUdt(T));
2369 
2370     MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
2371              *UDTRecordEnd = MMI->getContext().createTempSymbol();
2372     OS.AddComment("Record length");
2373     OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
2374     OS.EmitLabel(UDTRecordBegin);
2375 
2376     OS.AddComment("Record kind: S_UDT");
2377     OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
2378 
2379     OS.AddComment("Type");
2380     OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
2381 
2382     emitNullTerminatedSymbolName(OS, UDT.first);
2383     OS.EmitLabel(UDTRecordEnd);
2384   }
2385 }
2386 
2387 void CodeViewDebug::emitDebugInfoForGlobals() {
2388   DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2389       GlobalMap;
2390   for (const GlobalVariable &GV : MMI->getModule()->globals()) {
2391     SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2392     GV.getDebugInfo(GVEs);
2393     for (const auto *GVE : GVEs)
2394       GlobalMap[GVE] = &GV;
2395   }
2396 
2397   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2398   for (const MDNode *Node : CUs->operands()) {
2399     const auto *CU = cast<DICompileUnit>(Node);
2400 
2401     // First, emit all globals that are not in a comdat in a single symbol
2402     // substream. MSVC doesn't like it if the substream is empty, so only open
2403     // it if we have at least one global to emit.
2404     switchToDebugSectionForSymbol(nullptr);
2405     MCSymbol *EndLabel = nullptr;
2406     for (const auto *GVE : CU->getGlobalVariables()) {
2407       if (const auto *GV = GlobalMap.lookup(GVE))
2408         if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
2409           if (!EndLabel) {
2410             OS.AddComment("Symbol subsection for globals");
2411             EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
2412           }
2413           // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2414           emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
2415         }
2416     }
2417     if (EndLabel)
2418       endCVSubsection(EndLabel);
2419 
2420     // Second, emit each global that is in a comdat into its own .debug$S
2421     // section along with its own symbol substream.
2422     for (const auto *GVE : CU->getGlobalVariables()) {
2423       if (const auto *GV = GlobalMap.lookup(GVE)) {
2424         if (GV->hasComdat()) {
2425           MCSymbol *GVSym = Asm->getSymbol(GV);
2426           OS.AddComment("Symbol subsection for " +
2427                         Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
2428           switchToDebugSectionForSymbol(GVSym);
2429           EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
2430           // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2431           emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
2432           endCVSubsection(EndLabel);
2433         }
2434       }
2435     }
2436   }
2437 }
2438 
2439 void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2440   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2441   for (const MDNode *Node : CUs->operands()) {
2442     for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2443       if (DIType *RT = dyn_cast<DIType>(Ty)) {
2444         getTypeIndex(RT);
2445         // FIXME: Add to global/local DTU list.
2446       }
2447     }
2448   }
2449 }
2450 
2451 void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
2452                                            const GlobalVariable *GV,
2453                                            MCSymbol *GVSym) {
2454   // DataSym record, see SymbolRecord.h for more info.
2455   // FIXME: Thread local data, etc
2456   MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2457            *DataEnd = MMI->getContext().createTempSymbol();
2458   const unsigned FixedLengthOfThisRecord = 12;
2459   OS.AddComment("Record length");
2460   OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2461   OS.EmitLabel(DataBegin);
2462   if (DIGV->isLocalToUnit()) {
2463     if (GV->isThreadLocal()) {
2464       OS.AddComment("Record kind: S_LTHREAD32");
2465       OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2466     } else {
2467       OS.AddComment("Record kind: S_LDATA32");
2468       OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2469     }
2470   } else {
2471     if (GV->isThreadLocal()) {
2472       OS.AddComment("Record kind: S_GTHREAD32");
2473       OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2474     } else {
2475       OS.AddComment("Record kind: S_GDATA32");
2476       OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2477     }
2478   }
2479   OS.AddComment("Type");
2480   OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2481   OS.AddComment("DataOffset");
2482   OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
2483   OS.AddComment("Segment");
2484   OS.EmitCOFFSectionIndex(GVSym);
2485   OS.AddComment("Name");
2486   emitNullTerminatedSymbolName(OS, DIGV->getName(), FixedLengthOfThisRecord);
2487   OS.EmitLabel(DataEnd);
2488 }
2489