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