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