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