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