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