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