1 //===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains support for writing Microsoft CodeView debug info.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CodeViewDebug.h"
14 #include "llvm/ADT/APSInt.h"
15 #include "llvm/ADT/None.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/TinyPtrVector.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/BinaryFormat/COFF.h"
24 #include "llvm/BinaryFormat/Dwarf.h"
25 #include "llvm/CodeGen/AsmPrinter.h"
26 #include "llvm/CodeGen/LexicalScopes.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/TargetFrameLowering.h"
32 #include "llvm/CodeGen/TargetRegisterInfo.h"
33 #include "llvm/CodeGen/TargetSubtargetInfo.h"
34 #include "llvm/Config/llvm-config.h"
35 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
36 #include "llvm/DebugInfo/CodeView/CodeViewRecordIO.h"
37 #include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h"
38 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
39 #include "llvm/DebugInfo/CodeView/EnumTables.h"
40 #include "llvm/DebugInfo/CodeView/Line.h"
41 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
42 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
43 #include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
44 #include "llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h"
45 #include "llvm/IR/Constants.h"
46 #include "llvm/IR/DataLayout.h"
47 #include "llvm/IR/DebugInfoMetadata.h"
48 #include "llvm/IR/Function.h"
49 #include "llvm/IR/GlobalValue.h"
50 #include "llvm/IR/GlobalVariable.h"
51 #include "llvm/IR/Metadata.h"
52 #include "llvm/IR/Module.h"
53 #include "llvm/MC/MCAsmInfo.h"
54 #include "llvm/MC/MCContext.h"
55 #include "llvm/MC/MCSectionCOFF.h"
56 #include "llvm/MC/MCStreamer.h"
57 #include "llvm/MC/MCSymbol.h"
58 #include "llvm/Support/BinaryStreamWriter.h"
59 #include "llvm/Support/Casting.h"
60 #include "llvm/Support/Endian.h"
61 #include "llvm/Support/Error.h"
62 #include "llvm/Support/ErrorHandling.h"
63 #include "llvm/Support/FormatVariadic.h"
64 #include "llvm/Support/Path.h"
65 #include "llvm/Support/Program.h"
66 #include "llvm/Support/SMLoc.h"
67 #include "llvm/Support/ScopedPrinter.h"
68 #include "llvm/Target/TargetLoweringObjectFile.h"
69 #include "llvm/Target/TargetMachine.h"
70 #include <algorithm>
71 #include <cassert>
72 #include <cctype>
73 #include <cstddef>
74 #include <iterator>
75 #include <limits>
76 
77 using namespace llvm;
78 using namespace llvm::codeview;
79 
80 namespace {
81 class CVMCAdapter : public CodeViewRecordStreamer {
82 public:
83   CVMCAdapter(MCStreamer &OS, TypeCollection &TypeTable)
84       : OS(&OS), TypeTable(TypeTable) {}
85 
86   void emitBytes(StringRef Data) override { OS->emitBytes(Data); }
87 
88   void emitIntValue(uint64_t Value, unsigned Size) override {
89     OS->emitIntValueInHex(Value, Size);
90   }
91 
92   void emitBinaryData(StringRef Data) override { OS->emitBinaryData(Data); }
93 
94   void AddComment(const Twine &T) override { OS->AddComment(T); }
95 
96   void AddRawComment(const Twine &T) override { OS->emitRawComment(T); }
97 
98   bool isVerboseAsm() override { return OS->isVerboseAsm(); }
99 
100   std::string getTypeName(TypeIndex TI) override {
101     std::string TypeName;
102     if (!TI.isNoneType()) {
103       if (TI.isSimple())
104         TypeName = std::string(TypeIndex::simpleTypeName(TI));
105       else
106         TypeName = std::string(TypeTable.getTypeName(TI));
107     }
108     return TypeName;
109   }
110 
111 private:
112   MCStreamer *OS = nullptr;
113   TypeCollection &TypeTable;
114 };
115 } // namespace
116 
117 static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
118   switch (Type) {
119   case Triple::ArchType::x86:
120     return CPUType::Pentium3;
121   case Triple::ArchType::x86_64:
122     return CPUType::X64;
123   case Triple::ArchType::thumb:
124     // LLVM currently doesn't support Windows CE and so thumb
125     // here is indiscriminately mapped to ARMNT specifically.
126     return CPUType::ARMNT;
127   case Triple::ArchType::aarch64:
128     return CPUType::ARM64;
129   default:
130     report_fatal_error("target architecture doesn't map to a CodeView CPUType");
131   }
132 }
133 
134 CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
135     : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {}
136 
137 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
138   std::string &Filepath = FileToFilepathMap[File];
139   if (!Filepath.empty())
140     return Filepath;
141 
142   StringRef Dir = File->getDirectory(), Filename = File->getFilename();
143 
144   // If this is a Unix-style path, just use it as is. Don't try to canonicalize
145   // it textually because one of the path components could be a symlink.
146   if (Dir.startswith("/") || Filename.startswith("/")) {
147     if (llvm::sys::path::is_absolute(Filename, llvm::sys::path::Style::posix))
148       return Filename;
149     Filepath = std::string(Dir);
150     if (Dir.back() != '/')
151       Filepath += '/';
152     Filepath += Filename;
153     return Filepath;
154   }
155 
156   // Clang emits directory and relative filename info into the IR, but CodeView
157   // operates on full paths.  We could change Clang to emit full paths too, but
158   // that would increase the IR size and probably not needed for other users.
159   // For now, just concatenate and canonicalize the path here.
160   if (Filename.find(':') == 1)
161     Filepath = std::string(Filename);
162   else
163     Filepath = (Dir + "\\" + Filename).str();
164 
165   // Canonicalize the path.  We have to do it textually because we may no longer
166   // have access the file in the filesystem.
167   // First, replace all slashes with backslashes.
168   std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
169 
170   // Remove all "\.\" with "\".
171   size_t Cursor = 0;
172   while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
173     Filepath.erase(Cursor, 2);
174 
175   // Replace all "\XXX\..\" with "\".  Don't try too hard though as the original
176   // path should be well-formatted, e.g. start with a drive letter, etc.
177   Cursor = 0;
178   while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
179     // Something's wrong if the path starts with "\..\", abort.
180     if (Cursor == 0)
181       break;
182 
183     size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
184     if (PrevSlash == std::string::npos)
185       // Something's wrong, abort.
186       break;
187 
188     Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
189     // The next ".." might be following the one we've just erased.
190     Cursor = PrevSlash;
191   }
192 
193   // Remove all duplicate backslashes.
194   Cursor = 0;
195   while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
196     Filepath.erase(Cursor, 1);
197 
198   return Filepath;
199 }
200 
201 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
202   StringRef FullPath = getFullFilepath(F);
203   unsigned NextId = FileIdMap.size() + 1;
204   auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
205   if (Insertion.second) {
206     // We have to compute the full filepath and emit a .cv_file directive.
207     ArrayRef<uint8_t> ChecksumAsBytes;
208     FileChecksumKind CSKind = FileChecksumKind::None;
209     if (F->getChecksum()) {
210       std::string Checksum = fromHex(F->getChecksum()->Value);
211       void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
212       memcpy(CKMem, Checksum.data(), Checksum.size());
213       ChecksumAsBytes = ArrayRef<uint8_t>(
214           reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
215       switch (F->getChecksum()->Kind) {
216       case DIFile::CSK_MD5:
217         CSKind = FileChecksumKind::MD5;
218         break;
219       case DIFile::CSK_SHA1:
220         CSKind = FileChecksumKind::SHA1;
221         break;
222       case DIFile::CSK_SHA256:
223         CSKind = FileChecksumKind::SHA256;
224         break;
225       }
226     }
227     bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
228                                           static_cast<unsigned>(CSKind));
229     (void)Success;
230     assert(Success && ".cv_file directive failed");
231   }
232   return Insertion.first->second;
233 }
234 
235 CodeViewDebug::InlineSite &
236 CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
237                              const DISubprogram *Inlinee) {
238   auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
239   InlineSite *Site = &SiteInsertion.first->second;
240   if (SiteInsertion.second) {
241     unsigned ParentFuncId = CurFn->FuncId;
242     if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
243       ParentFuncId =
244           getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
245               .SiteFuncId;
246 
247     Site->SiteFuncId = NextFuncId++;
248     OS.EmitCVInlineSiteIdDirective(
249         Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
250         InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
251     Site->Inlinee = Inlinee;
252     InlinedSubprograms.insert(Inlinee);
253     getFuncIdForSubprogram(Inlinee);
254   }
255   return *Site;
256 }
257 
258 static StringRef getPrettyScopeName(const DIScope *Scope) {
259   StringRef ScopeName = Scope->getName();
260   if (!ScopeName.empty())
261     return ScopeName;
262 
263   switch (Scope->getTag()) {
264   case dwarf::DW_TAG_enumeration_type:
265   case dwarf::DW_TAG_class_type:
266   case dwarf::DW_TAG_structure_type:
267   case dwarf::DW_TAG_union_type:
268     return "<unnamed-tag>";
269   case dwarf::DW_TAG_namespace:
270     return "`anonymous namespace'";
271   default:
272     return StringRef();
273   }
274 }
275 
276 const DISubprogram *CodeViewDebug::collectParentScopeNames(
277     const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
278   const DISubprogram *ClosestSubprogram = nullptr;
279   while (Scope != nullptr) {
280     if (ClosestSubprogram == nullptr)
281       ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
282 
283     // If a type appears in a scope chain, make sure it gets emitted. The
284     // frontend will be responsible for deciding if this should be a forward
285     // declaration or a complete type.
286     if (const auto *Ty = dyn_cast<DICompositeType>(Scope))
287       DeferredCompleteTypes.push_back(Ty);
288 
289     StringRef ScopeName = getPrettyScopeName(Scope);
290     if (!ScopeName.empty())
291       QualifiedNameComponents.push_back(ScopeName);
292     Scope = Scope->getScope();
293   }
294   return ClosestSubprogram;
295 }
296 
297 static std::string formatNestedName(ArrayRef<StringRef> QualifiedNameComponents,
298                                     StringRef TypeName) {
299   std::string FullyQualifiedName;
300   for (StringRef QualifiedNameComponent :
301        llvm::reverse(QualifiedNameComponents)) {
302     FullyQualifiedName.append(std::string(QualifiedNameComponent));
303     FullyQualifiedName.append("::");
304   }
305   FullyQualifiedName.append(std::string(TypeName));
306   return FullyQualifiedName;
307 }
308 
309 struct CodeViewDebug::TypeLoweringScope {
310   TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
311   ~TypeLoweringScope() {
312     // Don't decrement TypeEmissionLevel until after emitting deferred types, so
313     // inner TypeLoweringScopes don't attempt to emit deferred types.
314     if (CVD.TypeEmissionLevel == 1)
315       CVD.emitDeferredCompleteTypes();
316     --CVD.TypeEmissionLevel;
317   }
318   CodeViewDebug &CVD;
319 };
320 
321 std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Scope,
322                                                  StringRef Name) {
323   // Ensure types in the scope chain are emitted as soon as possible.
324   // This can create otherwise a situation where S_UDTs are emitted while
325   // looping in emitDebugInfoForUDTs.
326   TypeLoweringScope S(*this);
327   SmallVector<StringRef, 5> QualifiedNameComponents;
328   collectParentScopeNames(Scope, QualifiedNameComponents);
329   return formatNestedName(QualifiedNameComponents, Name);
330 }
331 
332 std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Ty) {
333   const DIScope *Scope = Ty->getScope();
334   return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
335 }
336 
337 TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
338   // No scope means global scope and that uses the zero index.
339   //
340   // We also use zero index when the scope is a DISubprogram
341   // to suppress the emission of LF_STRING_ID for the function,
342   // which can trigger a link-time error with the linker in
343   // VS2019 version 16.11.2 or newer.
344   // Note, however, skipping the debug info emission for the DISubprogram
345   // is a temporary fix. The root issue here is that we need to figure out
346   // the proper way to encode a function nested in another function
347   // (as introduced by the Fortran 'contains' keyword) in CodeView.
348   if (!Scope || isa<DIFile>(Scope) || isa<DISubprogram>(Scope))
349     return TypeIndex();
350 
351   assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
352 
353   // Check if we've already translated this scope.
354   auto I = TypeIndices.find({Scope, nullptr});
355   if (I != TypeIndices.end())
356     return I->second;
357 
358   // Build the fully qualified name of the scope.
359   std::string ScopeName = getFullyQualifiedName(Scope);
360   StringIdRecord SID(TypeIndex(), ScopeName);
361   auto TI = TypeTable.writeLeafType(SID);
362   return recordTypeIndexForDINode(Scope, TI);
363 }
364 
365 static StringRef removeTemplateArgs(StringRef Name) {
366   // Remove template args from the display name. Assume that the template args
367   // are the last thing in the name.
368   if (Name.empty() || Name.back() != '>')
369     return Name;
370 
371   int OpenBrackets = 0;
372   for (int i = Name.size() - 1; i >= 0; --i) {
373     if (Name[i] == '>')
374       ++OpenBrackets;
375     else if (Name[i] == '<') {
376       --OpenBrackets;
377       if (OpenBrackets == 0)
378         return Name.substr(0, i);
379     }
380   }
381   return Name;
382 }
383 
384 TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
385   assert(SP);
386 
387   // Check if we've already translated this subprogram.
388   auto I = TypeIndices.find({SP, nullptr});
389   if (I != TypeIndices.end())
390     return I->second;
391 
392   // The display name includes function template arguments. Drop them to match
393   // MSVC. We need to have the template arguments in the DISubprogram name
394   // because they are used in other symbol records, such as S_GPROC32_IDs.
395   StringRef DisplayName = removeTemplateArgs(SP->getName());
396 
397   const DIScope *Scope = SP->getScope();
398   TypeIndex TI;
399   if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
400     // If the scope is a DICompositeType, then this must be a method. Member
401     // function types take some special handling, and require access to the
402     // subprogram.
403     TypeIndex ClassType = getTypeIndex(Class);
404     MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
405                                DisplayName);
406     TI = TypeTable.writeLeafType(MFuncId);
407   } else {
408     // Otherwise, this must be a free function.
409     TypeIndex ParentScope = getScopeIndex(Scope);
410     FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
411     TI = TypeTable.writeLeafType(FuncId);
412   }
413 
414   return recordTypeIndexForDINode(SP, TI);
415 }
416 
417 static bool isNonTrivial(const DICompositeType *DCTy) {
418   return ((DCTy->getFlags() & DINode::FlagNonTrivial) == DINode::FlagNonTrivial);
419 }
420 
421 static FunctionOptions
422 getFunctionOptions(const DISubroutineType *Ty,
423                    const DICompositeType *ClassTy = nullptr,
424                    StringRef SPName = StringRef("")) {
425   FunctionOptions FO = FunctionOptions::None;
426   const DIType *ReturnTy = nullptr;
427   if (auto TypeArray = Ty->getTypeArray()) {
428     if (TypeArray.size())
429       ReturnTy = TypeArray[0];
430   }
431 
432   // Add CxxReturnUdt option to functions that return nontrivial record types
433   // or methods that return record types.
434   if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy))
435     if (isNonTrivial(ReturnDCTy) || ClassTy)
436       FO |= FunctionOptions::CxxReturnUdt;
437 
438   // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison.
439   if (ClassTy && isNonTrivial(ClassTy) && SPName == ClassTy->getName()) {
440     FO |= FunctionOptions::Constructor;
441 
442   // TODO: put the FunctionOptions::ConstructorWithVirtualBases flag.
443 
444   }
445   return FO;
446 }
447 
448 TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
449                                                const DICompositeType *Class) {
450   // Always use the method declaration as the key for the function type. The
451   // method declaration contains the this adjustment.
452   if (SP->getDeclaration())
453     SP = SP->getDeclaration();
454   assert(!SP->getDeclaration() && "should use declaration as key");
455 
456   // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
457   // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
458   auto I = TypeIndices.find({SP, Class});
459   if (I != TypeIndices.end())
460     return I->second;
461 
462   // Make sure complete type info for the class is emitted *after* the member
463   // function type, as the complete class type is likely to reference this
464   // member function type.
465   TypeLoweringScope S(*this);
466   const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
467 
468   FunctionOptions FO = getFunctionOptions(SP->getType(), Class, SP->getName());
469   TypeIndex TI = lowerTypeMemberFunction(
470       SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO);
471   return recordTypeIndexForDINode(SP, TI, Class);
472 }
473 
474 TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
475                                                   TypeIndex TI,
476                                                   const DIType *ClassTy) {
477   auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
478   (void)InsertResult;
479   assert(InsertResult.second && "DINode was already assigned a type index");
480   return TI;
481 }
482 
483 unsigned CodeViewDebug::getPointerSizeInBytes() {
484   return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
485 }
486 
487 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
488                                         const LexicalScope *LS) {
489   if (const DILocation *InlinedAt = LS->getInlinedAt()) {
490     // This variable was inlined. Associate it with the InlineSite.
491     const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
492     InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
493     Site.InlinedLocals.emplace_back(Var);
494   } else {
495     // This variable goes into the corresponding lexical scope.
496     ScopeVariables[LS].emplace_back(Var);
497   }
498 }
499 
500 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
501                                const DILocation *Loc) {
502   if (!llvm::is_contained(Locs, Loc))
503     Locs.push_back(Loc);
504 }
505 
506 void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
507                                         const MachineFunction *MF) {
508   // Skip this instruction if it has the same location as the previous one.
509   if (!DL || DL == PrevInstLoc)
510     return;
511 
512   const DIScope *Scope = DL->getScope();
513   if (!Scope)
514     return;
515 
516   // Skip this line if it is longer than the maximum we can record.
517   LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
518   if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
519       LI.isNeverStepInto())
520     return;
521 
522   ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
523   if (CI.getStartColumn() != DL.getCol())
524     return;
525 
526   if (!CurFn->HaveLineInfo)
527     CurFn->HaveLineInfo = true;
528   unsigned FileId = 0;
529   if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
530     FileId = CurFn->LastFileId;
531   else
532     FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
533   PrevInstLoc = DL;
534 
535   unsigned FuncId = CurFn->FuncId;
536   if (const DILocation *SiteLoc = DL->getInlinedAt()) {
537     const DILocation *Loc = DL.get();
538 
539     // If this location was actually inlined from somewhere else, give it the ID
540     // of the inline call site.
541     FuncId =
542         getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
543 
544     // Ensure we have links in the tree of inline call sites.
545     bool FirstLoc = true;
546     while ((SiteLoc = Loc->getInlinedAt())) {
547       InlineSite &Site =
548           getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
549       if (!FirstLoc)
550         addLocIfNotPresent(Site.ChildSites, Loc);
551       FirstLoc = false;
552       Loc = SiteLoc;
553     }
554     addLocIfNotPresent(CurFn->ChildSites, Loc);
555   }
556 
557   OS.emitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
558                         /*PrologueEnd=*/false, /*IsStmt=*/false,
559                         DL->getFilename(), SMLoc());
560 }
561 
562 void CodeViewDebug::emitCodeViewMagicVersion() {
563   OS.emitValueToAlignment(4);
564   OS.AddComment("Debug section magic");
565   OS.emitInt32(COFF::DEBUG_SECTION_MAGIC);
566 }
567 
568 static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
569   switch (DWLang) {
570   case dwarf::DW_LANG_C:
571   case dwarf::DW_LANG_C89:
572   case dwarf::DW_LANG_C99:
573   case dwarf::DW_LANG_C11:
574   case dwarf::DW_LANG_ObjC:
575     return SourceLanguage::C;
576   case dwarf::DW_LANG_C_plus_plus:
577   case dwarf::DW_LANG_C_plus_plus_03:
578   case dwarf::DW_LANG_C_plus_plus_11:
579   case dwarf::DW_LANG_C_plus_plus_14:
580     return SourceLanguage::Cpp;
581   case dwarf::DW_LANG_Fortran77:
582   case dwarf::DW_LANG_Fortran90:
583   case dwarf::DW_LANG_Fortran95:
584   case dwarf::DW_LANG_Fortran03:
585   case dwarf::DW_LANG_Fortran08:
586     return SourceLanguage::Fortran;
587   case dwarf::DW_LANG_Pascal83:
588     return SourceLanguage::Pascal;
589   case dwarf::DW_LANG_Cobol74:
590   case dwarf::DW_LANG_Cobol85:
591     return SourceLanguage::Cobol;
592   case dwarf::DW_LANG_Java:
593     return SourceLanguage::Java;
594   case dwarf::DW_LANG_D:
595     return SourceLanguage::D;
596   case dwarf::DW_LANG_Swift:
597     return SourceLanguage::Swift;
598   case dwarf::DW_LANG_Rust:
599     return SourceLanguage::Rust;
600   default:
601     // There's no CodeView representation for this language, and CV doesn't
602     // have an "unknown" option for the language field, so we'll use MASM,
603     // as it's very low level.
604     return SourceLanguage::Masm;
605   }
606 }
607 
608 void CodeViewDebug::beginModule(Module *M) {
609   // If module doesn't have named metadata anchors or COFF debug section
610   // is not available, skip any debug info related stuff.
611   NamedMDNode *CUs = M->getNamedMetadata("llvm.dbg.cu");
612   if (!CUs || !Asm->getObjFileLowering().getCOFFDebugSymbolsSection()) {
613     Asm = nullptr;
614     return;
615   }
616   // Tell MMI that we have and need debug info.
617   MMI->setDebugInfoAvailability(true);
618 
619   TheCPU = mapArchToCVCPUType(Triple(M->getTargetTriple()).getArch());
620 
621   // Get the current source language.
622   const MDNode *Node = *CUs->operands().begin();
623   const auto *CU = cast<DICompileUnit>(Node);
624 
625   CurrentSourceLanguage = MapDWLangToCVLang(CU->getSourceLanguage());
626 
627   collectGlobalVariableInfo();
628 
629   // Check if we should emit type record hashes.
630   ConstantInt *GH =
631       mdconst::extract_or_null<ConstantInt>(M->getModuleFlag("CodeViewGHash"));
632   EmitDebugGlobalHashes = GH && !GH->isZero();
633 }
634 
635 void CodeViewDebug::endModule() {
636   if (!Asm || !MMI->hasDebugInfo())
637     return;
638 
639   // The COFF .debug$S section consists of several subsections, each starting
640   // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
641   // of the payload followed by the payload itself.  The subsections are 4-byte
642   // aligned.
643 
644   // Use the generic .debug$S section, and make a subsection for all the inlined
645   // subprograms.
646   switchToDebugSectionForSymbol(nullptr);
647 
648   MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
649   emitObjName();
650   emitCompilerInformation();
651   endCVSubsection(CompilerInfo);
652 
653   emitInlineeLinesSubsection();
654 
655   // Emit per-function debug information.
656   for (auto &P : FnDebugInfo)
657     if (!P.first->isDeclarationForLinker())
658       emitDebugInfoForFunction(P.first, *P.second);
659 
660   // Get types used by globals without emitting anything.
661   // This is meant to collect all static const data members so they can be
662   // emitted as globals.
663   collectDebugInfoForGlobals();
664 
665   // Emit retained types.
666   emitDebugInfoForRetainedTypes();
667 
668   // Emit global variable debug information.
669   setCurrentSubprogram(nullptr);
670   emitDebugInfoForGlobals();
671 
672   // Switch back to the generic .debug$S section after potentially processing
673   // comdat symbol sections.
674   switchToDebugSectionForSymbol(nullptr);
675 
676   // Emit UDT records for any types used by global variables.
677   if (!GlobalUDTs.empty()) {
678     MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
679     emitDebugInfoForUDTs(GlobalUDTs);
680     endCVSubsection(SymbolsEnd);
681   }
682 
683   // This subsection holds a file index to offset in string table table.
684   OS.AddComment("File index to string table offset subsection");
685   OS.emitCVFileChecksumsDirective();
686 
687   // This subsection holds the string table.
688   OS.AddComment("String table");
689   OS.emitCVStringTableDirective();
690 
691   // Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol
692   // subsection in the generic .debug$S section at the end. There is no
693   // particular reason for this ordering other than to match MSVC.
694   emitBuildInfo();
695 
696   // Emit type information and hashes last, so that any types we translate while
697   // emitting function info are included.
698   emitTypeInformation();
699 
700   if (EmitDebugGlobalHashes)
701     emitTypeGlobalHashes();
702 
703   clear();
704 }
705 
706 static void
707 emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S,
708                              unsigned MaxFixedRecordLength = 0xF00) {
709   // The maximum CV record length is 0xFF00. Most of the strings we emit appear
710   // after a fixed length portion of the record. The fixed length portion should
711   // always be less than 0xF00 (3840) bytes, so truncate the string so that the
712   // overall record size is less than the maximum allowed.
713   SmallString<32> NullTerminatedString(
714       S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
715   NullTerminatedString.push_back('\0');
716   OS.emitBytes(NullTerminatedString);
717 }
718 
719 void CodeViewDebug::emitTypeInformation() {
720   if (TypeTable.empty())
721     return;
722 
723   // Start the .debug$T or .debug$P section with 0x4.
724   OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
725   emitCodeViewMagicVersion();
726 
727   TypeTableCollection Table(TypeTable.records());
728   TypeVisitorCallbackPipeline Pipeline;
729 
730   // To emit type record using Codeview MCStreamer adapter
731   CVMCAdapter CVMCOS(OS, Table);
732   TypeRecordMapping typeMapping(CVMCOS);
733   Pipeline.addCallbackToPipeline(typeMapping);
734 
735   Optional<TypeIndex> B = Table.getFirst();
736   while (B) {
737     // This will fail if the record data is invalid.
738     CVType Record = Table.getType(*B);
739 
740     Error E = codeview::visitTypeRecord(Record, *B, Pipeline);
741 
742     if (E) {
743       logAllUnhandledErrors(std::move(E), errs(), "error: ");
744       llvm_unreachable("produced malformed type record");
745     }
746 
747     B = Table.getNext(*B);
748   }
749 }
750 
751 void CodeViewDebug::emitTypeGlobalHashes() {
752   if (TypeTable.empty())
753     return;
754 
755   // Start the .debug$H section with the version and hash algorithm, currently
756   // hardcoded to version 0, SHA1.
757   OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
758 
759   OS.emitValueToAlignment(4);
760   OS.AddComment("Magic");
761   OS.emitInt32(COFF::DEBUG_HASHES_SECTION_MAGIC);
762   OS.AddComment("Section Version");
763   OS.emitInt16(0);
764   OS.AddComment("Hash Algorithm");
765   OS.emitInt16(uint16_t(GlobalTypeHashAlg::SHA1_8));
766 
767   TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
768   for (const auto &GHR : TypeTable.hashes()) {
769     if (OS.isVerboseAsm()) {
770       // Emit an EOL-comment describing which TypeIndex this hash corresponds
771       // to, as well as the stringified SHA1 hash.
772       SmallString<32> Comment;
773       raw_svector_ostream CommentOS(Comment);
774       CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
775       OS.AddComment(Comment);
776       ++TI;
777     }
778     assert(GHR.Hash.size() == 8);
779     StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
780                 GHR.Hash.size());
781     OS.emitBinaryData(S);
782   }
783 }
784 
785 void CodeViewDebug::emitObjName() {
786   MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_OBJNAME);
787 
788   StringRef PathRef(Asm->TM.Options.ObjectFilenameForDebug);
789   llvm::SmallString<256> PathStore(PathRef);
790 
791   if (PathRef.empty() || PathRef == "-") {
792     // Don't emit the filename if we're writing to stdout or to /dev/null.
793     PathRef = {};
794   } else {
795     llvm::sys::path::remove_dots(PathStore, /*remove_dot_dot=*/true);
796     PathRef = PathStore;
797   }
798 
799   OS.AddComment("Signature");
800   OS.emitIntValue(0, 4);
801 
802   OS.AddComment("Object name");
803   emitNullTerminatedSymbolName(OS, PathRef);
804 
805   endSymbolRecord(CompilerEnd);
806 }
807 
808 namespace {
809 struct Version {
810   int Part[4];
811 };
812 } // end anonymous namespace
813 
814 // Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
815 // the version number.
816 static Version parseVersion(StringRef Name) {
817   Version V = {{0}};
818   int N = 0;
819   for (const char C : Name) {
820     if (isdigit(C)) {
821       V.Part[N] *= 10;
822       V.Part[N] += C - '0';
823       V.Part[N] =
824           std::min<int>(V.Part[N], std::numeric_limits<uint16_t>::max());
825     } else if (C == '.') {
826       ++N;
827       if (N >= 4)
828         return V;
829     } else if (N > 0)
830       return V;
831   }
832   return V;
833 }
834 
835 void CodeViewDebug::emitCompilerInformation() {
836   MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_COMPILE3);
837   uint32_t Flags = 0;
838 
839   // The low byte of the flags indicates the source language.
840   Flags = CurrentSourceLanguage;
841   // TODO:  Figure out which other flags need to be set.
842   if (MMI->getModule()->getProfileSummary(/*IsCS*/ false) != nullptr) {
843     Flags |= static_cast<uint32_t>(CompileSym3Flags::PGO);
844   }
845   using ArchType = llvm::Triple::ArchType;
846   ArchType Arch = Triple(MMI->getModule()->getTargetTriple()).getArch();
847   if (Asm->TM.Options.Hotpatch || Arch == ArchType::thumb ||
848       Arch == ArchType::aarch64) {
849     Flags |= static_cast<uint32_t>(CompileSym3Flags::HotPatch);
850   }
851 
852   OS.AddComment("Flags and language");
853   OS.emitInt32(Flags);
854 
855   OS.AddComment("CPUType");
856   OS.emitInt16(static_cast<uint64_t>(TheCPU));
857 
858   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
859   const MDNode *Node = *CUs->operands().begin();
860   const auto *CU = cast<DICompileUnit>(Node);
861 
862   StringRef CompilerVersion = CU->getProducer();
863   Version FrontVer = parseVersion(CompilerVersion);
864   OS.AddComment("Frontend version");
865   for (int N : FrontVer.Part) {
866     OS.emitInt16(N);
867   }
868 
869   // Some Microsoft tools, like Binscope, expect a backend version number of at
870   // least 8.something, so we'll coerce the LLVM version into a form that
871   // guarantees it'll be big enough without really lying about the version.
872   int Major = 1000 * LLVM_VERSION_MAJOR +
873               10 * LLVM_VERSION_MINOR +
874               LLVM_VERSION_PATCH;
875   // Clamp it for builds that use unusually large version numbers.
876   Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
877   Version BackVer = {{ Major, 0, 0, 0 }};
878   OS.AddComment("Backend version");
879   for (int N : BackVer.Part)
880     OS.emitInt16(N);
881 
882   OS.AddComment("Null-terminated compiler version string");
883   emitNullTerminatedSymbolName(OS, CompilerVersion);
884 
885   endSymbolRecord(CompilerEnd);
886 }
887 
888 static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable,
889                                     StringRef S) {
890   StringIdRecord SIR(TypeIndex(0x0), S);
891   return TypeTable.writeLeafType(SIR);
892 }
893 
894 static std::string flattenCommandLine(ArrayRef<std::string> Args,
895                                       StringRef MainFilename) {
896   std::string FlatCmdLine;
897   raw_string_ostream OS(FlatCmdLine);
898   bool PrintedOneArg = false;
899   if (!StringRef(Args[0]).contains("-cc1")) {
900     llvm::sys::printArg(OS, "-cc1", /*Quote=*/true);
901     PrintedOneArg = true;
902   }
903   for (unsigned i = 0; i < Args.size(); i++) {
904     StringRef Arg = Args[i];
905     if (Arg.empty())
906       continue;
907     if (Arg == "-main-file-name" || Arg == "-o") {
908       i++; // Skip this argument and next one.
909       continue;
910     }
911     if (Arg.startswith("-object-file-name") || Arg == MainFilename)
912       continue;
913     if (PrintedOneArg)
914       OS << " ";
915     llvm::sys::printArg(OS, Arg, /*Quote=*/true);
916     PrintedOneArg = true;
917   }
918   OS.flush();
919   return FlatCmdLine;
920 }
921 
922 void CodeViewDebug::emitBuildInfo() {
923   // First, make LF_BUILDINFO. It's a sequence of strings with various bits of
924   // build info. The known prefix is:
925   // - Absolute path of current directory
926   // - Compiler path
927   // - Main source file path, relative to CWD or absolute
928   // - Type server PDB file
929   // - Canonical compiler command line
930   // If frontend and backend compilation are separated (think llc or LTO), it's
931   // not clear if the compiler path should refer to the executable for the
932   // frontend or the backend. Leave it blank for now.
933   TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {};
934   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
935   const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs.
936   const auto *CU = cast<DICompileUnit>(Node);
937   const DIFile *MainSourceFile = CU->getFile();
938   BuildInfoArgs[BuildInfoRecord::CurrentDirectory] =
939       getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory());
940   BuildInfoArgs[BuildInfoRecord::SourceFile] =
941       getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename());
942   // FIXME: PDB is intentionally blank unless we implement /Zi type servers.
943   BuildInfoArgs[BuildInfoRecord::TypeServerPDB] =
944       getStringIdTypeIdx(TypeTable, "");
945   if (Asm->TM.Options.MCOptions.Argv0 != nullptr) {
946     BuildInfoArgs[BuildInfoRecord::BuildTool] =
947         getStringIdTypeIdx(TypeTable, Asm->TM.Options.MCOptions.Argv0);
948     BuildInfoArgs[BuildInfoRecord::CommandLine] = getStringIdTypeIdx(
949         TypeTable, flattenCommandLine(Asm->TM.Options.MCOptions.CommandLineArgs,
950                                       MainSourceFile->getFilename()));
951   }
952   BuildInfoRecord BIR(BuildInfoArgs);
953   TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR);
954 
955   // Make a new .debug$S subsection for the S_BUILDINFO record, which points
956   // from the module symbols into the type stream.
957   MCSymbol *BISubsecEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
958   MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO);
959   OS.AddComment("LF_BUILDINFO index");
960   OS.emitInt32(BuildInfoIndex.getIndex());
961   endSymbolRecord(BIEnd);
962   endCVSubsection(BISubsecEnd);
963 }
964 
965 void CodeViewDebug::emitInlineeLinesSubsection() {
966   if (InlinedSubprograms.empty())
967     return;
968 
969   OS.AddComment("Inlinee lines subsection");
970   MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
971 
972   // We emit the checksum info for files.  This is used by debuggers to
973   // determine if a pdb matches the source before loading it.  Visual Studio,
974   // for instance, will display a warning that the breakpoints are not valid if
975   // the pdb does not match the source.
976   OS.AddComment("Inlinee lines signature");
977   OS.emitInt32(unsigned(InlineeLinesSignature::Normal));
978 
979   for (const DISubprogram *SP : InlinedSubprograms) {
980     assert(TypeIndices.count({SP, nullptr}));
981     TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
982 
983     OS.AddBlankLine();
984     unsigned FileId = maybeRecordFile(SP->getFile());
985     OS.AddComment("Inlined function " + SP->getName() + " starts at " +
986                   SP->getFilename() + Twine(':') + Twine(SP->getLine()));
987     OS.AddBlankLine();
988     OS.AddComment("Type index of inlined function");
989     OS.emitInt32(InlineeIdx.getIndex());
990     OS.AddComment("Offset into filechecksum table");
991     OS.emitCVFileChecksumOffsetDirective(FileId);
992     OS.AddComment("Starting line number");
993     OS.emitInt32(SP->getLine());
994   }
995 
996   endCVSubsection(InlineEnd);
997 }
998 
999 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
1000                                         const DILocation *InlinedAt,
1001                                         const InlineSite &Site) {
1002   assert(TypeIndices.count({Site.Inlinee, nullptr}));
1003   TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
1004 
1005   // SymbolRecord
1006   MCSymbol *InlineEnd = beginSymbolRecord(SymbolKind::S_INLINESITE);
1007 
1008   OS.AddComment("PtrParent");
1009   OS.emitInt32(0);
1010   OS.AddComment("PtrEnd");
1011   OS.emitInt32(0);
1012   OS.AddComment("Inlinee type index");
1013   OS.emitInt32(InlineeIdx.getIndex());
1014 
1015   unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
1016   unsigned StartLineNum = Site.Inlinee->getLine();
1017 
1018   OS.emitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
1019                                     FI.Begin, FI.End);
1020 
1021   endSymbolRecord(InlineEnd);
1022 
1023   emitLocalVariableList(FI, Site.InlinedLocals);
1024 
1025   // Recurse on child inlined call sites before closing the scope.
1026   for (const DILocation *ChildSite : Site.ChildSites) {
1027     auto I = FI.InlineSites.find(ChildSite);
1028     assert(I != FI.InlineSites.end() &&
1029            "child site not in function inline site map");
1030     emitInlinedCallSite(FI, ChildSite, I->second);
1031   }
1032 
1033   // Close the scope.
1034   emitEndSymbolRecord(SymbolKind::S_INLINESITE_END);
1035 }
1036 
1037 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
1038   // If we have a symbol, it may be in a section that is COMDAT. If so, find the
1039   // comdat key. A section may be comdat because of -ffunction-sections or
1040   // because it is comdat in the IR.
1041   MCSectionCOFF *GVSec =
1042       GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
1043   const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
1044 
1045   MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
1046       Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
1047   DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
1048 
1049   OS.SwitchSection(DebugSec);
1050 
1051   // Emit the magic version number if this is the first time we've switched to
1052   // this section.
1053   if (ComdatDebugSections.insert(DebugSec).second)
1054     emitCodeViewMagicVersion();
1055 }
1056 
1057 // Emit an S_THUNK32/S_END symbol pair for a thunk routine.
1058 // The only supported thunk ordinal is currently the standard type.
1059 void CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
1060                                           FunctionInfo &FI,
1061                                           const MCSymbol *Fn) {
1062   std::string FuncName =
1063       std::string(GlobalValue::dropLLVMManglingEscape(GV->getName()));
1064   const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
1065 
1066   OS.AddComment("Symbol subsection for " + Twine(FuncName));
1067   MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
1068 
1069   // Emit S_THUNK32
1070   MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32);
1071   OS.AddComment("PtrParent");
1072   OS.emitInt32(0);
1073   OS.AddComment("PtrEnd");
1074   OS.emitInt32(0);
1075   OS.AddComment("PtrNext");
1076   OS.emitInt32(0);
1077   OS.AddComment("Thunk section relative address");
1078   OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
1079   OS.AddComment("Thunk section index");
1080   OS.EmitCOFFSectionIndex(Fn);
1081   OS.AddComment("Code size");
1082   OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
1083   OS.AddComment("Ordinal");
1084   OS.emitInt8(unsigned(ordinal));
1085   OS.AddComment("Function name");
1086   emitNullTerminatedSymbolName(OS, FuncName);
1087   // Additional fields specific to the thunk ordinal would go here.
1088   endSymbolRecord(ThunkRecordEnd);
1089 
1090   // Local variables/inlined routines are purposely omitted here.  The point of
1091   // marking this as a thunk is so Visual Studio will NOT stop in this routine.
1092 
1093   // Emit S_PROC_ID_END
1094   emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
1095 
1096   endCVSubsection(SymbolsEnd);
1097 }
1098 
1099 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
1100                                              FunctionInfo &FI) {
1101   // For each function there is a separate subsection which holds the PC to
1102   // file:line table.
1103   const MCSymbol *Fn = Asm->getSymbol(GV);
1104   assert(Fn);
1105 
1106   // Switch to the to a comdat section, if appropriate.
1107   switchToDebugSectionForSymbol(Fn);
1108 
1109   std::string FuncName;
1110   auto *SP = GV->getSubprogram();
1111   assert(SP);
1112   setCurrentSubprogram(SP);
1113 
1114   if (SP->isThunk()) {
1115     emitDebugInfoForThunk(GV, FI, Fn);
1116     return;
1117   }
1118 
1119   // If we have a display name, build the fully qualified name by walking the
1120   // chain of scopes.
1121   if (!SP->getName().empty())
1122     FuncName = getFullyQualifiedName(SP->getScope(), SP->getName());
1123 
1124   // If our DISubprogram name is empty, use the mangled name.
1125   if (FuncName.empty())
1126     FuncName = std::string(GlobalValue::dropLLVMManglingEscape(GV->getName()));
1127 
1128   // Emit FPO data, but only on 32-bit x86. No other platforms use it.
1129   if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
1130     OS.EmitCVFPOData(Fn);
1131 
1132   // Emit a symbol subsection, required by VS2012+ to find function boundaries.
1133   OS.AddComment("Symbol subsection for " + Twine(FuncName));
1134   MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
1135   {
1136     SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID
1137                                                 : SymbolKind::S_GPROC32_ID;
1138     MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind);
1139 
1140     // These fields are filled in by tools like CVPACK which run after the fact.
1141     OS.AddComment("PtrParent");
1142     OS.emitInt32(0);
1143     OS.AddComment("PtrEnd");
1144     OS.emitInt32(0);
1145     OS.AddComment("PtrNext");
1146     OS.emitInt32(0);
1147     // This is the important bit that tells the debugger where the function
1148     // code is located and what's its size:
1149     OS.AddComment("Code size");
1150     OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
1151     OS.AddComment("Offset after prologue");
1152     OS.emitInt32(0);
1153     OS.AddComment("Offset before epilogue");
1154     OS.emitInt32(0);
1155     OS.AddComment("Function type index");
1156     OS.emitInt32(getFuncIdForSubprogram(GV->getSubprogram()).getIndex());
1157     OS.AddComment("Function section relative address");
1158     OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
1159     OS.AddComment("Function section index");
1160     OS.EmitCOFFSectionIndex(Fn);
1161     OS.AddComment("Flags");
1162     OS.emitInt8(0);
1163     // Emit the function display name as a null-terminated string.
1164     OS.AddComment("Function name");
1165     // Truncate the name so we won't overflow the record length field.
1166     emitNullTerminatedSymbolName(OS, FuncName);
1167     endSymbolRecord(ProcRecordEnd);
1168 
1169     MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC);
1170     // Subtract out the CSR size since MSVC excludes that and we include it.
1171     OS.AddComment("FrameSize");
1172     OS.emitInt32(FI.FrameSize - FI.CSRSize);
1173     OS.AddComment("Padding");
1174     OS.emitInt32(0);
1175     OS.AddComment("Offset of padding");
1176     OS.emitInt32(0);
1177     OS.AddComment("Bytes of callee saved registers");
1178     OS.emitInt32(FI.CSRSize);
1179     OS.AddComment("Exception handler offset");
1180     OS.emitInt32(0);
1181     OS.AddComment("Exception handler section");
1182     OS.emitInt16(0);
1183     OS.AddComment("Flags (defines frame register)");
1184     OS.emitInt32(uint32_t(FI.FrameProcOpts));
1185     endSymbolRecord(FrameProcEnd);
1186 
1187     emitLocalVariableList(FI, FI.Locals);
1188     emitGlobalVariableList(FI.Globals);
1189     emitLexicalBlockList(FI.ChildBlocks, FI);
1190 
1191     // Emit inlined call site information. Only emit functions inlined directly
1192     // into the parent function. We'll emit the other sites recursively as part
1193     // of their parent inline site.
1194     for (const DILocation *InlinedAt : FI.ChildSites) {
1195       auto I = FI.InlineSites.find(InlinedAt);
1196       assert(I != FI.InlineSites.end() &&
1197              "child site not in function inline site map");
1198       emitInlinedCallSite(FI, InlinedAt, I->second);
1199     }
1200 
1201     for (auto Annot : FI.Annotations) {
1202       MCSymbol *Label = Annot.first;
1203       MDTuple *Strs = cast<MDTuple>(Annot.second);
1204       MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION);
1205       OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
1206       // FIXME: Make sure we don't overflow the max record size.
1207       OS.EmitCOFFSectionIndex(Label);
1208       OS.emitInt16(Strs->getNumOperands());
1209       for (Metadata *MD : Strs->operands()) {
1210         // MDStrings are null terminated, so we can do EmitBytes and get the
1211         // nice .asciz directive.
1212         StringRef Str = cast<MDString>(MD)->getString();
1213         assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
1214         OS.emitBytes(StringRef(Str.data(), Str.size() + 1));
1215       }
1216       endSymbolRecord(AnnotEnd);
1217     }
1218 
1219     for (auto HeapAllocSite : FI.HeapAllocSites) {
1220       const MCSymbol *BeginLabel = std::get<0>(HeapAllocSite);
1221       const MCSymbol *EndLabel = std::get<1>(HeapAllocSite);
1222       const DIType *DITy = std::get<2>(HeapAllocSite);
1223       MCSymbol *HeapAllocEnd = beginSymbolRecord(SymbolKind::S_HEAPALLOCSITE);
1224       OS.AddComment("Call site offset");
1225       OS.EmitCOFFSecRel32(BeginLabel, /*Offset=*/0);
1226       OS.AddComment("Call site section index");
1227       OS.EmitCOFFSectionIndex(BeginLabel);
1228       OS.AddComment("Call instruction length");
1229       OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
1230       OS.AddComment("Type index");
1231       OS.emitInt32(getCompleteTypeIndex(DITy).getIndex());
1232       endSymbolRecord(HeapAllocEnd);
1233     }
1234 
1235     if (SP != nullptr)
1236       emitDebugInfoForUDTs(LocalUDTs);
1237 
1238     // We're done with this function.
1239     emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
1240   }
1241   endCVSubsection(SymbolsEnd);
1242 
1243   // We have an assembler directive that takes care of the whole line table.
1244   OS.emitCVLinetableDirective(FI.FuncId, Fn, FI.End);
1245 }
1246 
1247 CodeViewDebug::LocalVarDefRange
1248 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
1249   LocalVarDefRange DR;
1250   DR.InMemory = -1;
1251   DR.DataOffset = Offset;
1252   assert(DR.DataOffset == Offset && "truncation");
1253   DR.IsSubfield = 0;
1254   DR.StructOffset = 0;
1255   DR.CVRegister = CVRegister;
1256   return DR;
1257 }
1258 
1259 void CodeViewDebug::collectVariableInfoFromMFTable(
1260     DenseSet<InlinedEntity> &Processed) {
1261   const MachineFunction &MF = *Asm->MF;
1262   const TargetSubtargetInfo &TSI = MF.getSubtarget();
1263   const TargetFrameLowering *TFI = TSI.getFrameLowering();
1264   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1265 
1266   for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
1267     if (!VI.Var)
1268       continue;
1269     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1270            "Expected inlined-at fields to agree");
1271 
1272     Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
1273     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1274 
1275     // If variable scope is not found then skip this variable.
1276     if (!Scope)
1277       continue;
1278 
1279     // If the variable has an attached offset expression, extract it.
1280     // FIXME: Try to handle DW_OP_deref as well.
1281     int64_t ExprOffset = 0;
1282     bool Deref = false;
1283     if (VI.Expr) {
1284       // If there is one DW_OP_deref element, use offset of 0 and keep going.
1285       if (VI.Expr->getNumElements() == 1 &&
1286           VI.Expr->getElement(0) == llvm::dwarf::DW_OP_deref)
1287         Deref = true;
1288       else if (!VI.Expr->extractIfOffset(ExprOffset))
1289         continue;
1290     }
1291 
1292     // Get the frame register used and the offset.
1293     Register FrameReg;
1294     StackOffset FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
1295     uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
1296 
1297     assert(!FrameOffset.getScalable() &&
1298            "Frame offsets with a scalable component are not supported");
1299 
1300     // Calculate the label ranges.
1301     LocalVarDefRange DefRange =
1302         createDefRangeMem(CVReg, FrameOffset.getFixed() + ExprOffset);
1303 
1304     for (const InsnRange &Range : Scope->getRanges()) {
1305       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1306       const MCSymbol *End = getLabelAfterInsn(Range.second);
1307       End = End ? End : Asm->getFunctionEnd();
1308       DefRange.Ranges.emplace_back(Begin, End);
1309     }
1310 
1311     LocalVariable Var;
1312     Var.DIVar = VI.Var;
1313     Var.DefRanges.emplace_back(std::move(DefRange));
1314     if (Deref)
1315       Var.UseReferenceType = true;
1316 
1317     recordLocalVariable(std::move(Var), Scope);
1318   }
1319 }
1320 
1321 static bool canUseReferenceType(const DbgVariableLocation &Loc) {
1322   return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
1323 }
1324 
1325 static bool needsReferenceType(const DbgVariableLocation &Loc) {
1326   return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
1327 }
1328 
1329 void CodeViewDebug::calculateRanges(
1330     LocalVariable &Var, const DbgValueHistoryMap::Entries &Entries) {
1331   const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1332 
1333   // Calculate the definition ranges.
1334   for (auto I = Entries.begin(), E = Entries.end(); I != E; ++I) {
1335     const auto &Entry = *I;
1336     if (!Entry.isDbgValue())
1337       continue;
1338     const MachineInstr *DVInst = Entry.getInstr();
1339     assert(DVInst->isDebugValue() && "Invalid History entry");
1340     // FIXME: Find a way to represent constant variables, since they are
1341     // relatively common.
1342     Optional<DbgVariableLocation> Location =
1343         DbgVariableLocation::extractFromMachineInstruction(*DVInst);
1344     if (!Location)
1345       continue;
1346 
1347     // CodeView can only express variables in register and variables in memory
1348     // at a constant offset from a register. However, for variables passed
1349     // indirectly by pointer, it is common for that pointer to be spilled to a
1350     // stack location. For the special case of one offseted load followed by a
1351     // zero offset load (a pointer spilled to the stack), we change the type of
1352     // the local variable from a value type to a reference type. This tricks the
1353     // debugger into doing the load for us.
1354     if (Var.UseReferenceType) {
1355       // We're using a reference type. Drop the last zero offset load.
1356       if (canUseReferenceType(*Location))
1357         Location->LoadChain.pop_back();
1358       else
1359         continue;
1360     } else if (needsReferenceType(*Location)) {
1361       // This location can't be expressed without switching to a reference type.
1362       // Start over using that.
1363       Var.UseReferenceType = true;
1364       Var.DefRanges.clear();
1365       calculateRanges(Var, Entries);
1366       return;
1367     }
1368 
1369     // We can only handle a register or an offseted load of a register.
1370     if (Location->Register == 0 || Location->LoadChain.size() > 1)
1371       continue;
1372     {
1373       LocalVarDefRange DR;
1374       DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
1375       DR.InMemory = !Location->LoadChain.empty();
1376       DR.DataOffset =
1377           !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
1378       if (Location->FragmentInfo) {
1379         DR.IsSubfield = true;
1380         DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
1381       } else {
1382         DR.IsSubfield = false;
1383         DR.StructOffset = 0;
1384       }
1385 
1386       if (Var.DefRanges.empty() ||
1387           Var.DefRanges.back().isDifferentLocation(DR)) {
1388         Var.DefRanges.emplace_back(std::move(DR));
1389       }
1390     }
1391 
1392     // Compute the label range.
1393     const MCSymbol *Begin = getLabelBeforeInsn(Entry.getInstr());
1394     const MCSymbol *End;
1395     if (Entry.getEndIndex() != DbgValueHistoryMap::NoEntry) {
1396       auto &EndingEntry = Entries[Entry.getEndIndex()];
1397       End = EndingEntry.isDbgValue()
1398                 ? getLabelBeforeInsn(EndingEntry.getInstr())
1399                 : getLabelAfterInsn(EndingEntry.getInstr());
1400     } else
1401       End = Asm->getFunctionEnd();
1402 
1403     // If the last range end is our begin, just extend the last range.
1404     // Otherwise make a new range.
1405     SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1406         Var.DefRanges.back().Ranges;
1407     if (!R.empty() && R.back().second == Begin)
1408       R.back().second = End;
1409     else
1410       R.emplace_back(Begin, End);
1411 
1412     // FIXME: Do more range combining.
1413   }
1414 }
1415 
1416 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
1417   DenseSet<InlinedEntity> Processed;
1418   // Grab the variable info that was squirreled away in the MMI side-table.
1419   collectVariableInfoFromMFTable(Processed);
1420 
1421   for (const auto &I : DbgValues) {
1422     InlinedEntity IV = I.first;
1423     if (Processed.count(IV))
1424       continue;
1425     const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
1426     const DILocation *InlinedAt = IV.second;
1427 
1428     // Instruction ranges, specifying where IV is accessible.
1429     const auto &Entries = I.second;
1430 
1431     LexicalScope *Scope = nullptr;
1432     if (InlinedAt)
1433       Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1434     else
1435       Scope = LScopes.findLexicalScope(DIVar->getScope());
1436     // If variable scope is not found then skip this variable.
1437     if (!Scope)
1438       continue;
1439 
1440     LocalVariable Var;
1441     Var.DIVar = DIVar;
1442 
1443     calculateRanges(Var, Entries);
1444     recordLocalVariable(std::move(Var), Scope);
1445   }
1446 }
1447 
1448 void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
1449   const TargetSubtargetInfo &TSI = MF->getSubtarget();
1450   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1451   const MachineFrameInfo &MFI = MF->getFrameInfo();
1452   const Function &GV = MF->getFunction();
1453   auto Insertion = FnDebugInfo.insert({&GV, std::make_unique<FunctionInfo>()});
1454   assert(Insertion.second && "function already has info");
1455   CurFn = Insertion.first->second.get();
1456   CurFn->FuncId = NextFuncId++;
1457   CurFn->Begin = Asm->getFunctionBegin();
1458 
1459   // The S_FRAMEPROC record reports the stack size, and how many bytes of
1460   // callee-saved registers were used. For targets that don't use a PUSH
1461   // instruction (AArch64), this will be zero.
1462   CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
1463   CurFn->FrameSize = MFI.getStackSize();
1464   CurFn->OffsetAdjustment = MFI.getOffsetAdjustment();
1465   CurFn->HasStackRealignment = TRI->hasStackRealignment(*MF);
1466 
1467   // For this function S_FRAMEPROC record, figure out which codeview register
1468   // will be the frame pointer.
1469   CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
1470   CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
1471   if (CurFn->FrameSize > 0) {
1472     if (!TSI.getFrameLowering()->hasFP(*MF)) {
1473       CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1474       CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
1475     } else {
1476       // If there is an FP, parameters are always relative to it.
1477       CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
1478       if (CurFn->HasStackRealignment) {
1479         // If the stack needs realignment, locals are relative to SP or VFRAME.
1480         CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1481       } else {
1482         // Otherwise, locals are relative to EBP, and we probably have VLAs or
1483         // other stack adjustments.
1484         CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
1485       }
1486     }
1487   }
1488 
1489   // Compute other frame procedure options.
1490   FrameProcedureOptions FPO = FrameProcedureOptions::None;
1491   if (MFI.hasVarSizedObjects())
1492     FPO |= FrameProcedureOptions::HasAlloca;
1493   if (MF->exposesReturnsTwice())
1494     FPO |= FrameProcedureOptions::HasSetJmp;
1495   // FIXME: Set HasLongJmp if we ever track that info.
1496   if (MF->hasInlineAsm())
1497     FPO |= FrameProcedureOptions::HasInlineAssembly;
1498   if (GV.hasPersonalityFn()) {
1499     if (isAsynchronousEHPersonality(
1500             classifyEHPersonality(GV.getPersonalityFn())))
1501       FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
1502     else
1503       FPO |= FrameProcedureOptions::HasExceptionHandling;
1504   }
1505   if (GV.hasFnAttribute(Attribute::InlineHint))
1506     FPO |= FrameProcedureOptions::MarkedInline;
1507   if (GV.hasFnAttribute(Attribute::Naked))
1508     FPO |= FrameProcedureOptions::Naked;
1509   if (MFI.hasStackProtectorIndex())
1510     FPO |= FrameProcedureOptions::SecurityChecks;
1511   FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
1512   FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
1513   if (Asm->TM.getOptLevel() != CodeGenOpt::None &&
1514       !GV.hasOptSize() && !GV.hasOptNone())
1515     FPO |= FrameProcedureOptions::OptimizedForSpeed;
1516   if (GV.hasProfileData()) {
1517     FPO |= FrameProcedureOptions::ValidProfileCounts;
1518     FPO |= FrameProcedureOptions::ProfileGuidedOptimization;
1519   }
1520   // FIXME: Set GuardCfg when it is implemented.
1521   CurFn->FrameProcOpts = FPO;
1522 
1523   OS.EmitCVFuncIdDirective(CurFn->FuncId);
1524 
1525   // Find the end of the function prolog.  First known non-DBG_VALUE and
1526   // non-frame setup location marks the beginning of the function body.
1527   // FIXME: is there a simpler a way to do this? Can we just search
1528   // for the first instruction of the function, not the last of the prolog?
1529   DebugLoc PrologEndLoc;
1530   bool EmptyPrologue = true;
1531   for (const auto &MBB : *MF) {
1532     for (const auto &MI : MBB) {
1533       if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1534           MI.getDebugLoc()) {
1535         PrologEndLoc = MI.getDebugLoc();
1536         break;
1537       } else if (!MI.isMetaInstruction()) {
1538         EmptyPrologue = false;
1539       }
1540     }
1541   }
1542 
1543   // Record beginning of function if we have a non-empty prologue.
1544   if (PrologEndLoc && !EmptyPrologue) {
1545     DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
1546     maybeRecordLocation(FnStartDL, MF);
1547   }
1548 
1549   // Find heap alloc sites and emit labels around them.
1550   for (const auto &MBB : *MF) {
1551     for (const auto &MI : MBB) {
1552       if (MI.getHeapAllocMarker()) {
1553         requestLabelBeforeInsn(&MI);
1554         requestLabelAfterInsn(&MI);
1555       }
1556     }
1557   }
1558 }
1559 
1560 static bool shouldEmitUdt(const DIType *T) {
1561   if (!T)
1562     return false;
1563 
1564   // MSVC does not emit UDTs for typedefs that are scoped to classes.
1565   if (T->getTag() == dwarf::DW_TAG_typedef) {
1566     if (DIScope *Scope = T->getScope()) {
1567       switch (Scope->getTag()) {
1568       case dwarf::DW_TAG_structure_type:
1569       case dwarf::DW_TAG_class_type:
1570       case dwarf::DW_TAG_union_type:
1571         return false;
1572       default:
1573           // do nothing.
1574           ;
1575       }
1576     }
1577   }
1578 
1579   while (true) {
1580     if (!T || T->isForwardDecl())
1581       return false;
1582 
1583     const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
1584     if (!DT)
1585       return true;
1586     T = DT->getBaseType();
1587   }
1588   return true;
1589 }
1590 
1591 void CodeViewDebug::addToUDTs(const DIType *Ty) {
1592   // Don't record empty UDTs.
1593   if (Ty->getName().empty())
1594     return;
1595   if (!shouldEmitUdt(Ty))
1596     return;
1597 
1598   SmallVector<StringRef, 5> ParentScopeNames;
1599   const DISubprogram *ClosestSubprogram =
1600       collectParentScopeNames(Ty->getScope(), ParentScopeNames);
1601 
1602   std::string FullyQualifiedName =
1603       formatNestedName(ParentScopeNames, getPrettyScopeName(Ty));
1604 
1605   if (ClosestSubprogram == nullptr) {
1606     GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1607   } else if (ClosestSubprogram == CurrentSubprogram) {
1608     LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1609   }
1610 
1611   // TODO: What if the ClosestSubprogram is neither null or the current
1612   // subprogram?  Currently, the UDT just gets dropped on the floor.
1613   //
1614   // The current behavior is not desirable.  To get maximal fidelity, we would
1615   // need to perform all type translation before beginning emission of .debug$S
1616   // and then make LocalUDTs a member of FunctionInfo
1617 }
1618 
1619 TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
1620   // Generic dispatch for lowering an unknown type.
1621   switch (Ty->getTag()) {
1622   case dwarf::DW_TAG_array_type:
1623     return lowerTypeArray(cast<DICompositeType>(Ty));
1624   case dwarf::DW_TAG_typedef:
1625     return lowerTypeAlias(cast<DIDerivedType>(Ty));
1626   case dwarf::DW_TAG_base_type:
1627     return lowerTypeBasic(cast<DIBasicType>(Ty));
1628   case dwarf::DW_TAG_pointer_type:
1629     if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1630       return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1631     LLVM_FALLTHROUGH;
1632   case dwarf::DW_TAG_reference_type:
1633   case dwarf::DW_TAG_rvalue_reference_type:
1634     return lowerTypePointer(cast<DIDerivedType>(Ty));
1635   case dwarf::DW_TAG_ptr_to_member_type:
1636     return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1637   case dwarf::DW_TAG_restrict_type:
1638   case dwarf::DW_TAG_const_type:
1639   case dwarf::DW_TAG_volatile_type:
1640   // TODO: add support for DW_TAG_atomic_type here
1641     return lowerTypeModifier(cast<DIDerivedType>(Ty));
1642   case dwarf::DW_TAG_subroutine_type:
1643     if (ClassTy) {
1644       // The member function type of a member function pointer has no
1645       // ThisAdjustment.
1646       return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1647                                      /*ThisAdjustment=*/0,
1648                                      /*IsStaticMethod=*/false);
1649     }
1650     return lowerTypeFunction(cast<DISubroutineType>(Ty));
1651   case dwarf::DW_TAG_enumeration_type:
1652     return lowerTypeEnum(cast<DICompositeType>(Ty));
1653   case dwarf::DW_TAG_class_type:
1654   case dwarf::DW_TAG_structure_type:
1655     return lowerTypeClass(cast<DICompositeType>(Ty));
1656   case dwarf::DW_TAG_union_type:
1657     return lowerTypeUnion(cast<DICompositeType>(Ty));
1658   case dwarf::DW_TAG_string_type:
1659     return lowerTypeString(cast<DIStringType>(Ty));
1660   case dwarf::DW_TAG_unspecified_type:
1661     if (Ty->getName() == "decltype(nullptr)")
1662       return TypeIndex::NullptrT();
1663     return TypeIndex::None();
1664   default:
1665     // Use the null type index.
1666     return TypeIndex();
1667   }
1668 }
1669 
1670 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
1671   TypeIndex UnderlyingTypeIndex = getTypeIndex(Ty->getBaseType());
1672   StringRef TypeName = Ty->getName();
1673 
1674   addToUDTs(Ty);
1675 
1676   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
1677       TypeName == "HRESULT")
1678     return TypeIndex(SimpleTypeKind::HResult);
1679   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
1680       TypeName == "wchar_t")
1681     return TypeIndex(SimpleTypeKind::WideCharacter);
1682 
1683   return UnderlyingTypeIndex;
1684 }
1685 
1686 TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1687   const DIType *ElementType = Ty->getBaseType();
1688   TypeIndex ElementTypeIndex = getTypeIndex(ElementType);
1689   // IndexType is size_t, which depends on the bitness of the target.
1690   TypeIndex IndexType = getPointerSizeInBytes() == 8
1691                             ? TypeIndex(SimpleTypeKind::UInt64Quad)
1692                             : TypeIndex(SimpleTypeKind::UInt32Long);
1693 
1694   uint64_t ElementSize = getBaseTypeSize(ElementType) / 8;
1695 
1696   // Add subranges to array type.
1697   DINodeArray Elements = Ty->getElements();
1698   for (int i = Elements.size() - 1; i >= 0; --i) {
1699     const DINode *Element = Elements[i];
1700     assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1701 
1702     const DISubrange *Subrange = cast<DISubrange>(Element);
1703     int64_t Count = -1;
1704 
1705     // If Subrange has a Count field, use it.
1706     // Otherwise, if it has an upperboud, use (upperbound - lowerbound + 1),
1707     // where lowerbound is from the LowerBound field of the Subrange,
1708     // or the language default lowerbound if that field is unspecified.
1709     if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt *>())
1710       Count = CI->getSExtValue();
1711     else if (auto *UI = Subrange->getUpperBound().dyn_cast<ConstantInt *>()) {
1712       // Fortran uses 1 as the default lowerbound; other languages use 0.
1713       int64_t Lowerbound = (moduleIsInFortran()) ? 1 : 0;
1714       auto *LI = Subrange->getLowerBound().dyn_cast<ConstantInt *>();
1715       Lowerbound = (LI) ? LI->getSExtValue() : Lowerbound;
1716       Count = UI->getSExtValue() - Lowerbound + 1;
1717     }
1718 
1719     // Forward declarations of arrays without a size and VLAs use a count of -1.
1720     // Emit a count of zero in these cases to match what MSVC does for arrays
1721     // without a size. MSVC doesn't support VLAs, so it's not clear what we
1722     // should do for them even if we could distinguish them.
1723     if (Count == -1)
1724       Count = 0;
1725 
1726     // Update the element size and element type index for subsequent subranges.
1727     ElementSize *= Count;
1728 
1729     // If this is the outermost array, use the size from the array. It will be
1730     // more accurate if we had a VLA or an incomplete element type size.
1731     uint64_t ArraySize =
1732         (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1733 
1734     StringRef Name = (i == 0) ? Ty->getName() : "";
1735     ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1736     ElementTypeIndex = TypeTable.writeLeafType(AR);
1737   }
1738 
1739   return ElementTypeIndex;
1740 }
1741 
1742 // This function lowers a Fortran character type (DIStringType).
1743 // Note that it handles only the character*n variant (using SizeInBits
1744 // field in DIString to describe the type size) at the moment.
1745 // Other variants (leveraging the StringLength and StringLengthExp
1746 // fields in DIStringType) remain TBD.
1747 TypeIndex CodeViewDebug::lowerTypeString(const DIStringType *Ty) {
1748   TypeIndex CharType = TypeIndex(SimpleTypeKind::NarrowCharacter);
1749   uint64_t ArraySize = Ty->getSizeInBits() >> 3;
1750   StringRef Name = Ty->getName();
1751   // IndexType is size_t, which depends on the bitness of the target.
1752   TypeIndex IndexType = getPointerSizeInBytes() == 8
1753                             ? TypeIndex(SimpleTypeKind::UInt64Quad)
1754                             : TypeIndex(SimpleTypeKind::UInt32Long);
1755 
1756   // Create a type of character array of ArraySize.
1757   ArrayRecord AR(CharType, IndexType, ArraySize, Name);
1758 
1759   return TypeTable.writeLeafType(AR);
1760 }
1761 
1762 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1763   TypeIndex Index;
1764   dwarf::TypeKind Kind;
1765   uint32_t ByteSize;
1766 
1767   Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
1768   ByteSize = Ty->getSizeInBits() / 8;
1769 
1770   SimpleTypeKind STK = SimpleTypeKind::None;
1771   switch (Kind) {
1772   case dwarf::DW_ATE_address:
1773     // FIXME: Translate
1774     break;
1775   case dwarf::DW_ATE_boolean:
1776     switch (ByteSize) {
1777     case 1:  STK = SimpleTypeKind::Boolean8;   break;
1778     case 2:  STK = SimpleTypeKind::Boolean16;  break;
1779     case 4:  STK = SimpleTypeKind::Boolean32;  break;
1780     case 8:  STK = SimpleTypeKind::Boolean64;  break;
1781     case 16: STK = SimpleTypeKind::Boolean128; break;
1782     }
1783     break;
1784   case dwarf::DW_ATE_complex_float:
1785     switch (ByteSize) {
1786     case 2:  STK = SimpleTypeKind::Complex16;  break;
1787     case 4:  STK = SimpleTypeKind::Complex32;  break;
1788     case 8:  STK = SimpleTypeKind::Complex64;  break;
1789     case 10: STK = SimpleTypeKind::Complex80;  break;
1790     case 16: STK = SimpleTypeKind::Complex128; break;
1791     }
1792     break;
1793   case dwarf::DW_ATE_float:
1794     switch (ByteSize) {
1795     case 2:  STK = SimpleTypeKind::Float16;  break;
1796     case 4:  STK = SimpleTypeKind::Float32;  break;
1797     case 6:  STK = SimpleTypeKind::Float48;  break;
1798     case 8:  STK = SimpleTypeKind::Float64;  break;
1799     case 10: STK = SimpleTypeKind::Float80;  break;
1800     case 16: STK = SimpleTypeKind::Float128; break;
1801     }
1802     break;
1803   case dwarf::DW_ATE_signed:
1804     switch (ByteSize) {
1805     case 1:  STK = SimpleTypeKind::SignedCharacter; break;
1806     case 2:  STK = SimpleTypeKind::Int16Short;      break;
1807     case 4:  STK = SimpleTypeKind::Int32;           break;
1808     case 8:  STK = SimpleTypeKind::Int64Quad;       break;
1809     case 16: STK = SimpleTypeKind::Int128Oct;       break;
1810     }
1811     break;
1812   case dwarf::DW_ATE_unsigned:
1813     switch (ByteSize) {
1814     case 1:  STK = SimpleTypeKind::UnsignedCharacter; break;
1815     case 2:  STK = SimpleTypeKind::UInt16Short;       break;
1816     case 4:  STK = SimpleTypeKind::UInt32;            break;
1817     case 8:  STK = SimpleTypeKind::UInt64Quad;        break;
1818     case 16: STK = SimpleTypeKind::UInt128Oct;        break;
1819     }
1820     break;
1821   case dwarf::DW_ATE_UTF:
1822     switch (ByteSize) {
1823     case 1: STK = SimpleTypeKind::Character8; break;
1824     case 2: STK = SimpleTypeKind::Character16; break;
1825     case 4: STK = SimpleTypeKind::Character32; break;
1826     }
1827     break;
1828   case dwarf::DW_ATE_signed_char:
1829     if (ByteSize == 1)
1830       STK = SimpleTypeKind::SignedCharacter;
1831     break;
1832   case dwarf::DW_ATE_unsigned_char:
1833     if (ByteSize == 1)
1834       STK = SimpleTypeKind::UnsignedCharacter;
1835     break;
1836   default:
1837     break;
1838   }
1839 
1840   // Apply some fixups based on the source-level type name.
1841   // Include some amount of canonicalization from an old naming scheme Clang
1842   // used to use for integer types (in an outdated effort to be compatible with
1843   // GCC's debug info/GDB's behavior, which has since been addressed).
1844   if (STK == SimpleTypeKind::Int32 &&
1845       (Ty->getName() == "long int" || Ty->getName() == "long"))
1846     STK = SimpleTypeKind::Int32Long;
1847   if (STK == SimpleTypeKind::UInt32 && (Ty->getName() == "long unsigned int" ||
1848                                         Ty->getName() == "unsigned long"))
1849     STK = SimpleTypeKind::UInt32Long;
1850   if (STK == SimpleTypeKind::UInt16Short &&
1851       (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
1852     STK = SimpleTypeKind::WideCharacter;
1853   if ((STK == SimpleTypeKind::SignedCharacter ||
1854        STK == SimpleTypeKind::UnsignedCharacter) &&
1855       Ty->getName() == "char")
1856     STK = SimpleTypeKind::NarrowCharacter;
1857 
1858   return TypeIndex(STK);
1859 }
1860 
1861 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
1862                                           PointerOptions PO) {
1863   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1864 
1865   // Pointers to simple types without any options can use SimpleTypeMode, rather
1866   // than having a dedicated pointer type record.
1867   if (PointeeTI.isSimple() && PO == PointerOptions::None &&
1868       PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1869       Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1870     SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1871                               ? SimpleTypeMode::NearPointer64
1872                               : SimpleTypeMode::NearPointer32;
1873     return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1874   }
1875 
1876   PointerKind PK =
1877       Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1878   PointerMode PM = PointerMode::Pointer;
1879   switch (Ty->getTag()) {
1880   default: llvm_unreachable("not a pointer tag type");
1881   case dwarf::DW_TAG_pointer_type:
1882     PM = PointerMode::Pointer;
1883     break;
1884   case dwarf::DW_TAG_reference_type:
1885     PM = PointerMode::LValueReference;
1886     break;
1887   case dwarf::DW_TAG_rvalue_reference_type:
1888     PM = PointerMode::RValueReference;
1889     break;
1890   }
1891 
1892   if (Ty->isObjectPointer())
1893     PO |= PointerOptions::Const;
1894 
1895   PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1896   return TypeTable.writeLeafType(PR);
1897 }
1898 
1899 static PointerToMemberRepresentation
1900 translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1901   // SizeInBytes being zero generally implies that the member pointer type was
1902   // incomplete, which can happen if it is part of a function prototype. In this
1903   // case, use the unknown model instead of the general model.
1904   if (IsPMF) {
1905     switch (Flags & DINode::FlagPtrToMemberRep) {
1906     case 0:
1907       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1908                               : PointerToMemberRepresentation::GeneralFunction;
1909     case DINode::FlagSingleInheritance:
1910       return PointerToMemberRepresentation::SingleInheritanceFunction;
1911     case DINode::FlagMultipleInheritance:
1912       return PointerToMemberRepresentation::MultipleInheritanceFunction;
1913     case DINode::FlagVirtualInheritance:
1914       return PointerToMemberRepresentation::VirtualInheritanceFunction;
1915     }
1916   } else {
1917     switch (Flags & DINode::FlagPtrToMemberRep) {
1918     case 0:
1919       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1920                               : PointerToMemberRepresentation::GeneralData;
1921     case DINode::FlagSingleInheritance:
1922       return PointerToMemberRepresentation::SingleInheritanceData;
1923     case DINode::FlagMultipleInheritance:
1924       return PointerToMemberRepresentation::MultipleInheritanceData;
1925     case DINode::FlagVirtualInheritance:
1926       return PointerToMemberRepresentation::VirtualInheritanceData;
1927     }
1928   }
1929   llvm_unreachable("invalid ptr to member representation");
1930 }
1931 
1932 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
1933                                                 PointerOptions PO) {
1934   assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1935   bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1936   TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
1937   TypeIndex PointeeTI =
1938       getTypeIndex(Ty->getBaseType(), IsPMF ? Ty->getClassType() : nullptr);
1939   PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1940                                                 : PointerKind::Near32;
1941   PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1942                          : PointerMode::PointerToDataMember;
1943 
1944   assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1945   uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1946   MemberPointerInfo MPI(
1947       ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
1948   PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
1949   return TypeTable.writeLeafType(PR);
1950 }
1951 
1952 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1953 /// have a translation, use the NearC convention.
1954 static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1955   switch (DwarfCC) {
1956   case dwarf::DW_CC_normal:             return CallingConvention::NearC;
1957   case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1958   case dwarf::DW_CC_BORLAND_thiscall:   return CallingConvention::ThisCall;
1959   case dwarf::DW_CC_BORLAND_stdcall:    return CallingConvention::NearStdCall;
1960   case dwarf::DW_CC_BORLAND_pascal:     return CallingConvention::NearPascal;
1961   case dwarf::DW_CC_LLVM_vectorcall:    return CallingConvention::NearVector;
1962   }
1963   return CallingConvention::NearC;
1964 }
1965 
1966 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1967   ModifierOptions Mods = ModifierOptions::None;
1968   PointerOptions PO = PointerOptions::None;
1969   bool IsModifier = true;
1970   const DIType *BaseTy = Ty;
1971   while (IsModifier && BaseTy) {
1972     // FIXME: Need to add DWARF tags for __unaligned and _Atomic
1973     switch (BaseTy->getTag()) {
1974     case dwarf::DW_TAG_const_type:
1975       Mods |= ModifierOptions::Const;
1976       PO |= PointerOptions::Const;
1977       break;
1978     case dwarf::DW_TAG_volatile_type:
1979       Mods |= ModifierOptions::Volatile;
1980       PO |= PointerOptions::Volatile;
1981       break;
1982     case dwarf::DW_TAG_restrict_type:
1983       // Only pointer types be marked with __restrict. There is no known flag
1984       // for __restrict in LF_MODIFIER records.
1985       PO |= PointerOptions::Restrict;
1986       break;
1987     default:
1988       IsModifier = false;
1989       break;
1990     }
1991     if (IsModifier)
1992       BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType();
1993   }
1994 
1995   // Check if the inner type will use an LF_POINTER record. If so, the
1996   // qualifiers will go in the LF_POINTER record. This comes up for types like
1997   // 'int *const' and 'int *__restrict', not the more common cases like 'const
1998   // char *'.
1999   if (BaseTy) {
2000     switch (BaseTy->getTag()) {
2001     case dwarf::DW_TAG_pointer_type:
2002     case dwarf::DW_TAG_reference_type:
2003     case dwarf::DW_TAG_rvalue_reference_type:
2004       return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
2005     case dwarf::DW_TAG_ptr_to_member_type:
2006       return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
2007     default:
2008       break;
2009     }
2010   }
2011 
2012   TypeIndex ModifiedTI = getTypeIndex(BaseTy);
2013 
2014   // Return the base type index if there aren't any modifiers. For example, the
2015   // metadata could contain restrict wrappers around non-pointer types.
2016   if (Mods == ModifierOptions::None)
2017     return ModifiedTI;
2018 
2019   ModifierRecord MR(ModifiedTI, Mods);
2020   return TypeTable.writeLeafType(MR);
2021 }
2022 
2023 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
2024   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
2025   for (const DIType *ArgType : Ty->getTypeArray())
2026     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgType));
2027 
2028   // MSVC uses type none for variadic argument.
2029   if (ReturnAndArgTypeIndices.size() > 1 &&
2030       ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
2031     ReturnAndArgTypeIndices.back() = TypeIndex::None();
2032   }
2033   TypeIndex ReturnTypeIndex = TypeIndex::Void();
2034   ArrayRef<TypeIndex> ArgTypeIndices = None;
2035   if (!ReturnAndArgTypeIndices.empty()) {
2036     auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
2037     ReturnTypeIndex = ReturnAndArgTypesRef.front();
2038     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
2039   }
2040 
2041   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
2042   TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
2043 
2044   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
2045 
2046   FunctionOptions FO = getFunctionOptions(Ty);
2047   ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
2048                             ArgListIndex);
2049   return TypeTable.writeLeafType(Procedure);
2050 }
2051 
2052 TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
2053                                                  const DIType *ClassTy,
2054                                                  int ThisAdjustment,
2055                                                  bool IsStaticMethod,
2056                                                  FunctionOptions FO) {
2057   // Lower the containing class type.
2058   TypeIndex ClassType = getTypeIndex(ClassTy);
2059 
2060   DITypeRefArray ReturnAndArgs = Ty->getTypeArray();
2061 
2062   unsigned Index = 0;
2063   SmallVector<TypeIndex, 8> ArgTypeIndices;
2064   TypeIndex ReturnTypeIndex = TypeIndex::Void();
2065   if (ReturnAndArgs.size() > Index) {
2066     ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]);
2067   }
2068 
2069   // If the first argument is a pointer type and this isn't a static method,
2070   // treat it as the special 'this' parameter, which is encoded separately from
2071   // the arguments.
2072   TypeIndex ThisTypeIndex;
2073   if (!IsStaticMethod && ReturnAndArgs.size() > Index) {
2074     if (const DIDerivedType *PtrTy =
2075             dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index])) {
2076       if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) {
2077         ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty);
2078         Index++;
2079       }
2080     }
2081   }
2082 
2083   while (Index < ReturnAndArgs.size())
2084     ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++]));
2085 
2086   // MSVC uses type none for variadic argument.
2087   if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void())
2088     ArgTypeIndices.back() = TypeIndex::None();
2089 
2090   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
2091   TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
2092 
2093   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
2094 
2095   MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
2096                            ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
2097   return TypeTable.writeLeafType(MFR);
2098 }
2099 
2100 TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
2101   unsigned VSlotCount =
2102       Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
2103   SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
2104 
2105   VFTableShapeRecord VFTSR(Slots);
2106   return TypeTable.writeLeafType(VFTSR);
2107 }
2108 
2109 static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
2110   switch (Flags & DINode::FlagAccessibility) {
2111   case DINode::FlagPrivate:   return MemberAccess::Private;
2112   case DINode::FlagPublic:    return MemberAccess::Public;
2113   case DINode::FlagProtected: return MemberAccess::Protected;
2114   case 0:
2115     // If there was no explicit access control, provide the default for the tag.
2116     return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
2117                                                  : MemberAccess::Public;
2118   }
2119   llvm_unreachable("access flags are exclusive");
2120 }
2121 
2122 static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
2123   if (SP->isArtificial())
2124     return MethodOptions::CompilerGenerated;
2125 
2126   // FIXME: Handle other MethodOptions.
2127 
2128   return MethodOptions::None;
2129 }
2130 
2131 static MethodKind translateMethodKindFlags(const DISubprogram *SP,
2132                                            bool Introduced) {
2133   if (SP->getFlags() & DINode::FlagStaticMember)
2134     return MethodKind::Static;
2135 
2136   switch (SP->getVirtuality()) {
2137   case dwarf::DW_VIRTUALITY_none:
2138     break;
2139   case dwarf::DW_VIRTUALITY_virtual:
2140     return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
2141   case dwarf::DW_VIRTUALITY_pure_virtual:
2142     return Introduced ? MethodKind::PureIntroducingVirtual
2143                       : MethodKind::PureVirtual;
2144   default:
2145     llvm_unreachable("unhandled virtuality case");
2146   }
2147 
2148   return MethodKind::Vanilla;
2149 }
2150 
2151 static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
2152   switch (Ty->getTag()) {
2153   case dwarf::DW_TAG_class_type:
2154     return TypeRecordKind::Class;
2155   case dwarf::DW_TAG_structure_type:
2156     return TypeRecordKind::Struct;
2157   default:
2158     llvm_unreachable("unexpected tag");
2159   }
2160 }
2161 
2162 /// Return ClassOptions that should be present on both the forward declaration
2163 /// and the defintion of a tag type.
2164 static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
2165   ClassOptions CO = ClassOptions::None;
2166 
2167   // MSVC always sets this flag, even for local types. Clang doesn't always
2168   // appear to give every type a linkage name, which may be problematic for us.
2169   // FIXME: Investigate the consequences of not following them here.
2170   if (!Ty->getIdentifier().empty())
2171     CO |= ClassOptions::HasUniqueName;
2172 
2173   // Put the Nested flag on a type if it appears immediately inside a tag type.
2174   // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
2175   // here. That flag is only set on definitions, and not forward declarations.
2176   const DIScope *ImmediateScope = Ty->getScope();
2177   if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
2178     CO |= ClassOptions::Nested;
2179 
2180   // Put the Scoped flag on function-local types. MSVC puts this flag for enum
2181   // type only when it has an immediate function scope. Clang never puts enums
2182   // inside DILexicalBlock scopes. Enum types, as generated by clang, are
2183   // always in function, class, or file scopes.
2184   if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
2185     if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
2186       CO |= ClassOptions::Scoped;
2187   } else {
2188     for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
2189          Scope = Scope->getScope()) {
2190       if (isa<DISubprogram>(Scope)) {
2191         CO |= ClassOptions::Scoped;
2192         break;
2193       }
2194     }
2195   }
2196 
2197   return CO;
2198 }
2199 
2200 void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
2201   switch (Ty->getTag()) {
2202   case dwarf::DW_TAG_class_type:
2203   case dwarf::DW_TAG_structure_type:
2204   case dwarf::DW_TAG_union_type:
2205   case dwarf::DW_TAG_enumeration_type:
2206     break;
2207   default:
2208     return;
2209   }
2210 
2211   if (const auto *File = Ty->getFile()) {
2212     StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
2213     TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
2214 
2215     UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
2216     TypeTable.writeLeafType(USLR);
2217   }
2218 }
2219 
2220 TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
2221   ClassOptions CO = getCommonClassOptions(Ty);
2222   TypeIndex FTI;
2223   unsigned EnumeratorCount = 0;
2224 
2225   if (Ty->isForwardDecl()) {
2226     CO |= ClassOptions::ForwardReference;
2227   } else {
2228     ContinuationRecordBuilder ContinuationBuilder;
2229     ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
2230     for (const DINode *Element : Ty->getElements()) {
2231       // We assume that the frontend provides all members in source declaration
2232       // order, which is what MSVC does.
2233       if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
2234         // FIXME: Is it correct to always emit these as unsigned here?
2235         EnumeratorRecord ER(MemberAccess::Public,
2236                             APSInt(Enumerator->getValue(), true),
2237                             Enumerator->getName());
2238         ContinuationBuilder.writeMemberType(ER);
2239         EnumeratorCount++;
2240       }
2241     }
2242     FTI = TypeTable.insertRecord(ContinuationBuilder);
2243   }
2244 
2245   std::string FullName = getFullyQualifiedName(Ty);
2246 
2247   EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
2248                 getTypeIndex(Ty->getBaseType()));
2249   TypeIndex EnumTI = TypeTable.writeLeafType(ER);
2250 
2251   addUDTSrcLine(Ty, EnumTI);
2252 
2253   return EnumTI;
2254 }
2255 
2256 //===----------------------------------------------------------------------===//
2257 // ClassInfo
2258 //===----------------------------------------------------------------------===//
2259 
2260 struct llvm::ClassInfo {
2261   struct MemberInfo {
2262     const DIDerivedType *MemberTypeNode;
2263     uint64_t BaseOffset;
2264   };
2265   // [MemberInfo]
2266   using MemberList = std::vector<MemberInfo>;
2267 
2268   using MethodsList = TinyPtrVector<const DISubprogram *>;
2269   // MethodName -> MethodsList
2270   using MethodsMap = MapVector<MDString *, MethodsList>;
2271 
2272   /// Base classes.
2273   std::vector<const DIDerivedType *> Inheritance;
2274 
2275   /// Direct members.
2276   MemberList Members;
2277   // Direct overloaded methods gathered by name.
2278   MethodsMap Methods;
2279 
2280   TypeIndex VShapeTI;
2281 
2282   std::vector<const DIType *> NestedTypes;
2283 };
2284 
2285 void CodeViewDebug::clear() {
2286   assert(CurFn == nullptr);
2287   FileIdMap.clear();
2288   FnDebugInfo.clear();
2289   FileToFilepathMap.clear();
2290   LocalUDTs.clear();
2291   GlobalUDTs.clear();
2292   TypeIndices.clear();
2293   CompleteTypeIndices.clear();
2294   ScopeGlobals.clear();
2295   CVGlobalVariableOffsets.clear();
2296 }
2297 
2298 void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
2299                                       const DIDerivedType *DDTy) {
2300   if (!DDTy->getName().empty()) {
2301     Info.Members.push_back({DDTy, 0});
2302 
2303     // Collect static const data members with values.
2304     if ((DDTy->getFlags() & DINode::FlagStaticMember) ==
2305         DINode::FlagStaticMember) {
2306       if (DDTy->getConstant() && (isa<ConstantInt>(DDTy->getConstant()) ||
2307                                   isa<ConstantFP>(DDTy->getConstant())))
2308         StaticConstMembers.push_back(DDTy);
2309     }
2310 
2311     return;
2312   }
2313 
2314   // An unnamed member may represent a nested struct or union. Attempt to
2315   // interpret the unnamed member as a DICompositeType possibly wrapped in
2316   // qualifier types. Add all the indirect fields to the current record if that
2317   // succeeds, and drop the member if that fails.
2318   assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
2319   uint64_t Offset = DDTy->getOffsetInBits();
2320   const DIType *Ty = DDTy->getBaseType();
2321   bool FullyResolved = false;
2322   while (!FullyResolved) {
2323     switch (Ty->getTag()) {
2324     case dwarf::DW_TAG_const_type:
2325     case dwarf::DW_TAG_volatile_type:
2326       // FIXME: we should apply the qualifier types to the indirect fields
2327       // rather than dropping them.
2328       Ty = cast<DIDerivedType>(Ty)->getBaseType();
2329       break;
2330     default:
2331       FullyResolved = true;
2332       break;
2333     }
2334   }
2335 
2336   const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
2337   if (!DCTy)
2338     return;
2339 
2340   ClassInfo NestedInfo = collectClassInfo(DCTy);
2341   for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
2342     Info.Members.push_back(
2343         {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
2344 }
2345 
2346 ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
2347   ClassInfo Info;
2348   // Add elements to structure type.
2349   DINodeArray Elements = Ty->getElements();
2350   for (auto *Element : Elements) {
2351     // We assume that the frontend provides all members in source declaration
2352     // order, which is what MSVC does.
2353     if (!Element)
2354       continue;
2355     if (auto *SP = dyn_cast<DISubprogram>(Element)) {
2356       Info.Methods[SP->getRawName()].push_back(SP);
2357     } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
2358       if (DDTy->getTag() == dwarf::DW_TAG_member) {
2359         collectMemberInfo(Info, DDTy);
2360       } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
2361         Info.Inheritance.push_back(DDTy);
2362       } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
2363                  DDTy->getName() == "__vtbl_ptr_type") {
2364         Info.VShapeTI = getTypeIndex(DDTy);
2365       } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
2366         Info.NestedTypes.push_back(DDTy);
2367       } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
2368         // Ignore friend members. It appears that MSVC emitted info about
2369         // friends in the past, but modern versions do not.
2370       }
2371     } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
2372       Info.NestedTypes.push_back(Composite);
2373     }
2374     // Skip other unrecognized kinds of elements.
2375   }
2376   return Info;
2377 }
2378 
2379 static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) {
2380   // This routine is used by lowerTypeClass and lowerTypeUnion to determine
2381   // if a complete type should be emitted instead of a forward reference.
2382   return Ty->getName().empty() && Ty->getIdentifier().empty() &&
2383       !Ty->isForwardDecl();
2384 }
2385 
2386 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
2387   // Emit the complete type for unnamed structs.  C++ classes with methods
2388   // which have a circular reference back to the class type are expected to
2389   // be named by the front-end and should not be "unnamed".  C unnamed
2390   // structs should not have circular references.
2391   if (shouldAlwaysEmitCompleteClassType(Ty)) {
2392     // If this unnamed complete type is already in the process of being defined
2393     // then the description of the type is malformed and cannot be emitted
2394     // into CodeView correctly so report a fatal error.
2395     auto I = CompleteTypeIndices.find(Ty);
2396     if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
2397       report_fatal_error("cannot debug circular reference to unnamed type");
2398     return getCompleteTypeIndex(Ty);
2399   }
2400 
2401   // First, construct the forward decl.  Don't look into Ty to compute the
2402   // forward decl options, since it might not be available in all TUs.
2403   TypeRecordKind Kind = getRecordKind(Ty);
2404   ClassOptions CO =
2405       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2406   std::string FullName = getFullyQualifiedName(Ty);
2407   ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
2408                  FullName, Ty->getIdentifier());
2409   TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
2410   if (!Ty->isForwardDecl())
2411     DeferredCompleteTypes.push_back(Ty);
2412   return FwdDeclTI;
2413 }
2414 
2415 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
2416   // Construct the field list and complete type record.
2417   TypeRecordKind Kind = getRecordKind(Ty);
2418   ClassOptions CO = getCommonClassOptions(Ty);
2419   TypeIndex FieldTI;
2420   TypeIndex VShapeTI;
2421   unsigned FieldCount;
2422   bool ContainsNestedClass;
2423   std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
2424       lowerRecordFieldList(Ty);
2425 
2426   if (ContainsNestedClass)
2427     CO |= ClassOptions::ContainsNestedClass;
2428 
2429   // MSVC appears to set this flag by searching any destructor or method with
2430   // FunctionOptions::Constructor among the emitted members. Clang AST has all
2431   // the members, however special member functions are not yet emitted into
2432   // debug information. For now checking a class's non-triviality seems enough.
2433   // FIXME: not true for a nested unnamed struct.
2434   if (isNonTrivial(Ty))
2435     CO |= ClassOptions::HasConstructorOrDestructor;
2436 
2437   std::string FullName = getFullyQualifiedName(Ty);
2438 
2439   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2440 
2441   ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
2442                  SizeInBytes, FullName, Ty->getIdentifier());
2443   TypeIndex ClassTI = TypeTable.writeLeafType(CR);
2444 
2445   addUDTSrcLine(Ty, ClassTI);
2446 
2447   addToUDTs(Ty);
2448 
2449   return ClassTI;
2450 }
2451 
2452 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
2453   // Emit the complete type for unnamed unions.
2454   if (shouldAlwaysEmitCompleteClassType(Ty))
2455     return getCompleteTypeIndex(Ty);
2456 
2457   ClassOptions CO =
2458       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2459   std::string FullName = getFullyQualifiedName(Ty);
2460   UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
2461   TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
2462   if (!Ty->isForwardDecl())
2463     DeferredCompleteTypes.push_back(Ty);
2464   return FwdDeclTI;
2465 }
2466 
2467 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
2468   ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
2469   TypeIndex FieldTI;
2470   unsigned FieldCount;
2471   bool ContainsNestedClass;
2472   std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
2473       lowerRecordFieldList(Ty);
2474 
2475   if (ContainsNestedClass)
2476     CO |= ClassOptions::ContainsNestedClass;
2477 
2478   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2479   std::string FullName = getFullyQualifiedName(Ty);
2480 
2481   UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
2482                  Ty->getIdentifier());
2483   TypeIndex UnionTI = TypeTable.writeLeafType(UR);
2484 
2485   addUDTSrcLine(Ty, UnionTI);
2486 
2487   addToUDTs(Ty);
2488 
2489   return UnionTI;
2490 }
2491 
2492 std::tuple<TypeIndex, TypeIndex, unsigned, bool>
2493 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
2494   // Manually count members. MSVC appears to count everything that generates a
2495   // field list record. Each individual overload in a method overload group
2496   // contributes to this count, even though the overload group is a single field
2497   // list record.
2498   unsigned MemberCount = 0;
2499   ClassInfo Info = collectClassInfo(Ty);
2500   ContinuationRecordBuilder ContinuationBuilder;
2501   ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
2502 
2503   // Create base classes.
2504   for (const DIDerivedType *I : Info.Inheritance) {
2505     if (I->getFlags() & DINode::FlagVirtual) {
2506       // Virtual base.
2507       unsigned VBPtrOffset = I->getVBPtrOffset();
2508       // FIXME: Despite the accessor name, the offset is really in bytes.
2509       unsigned VBTableIndex = I->getOffsetInBits() / 4;
2510       auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
2511                             ? TypeRecordKind::IndirectVirtualBaseClass
2512                             : TypeRecordKind::VirtualBaseClass;
2513       VirtualBaseClassRecord VBCR(
2514           RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
2515           getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
2516           VBTableIndex);
2517 
2518       ContinuationBuilder.writeMemberType(VBCR);
2519       MemberCount++;
2520     } else {
2521       assert(I->getOffsetInBits() % 8 == 0 &&
2522              "bases must be on byte boundaries");
2523       BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
2524                           getTypeIndex(I->getBaseType()),
2525                           I->getOffsetInBits() / 8);
2526       ContinuationBuilder.writeMemberType(BCR);
2527       MemberCount++;
2528     }
2529   }
2530 
2531   // Create members.
2532   for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
2533     const DIDerivedType *Member = MemberInfo.MemberTypeNode;
2534     TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
2535     StringRef MemberName = Member->getName();
2536     MemberAccess Access =
2537         translateAccessFlags(Ty->getTag(), Member->getFlags());
2538 
2539     if (Member->isStaticMember()) {
2540       StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
2541       ContinuationBuilder.writeMemberType(SDMR);
2542       MemberCount++;
2543       continue;
2544     }
2545 
2546     // Virtual function pointer member.
2547     if ((Member->getFlags() & DINode::FlagArtificial) &&
2548         Member->getName().startswith("_vptr$")) {
2549       VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
2550       ContinuationBuilder.writeMemberType(VFPR);
2551       MemberCount++;
2552       continue;
2553     }
2554 
2555     // Data member.
2556     uint64_t MemberOffsetInBits =
2557         Member->getOffsetInBits() + MemberInfo.BaseOffset;
2558     if (Member->isBitField()) {
2559       uint64_t StartBitOffset = MemberOffsetInBits;
2560       if (const auto *CI =
2561               dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
2562         MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
2563       }
2564       StartBitOffset -= MemberOffsetInBits;
2565       BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2566                          StartBitOffset);
2567       MemberBaseType = TypeTable.writeLeafType(BFR);
2568     }
2569     uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
2570     DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2571                          MemberName);
2572     ContinuationBuilder.writeMemberType(DMR);
2573     MemberCount++;
2574   }
2575 
2576   // Create methods
2577   for (auto &MethodItr : Info.Methods) {
2578     StringRef Name = MethodItr.first->getString();
2579 
2580     std::vector<OneMethodRecord> Methods;
2581     for (const DISubprogram *SP : MethodItr.second) {
2582       TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2583       bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
2584 
2585       unsigned VFTableOffset = -1;
2586       if (Introduced)
2587         VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2588 
2589       Methods.push_back(OneMethodRecord(
2590           MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
2591           translateMethodKindFlags(SP, Introduced),
2592           translateMethodOptionFlags(SP), VFTableOffset, Name));
2593       MemberCount++;
2594     }
2595     assert(!Methods.empty() && "Empty methods map entry");
2596     if (Methods.size() == 1)
2597       ContinuationBuilder.writeMemberType(Methods[0]);
2598     else {
2599       // FIXME: Make this use its own ContinuationBuilder so that
2600       // MethodOverloadList can be split correctly.
2601       MethodOverloadListRecord MOLR(Methods);
2602       TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
2603 
2604       OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
2605       ContinuationBuilder.writeMemberType(OMR);
2606     }
2607   }
2608 
2609   // Create nested classes.
2610   for (const DIType *Nested : Info.NestedTypes) {
2611     NestedTypeRecord R(getTypeIndex(Nested), Nested->getName());
2612     ContinuationBuilder.writeMemberType(R);
2613     MemberCount++;
2614   }
2615 
2616   TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
2617   return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
2618                          !Info.NestedTypes.empty());
2619 }
2620 
2621 TypeIndex CodeViewDebug::getVBPTypeIndex() {
2622   if (!VBPType.getIndex()) {
2623     // Make a 'const int *' type.
2624     ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
2625     TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
2626 
2627     PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2628                                                   : PointerKind::Near32;
2629     PointerMode PM = PointerMode::Pointer;
2630     PointerOptions PO = PointerOptions::None;
2631     PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
2632     VBPType = TypeTable.writeLeafType(PR);
2633   }
2634 
2635   return VBPType;
2636 }
2637 
2638 TypeIndex CodeViewDebug::getTypeIndex(const DIType *Ty, const DIType *ClassTy) {
2639   // The null DIType is the void type. Don't try to hash it.
2640   if (!Ty)
2641     return TypeIndex::Void();
2642 
2643   // Check if we've already translated this type. Don't try to do a
2644   // get-or-create style insertion that caches the hash lookup across the
2645   // lowerType call. It will update the TypeIndices map.
2646   auto I = TypeIndices.find({Ty, ClassTy});
2647   if (I != TypeIndices.end())
2648     return I->second;
2649 
2650   TypeLoweringScope S(*this);
2651   TypeIndex TI = lowerType(Ty, ClassTy);
2652   return recordTypeIndexForDINode(Ty, TI, ClassTy);
2653 }
2654 
2655 codeview::TypeIndex
2656 CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy,
2657                                       const DISubroutineType *SubroutineTy) {
2658   assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type &&
2659          "this type must be a pointer type");
2660 
2661   PointerOptions Options = PointerOptions::None;
2662   if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference)
2663     Options = PointerOptions::LValueRefThisPointer;
2664   else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference)
2665     Options = PointerOptions::RValueRefThisPointer;
2666 
2667   // Check if we've already translated this type.  If there is no ref qualifier
2668   // on the function then we look up this pointer type with no associated class
2669   // so that the TypeIndex for the this pointer can be shared with the type
2670   // index for other pointers to this class type.  If there is a ref qualifier
2671   // then we lookup the pointer using the subroutine as the parent type.
2672   auto I = TypeIndices.find({PtrTy, SubroutineTy});
2673   if (I != TypeIndices.end())
2674     return I->second;
2675 
2676   TypeLoweringScope S(*this);
2677   TypeIndex TI = lowerTypePointer(PtrTy, Options);
2678   return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy);
2679 }
2680 
2681 TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(const DIType *Ty) {
2682   PointerRecord PR(getTypeIndex(Ty),
2683                    getPointerSizeInBytes() == 8 ? PointerKind::Near64
2684                                                 : PointerKind::Near32,
2685                    PointerMode::LValueReference, PointerOptions::None,
2686                    Ty->getSizeInBits() / 8);
2687   return TypeTable.writeLeafType(PR);
2688 }
2689 
2690 TypeIndex CodeViewDebug::getCompleteTypeIndex(const DIType *Ty) {
2691   // The null DIType is the void type. Don't try to hash it.
2692   if (!Ty)
2693     return TypeIndex::Void();
2694 
2695   // Look through typedefs when getting the complete type index. Call
2696   // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are
2697   // emitted only once.
2698   if (Ty->getTag() == dwarf::DW_TAG_typedef)
2699     (void)getTypeIndex(Ty);
2700   while (Ty->getTag() == dwarf::DW_TAG_typedef)
2701     Ty = cast<DIDerivedType>(Ty)->getBaseType();
2702 
2703   // If this is a non-record type, the complete type index is the same as the
2704   // normal type index. Just call getTypeIndex.
2705   switch (Ty->getTag()) {
2706   case dwarf::DW_TAG_class_type:
2707   case dwarf::DW_TAG_structure_type:
2708   case dwarf::DW_TAG_union_type:
2709     break;
2710   default:
2711     return getTypeIndex(Ty);
2712   }
2713 
2714   const auto *CTy = cast<DICompositeType>(Ty);
2715 
2716   TypeLoweringScope S(*this);
2717 
2718   // Make sure the forward declaration is emitted first. It's unclear if this
2719   // is necessary, but MSVC does it, and we should follow suit until we can show
2720   // otherwise.
2721   // We only emit a forward declaration for named types.
2722   if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
2723     TypeIndex FwdDeclTI = getTypeIndex(CTy);
2724 
2725     // Just use the forward decl if we don't have complete type info. This
2726     // might happen if the frontend is using modules and expects the complete
2727     // definition to be emitted elsewhere.
2728     if (CTy->isForwardDecl())
2729       return FwdDeclTI;
2730   }
2731 
2732   // Check if we've already translated the complete record type.
2733   // Insert the type with a null TypeIndex to signify that the type is currently
2734   // being lowered.
2735   auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
2736   if (!InsertResult.second)
2737     return InsertResult.first->second;
2738 
2739   TypeIndex TI;
2740   switch (CTy->getTag()) {
2741   case dwarf::DW_TAG_class_type:
2742   case dwarf::DW_TAG_structure_type:
2743     TI = lowerCompleteTypeClass(CTy);
2744     break;
2745   case dwarf::DW_TAG_union_type:
2746     TI = lowerCompleteTypeUnion(CTy);
2747     break;
2748   default:
2749     llvm_unreachable("not a record");
2750   }
2751 
2752   // Update the type index associated with this CompositeType.  This cannot
2753   // use the 'InsertResult' iterator above because it is potentially
2754   // invalidated by map insertions which can occur while lowering the class
2755   // type above.
2756   CompleteTypeIndices[CTy] = TI;
2757   return TI;
2758 }
2759 
2760 /// Emit all the deferred complete record types. Try to do this in FIFO order,
2761 /// and do this until fixpoint, as each complete record type typically
2762 /// references
2763 /// many other record types.
2764 void CodeViewDebug::emitDeferredCompleteTypes() {
2765   SmallVector<const DICompositeType *, 4> TypesToEmit;
2766   while (!DeferredCompleteTypes.empty()) {
2767     std::swap(DeferredCompleteTypes, TypesToEmit);
2768     for (const DICompositeType *RecordTy : TypesToEmit)
2769       getCompleteTypeIndex(RecordTy);
2770     TypesToEmit.clear();
2771   }
2772 }
2773 
2774 void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
2775                                           ArrayRef<LocalVariable> Locals) {
2776   // Get the sorted list of parameters and emit them first.
2777   SmallVector<const LocalVariable *, 6> Params;
2778   for (const LocalVariable &L : Locals)
2779     if (L.DIVar->isParameter())
2780       Params.push_back(&L);
2781   llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
2782     return L->DIVar->getArg() < R->DIVar->getArg();
2783   });
2784   for (const LocalVariable *L : Params)
2785     emitLocalVariable(FI, *L);
2786 
2787   // Next emit all non-parameters in the order that we found them.
2788   for (const LocalVariable &L : Locals)
2789     if (!L.DIVar->isParameter())
2790       emitLocalVariable(FI, L);
2791 }
2792 
2793 void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
2794                                       const LocalVariable &Var) {
2795   // LocalSym record, see SymbolRecord.h for more info.
2796   MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL);
2797 
2798   LocalSymFlags Flags = LocalSymFlags::None;
2799   if (Var.DIVar->isParameter())
2800     Flags |= LocalSymFlags::IsParameter;
2801   if (Var.DefRanges.empty())
2802     Flags |= LocalSymFlags::IsOptimizedOut;
2803 
2804   OS.AddComment("TypeIndex");
2805   TypeIndex TI = Var.UseReferenceType
2806                      ? getTypeIndexForReferenceTo(Var.DIVar->getType())
2807                      : getCompleteTypeIndex(Var.DIVar->getType());
2808   OS.emitInt32(TI.getIndex());
2809   OS.AddComment("Flags");
2810   OS.emitInt16(static_cast<uint16_t>(Flags));
2811   // Truncate the name so we won't overflow the record length field.
2812   emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
2813   endSymbolRecord(LocalEnd);
2814 
2815   // Calculate the on disk prefix of the appropriate def range record. The
2816   // records and on disk formats are described in SymbolRecords.h. BytePrefix
2817   // should be big enough to hold all forms without memory allocation.
2818   SmallString<20> BytePrefix;
2819   for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2820     BytePrefix.clear();
2821     if (DefRange.InMemory) {
2822       int Offset = DefRange.DataOffset;
2823       unsigned Reg = DefRange.CVRegister;
2824 
2825       // 32-bit x86 call sequences often use PUSH instructions, which disrupt
2826       // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
2827       // instead. In frames without stack realignment, $T0 will be the CFA.
2828       if (RegisterId(Reg) == RegisterId::ESP) {
2829         Reg = unsigned(RegisterId::VFRAME);
2830         Offset += FI.OffsetAdjustment;
2831       }
2832 
2833       // If we can use the chosen frame pointer for the frame and this isn't a
2834       // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
2835       // Otherwise, use S_DEFRANGE_REGISTER_REL.
2836       EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU);
2837       if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
2838           (bool(Flags & LocalSymFlags::IsParameter)
2839                ? (EncFP == FI.EncodedParamFramePtrReg)
2840                : (EncFP == FI.EncodedLocalFramePtrReg))) {
2841         DefRangeFramePointerRelHeader DRHdr;
2842         DRHdr.Offset = Offset;
2843         OS.emitCVDefRangeDirective(DefRange.Ranges, DRHdr);
2844       } else {
2845         uint16_t RegRelFlags = 0;
2846         if (DefRange.IsSubfield) {
2847           RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2848                         (DefRange.StructOffset
2849                          << DefRangeRegisterRelSym::OffsetInParentShift);
2850         }
2851         DefRangeRegisterRelHeader DRHdr;
2852         DRHdr.Register = Reg;
2853         DRHdr.Flags = RegRelFlags;
2854         DRHdr.BasePointerOffset = Offset;
2855         OS.emitCVDefRangeDirective(DefRange.Ranges, DRHdr);
2856       }
2857     } else {
2858       assert(DefRange.DataOffset == 0 && "unexpected offset into register");
2859       if (DefRange.IsSubfield) {
2860         DefRangeSubfieldRegisterHeader DRHdr;
2861         DRHdr.Register = DefRange.CVRegister;
2862         DRHdr.MayHaveNoName = 0;
2863         DRHdr.OffsetInParent = DefRange.StructOffset;
2864         OS.emitCVDefRangeDirective(DefRange.Ranges, DRHdr);
2865       } else {
2866         DefRangeRegisterHeader DRHdr;
2867         DRHdr.Register = DefRange.CVRegister;
2868         DRHdr.MayHaveNoName = 0;
2869         OS.emitCVDefRangeDirective(DefRange.Ranges, DRHdr);
2870       }
2871     }
2872   }
2873 }
2874 
2875 void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
2876                                          const FunctionInfo& FI) {
2877   for (LexicalBlock *Block : Blocks)
2878     emitLexicalBlock(*Block, FI);
2879 }
2880 
2881 /// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
2882 /// lexical block scope.
2883 void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
2884                                      const FunctionInfo& FI) {
2885   MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32);
2886   OS.AddComment("PtrParent");
2887   OS.emitInt32(0); // PtrParent
2888   OS.AddComment("PtrEnd");
2889   OS.emitInt32(0); // PtrEnd
2890   OS.AddComment("Code size");
2891   OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4);   // Code Size
2892   OS.AddComment("Function section relative address");
2893   OS.EmitCOFFSecRel32(Block.Begin, /*Offset=*/0);         // Func Offset
2894   OS.AddComment("Function section index");
2895   OS.EmitCOFFSectionIndex(FI.Begin);                      // Func Symbol
2896   OS.AddComment("Lexical block name");
2897   emitNullTerminatedSymbolName(OS, Block.Name);           // Name
2898   endSymbolRecord(RecordEnd);
2899 
2900   // Emit variables local to this lexical block.
2901   emitLocalVariableList(FI, Block.Locals);
2902   emitGlobalVariableList(Block.Globals);
2903 
2904   // Emit lexical blocks contained within this block.
2905   emitLexicalBlockList(Block.Children, FI);
2906 
2907   // Close the lexical block scope.
2908   emitEndSymbolRecord(SymbolKind::S_END);
2909 }
2910 
2911 /// Convenience routine for collecting lexical block information for a list
2912 /// of lexical scopes.
2913 void CodeViewDebug::collectLexicalBlockInfo(
2914         SmallVectorImpl<LexicalScope *> &Scopes,
2915         SmallVectorImpl<LexicalBlock *> &Blocks,
2916         SmallVectorImpl<LocalVariable> &Locals,
2917         SmallVectorImpl<CVGlobalVariable> &Globals) {
2918   for (LexicalScope *Scope : Scopes)
2919     collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals);
2920 }
2921 
2922 /// Populate the lexical blocks and local variable lists of the parent with
2923 /// information about the specified lexical scope.
2924 void CodeViewDebug::collectLexicalBlockInfo(
2925     LexicalScope &Scope,
2926     SmallVectorImpl<LexicalBlock *> &ParentBlocks,
2927     SmallVectorImpl<LocalVariable> &ParentLocals,
2928     SmallVectorImpl<CVGlobalVariable> &ParentGlobals) {
2929   if (Scope.isAbstractScope())
2930     return;
2931 
2932   // Gather information about the lexical scope including local variables,
2933   // global variables, and address ranges.
2934   bool IgnoreScope = false;
2935   auto LI = ScopeVariables.find(&Scope);
2936   SmallVectorImpl<LocalVariable> *Locals =
2937       LI != ScopeVariables.end() ? &LI->second : nullptr;
2938   auto GI = ScopeGlobals.find(Scope.getScopeNode());
2939   SmallVectorImpl<CVGlobalVariable> *Globals =
2940       GI != ScopeGlobals.end() ? GI->second.get() : nullptr;
2941   const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
2942   const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
2943 
2944   // Ignore lexical scopes which do not contain variables.
2945   if (!Locals && !Globals)
2946     IgnoreScope = true;
2947 
2948   // Ignore lexical scopes which are not lexical blocks.
2949   if (!DILB)
2950     IgnoreScope = true;
2951 
2952   // Ignore scopes which have too many address ranges to represent in the
2953   // current CodeView format or do not have a valid address range.
2954   //
2955   // For lexical scopes with multiple address ranges you may be tempted to
2956   // construct a single range covering every instruction where the block is
2957   // live and everything in between.  Unfortunately, Visual Studio only
2958   // displays variables from the first matching lexical block scope.  If the
2959   // first lexical block contains exception handling code or cold code which
2960   // is moved to the bottom of the routine creating a single range covering
2961   // nearly the entire routine, then it will hide all other lexical blocks
2962   // and the variables they contain.
2963   if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second))
2964     IgnoreScope = true;
2965 
2966   if (IgnoreScope) {
2967     // This scope can be safely ignored and eliminating it will reduce the
2968     // size of the debug information. Be sure to collect any variable and scope
2969     // information from the this scope or any of its children and collapse them
2970     // into the parent scope.
2971     if (Locals)
2972       ParentLocals.append(Locals->begin(), Locals->end());
2973     if (Globals)
2974       ParentGlobals.append(Globals->begin(), Globals->end());
2975     collectLexicalBlockInfo(Scope.getChildren(),
2976                             ParentBlocks,
2977                             ParentLocals,
2978                             ParentGlobals);
2979     return;
2980   }
2981 
2982   // Create a new CodeView lexical block for this lexical scope.  If we've
2983   // seen this DILexicalBlock before then the scope tree is malformed and
2984   // we can handle this gracefully by not processing it a second time.
2985   auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
2986   if (!BlockInsertion.second)
2987     return;
2988 
2989   // Create a lexical block containing the variables and collect the the
2990   // lexical block information for the children.
2991   const InsnRange &Range = Ranges.front();
2992   assert(Range.first && Range.second);
2993   LexicalBlock &Block = BlockInsertion.first->second;
2994   Block.Begin = getLabelBeforeInsn(Range.first);
2995   Block.End = getLabelAfterInsn(Range.second);
2996   assert(Block.Begin && "missing label for scope begin");
2997   assert(Block.End && "missing label for scope end");
2998   Block.Name = DILB->getName();
2999   if (Locals)
3000     Block.Locals = std::move(*Locals);
3001   if (Globals)
3002     Block.Globals = std::move(*Globals);
3003   ParentBlocks.push_back(&Block);
3004   collectLexicalBlockInfo(Scope.getChildren(),
3005                           Block.Children,
3006                           Block.Locals,
3007                           Block.Globals);
3008 }
3009 
3010 void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
3011   const Function &GV = MF->getFunction();
3012   assert(FnDebugInfo.count(&GV));
3013   assert(CurFn == FnDebugInfo[&GV].get());
3014 
3015   collectVariableInfo(GV.getSubprogram());
3016 
3017   // Build the lexical block structure to emit for this routine.
3018   if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
3019     collectLexicalBlockInfo(*CFS,
3020                             CurFn->ChildBlocks,
3021                             CurFn->Locals,
3022                             CurFn->Globals);
3023 
3024   // Clear the scope and variable information from the map which will not be
3025   // valid after we have finished processing this routine.  This also prepares
3026   // the map for the subsequent routine.
3027   ScopeVariables.clear();
3028 
3029   // Don't emit anything if we don't have any line tables.
3030   // Thunks are compiler-generated and probably won't have source correlation.
3031   if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
3032     FnDebugInfo.erase(&GV);
3033     CurFn = nullptr;
3034     return;
3035   }
3036 
3037   // Find heap alloc sites and add to list.
3038   for (const auto &MBB : *MF) {
3039     for (const auto &MI : MBB) {
3040       if (MDNode *MD = MI.getHeapAllocMarker()) {
3041         CurFn->HeapAllocSites.push_back(std::make_tuple(getLabelBeforeInsn(&MI),
3042                                                         getLabelAfterInsn(&MI),
3043                                                         dyn_cast<DIType>(MD)));
3044       }
3045     }
3046   }
3047 
3048   CurFn->Annotations = MF->getCodeViewAnnotations();
3049 
3050   CurFn->End = Asm->getFunctionEnd();
3051 
3052   CurFn = nullptr;
3053 }
3054 
3055 // Usable locations are valid with non-zero line numbers. A line number of zero
3056 // corresponds to optimized code that doesn't have a distinct source location.
3057 // In this case, we try to use the previous or next source location depending on
3058 // the context.
3059 static bool isUsableDebugLoc(DebugLoc DL) {
3060   return DL && DL.getLine() != 0;
3061 }
3062 
3063 void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
3064   DebugHandlerBase::beginInstruction(MI);
3065 
3066   // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
3067   if (!Asm || !CurFn || MI->isDebugInstr() ||
3068       MI->getFlag(MachineInstr::FrameSetup))
3069     return;
3070 
3071   // If the first instruction of a new MBB has no location, find the first
3072   // instruction with a location and use that.
3073   DebugLoc DL = MI->getDebugLoc();
3074   if (!isUsableDebugLoc(DL) && MI->getParent() != PrevInstBB) {
3075     for (const auto &NextMI : *MI->getParent()) {
3076       if (NextMI.isDebugInstr())
3077         continue;
3078       DL = NextMI.getDebugLoc();
3079       if (isUsableDebugLoc(DL))
3080         break;
3081     }
3082     // FIXME: Handle the case where the BB has no valid locations. This would
3083     // probably require doing a real dataflow analysis.
3084   }
3085   PrevInstBB = MI->getParent();
3086 
3087   // If we still don't have a debug location, don't record a location.
3088   if (!isUsableDebugLoc(DL))
3089     return;
3090 
3091   maybeRecordLocation(DL, Asm->MF);
3092 }
3093 
3094 MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
3095   MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
3096            *EndLabel = MMI->getContext().createTempSymbol();
3097   OS.emitInt32(unsigned(Kind));
3098   OS.AddComment("Subsection size");
3099   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
3100   OS.emitLabel(BeginLabel);
3101   return EndLabel;
3102 }
3103 
3104 void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
3105   OS.emitLabel(EndLabel);
3106   // Every subsection must be aligned to a 4-byte boundary.
3107   OS.emitValueToAlignment(4);
3108 }
3109 
3110 static StringRef getSymbolName(SymbolKind SymKind) {
3111   for (const EnumEntry<SymbolKind> &EE : getSymbolTypeNames())
3112     if (EE.Value == SymKind)
3113       return EE.Name;
3114   return "";
3115 }
3116 
3117 MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) {
3118   MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
3119            *EndLabel = MMI->getContext().createTempSymbol();
3120   OS.AddComment("Record length");
3121   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
3122   OS.emitLabel(BeginLabel);
3123   if (OS.isVerboseAsm())
3124     OS.AddComment("Record kind: " + getSymbolName(SymKind));
3125   OS.emitInt16(unsigned(SymKind));
3126   return EndLabel;
3127 }
3128 
3129 void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) {
3130   // MSVC does not pad out symbol records to four bytes, but LLVM does to avoid
3131   // an extra copy of every symbol record in LLD. This increases object file
3132   // size by less than 1% in the clang build, and is compatible with the Visual
3133   // C++ linker.
3134   OS.emitValueToAlignment(4);
3135   OS.emitLabel(SymEnd);
3136 }
3137 
3138 void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) {
3139   OS.AddComment("Record length");
3140   OS.emitInt16(2);
3141   if (OS.isVerboseAsm())
3142     OS.AddComment("Record kind: " + getSymbolName(EndKind));
3143   OS.emitInt16(uint16_t(EndKind)); // Record Kind
3144 }
3145 
3146 void CodeViewDebug::emitDebugInfoForUDTs(
3147     const std::vector<std::pair<std::string, const DIType *>> &UDTs) {
3148 #ifndef NDEBUG
3149   size_t OriginalSize = UDTs.size();
3150 #endif
3151   for (const auto &UDT : UDTs) {
3152     const DIType *T = UDT.second;
3153     assert(shouldEmitUdt(T));
3154     MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT);
3155     OS.AddComment("Type");
3156     OS.emitInt32(getCompleteTypeIndex(T).getIndex());
3157     assert(OriginalSize == UDTs.size() &&
3158            "getCompleteTypeIndex found new UDTs!");
3159     emitNullTerminatedSymbolName(OS, UDT.first);
3160     endSymbolRecord(UDTRecordEnd);
3161   }
3162 }
3163 
3164 void CodeViewDebug::collectGlobalVariableInfo() {
3165   DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
3166       GlobalMap;
3167   for (const GlobalVariable &GV : MMI->getModule()->globals()) {
3168     SmallVector<DIGlobalVariableExpression *, 1> GVEs;
3169     GV.getDebugInfo(GVEs);
3170     for (const auto *GVE : GVEs)
3171       GlobalMap[GVE] = &GV;
3172   }
3173 
3174   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
3175   for (const MDNode *Node : CUs->operands()) {
3176     const auto *CU = cast<DICompileUnit>(Node);
3177     for (const auto *GVE : CU->getGlobalVariables()) {
3178       const DIGlobalVariable *DIGV = GVE->getVariable();
3179       const DIExpression *DIE = GVE->getExpression();
3180 
3181       if ((DIE->getNumElements() == 2) &&
3182           (DIE->getElement(0) == dwarf::DW_OP_plus_uconst))
3183         // Record the constant offset for the variable.
3184         //
3185         // A Fortran common block uses this idiom to encode the offset
3186         // of a variable from the common block's starting address.
3187         CVGlobalVariableOffsets.insert(
3188             std::make_pair(DIGV, DIE->getElement(1)));
3189 
3190       // Emit constant global variables in a global symbol section.
3191       if (GlobalMap.count(GVE) == 0 && DIE->isConstant()) {
3192         CVGlobalVariable CVGV = {DIGV, DIE};
3193         GlobalVariables.emplace_back(std::move(CVGV));
3194       }
3195 
3196       const auto *GV = GlobalMap.lookup(GVE);
3197       if (!GV || GV->isDeclarationForLinker())
3198         continue;
3199 
3200       DIScope *Scope = DIGV->getScope();
3201       SmallVector<CVGlobalVariable, 1> *VariableList;
3202       if (Scope && isa<DILocalScope>(Scope)) {
3203         // Locate a global variable list for this scope, creating one if
3204         // necessary.
3205         auto Insertion = ScopeGlobals.insert(
3206             {Scope, std::unique_ptr<GlobalVariableList>()});
3207         if (Insertion.second)
3208           Insertion.first->second = std::make_unique<GlobalVariableList>();
3209         VariableList = Insertion.first->second.get();
3210       } else if (GV->hasComdat())
3211         // Emit this global variable into a COMDAT section.
3212         VariableList = &ComdatVariables;
3213       else
3214         // Emit this global variable in a single global symbol section.
3215         VariableList = &GlobalVariables;
3216       CVGlobalVariable CVGV = {DIGV, GV};
3217       VariableList->emplace_back(std::move(CVGV));
3218     }
3219   }
3220 }
3221 
3222 void CodeViewDebug::collectDebugInfoForGlobals() {
3223   for (const CVGlobalVariable &CVGV : GlobalVariables) {
3224     const DIGlobalVariable *DIGV = CVGV.DIGV;
3225     const DIScope *Scope = DIGV->getScope();
3226     getCompleteTypeIndex(DIGV->getType());
3227     getFullyQualifiedName(Scope, DIGV->getName());
3228   }
3229 
3230   for (const CVGlobalVariable &CVGV : ComdatVariables) {
3231     const DIGlobalVariable *DIGV = CVGV.DIGV;
3232     const DIScope *Scope = DIGV->getScope();
3233     getCompleteTypeIndex(DIGV->getType());
3234     getFullyQualifiedName(Scope, DIGV->getName());
3235   }
3236 }
3237 
3238 void CodeViewDebug::emitDebugInfoForGlobals() {
3239   // First, emit all globals that are not in a comdat in a single symbol
3240   // substream. MSVC doesn't like it if the substream is empty, so only open
3241   // it if we have at least one global to emit.
3242   switchToDebugSectionForSymbol(nullptr);
3243   if (!GlobalVariables.empty() || !StaticConstMembers.empty()) {
3244     OS.AddComment("Symbol subsection for globals");
3245     MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
3246     emitGlobalVariableList(GlobalVariables);
3247     emitStaticConstMemberList();
3248     endCVSubsection(EndLabel);
3249   }
3250 
3251   // Second, emit each global that is in a comdat into its own .debug$S
3252   // section along with its own symbol substream.
3253   for (const CVGlobalVariable &CVGV : ComdatVariables) {
3254     const GlobalVariable *GV = CVGV.GVInfo.get<const GlobalVariable *>();
3255     MCSymbol *GVSym = Asm->getSymbol(GV);
3256     OS.AddComment("Symbol subsection for " +
3257                   Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
3258     switchToDebugSectionForSymbol(GVSym);
3259     MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
3260     // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3261     emitDebugInfoForGlobal(CVGV);
3262     endCVSubsection(EndLabel);
3263   }
3264 }
3265 
3266 void CodeViewDebug::emitDebugInfoForRetainedTypes() {
3267   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
3268   for (const MDNode *Node : CUs->operands()) {
3269     for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
3270       if (DIType *RT = dyn_cast<DIType>(Ty)) {
3271         getTypeIndex(RT);
3272         // FIXME: Add to global/local DTU list.
3273       }
3274     }
3275   }
3276 }
3277 
3278 // Emit each global variable in the specified array.
3279 void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) {
3280   for (const CVGlobalVariable &CVGV : Globals) {
3281     // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3282     emitDebugInfoForGlobal(CVGV);
3283   }
3284 }
3285 
3286 void CodeViewDebug::emitConstantSymbolRecord(const DIType *DTy, APSInt &Value,
3287                                              const std::string &QualifiedName) {
3288   MCSymbol *SConstantEnd = beginSymbolRecord(SymbolKind::S_CONSTANT);
3289   OS.AddComment("Type");
3290   OS.emitInt32(getTypeIndex(DTy).getIndex());
3291 
3292   OS.AddComment("Value");
3293 
3294   // Encoded integers shouldn't need more than 10 bytes.
3295   uint8_t Data[10];
3296   BinaryStreamWriter Writer(Data, llvm::support::endianness::little);
3297   CodeViewRecordIO IO(Writer);
3298   cantFail(IO.mapEncodedInteger(Value));
3299   StringRef SRef((char *)Data, Writer.getOffset());
3300   OS.emitBinaryData(SRef);
3301 
3302   OS.AddComment("Name");
3303   emitNullTerminatedSymbolName(OS, QualifiedName);
3304   endSymbolRecord(SConstantEnd);
3305 }
3306 
3307 void CodeViewDebug::emitStaticConstMemberList() {
3308   for (const DIDerivedType *DTy : StaticConstMembers) {
3309     const DIScope *Scope = DTy->getScope();
3310 
3311     APSInt Value;
3312     if (const ConstantInt *CI =
3313             dyn_cast_or_null<ConstantInt>(DTy->getConstant()))
3314       Value = APSInt(CI->getValue(),
3315                      DebugHandlerBase::isUnsignedDIType(DTy->getBaseType()));
3316     else if (const ConstantFP *CFP =
3317                  dyn_cast_or_null<ConstantFP>(DTy->getConstant()))
3318       Value = APSInt(CFP->getValueAPF().bitcastToAPInt(), true);
3319     else
3320       llvm_unreachable("cannot emit a constant without a value");
3321 
3322     emitConstantSymbolRecord(DTy->getBaseType(), Value,
3323                              getFullyQualifiedName(Scope, DTy->getName()));
3324   }
3325 }
3326 
3327 static bool isFloatDIType(const DIType *Ty) {
3328   if (isa<DICompositeType>(Ty))
3329     return false;
3330 
3331   if (auto *DTy = dyn_cast<DIDerivedType>(Ty)) {
3332     dwarf::Tag T = (dwarf::Tag)Ty->getTag();
3333     if (T == dwarf::DW_TAG_pointer_type ||
3334         T == dwarf::DW_TAG_ptr_to_member_type ||
3335         T == dwarf::DW_TAG_reference_type ||
3336         T == dwarf::DW_TAG_rvalue_reference_type)
3337       return false;
3338     assert(DTy->getBaseType() && "Expected valid base type");
3339     return isFloatDIType(DTy->getBaseType());
3340   }
3341 
3342   auto *BTy = cast<DIBasicType>(Ty);
3343   return (BTy->getEncoding() == dwarf::DW_ATE_float);
3344 }
3345 
3346 void CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable &CVGV) {
3347   const DIGlobalVariable *DIGV = CVGV.DIGV;
3348 
3349   const DIScope *Scope = DIGV->getScope();
3350   // For static data members, get the scope from the declaration.
3351   if (const auto *MemberDecl = dyn_cast_or_null<DIDerivedType>(
3352           DIGV->getRawStaticDataMemberDeclaration()))
3353     Scope = MemberDecl->getScope();
3354   // For Fortran, the scoping portion is elided in its name so that we can
3355   // reference the variable in the command line of the VS debugger.
3356   std::string QualifiedName =
3357       (moduleIsInFortran()) ? std::string(DIGV->getName())
3358                             : getFullyQualifiedName(Scope, DIGV->getName());
3359 
3360   if (const GlobalVariable *GV =
3361           CVGV.GVInfo.dyn_cast<const GlobalVariable *>()) {
3362     // DataSym record, see SymbolRecord.h for more info. Thread local data
3363     // happens to have the same format as global data.
3364     MCSymbol *GVSym = Asm->getSymbol(GV);
3365     SymbolKind DataSym = GV->isThreadLocal()
3366                              ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32
3367                                                       : SymbolKind::S_GTHREAD32)
3368                              : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32
3369                                                       : SymbolKind::S_GDATA32);
3370     MCSymbol *DataEnd = beginSymbolRecord(DataSym);
3371     OS.AddComment("Type");
3372     OS.emitInt32(getCompleteTypeIndex(DIGV->getType()).getIndex());
3373     OS.AddComment("DataOffset");
3374 
3375     uint64_t Offset = 0;
3376     if (CVGlobalVariableOffsets.find(DIGV) != CVGlobalVariableOffsets.end())
3377       // Use the offset seen while collecting info on globals.
3378       Offset = CVGlobalVariableOffsets[DIGV];
3379     OS.EmitCOFFSecRel32(GVSym, Offset);
3380 
3381     OS.AddComment("Segment");
3382     OS.EmitCOFFSectionIndex(GVSym);
3383     OS.AddComment("Name");
3384     const unsigned LengthOfDataRecord = 12;
3385     emitNullTerminatedSymbolName(OS, QualifiedName, LengthOfDataRecord);
3386     endSymbolRecord(DataEnd);
3387   } else {
3388     const DIExpression *DIE = CVGV.GVInfo.get<const DIExpression *>();
3389     assert(DIE->isConstant() &&
3390            "Global constant variables must contain a constant expression.");
3391 
3392     // Use unsigned for floats.
3393     bool isUnsigned = isFloatDIType(DIGV->getType())
3394                           ? true
3395                           : DebugHandlerBase::isUnsignedDIType(DIGV->getType());
3396     APSInt Value(APInt(/*BitWidth=*/64, DIE->getElement(1)), isUnsigned);
3397     emitConstantSymbolRecord(DIGV->getType(), Value, QualifiedName);
3398   }
3399 }
3400