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