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