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