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