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