blob: 8cabad4ad312391a1561bf9e22a6219e71be6046 [file] [log] [blame]
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001//===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===//
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Reid Kleckner70f5bc92016-01-14 19:25:04 +000010// This file contains support for writing Microsoft CodeView debug info.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000011//
12//===----------------------------------------------------------------------===//
13
Reid Kleckner70f5bc92016-01-14 19:25:04 +000014#include "CodeViewDebug.h"
Adrian Prantl032d2382017-08-01 21:45:24 +000015#include "DwarfExpression.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000016#include "llvm/ADT/APSInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/DenseSet.h"
20#include "llvm/ADT/MapVector.h"
21#include "llvm/ADT/None.h"
22#include "llvm/ADT/Optional.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000023#include "llvm/ADT/STLExtras.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000024#include "llvm/ADT/SmallString.h"
25#include "llvm/ADT/SmallVector.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000026#include "llvm/ADT/StringRef.h"
Reid Kleckner156a7232016-06-22 18:31:14 +000027#include "llvm/ADT/TinyPtrVector.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000028#include "llvm/ADT/Triple.h"
29#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000030#include "llvm/BinaryFormat/COFF.h"
31#include "llvm/BinaryFormat/Dwarf.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000032#include "llvm/CodeGen/AsmPrinter.h"
33#include "llvm/CodeGen/LexicalScopes.h"
Reid Kleckner9ea2c012018-10-01 21:59:45 +000034#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000035#include "llvm/CodeGen/MachineFunction.h"
36#include "llvm/CodeGen/MachineInstr.h"
37#include "llvm/CodeGen/MachineModuleInfo.h"
38#include "llvm/CodeGen/MachineOperand.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000039#include "llvm/CodeGen/TargetFrameLowering.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000040#include "llvm/CodeGen/TargetRegisterInfo.h"
41#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000042#include "llvm/Config/llvm-config.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000043#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000044#include "llvm/DebugInfo/CodeView/CodeView.h"
Zachary Turner6900de12017-11-28 18:33:17 +000045#include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h"
Zachary Turner8c099fe2017-05-30 16:36:15 +000046#include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
Reid Kleckner5bf71d12018-12-14 22:40:28 +000047#include "llvm/DebugInfo/CodeView/EnumTables.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000048#include "llvm/DebugInfo/CodeView/Line.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000049#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
Zachary Turner629cb7d2017-01-11 23:24:22 +000050#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000051#include "llvm/DebugInfo/CodeView/TypeIndex.h"
52#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Zachary Turner526f4f22017-05-19 19:26:58 +000053#include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
David Majnemer9319cbc2016-06-30 03:00:20 +000054#include "llvm/IR/Constants.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000055#include "llvm/IR/DataLayout.h"
56#include "llvm/IR/DebugInfoMetadata.h"
57#include "llvm/IR/DebugLoc.h"
58#include "llvm/IR/Function.h"
59#include "llvm/IR/GlobalValue.h"
60#include "llvm/IR/GlobalVariable.h"
61#include "llvm/IR/Metadata.h"
62#include "llvm/IR/Module.h"
Reid Kleckner46cb48c2016-07-27 16:03:57 +000063#include "llvm/MC/MCAsmInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000064#include "llvm/MC/MCContext.h"
Reid Kleckner5d122f82016-05-25 23:16:12 +000065#include "llvm/MC/MCSectionCOFF.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000066#include "llvm/MC/MCStreamer.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000067#include "llvm/MC/MCSymbol.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000068#include "llvm/Support/BinaryByteStream.h"
69#include "llvm/Support/BinaryStreamReader.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000070#include "llvm/Support/Casting.h"
Zachary Turner048f8f92017-12-13 22:33:58 +000071#include "llvm/Support/CommandLine.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000072#include "llvm/Support/Compiler.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000073#include "llvm/Support/Endian.h"
74#include "llvm/Support/Error.h"
75#include "llvm/Support/ErrorHandling.h"
Zachary Turner048f8f92017-12-13 22:33:58 +000076#include "llvm/Support/FormatVariadic.h"
Zachary Turner5bba1ca2018-10-12 17:26:19 +000077#include "llvm/Support/Path.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000078#include "llvm/Support/SMLoc.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000079#include "llvm/Support/ScopedPrinter.h"
David Blaikie6054e652018-03-23 23:58:19 +000080#include "llvm/Target/TargetLoweringObjectFile.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000081#include "llvm/Target/TargetMachine.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000082#include <algorithm>
83#include <cassert>
84#include <cctype>
85#include <cstddef>
86#include <cstdint>
87#include <iterator>
88#include <limits>
89#include <string>
90#include <utility>
91#include <vector>
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000092
Reid Klecknerf9c275f2016-02-10 20:55:49 +000093using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000094using namespace llvm::codeview;
95
Reid Kleckner9ea2c012018-10-01 21:59:45 +000096static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
97 switch (Type) {
98 case Triple::ArchType::x86:
99 return CPUType::Pentium3;
100 case Triple::ArchType::x86_64:
101 return CPUType::X64;
102 case Triple::ArchType::thumb:
103 return CPUType::Thumb;
104 case Triple::ArchType::aarch64:
105 return CPUType::ARM64;
106 default:
107 report_fatal_error("target architecture doesn't map to a CodeView CPUType");
108 }
109}
110
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000111CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000112 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000113 // If module doesn't have named metadata anchors or COFF debug section
114 // is not available, skip any debug info related stuff.
115 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
116 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
117 Asm = nullptr;
Matthias Braun8763c0c2018-10-31 17:18:41 +0000118 MMI->setDebugInfoAvailability(false);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000119 return;
120 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000121 // Tell MMI that we have debug info.
122 MMI->setDebugInfoAvailability(true);
Reid Kleckner9ea2c012018-10-01 21:59:45 +0000123
124 TheCPU =
125 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
Reid Kleckner75557712018-11-16 18:47:41 +0000126
Brock Wymab17464e2018-12-20 17:33:45 +0000127 collectGlobalVariableInfo();
128
Reid Kleckner75557712018-11-16 18:47:41 +0000129 // Check if we should emit type record hashes.
130 ConstantInt *GH = mdconst::extract_or_null<ConstantInt>(
131 MMI->getModule()->getModuleFlag("CodeViewGHash"));
132 EmitDebugGlobalHashes = GH && !GH->isZero();
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000133}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000134
Reid Kleckner9533af42016-01-16 00:09:09 +0000135StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
136 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000137 if (!Filepath.empty())
138 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000139
Reid Kleckner9533af42016-01-16 00:09:09 +0000140 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
141
Peter Collingbournecb8a6662018-04-11 18:24:03 +0000142 // If this is a Unix-style path, just use it as is. Don't try to canonicalize
143 // it textually because one of the path components could be a symlink.
Zachary Turner5bba1ca2018-10-12 17:26:19 +0000144 if (Dir.startswith("/") || Filename.startswith("/")) {
145 if (llvm::sys::path::is_absolute(Filename, llvm::sys::path::Style::posix))
146 return Filename;
Peter Collingbournecb8a6662018-04-11 18:24:03 +0000147 Filepath = Dir;
148 if (Dir.back() != '/')
149 Filepath += '/';
150 Filepath += Filename;
151 return Filepath;
152 }
153
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000154 // Clang emits directory and relative filename info into the IR, but CodeView
155 // operates on full paths. We could change Clang to emit full paths too, but
156 // that would increase the IR size and probably not needed for other users.
157 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000158 if (Filename.find(':') == 1)
159 Filepath = Filename;
160 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +0000161 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000162
163 // Canonicalize the path. We have to do it textually because we may no longer
164 // have access the file in the filesystem.
165 // First, replace all slashes with backslashes.
166 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
167
168 // Remove all "\.\" with "\".
169 size_t Cursor = 0;
170 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
171 Filepath.erase(Cursor, 2);
172
173 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
174 // path should be well-formatted, e.g. start with a drive letter, etc.
175 Cursor = 0;
176 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
177 // Something's wrong if the path starts with "\..\", abort.
178 if (Cursor == 0)
179 break;
180
181 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
182 if (PrevSlash == std::string::npos)
183 // Something's wrong, abort.
184 break;
185
186 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
187 // The next ".." might be following the one we've just erased.
188 Cursor = PrevSlash;
189 }
190
191 // Remove all duplicate backslashes.
192 Cursor = 0;
193 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
194 Filepath.erase(Cursor, 1);
195
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000196 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000197}
198
Reid Kleckner2214ed82016-01-29 00:49:42 +0000199unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
Reid Klecknerbc6f52d2017-10-31 21:52:15 +0000200 StringRef FullPath = getFullFilepath(F);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000201 unsigned NextId = FileIdMap.size() + 1;
Reid Klecknerbc6f52d2017-10-31 21:52:15 +0000202 auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
Reid Kleckner2214ed82016-01-29 00:49:42 +0000203 if (Insertion.second) {
204 // We have to compute the full filepath and emit a .cv_file directive.
Scott Linder71603842018-02-12 19:45:54 +0000205 ArrayRef<uint8_t> ChecksumAsBytes;
206 FileChecksumKind CSKind = FileChecksumKind::None;
207 if (F->getChecksum()) {
208 std::string Checksum = fromHex(F->getChecksum()->Value);
209 void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
210 memcpy(CKMem, Checksum.data(), Checksum.size());
211 ChecksumAsBytes = ArrayRef<uint8_t>(
212 reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
213 switch (F->getChecksum()->Kind) {
214 case DIFile::CSK_MD5: CSKind = FileChecksumKind::MD5; break;
215 case DIFile::CSK_SHA1: CSKind = FileChecksumKind::SHA1; break;
216 }
217 }
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000218 bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
Scott Linder71603842018-02-12 19:45:54 +0000219 static_cast<unsigned>(CSKind));
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000220 (void)Success;
221 assert(Success && ".cv_file directive failed");
Reid Kleckner2214ed82016-01-29 00:49:42 +0000222 }
223 return Insertion.first->second;
224}
225
Reid Kleckner876330d2016-02-12 21:48:30 +0000226CodeViewDebug::InlineSite &
227CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
228 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000229 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
230 InlineSite *Site = &SiteInsertion.first->second;
231 if (SiteInsertion.second) {
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000232 unsigned ParentFuncId = CurFn->FuncId;
233 if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
234 ParentFuncId =
235 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
236 .SiteFuncId;
237
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000238 Site->SiteFuncId = NextFuncId++;
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000239 OS.EmitCVInlineSiteIdDirective(
240 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
241 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
Reid Kleckner876330d2016-02-12 21:48:30 +0000242 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000243 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000244 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000245 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000246 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000247}
248
David Majnemer6bdc24e2016-07-01 23:12:45 +0000249static StringRef getPrettyScopeName(const DIScope *Scope) {
250 StringRef ScopeName = Scope->getName();
251 if (!ScopeName.empty())
252 return ScopeName;
253
254 switch (Scope->getTag()) {
255 case dwarf::DW_TAG_enumeration_type:
256 case dwarf::DW_TAG_class_type:
257 case dwarf::DW_TAG_structure_type:
258 case dwarf::DW_TAG_union_type:
259 return "<unnamed-tag>";
260 case dwarf::DW_TAG_namespace:
261 return "`anonymous namespace'";
262 }
263
264 return StringRef();
265}
266
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000267static const DISubprogram *getQualifiedNameComponents(
268 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
269 const DISubprogram *ClosestSubprogram = nullptr;
270 while (Scope != nullptr) {
271 if (ClosestSubprogram == nullptr)
272 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
David Majnemer6bdc24e2016-07-01 23:12:45 +0000273 StringRef ScopeName = getPrettyScopeName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000274 if (!ScopeName.empty())
275 QualifiedNameComponents.push_back(ScopeName);
276 Scope = Scope->getScope().resolve();
277 }
278 return ClosestSubprogram;
279}
280
281static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
282 StringRef TypeName) {
283 std::string FullyQualifiedName;
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000284 for (StringRef QualifiedNameComponent :
285 llvm::reverse(QualifiedNameComponents)) {
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000286 FullyQualifiedName.append(QualifiedNameComponent);
287 FullyQualifiedName.append("::");
288 }
289 FullyQualifiedName.append(TypeName);
290 return FullyQualifiedName;
291}
292
293static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
294 SmallVector<StringRef, 5> QualifiedNameComponents;
295 getQualifiedNameComponents(Scope, QualifiedNameComponents);
296 return getQualifiedName(QualifiedNameComponents, Name);
297}
298
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000299struct CodeViewDebug::TypeLoweringScope {
300 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
301 ~TypeLoweringScope() {
302 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
303 // inner TypeLoweringScopes don't attempt to emit deferred types.
304 if (CVD.TypeEmissionLevel == 1)
305 CVD.emitDeferredCompleteTypes();
306 --CVD.TypeEmissionLevel;
307 }
308 CodeViewDebug &CVD;
309};
310
David Majnemer6bdc24e2016-07-01 23:12:45 +0000311static std::string getFullyQualifiedName(const DIScope *Ty) {
312 const DIScope *Scope = Ty->getScope().resolve();
313 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
314}
315
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000316TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
317 // No scope means global scope and that uses the zero index.
318 if (!Scope || isa<DIFile>(Scope))
319 return TypeIndex();
320
321 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
322
323 // Check if we've already translated this scope.
324 auto I = TypeIndices.find({Scope, nullptr});
325 if (I != TypeIndices.end())
326 return I->second;
327
328 // Build the fully qualified name of the scope.
David Majnemer6bdc24e2016-07-01 23:12:45 +0000329 std::string ScopeName = getFullyQualifiedName(Scope);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000330 StringIdRecord SID(TypeIndex(), ScopeName);
Zachary Turner6900de12017-11-28 18:33:17 +0000331 auto TI = TypeTable.writeLeafType(SID);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000332 return recordTypeIndexForDINode(Scope, TI);
333}
334
David Majnemer75c3ebf2016-06-02 17:13:53 +0000335TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
David Majnemer67f684e2016-07-28 05:03:22 +0000336 assert(SP);
Reid Kleckner2280f932016-05-23 20:23:46 +0000337
David Majnemer75c3ebf2016-06-02 17:13:53 +0000338 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000339 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000340 if (I != TypeIndices.end())
341 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000342
Reid Klecknerac945e22016-06-17 16:11:20 +0000343 // The display name includes function template arguments. Drop them to match
344 // MSVC.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000345 StringRef DisplayName = SP->getName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000346
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000347 const DIScope *Scope = SP->getScope().resolve();
348 TypeIndex TI;
349 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
350 // If the scope is a DICompositeType, then this must be a method. Member
351 // function types take some special handling, and require access to the
352 // subprogram.
353 TypeIndex ClassType = getTypeIndex(Class);
354 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
355 DisplayName);
Zachary Turner6900de12017-11-28 18:33:17 +0000356 TI = TypeTable.writeLeafType(MFuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000357 } else {
358 // Otherwise, this must be a free function.
359 TypeIndex ParentScope = getScopeIndex(Scope);
360 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Zachary Turner6900de12017-11-28 18:33:17 +0000361 TI = TypeTable.writeLeafType(FuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000362 }
363
364 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000365}
366
Aaron Smith802b0332018-10-02 20:21:05 +0000367static bool isTrivial(const DICompositeType *DCTy) {
368 return ((DCTy->getFlags() & DINode::FlagTrivial) == DINode::FlagTrivial);
369}
370
371static FunctionOptions
372getFunctionOptions(const DISubroutineType *Ty,
373 const DICompositeType *ClassTy = nullptr,
374 StringRef SPName = StringRef("")) {
375 FunctionOptions FO = FunctionOptions::None;
376 const DIType *ReturnTy = nullptr;
377 if (auto TypeArray = Ty->getTypeArray()) {
378 if (TypeArray.size())
379 ReturnTy = TypeArray[0].resolve();
380 }
381
382 if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy)) {
383 if (!isTrivial(ReturnDCTy))
384 FO |= FunctionOptions::CxxReturnUdt;
385 }
386
387 // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison.
388 if (ClassTy && !isTrivial(ClassTy) && SPName == ClassTy->getName()) {
389 FO |= FunctionOptions::Constructor;
390
391 // TODO: put the FunctionOptions::ConstructorWithVirtualBases flag.
392
393 }
394 return FO;
395}
396
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000397TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
398 const DICompositeType *Class) {
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000399 // Always use the method declaration as the key for the function type. The
400 // method declaration contains the this adjustment.
401 if (SP->getDeclaration())
402 SP = SP->getDeclaration();
403 assert(!SP->getDeclaration() && "should use declaration as key");
404
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000405 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
406 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000407 auto I = TypeIndices.find({SP, Class});
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000408 if (I != TypeIndices.end())
409 return I->second;
410
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000411 // Make sure complete type info for the class is emitted *after* the member
412 // function type, as the complete class type is likely to reference this
413 // member function type.
414 TypeLoweringScope S(*this);
Adrian McCarthyd91bf392017-09-13 20:53:55 +0000415 const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
Aaron Smith802b0332018-10-02 20:21:05 +0000416
417 FunctionOptions FO = getFunctionOptions(SP->getType(), Class, SP->getName());
Adrian McCarthyd91bf392017-09-13 20:53:55 +0000418 TypeIndex TI = lowerTypeMemberFunction(
Aaron Smith802b0332018-10-02 20:21:05 +0000419 SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000420 return recordTypeIndexForDINode(SP, TI, Class);
421}
422
Amjad Aboudacee5682016-07-12 12:06:34 +0000423TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
424 TypeIndex TI,
425 const DIType *ClassTy) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000426 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000427 (void)InsertResult;
428 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000429 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000430}
431
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000432unsigned CodeViewDebug::getPointerSizeInBytes() {
433 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
434}
435
Reid Kleckner876330d2016-02-12 21:48:30 +0000436void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
Reid Kleckner5a791ee2018-03-15 21:24:04 +0000437 const LexicalScope *LS) {
438 if (const DILocation *InlinedAt = LS->getInlinedAt()) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000439 // This variable was inlined. Associate it with the InlineSite.
440 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
441 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
442 Site.InlinedLocals.emplace_back(Var);
443 } else {
Reid Kleckner5a791ee2018-03-15 21:24:04 +0000444 // This variable goes into the corresponding lexical scope.
445 ScopeVariables[LS].emplace_back(Var);
Reid Kleckner876330d2016-02-12 21:48:30 +0000446 }
447}
448
Reid Kleckner829365a2016-02-11 19:41:47 +0000449static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
450 const DILocation *Loc) {
451 auto B = Locs.begin(), E = Locs.end();
452 if (std::find(B, E, Loc) == E)
453 Locs.push_back(Loc);
454}
455
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000456void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000457 const MachineFunction *MF) {
458 // Skip this instruction if it has the same location as the previous one.
Reid Kleckner45a74622017-06-30 21:33:44 +0000459 if (!DL || DL == PrevInstLoc)
Reid Kleckner9533af42016-01-16 00:09:09 +0000460 return;
461
462 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000463 if (!Scope)
464 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000465
David Majnemerc3340db2016-01-13 01:05:23 +0000466 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000467 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
468 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
469 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000470 return;
471
Reid Kleckner2214ed82016-01-29 00:49:42 +0000472 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
473 if (CI.getStartColumn() != DL.getCol())
474 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000475
Reid Kleckner2214ed82016-01-29 00:49:42 +0000476 if (!CurFn->HaveLineInfo)
477 CurFn->HaveLineInfo = true;
478 unsigned FileId = 0;
Reid Kleckner45a74622017-06-30 21:33:44 +0000479 if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
Reid Kleckner2214ed82016-01-29 00:49:42 +0000480 FileId = CurFn->LastFileId;
481 else
482 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
Reid Kleckner45a74622017-06-30 21:33:44 +0000483 PrevInstLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000484
485 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000486 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000487 const DILocation *Loc = DL.get();
488
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000489 // If this location was actually inlined from somewhere else, give it the ID
490 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000491 FuncId =
492 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000493
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000494 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000495 bool FirstLoc = true;
496 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000497 InlineSite &Site =
498 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000499 if (!FirstLoc)
500 addLocIfNotPresent(Site.ChildSites, Loc);
501 FirstLoc = false;
502 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000503 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000504 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000505 }
506
Reid Klecknerdac21b42016-02-03 21:15:48 +0000507 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000508 /*PrologueEnd=*/false, /*IsStmt=*/false,
509 DL->getFilename(), SMLoc());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000510}
511
Reid Kleckner5d122f82016-05-25 23:16:12 +0000512void CodeViewDebug::emitCodeViewMagicVersion() {
513 OS.EmitValueToAlignment(4);
514 OS.AddComment("Debug section magic");
515 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
516}
517
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000518void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000519 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000520 return;
521
522 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000523
524 // The COFF .debug$S section consists of several subsections, each starting
525 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
526 // of the payload followed by the payload itself. The subsections are 4-byte
527 // aligned.
528
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000529 // Use the generic .debug$S section, and make a subsection for all the inlined
530 // subprograms.
531 switchToDebugSectionForSymbol(nullptr);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000532
Zachary Turner8c099fe2017-05-30 16:36:15 +0000533 MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000534 emitCompilerInformation();
535 endCVSubsection(CompilerInfo);
536
Reid Kleckner5d122f82016-05-25 23:16:12 +0000537 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000538
Reid Kleckner2214ed82016-01-29 00:49:42 +0000539 // Emit per-function debug information.
540 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000541 if (!P.first->isDeclarationForLinker())
Reid Kleckner55baeef2018-03-15 21:12:21 +0000542 emitDebugInfoForFunction(P.first, *P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000543
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000544 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000545 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000546 emitDebugInfoForGlobals();
547
Hans Wennborgb510b452016-06-23 16:33:53 +0000548 // Emit retained types.
549 emitDebugInfoForRetainedTypes();
550
Reid Kleckner5d122f82016-05-25 23:16:12 +0000551 // Switch back to the generic .debug$S section after potentially processing
552 // comdat symbol sections.
553 switchToDebugSectionForSymbol(nullptr);
554
David Majnemer3128b102016-06-15 18:00:01 +0000555 // Emit UDT records for any types used by global variables.
556 if (!GlobalUDTs.empty()) {
Zachary Turner8c099fe2017-05-30 16:36:15 +0000557 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
David Majnemer3128b102016-06-15 18:00:01 +0000558 emitDebugInfoForUDTs(GlobalUDTs);
559 endCVSubsection(SymbolsEnd);
560 }
561
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000562 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000563 OS.AddComment("File index to string table offset subsection");
564 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000565
566 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000567 OS.AddComment("String table");
568 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000569
Reid Kleckner810687c2018-10-12 18:19:06 +0000570 // Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol
571 // subsection in the generic .debug$S section at the end. There is no
572 // particular reason for this ordering other than to match MSVC.
573 emitBuildInfo();
574
Zachary Turner048f8f92017-12-13 22:33:58 +0000575 // Emit type information and hashes last, so that any types we translate while
576 // emitting function info are included.
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000577 emitTypeInformation();
578
Zachary Turner048f8f92017-12-13 22:33:58 +0000579 if (EmitDebugGlobalHashes)
580 emitTypeGlobalHashes();
581
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000582 clear();
583}
584
Brock Wyma19e17b32018-02-11 21:26:46 +0000585static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S,
586 unsigned MaxFixedRecordLength = 0xF00) {
Reid Klecknerbb96df62016-10-05 22:36:07 +0000587 // The maximum CV record length is 0xFF00. Most of the strings we emit appear
588 // after a fixed length portion of the record. The fixed length portion should
589 // always be less than 0xF00 (3840) bytes, so truncate the string so that the
590 // overall record size is less than the maximum allowed.
Reid Klecknerbb96df62016-10-05 22:36:07 +0000591 SmallString<32> NullTerminatedString(
592 S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
David Majnemerb9456a52016-03-14 05:15:09 +0000593 NullTerminatedString.push_back('\0');
594 OS.EmitBytes(NullTerminatedString);
595}
596
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000597void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000598 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000599 return;
600
Alexandre Ganead9e96742018-04-09 20:17:56 +0000601 // Start the .debug$T or .debug$P section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000602 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000603 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000604
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000605 SmallString<8> CommentPrefix;
606 if (OS.isVerboseAsm()) {
607 CommentPrefix += '\t';
608 CommentPrefix += Asm->MAI->getCommentString();
609 CommentPrefix += ' ';
610 }
611
Zachary Turner526f4f22017-05-19 19:26:58 +0000612 TypeTableCollection Table(TypeTable.records());
613 Optional<TypeIndex> B = Table.getFirst();
614 while (B) {
615 // This will fail if the record data is invalid.
616 CVType Record = Table.getType(*B);
617
Zachary Turner4efa0a42016-11-08 22:24:53 +0000618 if (OS.isVerboseAsm()) {
619 // Emit a block comment describing the type record for readability.
620 SmallString<512> CommentBlock;
621 raw_svector_ostream CommentOS(CommentBlock);
622 ScopedPrinter SP(CommentOS);
623 SP.setPrefix(CommentPrefix);
Zachary Turner526f4f22017-05-19 19:26:58 +0000624 TypeDumpVisitor TDV(Table, &SP, false);
625
626 Error E = codeview::visitTypeRecord(Record, *B, TDV);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000627 if (E) {
628 logAllUnhandledErrors(std::move(E), errs(), "error: ");
629 llvm_unreachable("produced malformed type record");
630 }
631 // emitRawComment will insert its own tab and comment string before
632 // the first line, so strip off our first one. It also prints its own
633 // newline.
634 OS.emitRawComment(
635 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
Zachary Turner4efa0a42016-11-08 22:24:53 +0000636 }
Zachary Turner526f4f22017-05-19 19:26:58 +0000637 OS.EmitBinaryData(Record.str_data());
638 B = Table.getNext(*B);
639 }
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000640}
641
Zachary Turner048f8f92017-12-13 22:33:58 +0000642void CodeViewDebug::emitTypeGlobalHashes() {
643 if (TypeTable.empty())
644 return;
645
646 // Start the .debug$H section with the version and hash algorithm, currently
647 // hardcoded to version 0, SHA1.
648 OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
649
650 OS.EmitValueToAlignment(4);
651 OS.AddComment("Magic");
652 OS.EmitIntValue(COFF::DEBUG_HASHES_SECTION_MAGIC, 4);
653 OS.AddComment("Section Version");
654 OS.EmitIntValue(0, 2);
655 OS.AddComment("Hash Algorithm");
Zachary Turnerc7626662018-05-17 22:55:15 +0000656 OS.EmitIntValue(uint16_t(GlobalTypeHashAlg::SHA1_8), 2);
Zachary Turner048f8f92017-12-13 22:33:58 +0000657
658 TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
659 for (const auto &GHR : TypeTable.hashes()) {
660 if (OS.isVerboseAsm()) {
661 // Emit an EOL-comment describing which TypeIndex this hash corresponds
662 // to, as well as the stringified SHA1 hash.
663 SmallString<32> Comment;
664 raw_svector_ostream CommentOS(Comment);
665 CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
666 OS.AddComment(Comment);
667 ++TI;
668 }
Zachary Turnerc7626662018-05-17 22:55:15 +0000669 assert(GHR.Hash.size() == 8);
Zachary Turner048f8f92017-12-13 22:33:58 +0000670 StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
671 GHR.Hash.size());
672 OS.EmitBinaryData(S);
673 }
674}
675
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000676static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
677 switch (DWLang) {
678 case dwarf::DW_LANG_C:
679 case dwarf::DW_LANG_C89:
680 case dwarf::DW_LANG_C99:
681 case dwarf::DW_LANG_C11:
682 case dwarf::DW_LANG_ObjC:
683 return SourceLanguage::C;
684 case dwarf::DW_LANG_C_plus_plus:
685 case dwarf::DW_LANG_C_plus_plus_03:
686 case dwarf::DW_LANG_C_plus_plus_11:
687 case dwarf::DW_LANG_C_plus_plus_14:
688 return SourceLanguage::Cpp;
689 case dwarf::DW_LANG_Fortran77:
690 case dwarf::DW_LANG_Fortran90:
691 case dwarf::DW_LANG_Fortran03:
692 case dwarf::DW_LANG_Fortran08:
693 return SourceLanguage::Fortran;
694 case dwarf::DW_LANG_Pascal83:
695 return SourceLanguage::Pascal;
696 case dwarf::DW_LANG_Cobol74:
697 case dwarf::DW_LANG_Cobol85:
698 return SourceLanguage::Cobol;
699 case dwarf::DW_LANG_Java:
700 return SourceLanguage::Java;
Reid Kleckner898ddf62017-07-24 16:16:42 +0000701 case dwarf::DW_LANG_D:
702 return SourceLanguage::D;
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000703 default:
704 // There's no CodeView representation for this language, and CV doesn't
705 // have an "unknown" option for the language field, so we'll use MASM,
706 // as it's very low level.
707 return SourceLanguage::Masm;
708 }
709}
710
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000711namespace {
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000712struct Version {
713 int Part[4];
714};
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000715} // end anonymous namespace
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000716
717// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
718// the version number.
719static Version parseVersion(StringRef Name) {
Adrian McCarthyad8ac542016-09-20 17:42:13 +0000720 Version V = {{0}};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000721 int N = 0;
722 for (const char C : Name) {
723 if (isdigit(C)) {
724 V.Part[N] *= 10;
725 V.Part[N] += C - '0';
726 } else if (C == '.') {
727 ++N;
728 if (N >= 4)
729 return V;
730 } else if (N > 0)
731 return V;
732 }
733 return V;
734}
735
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000736void CodeViewDebug::emitCompilerInformation() {
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000737 MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_COMPILE3);
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000738 uint32_t Flags = 0;
739
740 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
741 const MDNode *Node = *CUs->operands().begin();
742 const auto *CU = cast<DICompileUnit>(Node);
743
744 // The low byte of the flags indicates the source language.
745 Flags = MapDWLangToCVLang(CU->getSourceLanguage());
746 // TODO: Figure out which other flags need to be set.
747
748 OS.AddComment("Flags and language");
749 OS.EmitIntValue(Flags, 4);
750
751 OS.AddComment("CPUType");
Reid Kleckner9ea2c012018-10-01 21:59:45 +0000752 OS.EmitIntValue(static_cast<uint64_t>(TheCPU), 2);
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000753
754 StringRef CompilerVersion = CU->getProducer();
755 Version FrontVer = parseVersion(CompilerVersion);
756 OS.AddComment("Frontend version");
757 for (int N = 0; N < 4; ++N)
758 OS.EmitIntValue(FrontVer.Part[N], 2);
759
760 // Some Microsoft tools, like Binscope, expect a backend version number of at
761 // least 8.something, so we'll coerce the LLVM version into a form that
762 // guarantees it'll be big enough without really lying about the version.
Adrian McCarthyd1185fc2016-09-29 20:28:25 +0000763 int Major = 1000 * LLVM_VERSION_MAJOR +
764 10 * LLVM_VERSION_MINOR +
765 LLVM_VERSION_PATCH;
766 // Clamp it for builds that use unusually large version numbers.
767 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
768 Version BackVer = {{ Major, 0, 0, 0 }};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000769 OS.AddComment("Backend version");
770 for (int N = 0; N < 4; ++N)
771 OS.EmitIntValue(BackVer.Part[N], 2);
772
773 OS.AddComment("Null-terminated compiler version string");
774 emitNullTerminatedSymbolName(OS, CompilerVersion);
775
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000776 endSymbolRecord(CompilerEnd);
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000777}
778
Reid Kleckner810687c2018-10-12 18:19:06 +0000779static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable,
780 StringRef S) {
781 StringIdRecord SIR(TypeIndex(0x0), S);
782 return TypeTable.writeLeafType(SIR);
783}
784
785void CodeViewDebug::emitBuildInfo() {
786 // First, make LF_BUILDINFO. It's a sequence of strings with various bits of
787 // build info. The known prefix is:
788 // - Absolute path of current directory
789 // - Compiler path
790 // - Main source file path, relative to CWD or absolute
791 // - Type server PDB file
792 // - Canonical compiler command line
793 // If frontend and backend compilation are separated (think llc or LTO), it's
794 // not clear if the compiler path should refer to the executable for the
795 // frontend or the backend. Leave it blank for now.
796 TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {};
797 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
798 const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs.
799 const auto *CU = cast<DICompileUnit>(Node);
800 const DIFile *MainSourceFile = CU->getFile();
801 BuildInfoArgs[BuildInfoRecord::CurrentDirectory] =
802 getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory());
803 BuildInfoArgs[BuildInfoRecord::SourceFile] =
804 getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename());
805 // FIXME: Path to compiler and command line. PDB is intentionally blank unless
806 // we implement /Zi type servers.
807 BuildInfoRecord BIR(BuildInfoArgs);
808 TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR);
809
810 // Make a new .debug$S subsection for the S_BUILDINFO record, which points
811 // from the module symbols into the type stream.
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000812 MCSymbol *BISubsecEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
813 MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO);
Reid Kleckner810687c2018-10-12 18:19:06 +0000814 OS.AddComment("LF_BUILDINFO index");
815 OS.EmitIntValue(BuildInfoIndex.getIndex(), 4);
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000816 endSymbolRecord(BIEnd);
817 endCVSubsection(BISubsecEnd);
Reid Kleckner810687c2018-10-12 18:19:06 +0000818}
819
Reid Kleckner5d122f82016-05-25 23:16:12 +0000820void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000821 if (InlinedSubprograms.empty())
822 return;
823
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000824 OS.AddComment("Inlinee lines subsection");
Zachary Turner8c099fe2017-05-30 16:36:15 +0000825 MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000826
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000827 // We emit the checksum info for files. This is used by debuggers to
828 // determine if a pdb matches the source before loading it. Visual Studio,
829 // for instance, will display a warning that the breakpoints are not valid if
830 // the pdb does not match the source.
David Majnemer30579ec2016-02-02 23:18:23 +0000831 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000832 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
833
834 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000835 assert(TypeIndices.count({SP, nullptr}));
836 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000837
David Majnemer30579ec2016-02-02 23:18:23 +0000838 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000839 unsigned FileId = maybeRecordFile(SP->getFile());
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000840 OS.AddComment("Inlined function " + SP->getName() + " starts at " +
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000841 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000842 OS.AddBlankLine();
David Majnemer30579ec2016-02-02 23:18:23 +0000843 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000844 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000845 OS.AddComment("Offset into filechecksum table");
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000846 OS.EmitCVFileChecksumOffsetDirective(FileId);
David Majnemer30579ec2016-02-02 23:18:23 +0000847 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000848 OS.EmitIntValue(SP->getLine(), 4);
849 }
850
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000851 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000852}
853
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000854void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
855 const DILocation *InlinedAt,
856 const InlineSite &Site) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000857 assert(TypeIndices.count({Site.Inlinee, nullptr}));
858 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000859
860 // SymbolRecord
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000861 MCSymbol *InlineEnd = beginSymbolRecord(SymbolKind::S_INLINESITE);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000862
Reid Klecknerdac21b42016-02-03 21:15:48 +0000863 OS.AddComment("PtrParent");
864 OS.EmitIntValue(0, 4);
865 OS.AddComment("PtrEnd");
866 OS.EmitIntValue(0, 4);
867 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000868 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000869
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000870 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
871 unsigned StartLineNum = Site.Inlinee->getLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000872
873 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000874 FI.Begin, FI.End);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000875
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000876 endSymbolRecord(InlineEnd);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000877
Reid Kleckner9ea2c012018-10-01 21:59:45 +0000878 emitLocalVariableList(FI, Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000879
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000880 // Recurse on child inlined call sites before closing the scope.
881 for (const DILocation *ChildSite : Site.ChildSites) {
882 auto I = FI.InlineSites.find(ChildSite);
883 assert(I != FI.InlineSites.end() &&
884 "child site not in function inline site map");
885 emitInlinedCallSite(FI, ChildSite, I->second);
886 }
887
888 // Close the scope.
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000889 emitEndSymbolRecord(SymbolKind::S_INLINESITE_END);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000890}
891
Reid Kleckner5d122f82016-05-25 23:16:12 +0000892void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
893 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
894 // comdat key. A section may be comdat because of -ffunction-sections or
895 // because it is comdat in the IR.
896 MCSectionCOFF *GVSec =
897 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
898 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
899
900 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
901 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
902 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
903
904 OS.SwitchSection(DebugSec);
905
906 // Emit the magic version number if this is the first time we've switched to
907 // this section.
908 if (ComdatDebugSections.insert(DebugSec).second)
909 emitCodeViewMagicVersion();
910}
911
Brock Wyma94ece8f2018-04-16 16:53:57 +0000912// Emit an S_THUNK32/S_END symbol pair for a thunk routine.
913// The only supported thunk ordinal is currently the standard type.
914void CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
915 FunctionInfo &FI,
916 const MCSymbol *Fn) {
917 std::string FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
918 const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
919
920 OS.AddComment("Symbol subsection for " + Twine(FuncName));
921 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
922
923 // Emit S_THUNK32
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000924 MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32);
Brock Wyma94ece8f2018-04-16 16:53:57 +0000925 OS.AddComment("PtrParent");
926 OS.EmitIntValue(0, 4);
927 OS.AddComment("PtrEnd");
928 OS.EmitIntValue(0, 4);
929 OS.AddComment("PtrNext");
930 OS.EmitIntValue(0, 4);
931 OS.AddComment("Thunk section relative address");
932 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
933 OS.AddComment("Thunk section index");
934 OS.EmitCOFFSectionIndex(Fn);
935 OS.AddComment("Code size");
936 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
937 OS.AddComment("Ordinal");
938 OS.EmitIntValue(unsigned(ordinal), 1);
939 OS.AddComment("Function name");
940 emitNullTerminatedSymbolName(OS, FuncName);
941 // Additional fields specific to the thunk ordinal would go here.
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000942 endSymbolRecord(ThunkRecordEnd);
Brock Wyma94ece8f2018-04-16 16:53:57 +0000943
944 // Local variables/inlined routines are purposely omitted here. The point of
945 // marking this as a thunk is so Visual Studio will NOT stop in this routine.
946
947 // Emit S_PROC_ID_END
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000948 emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
Brock Wyma94ece8f2018-04-16 16:53:57 +0000949
950 endCVSubsection(SymbolsEnd);
951}
952
Reid Kleckner2214ed82016-01-29 00:49:42 +0000953void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
954 FunctionInfo &FI) {
Brock Wyma31cc1eb2018-01-30 13:16:50 +0000955 // For each function there is a separate subsection which holds the PC to
956 // file:line table.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000957 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000958 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000959
Reid Kleckner5d122f82016-05-25 23:16:12 +0000960 // Switch to the to a comdat section, if appropriate.
961 switchToDebugSectionForSymbol(Fn);
962
Reid Klecknerac945e22016-06-17 16:11:20 +0000963 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000964 auto *SP = GV->getSubprogram();
David Majnemer67f684e2016-07-28 05:03:22 +0000965 assert(SP);
David Majnemer3128b102016-06-15 18:00:01 +0000966 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000967
Brock Wyma94ece8f2018-04-16 16:53:57 +0000968 if (SP->isThunk()) {
969 emitDebugInfoForThunk(GV, FI, Fn);
970 return;
971 }
972
Reid Klecknerac945e22016-06-17 16:11:20 +0000973 // If we have a display name, build the fully qualified name by walking the
974 // chain of scopes.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000975 if (!SP->getName().empty())
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000976 FuncName =
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000977 getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000978
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000979 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000980 if (FuncName.empty())
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +0000981 FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000982
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000983 // Emit FPO data, but only on 32-bit x86. No other platforms use it.
984 if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
985 OS.EmitCVFPOData(Fn);
986
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000987 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000988 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Zachary Turner8c099fe2017-05-30 16:36:15 +0000989 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000990 {
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000991 SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID
992 : SymbolKind::S_GPROC32_ID;
993 MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind);
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000994
David Majnemer30579ec2016-02-02 23:18:23 +0000995 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000996 OS.AddComment("PtrParent");
997 OS.EmitIntValue(0, 4);
998 OS.AddComment("PtrEnd");
999 OS.EmitIntValue(0, 4);
1000 OS.AddComment("PtrNext");
1001 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001002 // This is the important bit that tells the debugger where the function
1003 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +00001004 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +00001005 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +00001006 OS.AddComment("Offset after prologue");
1007 OS.EmitIntValue(0, 4);
1008 OS.AddComment("Offset before epilogue");
1009 OS.EmitIntValue(0, 4);
1010 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +00001011 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +00001012 OS.AddComment("Function section relative address");
Keno Fischerf7d84ee2017-01-02 03:00:19 +00001013 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
Reid Klecknerdac21b42016-02-03 21:15:48 +00001014 OS.AddComment("Function section index");
1015 OS.EmitCOFFSectionIndex(Fn);
1016 OS.AddComment("Flags");
1017 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +00001018 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +00001019 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +00001020 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00001021 emitNullTerminatedSymbolName(OS, FuncName);
Reid Kleckner5bf71d12018-12-14 22:40:28 +00001022 endSymbolRecord(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001023
Reid Kleckner5bf71d12018-12-14 22:40:28 +00001024 MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC);
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001025 // Subtract out the CSR size since MSVC excludes that and we include it.
1026 OS.AddComment("FrameSize");
1027 OS.EmitIntValue(FI.FrameSize - FI.CSRSize, 4);
1028 OS.AddComment("Padding");
1029 OS.EmitIntValue(0, 4);
1030 OS.AddComment("Offset of padding");
1031 OS.EmitIntValue(0, 4);
1032 OS.AddComment("Bytes of callee saved registers");
1033 OS.EmitIntValue(FI.CSRSize, 4);
1034 OS.AddComment("Exception handler offset");
1035 OS.EmitIntValue(0, 4);
1036 OS.AddComment("Exception handler section");
1037 OS.EmitIntValue(0, 2);
1038 OS.AddComment("Flags (defines frame register)");
1039 OS.EmitIntValue(uint32_t(FI.FrameProcOpts), 4);
Reid Kleckner5bf71d12018-12-14 22:40:28 +00001040 endSymbolRecord(FrameProcEnd);
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001041
1042 emitLocalVariableList(FI, FI.Locals);
Brock Wymab17464e2018-12-20 17:33:45 +00001043 emitGlobalVariableList(FI.Globals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00001044 emitLexicalBlockList(FI.ChildBlocks, FI);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001045
Reid Klecknerf3b9ba42016-01-29 18:16:43 +00001046 // Emit inlined call site information. Only emit functions inlined directly
1047 // into the parent function. We'll emit the other sites recursively as part
1048 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001049 for (const DILocation *InlinedAt : FI.ChildSites) {
1050 auto I = FI.InlineSites.find(InlinedAt);
1051 assert(I != FI.InlineSites.end() &&
1052 "child site not in function inline site map");
1053 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +00001054 }
1055
Reid Klecknere33c94f2017-09-05 20:14:58 +00001056 for (auto Annot : FI.Annotations) {
1057 MCSymbol *Label = Annot.first;
1058 MDTuple *Strs = cast<MDTuple>(Annot.second);
Reid Kleckner5bf71d12018-12-14 22:40:28 +00001059 MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION);
Reid Klecknere33c94f2017-09-05 20:14:58 +00001060 OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
1061 // FIXME: Make sure we don't overflow the max record size.
1062 OS.EmitCOFFSectionIndex(Label);
1063 OS.EmitIntValue(Strs->getNumOperands(), 2);
1064 for (Metadata *MD : Strs->operands()) {
1065 // MDStrings are null terminated, so we can do EmitBytes and get the
1066 // nice .asciz directive.
1067 StringRef Str = cast<MDString>(MD)->getString();
1068 assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
1069 OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
1070 }
Reid Kleckner5bf71d12018-12-14 22:40:28 +00001071 endSymbolRecord(AnnotEnd);
Reid Klecknere33c94f2017-09-05 20:14:58 +00001072 }
1073
David Majnemer3128b102016-06-15 18:00:01 +00001074 if (SP != nullptr)
1075 emitDebugInfoForUDTs(LocalUDTs);
1076
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001077 // We're done with this function.
Reid Kleckner5bf71d12018-12-14 22:40:28 +00001078 emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001079 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001080 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001081
Reid Kleckner2214ed82016-01-29 00:49:42 +00001082 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +00001083 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001084}
1085
Reid Kleckner876330d2016-02-12 21:48:30 +00001086CodeViewDebug::LocalVarDefRange
1087CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
1088 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +00001089 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +00001090 DR.DataOffset = Offset;
1091 assert(DR.DataOffset == Offset && "truncation");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00001092 DR.IsSubfield = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +00001093 DR.StructOffset = 0;
1094 DR.CVRegister = CVRegister;
1095 return DR;
1096}
1097
Matthias Braunef331ef2016-11-30 23:48:50 +00001098void CodeViewDebug::collectVariableInfoFromMFTable(
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001099 DenseSet<InlinedEntity> &Processed) {
Matthias Braunef331ef2016-11-30 23:48:50 +00001100 const MachineFunction &MF = *Asm->MF;
1101 const TargetSubtargetInfo &TSI = MF.getSubtarget();
Reid Kleckner876330d2016-02-12 21:48:30 +00001102 const TargetFrameLowering *TFI = TSI.getFrameLowering();
1103 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1104
Matthias Braunef331ef2016-11-30 23:48:50 +00001105 for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001106 if (!VI.Var)
1107 continue;
1108 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1109 "Expected inlined-at fields to agree");
1110
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001111 Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001112 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1113
1114 // If variable scope is not found then skip this variable.
1115 if (!Scope)
1116 continue;
1117
Reid Klecknerb5fced72017-05-09 19:59:29 +00001118 // If the variable has an attached offset expression, extract it.
1119 // FIXME: Try to handle DW_OP_deref as well.
1120 int64_t ExprOffset = 0;
1121 if (VI.Expr)
1122 if (!VI.Expr->extractIfOffset(ExprOffset))
1123 continue;
1124
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001125 // Get the frame register used and the offset.
1126 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +00001127 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
1128 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001129
1130 // Calculate the label ranges.
Reid Klecknerb5fced72017-05-09 19:59:29 +00001131 LocalVarDefRange DefRange =
1132 createDefRangeMem(CVReg, FrameOffset + ExprOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001133 for (const InsnRange &Range : Scope->getRanges()) {
1134 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1135 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +00001136 End = End ? End : Asm->getFunctionEnd();
1137 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001138 }
1139
Reid Kleckner876330d2016-02-12 21:48:30 +00001140 LocalVariable Var;
1141 Var.DIVar = VI.Var;
1142 Var.DefRanges.emplace_back(std::move(DefRange));
Reid Kleckner5a791ee2018-03-15 21:24:04 +00001143 recordLocalVariable(std::move(Var), Scope);
Reid Kleckner876330d2016-02-12 21:48:30 +00001144 }
1145}
1146
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001147static bool canUseReferenceType(const DbgVariableLocation &Loc) {
1148 return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
1149}
1150
1151static bool needsReferenceType(const DbgVariableLocation &Loc) {
1152 return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
1153}
1154
Bob Haarman223303c2017-08-29 20:59:25 +00001155void CodeViewDebug::calculateRanges(
1156 LocalVariable &Var, const DbgValueHistoryMap::InstrRanges &Ranges) {
1157 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1158
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001159 // Calculate the definition ranges.
Bob Haarman223303c2017-08-29 20:59:25 +00001160 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1161 const InsnRange &Range = *I;
1162 const MachineInstr *DVInst = Range.first;
1163 assert(DVInst->isDebugValue() && "Invalid History entry");
1164 // FIXME: Find a way to represent constant variables, since they are
1165 // relatively common.
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001166 Optional<DbgVariableLocation> Location =
1167 DbgVariableLocation::extractFromMachineInstruction(*DVInst);
1168 if (!Location)
Bob Haarmana88bce12017-08-29 21:01:55 +00001169 continue;
Bob Haarman223303c2017-08-29 20:59:25 +00001170
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001171 // CodeView can only express variables in register and variables in memory
1172 // at a constant offset from a register. However, for variables passed
1173 // indirectly by pointer, it is common for that pointer to be spilled to a
1174 // stack location. For the special case of one offseted load followed by a
1175 // zero offset load (a pointer spilled to the stack), we change the type of
1176 // the local variable from a value type to a reference type. This tricks the
1177 // debugger into doing the load for us.
1178 if (Var.UseReferenceType) {
1179 // We're using a reference type. Drop the last zero offset load.
1180 if (canUseReferenceType(*Location))
1181 Location->LoadChain.pop_back();
1182 else
1183 continue;
1184 } else if (needsReferenceType(*Location)) {
1185 // This location can't be expressed without switching to a reference type.
1186 // Start over using that.
1187 Var.UseReferenceType = true;
Bob Haarman223303c2017-08-29 20:59:25 +00001188 Var.DefRanges.clear();
1189 calculateRanges(Var, Ranges);
1190 return;
1191 }
1192
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001193 // We can only handle a register or an offseted load of a register.
1194 if (Location->Register == 0 || Location->LoadChain.size() > 1)
Bob Haarman223303c2017-08-29 20:59:25 +00001195 continue;
Bob Haarman223303c2017-08-29 20:59:25 +00001196 {
1197 LocalVarDefRange DR;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001198 DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001199 DR.InMemory = !Location->LoadChain.empty();
1200 DR.DataOffset =
1201 !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001202 if (Location->FragmentInfo) {
Bob Haarman223303c2017-08-29 20:59:25 +00001203 DR.IsSubfield = true;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001204 DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
Bob Haarman223303c2017-08-29 20:59:25 +00001205 } else {
1206 DR.IsSubfield = false;
1207 DR.StructOffset = 0;
1208 }
1209
1210 if (Var.DefRanges.empty() ||
1211 Var.DefRanges.back().isDifferentLocation(DR)) {
1212 Var.DefRanges.emplace_back(std::move(DR));
1213 }
1214 }
1215
1216 // Compute the label range.
1217 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1218 const MCSymbol *End = getLabelAfterInsn(Range.second);
1219 if (!End) {
1220 // This range is valid until the next overlapping bitpiece. In the
1221 // common case, ranges will not be bitpieces, so they will overlap.
1222 auto J = std::next(I);
1223 const DIExpression *DIExpr = DVInst->getDebugExpression();
1224 while (J != E &&
Bjorn Petterssona223f8152018-03-12 18:02:39 +00001225 !DIExpr->fragmentsOverlap(J->first->getDebugExpression()))
Bob Haarman223303c2017-08-29 20:59:25 +00001226 ++J;
1227 if (J != E)
1228 End = getLabelBeforeInsn(J->first);
1229 else
1230 End = Asm->getFunctionEnd();
1231 }
1232
1233 // If the last range end is our begin, just extend the last range.
1234 // Otherwise make a new range.
1235 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1236 Var.DefRanges.back().Ranges;
1237 if (!R.empty() && R.back().second == Begin)
1238 R.back().second = End;
1239 else
1240 R.emplace_back(Begin, End);
1241
1242 // FIXME: Do more range combining.
1243 }
1244}
1245
Reid Kleckner876330d2016-02-12 21:48:30 +00001246void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001247 DenseSet<InlinedEntity> Processed;
Reid Kleckner876330d2016-02-12 21:48:30 +00001248 // Grab the variable info that was squirreled away in the MMI side-table.
Matthias Braunef331ef2016-11-30 23:48:50 +00001249 collectVariableInfoFromMFTable(Processed);
Reid Kleckner876330d2016-02-12 21:48:30 +00001250
Reid Kleckner876330d2016-02-12 21:48:30 +00001251 for (const auto &I : DbgValues) {
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001252 InlinedEntity IV = I.first;
Reid Kleckner876330d2016-02-12 21:48:30 +00001253 if (Processed.count(IV))
1254 continue;
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001255 const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
Reid Kleckner876330d2016-02-12 21:48:30 +00001256 const DILocation *InlinedAt = IV.second;
1257
1258 // Instruction ranges, specifying where IV is accessible.
1259 const auto &Ranges = I.second;
1260
1261 LexicalScope *Scope = nullptr;
1262 if (InlinedAt)
1263 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1264 else
1265 Scope = LScopes.findLexicalScope(DIVar->getScope());
1266 // If variable scope is not found then skip this variable.
1267 if (!Scope)
1268 continue;
1269
1270 LocalVariable Var;
1271 Var.DIVar = DIVar;
1272
Bob Haarman223303c2017-08-29 20:59:25 +00001273 calculateRanges(Var, Ranges);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00001274 recordLocalVariable(std::move(Var), Scope);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001275 }
1276}
1277
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001278void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001279 const TargetSubtargetInfo &TSI = MF->getSubtarget();
1280 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1281 const MachineFrameInfo &MFI = MF->getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00001282 const Function &GV = MF->getFunction();
Reid Kleckner55baeef2018-03-15 21:12:21 +00001283 auto Insertion = FnDebugInfo.insert({&GV, llvm::make_unique<FunctionInfo>()});
Reid Klecknere9dc30d2018-03-15 21:18:42 +00001284 assert(Insertion.second && "function already has info");
Reid Kleckner55baeef2018-03-15 21:12:21 +00001285 CurFn = Insertion.first->second.get();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001286 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +00001287 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001288
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001289 // The S_FRAMEPROC record reports the stack size, and how many bytes of
1290 // callee-saved registers were used. For targets that don't use a PUSH
1291 // instruction (AArch64), this will be zero.
1292 CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
1293 CurFn->FrameSize = MFI.getStackSize();
Reid Kleckner2bcb2882018-11-03 00:41:52 +00001294 CurFn->OffsetAdjustment = MFI.getOffsetAdjustment();
Reid Klecknerd5e4ec72018-10-02 16:43:52 +00001295 CurFn->HasStackRealignment = TRI->needsStackRealignment(*MF);
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001296
1297 // For this function S_FRAMEPROC record, figure out which codeview register
1298 // will be the frame pointer.
1299 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
1300 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
1301 if (CurFn->FrameSize > 0) {
1302 if (!TSI.getFrameLowering()->hasFP(*MF)) {
1303 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1304 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
1305 } else {
1306 // If there is an FP, parameters are always relative to it.
1307 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
Reid Klecknerd5e4ec72018-10-02 16:43:52 +00001308 if (CurFn->HasStackRealignment) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001309 // If the stack needs realignment, locals are relative to SP or VFRAME.
1310 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1311 } else {
1312 // Otherwise, locals are relative to EBP, and we probably have VLAs or
1313 // other stack adjustments.
1314 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
1315 }
1316 }
1317 }
1318
1319 // Compute other frame procedure options.
1320 FrameProcedureOptions FPO = FrameProcedureOptions::None;
1321 if (MFI.hasVarSizedObjects())
1322 FPO |= FrameProcedureOptions::HasAlloca;
1323 if (MF->exposesReturnsTwice())
1324 FPO |= FrameProcedureOptions::HasSetJmp;
1325 // FIXME: Set HasLongJmp if we ever track that info.
1326 if (MF->hasInlineAsm())
1327 FPO |= FrameProcedureOptions::HasInlineAssembly;
1328 if (GV.hasPersonalityFn()) {
1329 if (isAsynchronousEHPersonality(
1330 classifyEHPersonality(GV.getPersonalityFn())))
1331 FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
1332 else
1333 FPO |= FrameProcedureOptions::HasExceptionHandling;
1334 }
1335 if (GV.hasFnAttribute(Attribute::InlineHint))
1336 FPO |= FrameProcedureOptions::MarkedInline;
1337 if (GV.hasFnAttribute(Attribute::Naked))
1338 FPO |= FrameProcedureOptions::Naked;
1339 if (MFI.hasStackProtectorIndex())
1340 FPO |= FrameProcedureOptions::SecurityChecks;
1341 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
1342 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
1343 if (Asm->TM.getOptLevel() != CodeGenOpt::None && !GV.optForSize() &&
1344 !GV.hasFnAttribute(Attribute::OptimizeNone))
1345 FPO |= FrameProcedureOptions::OptimizedForSpeed;
1346 // FIXME: Set GuardCfg when it is implemented.
1347 CurFn->FrameProcOpts = FPO;
1348
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001349 OS.EmitCVFuncIdDirective(CurFn->FuncId);
1350
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001351 // Find the end of the function prolog. First known non-DBG_VALUE and
1352 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001353 // FIXME: is there a simpler a way to do this? Can we just search
1354 // for the first instruction of the function, not the last of the prolog?
1355 DebugLoc PrologEndLoc;
1356 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001357 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001358 for (const auto &MI : MBB) {
Adrian Prantlfb31da12017-05-22 20:47:09 +00001359 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001360 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001361 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001362 break;
Adrian Prantlfb31da12017-05-22 20:47:09 +00001363 } else if (!MI.isMetaInstruction()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001364 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001365 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001366 }
1367 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001368
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001369 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001370 if (PrologEndLoc && !EmptyPrologue) {
1371 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001372 maybeRecordLocation(FnStartDL, MF);
1373 }
1374}
1375
Zachary Turnera7b04172017-08-28 18:49:04 +00001376static bool shouldEmitUdt(const DIType *T) {
Zachary Turner37c74742017-09-05 22:06:39 +00001377 if (!T)
1378 return false;
1379
1380 // MSVC does not emit UDTs for typedefs that are scoped to classes.
1381 if (T->getTag() == dwarf::DW_TAG_typedef) {
1382 if (DIScope *Scope = T->getScope().resolve()) {
1383 switch (Scope->getTag()) {
1384 case dwarf::DW_TAG_structure_type:
1385 case dwarf::DW_TAG_class_type:
1386 case dwarf::DW_TAG_union_type:
1387 return false;
1388 }
1389 }
1390 }
1391
Zachary Turnera7b04172017-08-28 18:49:04 +00001392 while (true) {
1393 if (!T || T->isForwardDecl())
1394 return false;
1395
1396 const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
1397 if (!DT)
1398 return true;
1399 T = DT->getBaseType().resolve();
1400 }
1401 return true;
1402}
1403
1404void CodeViewDebug::addToUDTs(const DIType *Ty) {
Reid Klecknerad56ea32016-07-01 22:24:51 +00001405 // Don't record empty UDTs.
1406 if (Ty->getName().empty())
1407 return;
Zachary Turnera7b04172017-08-28 18:49:04 +00001408 if (!shouldEmitUdt(Ty))
1409 return;
Reid Klecknerad56ea32016-07-01 22:24:51 +00001410
Hans Wennborg4b63a982016-06-23 22:57:25 +00001411 SmallVector<StringRef, 5> QualifiedNameComponents;
1412 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1413 Ty->getScope().resolve(), QualifiedNameComponents);
1414
1415 std::string FullyQualifiedName =
David Majnemer6bdc24e2016-07-01 23:12:45 +00001416 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
Hans Wennborg4b63a982016-06-23 22:57:25 +00001417
Zachary Turnera7b04172017-08-28 18:49:04 +00001418 if (ClosestSubprogram == nullptr) {
1419 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1420 } else if (ClosestSubprogram == CurrentSubprogram) {
1421 LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1422 }
Hans Wennborg4b63a982016-06-23 22:57:25 +00001423
1424 // TODO: What if the ClosestSubprogram is neither null or the current
1425 // subprogram? Currently, the UDT just gets dropped on the floor.
1426 //
1427 // The current behavior is not desirable. To get maximal fidelity, we would
1428 // need to perform all type translation before beginning emission of .debug$S
1429 // and then make LocalUDTs a member of FunctionInfo
1430}
1431
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001432TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001433 // Generic dispatch for lowering an unknown type.
1434 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001435 case dwarf::DW_TAG_array_type:
1436 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +00001437 case dwarf::DW_TAG_typedef:
1438 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001439 case dwarf::DW_TAG_base_type:
1440 return lowerTypeBasic(cast<DIBasicType>(Ty));
1441 case dwarf::DW_TAG_pointer_type:
Reid Kleckner9dac4732016-08-31 15:59:30 +00001442 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1443 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1444 LLVM_FALLTHROUGH;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001445 case dwarf::DW_TAG_reference_type:
1446 case dwarf::DW_TAG_rvalue_reference_type:
1447 return lowerTypePointer(cast<DIDerivedType>(Ty));
1448 case dwarf::DW_TAG_ptr_to_member_type:
1449 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
Reid Kleckner3acdc672018-02-27 22:08:15 +00001450 case dwarf::DW_TAG_restrict_type:
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001451 case dwarf::DW_TAG_const_type:
1452 case dwarf::DW_TAG_volatile_type:
Victor Leschuke1156c22016-10-31 19:09:38 +00001453 // TODO: add support for DW_TAG_atomic_type here
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001454 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +00001455 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001456 if (ClassTy) {
1457 // The member function type of a member function pointer has no
1458 // ThisAdjustment.
1459 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001460 /*ThisAdjustment=*/0,
1461 /*IsStaticMethod=*/false);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001462 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001463 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +00001464 case dwarf::DW_TAG_enumeration_type:
1465 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +00001466 case dwarf::DW_TAG_class_type:
1467 case dwarf::DW_TAG_structure_type:
1468 return lowerTypeClass(cast<DICompositeType>(Ty));
1469 case dwarf::DW_TAG_union_type:
1470 return lowerTypeUnion(cast<DICompositeType>(Ty));
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001471 case dwarf::DW_TAG_unspecified_type:
Zachary Turner56a5a0c2018-11-01 04:02:41 +00001472 if (Ty->getName() == "decltype(nullptr)")
1473 return TypeIndex::NullptrT();
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001474 return TypeIndex::None();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001475 default:
1476 // Use the null type index.
1477 return TypeIndex();
1478 }
1479}
1480
David Majnemerd065e232016-06-02 06:21:37 +00001481TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +00001482 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1483 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +00001484 StringRef TypeName = Ty->getName();
1485
Zachary Turnera7b04172017-08-28 18:49:04 +00001486 addToUDTs(Ty);
David Majnemer3128b102016-06-15 18:00:01 +00001487
David Majnemerd065e232016-06-02 06:21:37 +00001488 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +00001489 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +00001490 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +00001491 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +00001492 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +00001493 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001494
David Majnemerd065e232016-06-02 06:21:37 +00001495 return UnderlyingTypeIndex;
1496}
1497
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001498TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1499 DITypeRef ElementTypeRef = Ty->getBaseType();
1500 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1501 // IndexType is size_t, which depends on the bitness of the target.
Matt Arsenault41e5ac42018-03-14 00:36:23 +00001502 TypeIndex IndexType = getPointerSizeInBytes() == 8
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001503 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1504 : TypeIndex(SimpleTypeKind::UInt32Long);
Amjad Aboudacee5682016-07-12 12:06:34 +00001505
1506 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1507
Amjad Aboudacee5682016-07-12 12:06:34 +00001508 // Add subranges to array type.
1509 DINodeArray Elements = Ty->getElements();
1510 for (int i = Elements.size() - 1; i >= 0; --i) {
1511 const DINode *Element = Elements[i];
1512 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1513
1514 const DISubrange *Subrange = cast<DISubrange>(Element);
1515 assert(Subrange->getLowerBound() == 0 &&
1516 "codeview doesn't support subranges with lower bounds");
Sander de Smalenfdf40912018-01-24 09:56:07 +00001517 int64_t Count = -1;
1518 if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>())
1519 Count = CI->getSExtValue();
Amjad Aboudacee5682016-07-12 12:06:34 +00001520
Reid Klecknercd7bba02017-09-13 23:30:01 +00001521 // Forward declarations of arrays without a size and VLAs use a count of -1.
1522 // Emit a count of zero in these cases to match what MSVC does for arrays
1523 // without a size. MSVC doesn't support VLAs, so it's not clear what we
1524 // should do for them even if we could distinguish them.
Reid Kleckner6b78e162017-03-24 23:28:42 +00001525 if (Count == -1)
Reid Kleckner89af1122017-09-13 21:54:20 +00001526 Count = 0;
Amjad Aboudacee5682016-07-12 12:06:34 +00001527
Amjad Aboudacee5682016-07-12 12:06:34 +00001528 // Update the element size and element type index for subsequent subranges.
1529 ElementSize *= Count;
Reid Kleckner10762882016-09-09 17:29:36 +00001530
1531 // If this is the outermost array, use the size from the array. It will be
Reid Kleckner6b78e162017-03-24 23:28:42 +00001532 // more accurate if we had a VLA or an incomplete element type size.
Reid Kleckner10762882016-09-09 17:29:36 +00001533 uint64_t ArraySize =
1534 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1535
1536 StringRef Name = (i == 0) ? Ty->getName() : "";
Zachary Turner4efa0a42016-11-08 22:24:53 +00001537 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
Zachary Turner6900de12017-11-28 18:33:17 +00001538 ElementTypeIndex = TypeTable.writeLeafType(AR);
Amjad Aboudacee5682016-07-12 12:06:34 +00001539 }
1540
Amjad Aboudacee5682016-07-12 12:06:34 +00001541 return ElementTypeIndex;
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001542}
1543
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001544TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1545 TypeIndex Index;
1546 dwarf::TypeKind Kind;
1547 uint32_t ByteSize;
1548
1549 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +00001550 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001551
1552 SimpleTypeKind STK = SimpleTypeKind::None;
1553 switch (Kind) {
1554 case dwarf::DW_ATE_address:
1555 // FIXME: Translate
1556 break;
1557 case dwarf::DW_ATE_boolean:
1558 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001559 case 1: STK = SimpleTypeKind::Boolean8; break;
1560 case 2: STK = SimpleTypeKind::Boolean16; break;
1561 case 4: STK = SimpleTypeKind::Boolean32; break;
1562 case 8: STK = SimpleTypeKind::Boolean64; break;
1563 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001564 }
1565 break;
1566 case dwarf::DW_ATE_complex_float:
1567 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001568 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001569 case 4: STK = SimpleTypeKind::Complex32; break;
1570 case 8: STK = SimpleTypeKind::Complex64; break;
1571 case 10: STK = SimpleTypeKind::Complex80; break;
1572 case 16: STK = SimpleTypeKind::Complex128; break;
1573 }
1574 break;
1575 case dwarf::DW_ATE_float:
1576 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001577 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001578 case 4: STK = SimpleTypeKind::Float32; break;
1579 case 6: STK = SimpleTypeKind::Float48; break;
1580 case 8: STK = SimpleTypeKind::Float64; break;
1581 case 10: STK = SimpleTypeKind::Float80; break;
1582 case 16: STK = SimpleTypeKind::Float128; break;
1583 }
1584 break;
1585 case dwarf::DW_ATE_signed:
1586 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001587 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1588 case 2: STK = SimpleTypeKind::Int16Short; break;
1589 case 4: STK = SimpleTypeKind::Int32; break;
1590 case 8: STK = SimpleTypeKind::Int64Quad; break;
1591 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001592 }
1593 break;
1594 case dwarf::DW_ATE_unsigned:
1595 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001596 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1597 case 2: STK = SimpleTypeKind::UInt16Short; break;
1598 case 4: STK = SimpleTypeKind::UInt32; break;
1599 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1600 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001601 }
1602 break;
1603 case dwarf::DW_ATE_UTF:
1604 switch (ByteSize) {
1605 case 2: STK = SimpleTypeKind::Character16; break;
1606 case 4: STK = SimpleTypeKind::Character32; break;
1607 }
1608 break;
1609 case dwarf::DW_ATE_signed_char:
1610 if (ByteSize == 1)
1611 STK = SimpleTypeKind::SignedCharacter;
1612 break;
1613 case dwarf::DW_ATE_unsigned_char:
1614 if (ByteSize == 1)
1615 STK = SimpleTypeKind::UnsignedCharacter;
1616 break;
1617 default:
1618 break;
1619 }
1620
1621 // Apply some fixups based on the source-level type name.
1622 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1623 STK = SimpleTypeKind::Int32Long;
1624 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1625 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001626 if (STK == SimpleTypeKind::UInt16Short &&
1627 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001628 STK = SimpleTypeKind::WideCharacter;
1629 if ((STK == SimpleTypeKind::SignedCharacter ||
1630 STK == SimpleTypeKind::UnsignedCharacter) &&
1631 Ty->getName() == "char")
1632 STK = SimpleTypeKind::NarrowCharacter;
1633
1634 return TypeIndex(STK);
1635}
1636
Reid Kleckner3acdc672018-02-27 22:08:15 +00001637TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
1638 PointerOptions PO) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001639 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1640
Reid Kleckner3acdc672018-02-27 22:08:15 +00001641 // Pointers to simple types without any options can use SimpleTypeMode, rather
1642 // than having a dedicated pointer type record.
1643 if (PointeeTI.isSimple() && PO == PointerOptions::None &&
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001644 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1645 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1646 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1647 ? SimpleTypeMode::NearPointer64
1648 : SimpleTypeMode::NearPointer32;
1649 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1650 }
1651
1652 PointerKind PK =
1653 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1654 PointerMode PM = PointerMode::Pointer;
1655 switch (Ty->getTag()) {
1656 default: llvm_unreachable("not a pointer tag type");
1657 case dwarf::DW_TAG_pointer_type:
1658 PM = PointerMode::Pointer;
1659 break;
1660 case dwarf::DW_TAG_reference_type:
1661 PM = PointerMode::LValueReference;
1662 break;
1663 case dwarf::DW_TAG_rvalue_reference_type:
1664 PM = PointerMode::RValueReference;
1665 break;
1666 }
Reid Kleckner3acdc672018-02-27 22:08:15 +00001667
Zachary Turner38265662018-11-20 22:13:23 +00001668 if (Ty->isObjectPointer())
1669 PO |= PointerOptions::Const;
1670
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001671 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00001672 return TypeTable.writeLeafType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001673}
1674
Reid Kleckner6fa15462016-06-17 22:14:39 +00001675static PointerToMemberRepresentation
1676translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1677 // SizeInBytes being zero generally implies that the member pointer type was
1678 // incomplete, which can happen if it is part of a function prototype. In this
1679 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001680 if (IsPMF) {
1681 switch (Flags & DINode::FlagPtrToMemberRep) {
1682 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001683 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1684 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001685 case DINode::FlagSingleInheritance:
1686 return PointerToMemberRepresentation::SingleInheritanceFunction;
1687 case DINode::FlagMultipleInheritance:
1688 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1689 case DINode::FlagVirtualInheritance:
1690 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1691 }
1692 } else {
1693 switch (Flags & DINode::FlagPtrToMemberRep) {
1694 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001695 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1696 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001697 case DINode::FlagSingleInheritance:
1698 return PointerToMemberRepresentation::SingleInheritanceData;
1699 case DINode::FlagMultipleInheritance:
1700 return PointerToMemberRepresentation::MultipleInheritanceData;
1701 case DINode::FlagVirtualInheritance:
1702 return PointerToMemberRepresentation::VirtualInheritanceData;
1703 }
1704 }
1705 llvm_unreachable("invalid ptr to member representation");
1706}
1707
Reid Kleckner3acdc672018-02-27 22:08:15 +00001708TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
1709 PointerOptions PO) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001710 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1711 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001712 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Matt Arsenault41e5ac42018-03-14 00:36:23 +00001713 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1714 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001715 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1716 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1717 : PointerMode::PointerToDataMember;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001718
Reid Kleckner6fa15462016-06-17 22:14:39 +00001719 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1720 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1721 MemberPointerInfo MPI(
1722 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001723 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Zachary Turner6900de12017-11-28 18:33:17 +00001724 return TypeTable.writeLeafType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001725}
1726
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001727/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1728/// have a translation, use the NearC convention.
1729static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1730 switch (DwarfCC) {
1731 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1732 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1733 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1734 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1735 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1736 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1737 }
1738 return CallingConvention::NearC;
1739}
1740
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001741TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1742 ModifierOptions Mods = ModifierOptions::None;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001743 PointerOptions PO = PointerOptions::None;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001744 bool IsModifier = true;
1745 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001746 while (IsModifier && BaseTy) {
Victor Leschuke1156c22016-10-31 19:09:38 +00001747 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001748 switch (BaseTy->getTag()) {
1749 case dwarf::DW_TAG_const_type:
1750 Mods |= ModifierOptions::Const;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001751 PO |= PointerOptions::Const;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001752 break;
1753 case dwarf::DW_TAG_volatile_type:
1754 Mods |= ModifierOptions::Volatile;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001755 PO |= PointerOptions::Volatile;
1756 break;
1757 case dwarf::DW_TAG_restrict_type:
1758 // Only pointer types be marked with __restrict. There is no known flag
1759 // for __restrict in LF_MODIFIER records.
1760 PO |= PointerOptions::Restrict;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001761 break;
1762 default:
1763 IsModifier = false;
1764 break;
1765 }
1766 if (IsModifier)
1767 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1768 }
Reid Kleckner3acdc672018-02-27 22:08:15 +00001769
1770 // Check if the inner type will use an LF_POINTER record. If so, the
1771 // qualifiers will go in the LF_POINTER record. This comes up for types like
1772 // 'int *const' and 'int *__restrict', not the more common cases like 'const
1773 // char *'.
1774 if (BaseTy) {
1775 switch (BaseTy->getTag()) {
1776 case dwarf::DW_TAG_pointer_type:
1777 case dwarf::DW_TAG_reference_type:
1778 case dwarf::DW_TAG_rvalue_reference_type:
1779 return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
1780 case dwarf::DW_TAG_ptr_to_member_type:
1781 return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
1782 default:
1783 break;
1784 }
1785 }
1786
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001787 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Reid Kleckner3acdc672018-02-27 22:08:15 +00001788
1789 // Return the base type index if there aren't any modifiers. For example, the
1790 // metadata could contain restrict wrappers around non-pointer types.
1791 if (Mods == ModifierOptions::None)
1792 return ModifiedTI;
1793
Zachary Turner4efa0a42016-11-08 22:24:53 +00001794 ModifierRecord MR(ModifiedTI, Mods);
Zachary Turner6900de12017-11-28 18:33:17 +00001795 return TypeTable.writeLeafType(MR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001796}
1797
David Majnemer75c3ebf2016-06-02 17:13:53 +00001798TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1799 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1800 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1801 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1802
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001803 // MSVC uses type none for variadic argument.
1804 if (ReturnAndArgTypeIndices.size() > 1 &&
1805 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1806 ReturnAndArgTypeIndices.back() = TypeIndex::None();
1807 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001808 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1809 ArrayRef<TypeIndex> ArgTypeIndices = None;
1810 if (!ReturnAndArgTypeIndices.empty()) {
1811 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1812 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1813 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1814 }
1815
1816 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner6900de12017-11-28 18:33:17 +00001817 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001818
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001819 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1820
Aaron Smith802b0332018-10-02 20:21:05 +00001821 FunctionOptions FO = getFunctionOptions(Ty);
1822 ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
1823 ArgListIndex);
Zachary Turner6900de12017-11-28 18:33:17 +00001824 return TypeTable.writeLeafType(Procedure);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001825}
1826
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001827TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001828 const DIType *ClassTy,
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001829 int ThisAdjustment,
Aaron Smith802b0332018-10-02 20:21:05 +00001830 bool IsStaticMethod,
1831 FunctionOptions FO) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001832 // Lower the containing class type.
1833 TypeIndex ClassType = getTypeIndex(ClassTy);
1834
Zachary Turnerc68f8952018-11-20 22:13:43 +00001835 DITypeRefArray ReturnAndArgs = Ty->getTypeArray();
1836
1837 unsigned Index = 0;
1838 SmallVector<TypeIndex, 8> ArgTypeIndices;
1839 TypeIndex ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]);
1840
Reid Klecknerc168c6f2018-12-26 21:52:17 +00001841 // If the first argument is a pointer type and this isn't a static method,
1842 // treat it as the special 'this' parameter, which is encoded separately from
1843 // the arguments.
Zachary Turnerc68f8952018-11-20 22:13:43 +00001844 TypeIndex ThisTypeIndex;
Reid Klecknerc168c6f2018-12-26 21:52:17 +00001845 if (!IsStaticMethod && ReturnAndArgs.size() > Index) {
1846 if (const DIDerivedType *PtrTy =
1847 dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index].resolve())) {
1848 if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) {
1849 ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty);
1850 Index++;
1851 }
1852 }
1853 }
Zachary Turnerc68f8952018-11-20 22:13:43 +00001854
1855 while (Index < ReturnAndArgs.size())
1856 ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++]));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001857
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001858 // MSVC uses type none for variadic argument.
Zachary Turnerc68f8952018-11-20 22:13:43 +00001859 if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void())
1860 ArgTypeIndices.back() = TypeIndex::None();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001861
1862 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner6900de12017-11-28 18:33:17 +00001863 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001864
1865 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1866
Aaron Smith802b0332018-10-02 20:21:05 +00001867 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
1868 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
Zachary Turner6900de12017-11-28 18:33:17 +00001869 return TypeTable.writeLeafType(MFR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001870}
1871
Reid Kleckner9dac4732016-08-31 15:59:30 +00001872TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001873 unsigned VSlotCount =
1874 Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
Reid Kleckner9dac4732016-08-31 15:59:30 +00001875 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001876
1877 VFTableShapeRecord VFTSR(Slots);
Zachary Turner6900de12017-11-28 18:33:17 +00001878 return TypeTable.writeLeafType(VFTSR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001879}
1880
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001881static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1882 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001883 case DINode::FlagPrivate: return MemberAccess::Private;
1884 case DINode::FlagPublic: return MemberAccess::Public;
1885 case DINode::FlagProtected: return MemberAccess::Protected;
1886 case 0:
1887 // If there was no explicit access control, provide the default for the tag.
1888 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1889 : MemberAccess::Public;
1890 }
1891 llvm_unreachable("access flags are exclusive");
1892}
1893
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001894static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1895 if (SP->isArtificial())
1896 return MethodOptions::CompilerGenerated;
1897
1898 // FIXME: Handle other MethodOptions.
1899
1900 return MethodOptions::None;
1901}
1902
1903static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1904 bool Introduced) {
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001905 if (SP->getFlags() & DINode::FlagStaticMember)
1906 return MethodKind::Static;
1907
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001908 switch (SP->getVirtuality()) {
1909 case dwarf::DW_VIRTUALITY_none:
1910 break;
1911 case dwarf::DW_VIRTUALITY_virtual:
1912 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1913 case dwarf::DW_VIRTUALITY_pure_virtual:
1914 return Introduced ? MethodKind::PureIntroducingVirtual
1915 : MethodKind::PureVirtual;
1916 default:
1917 llvm_unreachable("unhandled virtuality case");
1918 }
1919
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001920 return MethodKind::Vanilla;
1921}
1922
Reid Klecknera8d57402016-06-03 15:58:20 +00001923static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1924 switch (Ty->getTag()) {
1925 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1926 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1927 }
1928 llvm_unreachable("unexpected tag");
1929}
1930
Reid Klecknere092dad2016-07-02 00:11:07 +00001931/// Return ClassOptions that should be present on both the forward declaration
1932/// and the defintion of a tag type.
1933static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1934 ClassOptions CO = ClassOptions::None;
1935
1936 // MSVC always sets this flag, even for local types. Clang doesn't always
Reid Klecknera8d57402016-06-03 15:58:20 +00001937 // appear to give every type a linkage name, which may be problematic for us.
1938 // FIXME: Investigate the consequences of not following them here.
Reid Klecknere092dad2016-07-02 00:11:07 +00001939 if (!Ty->getIdentifier().empty())
1940 CO |= ClassOptions::HasUniqueName;
1941
1942 // Put the Nested flag on a type if it appears immediately inside a tag type.
1943 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1944 // here. That flag is only set on definitions, and not forward declarations.
1945 const DIScope *ImmediateScope = Ty->getScope().resolve();
1946 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1947 CO |= ClassOptions::Nested;
1948
Aaron Smithda0602c2018-10-02 20:28:15 +00001949 // Put the Scoped flag on function-local types. MSVC puts this flag for enum
Zachary Turnerc68f8952018-11-20 22:13:43 +00001950 // type only when it has an immediate function scope. Clang never puts enums
1951 // inside DILexicalBlock scopes. Enum types, as generated by clang, are
Aaron Smithda0602c2018-10-02 20:28:15 +00001952 // always in function, class, or file scopes.
1953 if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
1954 if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
Reid Klecknere092dad2016-07-02 00:11:07 +00001955 CO |= ClassOptions::Scoped;
Aaron Smithda0602c2018-10-02 20:28:15 +00001956 } else {
1957 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1958 Scope = Scope->getScope().resolve()) {
1959 if (isa<DISubprogram>(Scope)) {
1960 CO |= ClassOptions::Scoped;
1961 break;
1962 }
Reid Klecknere092dad2016-07-02 00:11:07 +00001963 }
1964 }
1965
1966 return CO;
Reid Klecknera8d57402016-06-03 15:58:20 +00001967}
1968
Aaron Smith122d9e72018-03-06 18:20:22 +00001969void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
1970 switch (Ty->getTag()) {
1971 case dwarf::DW_TAG_class_type:
1972 case dwarf::DW_TAG_structure_type:
1973 case dwarf::DW_TAG_union_type:
1974 case dwarf::DW_TAG_enumeration_type:
1975 break;
1976 default:
1977 return;
1978 }
1979
1980 if (const auto *File = Ty->getFile()) {
1981 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
1982 TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
1983
1984 UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
1985 TypeTable.writeLeafType(USLR);
1986 }
1987}
1988
David Majnemer979cb882016-06-16 21:32:16 +00001989TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
Reid Klecknere092dad2016-07-02 00:11:07 +00001990 ClassOptions CO = getCommonClassOptions(Ty);
David Majnemer979cb882016-06-16 21:32:16 +00001991 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001992 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001993
David Majnemerda9548f2016-06-17 16:13:21 +00001994 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001995 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001996 } else {
Zachary Turner6900de12017-11-28 18:33:17 +00001997 ContinuationRecordBuilder ContinuationBuilder;
1998 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
David Majnemerda9548f2016-06-17 16:13:21 +00001999 for (const DINode *Element : Ty->getElements()) {
2000 // We assume that the frontend provides all members in source declaration
2001 // order, which is what MSVC does.
2002 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00002003 EnumeratorRecord ER(MemberAccess::Public,
2004 APSInt::getUnsigned(Enumerator->getValue()),
2005 Enumerator->getName());
Zachary Turner6900de12017-11-28 18:33:17 +00002006 ContinuationBuilder.writeMemberType(ER);
David Majnemerda9548f2016-06-17 16:13:21 +00002007 EnumeratorCount++;
2008 }
2009 }
Zachary Turner6900de12017-11-28 18:33:17 +00002010 FTI = TypeTable.insertRecord(ContinuationBuilder);
David Majnemerda9548f2016-06-17 16:13:21 +00002011 }
David Majnemer979cb882016-06-16 21:32:16 +00002012
David Majnemer6bdc24e2016-07-01 23:12:45 +00002013 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00002014
Zachary Turner4efa0a42016-11-08 22:24:53 +00002015 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
2016 getTypeIndex(Ty->getBaseType()));
Aaron Smith122d9e72018-03-06 18:20:22 +00002017 TypeIndex EnumTI = TypeTable.writeLeafType(ER);
2018
2019 addUDTSrcLine(Ty, EnumTI);
2020
2021 return EnumTI;
David Majnemer979cb882016-06-16 21:32:16 +00002022}
2023
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002024//===----------------------------------------------------------------------===//
2025// ClassInfo
2026//===----------------------------------------------------------------------===//
2027
2028struct llvm::ClassInfo {
2029 struct MemberInfo {
2030 const DIDerivedType *MemberTypeNode;
David Majnemer08bd7442016-07-01 23:12:48 +00002031 uint64_t BaseOffset;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002032 };
2033 // [MemberInfo]
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002034 using MemberList = std::vector<MemberInfo>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002035
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002036 using MethodsList = TinyPtrVector<const DISubprogram *>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002037 // MethodName -> MethodsList
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002038 using MethodsMap = MapVector<MDString *, MethodsList>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002039
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002040 /// Base classes.
2041 std::vector<const DIDerivedType *> Inheritance;
2042
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002043 /// Direct members.
2044 MemberList Members;
2045 // Direct overloaded methods gathered by name.
2046 MethodsMap Methods;
Adrian McCarthy820ca542016-07-06 19:49:51 +00002047
Reid Kleckner9dac4732016-08-31 15:59:30 +00002048 TypeIndex VShapeTI;
2049
Reid Klecknere2e82062017-08-08 20:30:14 +00002050 std::vector<const DIType *> NestedTypes;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002051};
2052
2053void CodeViewDebug::clear() {
2054 assert(CurFn == nullptr);
2055 FileIdMap.clear();
2056 FnDebugInfo.clear();
2057 FileToFilepathMap.clear();
2058 LocalUDTs.clear();
2059 GlobalUDTs.clear();
2060 TypeIndices.clear();
2061 CompleteTypeIndices.clear();
Brock Wymab17464e2018-12-20 17:33:45 +00002062 ScopeGlobals.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002063}
2064
2065void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
2066 const DIDerivedType *DDTy) {
2067 if (!DDTy->getName().empty()) {
2068 Info.Members.push_back({DDTy, 0});
2069 return;
2070 }
Shoaib Meenai03303a32018-02-27 21:48:41 +00002071
2072 // An unnamed member may represent a nested struct or union. Attempt to
2073 // interpret the unnamed member as a DICompositeType possibly wrapped in
2074 // qualifier types. Add all the indirect fields to the current record if that
2075 // succeeds, and drop the member if that fails.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002076 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
David Majnemer08bd7442016-07-01 23:12:48 +00002077 uint64_t Offset = DDTy->getOffsetInBits();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002078 const DIType *Ty = DDTy->getBaseType().resolve();
Shoaib Meenai03303a32018-02-27 21:48:41 +00002079 bool FullyResolved = false;
2080 while (!FullyResolved) {
2081 switch (Ty->getTag()) {
2082 case dwarf::DW_TAG_const_type:
2083 case dwarf::DW_TAG_volatile_type:
2084 // FIXME: we should apply the qualifier types to the indirect fields
2085 // rather than dropping them.
2086 Ty = cast<DIDerivedType>(Ty)->getBaseType().resolve();
2087 break;
2088 default:
2089 FullyResolved = true;
2090 break;
2091 }
2092 }
2093
2094 const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
2095 if (!DCTy)
2096 return;
2097
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002098 ClassInfo NestedInfo = collectClassInfo(DCTy);
2099 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002100 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002101 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002102}
2103
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002104ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
2105 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002106 // Add elements to structure type.
2107 DINodeArray Elements = Ty->getElements();
2108 for (auto *Element : Elements) {
2109 // We assume that the frontend provides all members in source declaration
2110 // order, which is what MSVC does.
2111 if (!Element)
2112 continue;
2113 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00002114 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002115 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002116 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002117 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002118 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
2119 Info.Inheritance.push_back(DDTy);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002120 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
2121 DDTy->getName() == "__vtbl_ptr_type") {
2122 Info.VShapeTI = getTypeIndex(DDTy);
Reid Klecknere2e82062017-08-08 20:30:14 +00002123 } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
2124 Info.NestedTypes.push_back(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002125 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
2126 // Ignore friend members. It appears that MSVC emitted info about
2127 // friends in the past, but modern versions do not.
2128 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00002129 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
Reid Klecknere2e82062017-08-08 20:30:14 +00002130 Info.NestedTypes.push_back(Composite);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002131 }
2132 // Skip other unrecognized kinds of elements.
2133 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002134 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002135}
2136
Brock Wymab60532f2018-06-11 01:39:34 +00002137static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) {
2138 // This routine is used by lowerTypeClass and lowerTypeUnion to determine
2139 // if a complete type should be emitted instead of a forward reference.
2140 return Ty->getName().empty() && Ty->getIdentifier().empty() &&
2141 !Ty->isForwardDecl();
2142}
2143
Reid Klecknera8d57402016-06-03 15:58:20 +00002144TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
Brock Wymab60532f2018-06-11 01:39:34 +00002145 // Emit the complete type for unnamed structs. C++ classes with methods
2146 // which have a circular reference back to the class type are expected to
2147 // be named by the front-end and should not be "unnamed". C unnamed
2148 // structs should not have circular references.
2149 if (shouldAlwaysEmitCompleteClassType(Ty)) {
2150 // If this unnamed complete type is already in the process of being defined
2151 // then the description of the type is malformed and cannot be emitted
2152 // into CodeView correctly so report a fatal error.
2153 auto I = CompleteTypeIndices.find(Ty);
2154 if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
2155 report_fatal_error("cannot debug circular reference to unnamed type");
2156 return getCompleteTypeIndex(Ty);
2157 }
2158
Reid Klecknera8d57402016-06-03 15:58:20 +00002159 // First, construct the forward decl. Don't look into Ty to compute the
2160 // forward decl options, since it might not be available in all TUs.
2161 TypeRecordKind Kind = getRecordKind(Ty);
2162 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00002163 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00002164 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00002165 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
2166 FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002167 TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
Reid Kleckner643dd832016-06-22 17:15:28 +00002168 if (!Ty->isForwardDecl())
2169 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00002170 return FwdDeclTI;
2171}
2172
2173TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
2174 // Construct the field list and complete type record.
2175 TypeRecordKind Kind = getRecordKind(Ty);
Reid Klecknere092dad2016-07-02 00:11:07 +00002176 ClassOptions CO = getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002177 TypeIndex FieldTI;
2178 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002179 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00002180 bool ContainsNestedClass;
2181 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
2182 lowerRecordFieldList(Ty);
2183
2184 if (ContainsNestedClass)
2185 CO |= ClassOptions::ContainsNestedClass;
Reid Klecknera8d57402016-06-03 15:58:20 +00002186
David Majnemer6bdc24e2016-07-01 23:12:45 +00002187 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00002188
Reid Klecknera8d57402016-06-03 15:58:20 +00002189 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00002190
Zachary Turner4efa0a42016-11-08 22:24:53 +00002191 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
2192 SizeInBytes, FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002193 TypeIndex ClassTI = TypeTable.writeLeafType(CR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002194
Aaron Smith122d9e72018-03-06 18:20:22 +00002195 addUDTSrcLine(Ty, ClassTI);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002196
Zachary Turnera7b04172017-08-28 18:49:04 +00002197 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00002198
Hans Wennborg9a519a02016-06-22 21:22:13 +00002199 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002200}
2201
2202TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
Brock Wymab60532f2018-06-11 01:39:34 +00002203 // Emit the complete type for unnamed unions.
2204 if (shouldAlwaysEmitCompleteClassType(Ty))
2205 return getCompleteTypeIndex(Ty);
2206
Reid Klecknera8d57402016-06-03 15:58:20 +00002207 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00002208 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00002209 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00002210 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002211 TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
Reid Kleckner643dd832016-06-22 17:15:28 +00002212 if (!Ty->isForwardDecl())
2213 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00002214 return FwdDeclTI;
2215}
2216
2217TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
David Majnemere1e73722016-07-06 21:07:42 +00002218 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002219 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002220 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00002221 bool ContainsNestedClass;
2222 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
2223 lowerRecordFieldList(Ty);
2224
2225 if (ContainsNestedClass)
2226 CO |= ClassOptions::ContainsNestedClass;
2227
Reid Klecknera8d57402016-06-03 15:58:20 +00002228 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
David Majnemer6bdc24e2016-07-01 23:12:45 +00002229 std::string FullName = getFullyQualifiedName(Ty);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002230
Zachary Turner4efa0a42016-11-08 22:24:53 +00002231 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
2232 Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002233 TypeIndex UnionTI = TypeTable.writeLeafType(UR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002234
Aaron Smith122d9e72018-03-06 18:20:22 +00002235 addUDTSrcLine(Ty, UnionTI);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002236
Zachary Turnera7b04172017-08-28 18:49:04 +00002237 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00002238
Hans Wennborg9a519a02016-06-22 21:22:13 +00002239 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002240}
2241
Adrian McCarthy820ca542016-07-06 19:49:51 +00002242std::tuple<TypeIndex, TypeIndex, unsigned, bool>
Reid Klecknera8d57402016-06-03 15:58:20 +00002243CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
2244 // Manually count members. MSVC appears to count everything that generates a
2245 // field list record. Each individual overload in a method overload group
2246 // contributes to this count, even though the overload group is a single field
2247 // list record.
2248 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002249 ClassInfo Info = collectClassInfo(Ty);
Zachary Turner6900de12017-11-28 18:33:17 +00002250 ContinuationRecordBuilder ContinuationBuilder;
2251 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002252
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002253 // Create base classes.
2254 for (const DIDerivedType *I : Info.Inheritance) {
2255 if (I->getFlags() & DINode::FlagVirtual) {
2256 // Virtual base.
Brock Wyma3db2b102018-05-14 21:21:22 +00002257 unsigned VBPtrOffset = I->getVBPtrOffset();
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002258 // FIXME: Despite the accessor name, the offset is really in bytes.
2259 unsigned VBTableIndex = I->getOffsetInBits() / 4;
Bob Haarman26a87bd2016-10-25 22:11:52 +00002260 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
2261 ? TypeRecordKind::IndirectVirtualBaseClass
2262 : TypeRecordKind::VirtualBaseClass;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002263 VirtualBaseClassRecord VBCR(
Bob Haarman26a87bd2016-10-25 22:11:52 +00002264 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002265 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
Zachary Turner4efa0a42016-11-08 22:24:53 +00002266 VBTableIndex);
2267
Zachary Turner6900de12017-11-28 18:33:17 +00002268 ContinuationBuilder.writeMemberType(VBCR);
Brock Wyma4536c1f2018-02-01 20:37:38 +00002269 MemberCount++;
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002270 } else {
2271 assert(I->getOffsetInBits() % 8 == 0 &&
2272 "bases must be on byte boundaries");
Zachary Turner4efa0a42016-11-08 22:24:53 +00002273 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
2274 getTypeIndex(I->getBaseType()),
2275 I->getOffsetInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00002276 ContinuationBuilder.writeMemberType(BCR);
Brock Wyma4536c1f2018-02-01 20:37:38 +00002277 MemberCount++;
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002278 }
2279 }
2280
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002281 // Create members.
2282 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
2283 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
2284 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00002285 StringRef MemberName = Member->getName();
2286 MemberAccess Access =
2287 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002288
2289 if (Member->isStaticMember()) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00002290 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
Zachary Turner6900de12017-11-28 18:33:17 +00002291 ContinuationBuilder.writeMemberType(SDMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002292 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00002293 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00002294 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002295
Reid Kleckner9dac4732016-08-31 15:59:30 +00002296 // Virtual function pointer member.
2297 if ((Member->getFlags() & DINode::FlagArtificial) &&
2298 Member->getName().startswith("_vptr$")) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00002299 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
Zachary Turner6900de12017-11-28 18:33:17 +00002300 ContinuationBuilder.writeMemberType(VFPR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002301 MemberCount++;
2302 continue;
2303 }
2304
David Majnemer9319cbc2016-06-30 03:00:20 +00002305 // Data member.
David Majnemer08bd7442016-07-01 23:12:48 +00002306 uint64_t MemberOffsetInBits =
2307 Member->getOffsetInBits() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00002308 if (Member->isBitField()) {
2309 uint64_t StartBitOffset = MemberOffsetInBits;
2310 if (const auto *CI =
2311 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
David Majnemer08bd7442016-07-01 23:12:48 +00002312 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00002313 }
2314 StartBitOffset -= MemberOffsetInBits;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002315 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2316 StartBitOffset);
Zachary Turner6900de12017-11-28 18:33:17 +00002317 MemberBaseType = TypeTable.writeLeafType(BFR);
David Majnemer9319cbc2016-06-30 03:00:20 +00002318 }
2319 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002320 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2321 MemberName);
Zachary Turner6900de12017-11-28 18:33:17 +00002322 ContinuationBuilder.writeMemberType(DMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002323 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00002324 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002325
2326 // Create methods
2327 for (auto &MethodItr : Info.Methods) {
2328 StringRef Name = MethodItr.first->getString();
2329
2330 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00002331 for (const DISubprogram *SP : MethodItr.second) {
2332 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2333 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002334
2335 unsigned VFTableOffset = -1;
2336 if (Introduced)
2337 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2338
Zachary Turner7251ede2016-11-02 17:05:19 +00002339 Methods.push_back(OneMethodRecord(
2340 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
2341 translateMethodKindFlags(SP, Introduced),
2342 translateMethodOptionFlags(SP), VFTableOffset, Name));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002343 MemberCount++;
2344 }
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002345 assert(!Methods.empty() && "Empty methods map entry");
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002346 if (Methods.size() == 1)
Zachary Turner6900de12017-11-28 18:33:17 +00002347 ContinuationBuilder.writeMemberType(Methods[0]);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002348 else {
Zachary Turner6900de12017-11-28 18:33:17 +00002349 // FIXME: Make this use its own ContinuationBuilder so that
2350 // MethodOverloadList can be split correctly.
Zachary Turner4efa0a42016-11-08 22:24:53 +00002351 MethodOverloadListRecord MOLR(Methods);
Zachary Turner6900de12017-11-28 18:33:17 +00002352 TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
2353
Zachary Turner4efa0a42016-11-08 22:24:53 +00002354 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
Zachary Turner6900de12017-11-28 18:33:17 +00002355 ContinuationBuilder.writeMemberType(OMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002356 }
2357 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00002358
2359 // Create nested classes.
Reid Klecknere2e82062017-08-08 20:30:14 +00002360 for (const DIType *Nested : Info.NestedTypes) {
Adrian McCarthy820ca542016-07-06 19:49:51 +00002361 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
Zachary Turner6900de12017-11-28 18:33:17 +00002362 ContinuationBuilder.writeMemberType(R);
Adrian McCarthy820ca542016-07-06 19:49:51 +00002363 MemberCount++;
2364 }
2365
Zachary Turner6900de12017-11-28 18:33:17 +00002366 TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002367 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
Reid Klecknere2e82062017-08-08 20:30:14 +00002368 !Info.NestedTypes.empty());
Reid Klecknera8d57402016-06-03 15:58:20 +00002369}
2370
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002371TypeIndex CodeViewDebug::getVBPTypeIndex() {
2372 if (!VBPType.getIndex()) {
2373 // Make a 'const int *' type.
2374 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
Zachary Turner6900de12017-11-28 18:33:17 +00002375 TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002376
2377 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2378 : PointerKind::Near32;
2379 PointerMode PM = PointerMode::Pointer;
2380 PointerOptions PO = PointerOptions::None;
2381 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
Zachary Turner6900de12017-11-28 18:33:17 +00002382 VBPType = TypeTable.writeLeafType(PR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002383 }
2384
2385 return VBPType;
2386}
2387
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002388TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002389 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002390 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002391
2392 // The null DIType is the void type. Don't try to hash it.
2393 if (!Ty)
2394 return TypeIndex::Void();
2395
Reid Klecknera8d57402016-06-03 15:58:20 +00002396 // Check if we've already translated this type. Don't try to do a
2397 // get-or-create style insertion that caches the hash lookup across the
2398 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002399 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002400 if (I != TypeIndices.end())
2401 return I->second;
2402
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002403 TypeLoweringScope S(*this);
2404 TypeIndex TI = lowerType(Ty, ClassTy);
2405 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00002406}
2407
Zachary Turnerc68f8952018-11-20 22:13:43 +00002408codeview::TypeIndex
Reid Klecknerc168c6f2018-12-26 21:52:17 +00002409CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy,
Zachary Turnerc68f8952018-11-20 22:13:43 +00002410 const DISubroutineType *SubroutineTy) {
Reid Klecknerc168c6f2018-12-26 21:52:17 +00002411 assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type &&
2412 "this type must be a pointer type");
Zachary Turnerc68f8952018-11-20 22:13:43 +00002413
2414 PointerOptions Options = PointerOptions::None;
2415 if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference)
2416 Options = PointerOptions::LValueRefThisPointer;
2417 else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference)
2418 Options = PointerOptions::RValueRefThisPointer;
2419
2420 // Check if we've already translated this type. If there is no ref qualifier
2421 // on the function then we look up this pointer type with no associated class
2422 // so that the TypeIndex for the this pointer can be shared with the type
2423 // index for other pointers to this class type. If there is a ref qualifier
2424 // then we lookup the pointer using the subroutine as the parent type.
Reid Klecknerc168c6f2018-12-26 21:52:17 +00002425 auto I = TypeIndices.find({PtrTy, SubroutineTy});
Zachary Turnerc68f8952018-11-20 22:13:43 +00002426 if (I != TypeIndices.end())
2427 return I->second;
2428
2429 TypeLoweringScope S(*this);
Reid Klecknerc168c6f2018-12-26 21:52:17 +00002430 TypeIndex TI = lowerTypePointer(PtrTy, Options);
2431 return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy);
Zachary Turnerc68f8952018-11-20 22:13:43 +00002432}
2433
Bob Haarman223303c2017-08-29 20:59:25 +00002434TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(DITypeRef TypeRef) {
2435 DIType *Ty = TypeRef.resolve();
2436 PointerRecord PR(getTypeIndex(Ty),
2437 getPointerSizeInBytes() == 8 ? PointerKind::Near64
2438 : PointerKind::Near32,
2439 PointerMode::LValueReference, PointerOptions::None,
2440 Ty->getSizeInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00002441 return TypeTable.writeLeafType(PR);
Bob Haarman223303c2017-08-29 20:59:25 +00002442}
2443
Reid Klecknera8d57402016-06-03 15:58:20 +00002444TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
2445 const DIType *Ty = TypeRef.resolve();
2446
2447 // The null DIType is the void type. Don't try to hash it.
2448 if (!Ty)
2449 return TypeIndex::Void();
2450
Reid Kleckner9571c802018-12-11 23:07:39 +00002451 // Look through typedefs when getting the complete type index. Call
2452 // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are
2453 // emitted only once.
2454 if (Ty->getTag() == dwarf::DW_TAG_typedef)
2455 (void)getTypeIndex(Ty);
2456 while (Ty->getTag() == dwarf::DW_TAG_typedef)
2457 Ty = cast<DIDerivedType>(Ty)->getBaseType().resolve();
2458
Reid Klecknera8d57402016-06-03 15:58:20 +00002459 // If this is a non-record type, the complete type index is the same as the
2460 // normal type index. Just call getTypeIndex.
2461 switch (Ty->getTag()) {
2462 case dwarf::DW_TAG_class_type:
2463 case dwarf::DW_TAG_structure_type:
2464 case dwarf::DW_TAG_union_type:
2465 break;
2466 default:
2467 return getTypeIndex(Ty);
2468 }
2469
Brock Wymab60532f2018-06-11 01:39:34 +00002470 // Check if we've already translated the complete record type.
Reid Klecknera8d57402016-06-03 15:58:20 +00002471 const auto *CTy = cast<DICompositeType>(Ty);
2472 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
2473 if (!InsertResult.second)
2474 return InsertResult.first->second;
2475
Reid Kleckner643dd832016-06-22 17:15:28 +00002476 TypeLoweringScope S(*this);
2477
Reid Klecknera8d57402016-06-03 15:58:20 +00002478 // Make sure the forward declaration is emitted first. It's unclear if this
2479 // is necessary, but MSVC does it, and we should follow suit until we can show
2480 // otherwise.
Brock Wymab60532f2018-06-11 01:39:34 +00002481 // We only emit a forward declaration for named types.
2482 if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
2483 TypeIndex FwdDeclTI = getTypeIndex(CTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00002484
Brock Wymab60532f2018-06-11 01:39:34 +00002485 // Just use the forward decl if we don't have complete type info. This
2486 // might happen if the frontend is using modules and expects the complete
2487 // definition to be emitted elsewhere.
2488 if (CTy->isForwardDecl())
2489 return FwdDeclTI;
2490 }
Reid Klecknera8d57402016-06-03 15:58:20 +00002491
2492 TypeIndex TI;
2493 switch (CTy->getTag()) {
2494 case dwarf::DW_TAG_class_type:
2495 case dwarf::DW_TAG_structure_type:
2496 TI = lowerCompleteTypeClass(CTy);
2497 break;
2498 case dwarf::DW_TAG_union_type:
2499 TI = lowerCompleteTypeUnion(CTy);
2500 break;
2501 default:
2502 llvm_unreachable("not a record");
2503 }
2504
Brock Wymab60532f2018-06-11 01:39:34 +00002505 // Update the type index associated with this CompositeType. This cannot
2506 // use the 'InsertResult' iterator above because it is potentially
2507 // invalidated by map insertions which can occur while lowering the class
2508 // type above.
2509 CompleteTypeIndices[CTy] = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002510 return TI;
2511}
2512
Reid Kleckner643dd832016-06-22 17:15:28 +00002513/// Emit all the deferred complete record types. Try to do this in FIFO order,
Amjad Aboudacee5682016-07-12 12:06:34 +00002514/// and do this until fixpoint, as each complete record type typically
2515/// references
Reid Kleckner643dd832016-06-22 17:15:28 +00002516/// many other record types.
2517void CodeViewDebug::emitDeferredCompleteTypes() {
2518 SmallVector<const DICompositeType *, 4> TypesToEmit;
2519 while (!DeferredCompleteTypes.empty()) {
2520 std::swap(DeferredCompleteTypes, TypesToEmit);
2521 for (const DICompositeType *RecordTy : TypesToEmit)
2522 getCompleteTypeIndex(RecordTy);
2523 TypesToEmit.clear();
2524 }
2525}
2526
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002527void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
2528 ArrayRef<LocalVariable> Locals) {
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002529 // Get the sorted list of parameters and emit them first.
2530 SmallVector<const LocalVariable *, 6> Params;
2531 for (const LocalVariable &L : Locals)
2532 if (L.DIVar->isParameter())
2533 Params.push_back(&L);
Fangrui Song0cac7262018-09-27 02:13:45 +00002534 llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
2535 return L->DIVar->getArg() < R->DIVar->getArg();
2536 });
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002537 for (const LocalVariable *L : Params)
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002538 emitLocalVariable(FI, *L);
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002539
2540 // Next emit all non-parameters in the order that we found them.
2541 for (const LocalVariable &L : Locals)
2542 if (!L.DIVar->isParameter())
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002543 emitLocalVariable(FI, L);
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002544}
2545
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002546/// Only call this on endian-specific types like ulittle16_t and little32_t, or
2547/// structs composed of them.
2548template <typename T>
2549static void copyBytesForDefRange(SmallString<20> &BytePrefix,
2550 SymbolKind SymKind, const T &DefRangeHeader) {
2551 BytePrefix.resize(2 + sizeof(T));
2552 ulittle16_t SymKindLE = ulittle16_t(SymKind);
2553 memcpy(&BytePrefix[0], &SymKindLE, 2);
2554 memcpy(&BytePrefix[2], &DefRangeHeader, sizeof(T));
2555}
2556
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002557void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
2558 const LocalVariable &Var) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002559 // LocalSym record, see SymbolRecord.h for more info.
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002560 MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002561
Zachary Turner63a28462016-05-17 23:50:21 +00002562 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002563 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00002564 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00002565 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00002566 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002567
2568 OS.AddComment("TypeIndex");
Reid Kleckner08f5fd52017-08-31 15:56:49 +00002569 TypeIndex TI = Var.UseReferenceType
2570 ? getTypeIndexForReferenceTo(Var.DIVar->getType())
2571 : getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002572 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002573 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00002574 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00002575 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00002576 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002577 endSymbolRecord(LocalEnd);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002578
Reid Kleckner876330d2016-02-12 21:48:30 +00002579 // Calculate the on disk prefix of the appropriate def range record. The
2580 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2581 // should be big enough to hold all forms without memory allocation.
2582 SmallString<20> BytePrefix;
2583 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2584 BytePrefix.clear();
Reid Kleckner876330d2016-02-12 21:48:30 +00002585 if (DefRange.InMemory) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002586 int Offset = DefRange.DataOffset;
2587 unsigned Reg = DefRange.CVRegister;
2588
Reid Klecknerd5e4ec72018-10-02 16:43:52 +00002589 // 32-bit x86 call sequences often use PUSH instructions, which disrupt
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002590 // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
Reid Kleckner2bcb2882018-11-03 00:41:52 +00002591 // instead. In frames without stack realignment, $T0 will be the CFA.
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002592 if (RegisterId(Reg) == RegisterId::ESP) {
2593 Reg = unsigned(RegisterId::VFRAME);
Reid Kleckner2bcb2882018-11-03 00:41:52 +00002594 Offset += FI.OffsetAdjustment;
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002595 }
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002596
2597 // If we can use the chosen frame pointer for the frame and this isn't a
2598 // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
2599 // Otherwise, use S_DEFRANGE_REGISTER_REL.
2600 EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU);
2601 if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
2602 (bool(Flags & LocalSymFlags::IsParameter)
2603 ? (EncFP == FI.EncodedParamFramePtrReg)
2604 : (EncFP == FI.EncodedLocalFramePtrReg))) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002605 little32_t FPOffset = little32_t(Offset);
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002606 copyBytesForDefRange(BytePrefix, S_DEFRANGE_FRAMEPOINTER_REL, FPOffset);
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002607 } else {
2608 uint16_t RegRelFlags = 0;
2609 if (DefRange.IsSubfield) {
2610 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2611 (DefRange.StructOffset
2612 << DefRangeRegisterRelSym::OffsetInParentShift);
2613 }
2614 DefRangeRegisterRelSym::Header DRHdr;
2615 DRHdr.Register = Reg;
2616 DRHdr.Flags = RegRelFlags;
2617 DRHdr.BasePointerOffset = Offset;
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002618 copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER_REL, DRHdr);
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002619 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002620 } else {
2621 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002622 if (DefRange.IsSubfield) {
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002623 DefRangeSubfieldRegisterSym::Header DRHdr;
2624 DRHdr.Register = DefRange.CVRegister;
2625 DRHdr.MayHaveNoName = 0;
2626 DRHdr.OffsetInParent = DefRange.StructOffset;
2627 copyBytesForDefRange(BytePrefix, S_DEFRANGE_SUBFIELD_REGISTER, DRHdr);
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002628 } else {
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002629 DefRangeRegisterSym::Header DRHdr;
2630 DRHdr.Register = DefRange.CVRegister;
2631 DRHdr.MayHaveNoName = 0;
2632 copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER, DRHdr);
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002633 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002634 }
2635 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2636 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002637}
2638
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002639void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
2640 const FunctionInfo& FI) {
2641 for (LexicalBlock *Block : Blocks)
2642 emitLexicalBlock(*Block, FI);
2643}
2644
2645/// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
2646/// lexical block scope.
2647void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
2648 const FunctionInfo& FI) {
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002649 MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002650 OS.AddComment("PtrParent");
2651 OS.EmitIntValue(0, 4); // PtrParent
2652 OS.AddComment("PtrEnd");
2653 OS.EmitIntValue(0, 4); // PtrEnd
2654 OS.AddComment("Code size");
2655 OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4); // Code Size
2656 OS.AddComment("Function section relative address");
2657 OS.EmitCOFFSecRel32(Block.Begin, /*Offset=*/0); // Func Offset
2658 OS.AddComment("Function section index");
2659 OS.EmitCOFFSectionIndex(FI.Begin); // Func Symbol
2660 OS.AddComment("Lexical block name");
2661 emitNullTerminatedSymbolName(OS, Block.Name); // Name
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002662 endSymbolRecord(RecordEnd);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002663
2664 // Emit variables local to this lexical block.
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002665 emitLocalVariableList(FI, Block.Locals);
Brock Wymab17464e2018-12-20 17:33:45 +00002666 emitGlobalVariableList(Block.Globals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002667
2668 // Emit lexical blocks contained within this block.
2669 emitLexicalBlockList(Block.Children, FI);
2670
2671 // Close the lexical block scope.
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002672 emitEndSymbolRecord(SymbolKind::S_END);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002673}
2674
2675/// Convenience routine for collecting lexical block information for a list
2676/// of lexical scopes.
2677void CodeViewDebug::collectLexicalBlockInfo(
2678 SmallVectorImpl<LexicalScope *> &Scopes,
2679 SmallVectorImpl<LexicalBlock *> &Blocks,
Brock Wymab17464e2018-12-20 17:33:45 +00002680 SmallVectorImpl<LocalVariable> &Locals,
2681 SmallVectorImpl<CVGlobalVariable> &Globals) {
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002682 for (LexicalScope *Scope : Scopes)
Brock Wymab17464e2018-12-20 17:33:45 +00002683 collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002684}
2685
2686/// Populate the lexical blocks and local variable lists of the parent with
2687/// information about the specified lexical scope.
2688void CodeViewDebug::collectLexicalBlockInfo(
2689 LexicalScope &Scope,
2690 SmallVectorImpl<LexicalBlock *> &ParentBlocks,
Brock Wymab17464e2018-12-20 17:33:45 +00002691 SmallVectorImpl<LocalVariable> &ParentLocals,
2692 SmallVectorImpl<CVGlobalVariable> &ParentGlobals) {
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002693 if (Scope.isAbstractScope())
2694 return;
2695
Brock Wymab17464e2018-12-20 17:33:45 +00002696 // Gather information about the lexical scope including local variables,
2697 // global variables, and address ranges.
2698 bool IgnoreScope = false;
2699 auto LI = ScopeVariables.find(&Scope);
2700 SmallVectorImpl<LocalVariable> *Locals =
2701 LI != ScopeVariables.end() ? &LI->second : nullptr;
2702 auto GI = ScopeGlobals.find(Scope.getScopeNode());
2703 SmallVectorImpl<CVGlobalVariable> *Globals =
2704 GI != ScopeGlobals.end() ? GI->second.get() : nullptr;
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002705 const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002706 const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
Brock Wymab17464e2018-12-20 17:33:45 +00002707
2708 // Ignore lexical scopes which do not contain variables.
2709 if (!Locals && !Globals)
2710 IgnoreScope = true;
2711
2712 // Ignore lexical scopes which are not lexical blocks.
2713 if (!DILB)
2714 IgnoreScope = true;
2715
2716 // Ignore scopes which have too many address ranges to represent in the
2717 // current CodeView format or do not have a valid address range.
2718 //
2719 // For lexical scopes with multiple address ranges you may be tempted to
2720 // construct a single range covering every instruction where the block is
2721 // live and everything in between. Unfortunately, Visual Studio only
2722 // displays variables from the first matching lexical block scope. If the
2723 // first lexical block contains exception handling code or cold code which
2724 // is moved to the bottom of the routine creating a single range covering
2725 // nearly the entire routine, then it will hide all other lexical blocks
2726 // and the variables they contain.
2727 if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second))
2728 IgnoreScope = true;
2729
2730 if (IgnoreScope) {
2731 // This scope can be safely ignored and eliminating it will reduce the
2732 // size of the debug information. Be sure to collect any variable and scope
2733 // information from the this scope or any of its children and collapse them
2734 // into the parent scope.
2735 if (Locals)
2736 ParentLocals.append(Locals->begin(), Locals->end());
2737 if (Globals)
2738 ParentGlobals.append(Globals->begin(), Globals->end());
2739 collectLexicalBlockInfo(Scope.getChildren(),
2740 ParentBlocks,
2741 ParentLocals,
2742 ParentGlobals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002743 return;
2744 }
2745
2746 // Create a new CodeView lexical block for this lexical scope. If we've
2747 // seen this DILexicalBlock before then the scope tree is malformed and
2748 // we can handle this gracefully by not processing it a second time.
2749 auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
2750 if (!BlockInsertion.second)
2751 return;
2752
Brock Wymab17464e2018-12-20 17:33:45 +00002753 // Create a lexical block containing the variables and collect the the
2754 // lexical block information for the children.
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002755 const InsnRange &Range = Ranges.front();
2756 assert(Range.first && Range.second);
2757 LexicalBlock &Block = BlockInsertion.first->second;
2758 Block.Begin = getLabelBeforeInsn(Range.first);
2759 Block.End = getLabelAfterInsn(Range.second);
2760 assert(Block.Begin && "missing label for scope begin");
2761 assert(Block.End && "missing label for scope end");
2762 Block.Name = DILB->getName();
Brock Wymab17464e2018-12-20 17:33:45 +00002763 if (Locals)
2764 Block.Locals = std::move(*Locals);
2765 if (Globals)
2766 Block.Globals = std::move(*Globals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002767 ParentBlocks.push_back(&Block);
Brock Wymab17464e2018-12-20 17:33:45 +00002768 collectLexicalBlockInfo(Scope.getChildren(),
2769 Block.Children,
2770 Block.Locals,
2771 Block.Globals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002772}
2773
David Blaikieb2fbb4b2017-02-16 18:48:33 +00002774void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002775 const Function &GV = MF->getFunction();
2776 assert(FnDebugInfo.count(&GV));
Reid Kleckner55baeef2018-03-15 21:12:21 +00002777 assert(CurFn == FnDebugInfo[&GV].get());
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002778
Matthias Braunf1caa282017-12-15 22:22:58 +00002779 collectVariableInfo(GV.getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00002780
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002781 // Build the lexical block structure to emit for this routine.
2782 if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
Brock Wymab17464e2018-12-20 17:33:45 +00002783 collectLexicalBlockInfo(*CFS,
2784 CurFn->ChildBlocks,
2785 CurFn->Locals,
2786 CurFn->Globals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002787
2788 // Clear the scope and variable information from the map which will not be
2789 // valid after we have finished processing this routine. This also prepares
2790 // the map for the subsequent routine.
2791 ScopeVariables.clear();
2792
Reid Kleckner2214ed82016-01-29 00:49:42 +00002793 // Don't emit anything if we don't have any line tables.
Brock Wyma94ece8f2018-04-16 16:53:57 +00002794 // Thunks are compiler-generated and probably won't have source correlation.
2795 if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002796 FnDebugInfo.erase(&GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002797 CurFn = nullptr;
2798 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00002799 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002800
Reid Klecknere33c94f2017-09-05 20:14:58 +00002801 CurFn->Annotations = MF->getCodeViewAnnotations();
2802
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002803 CurFn->End = Asm->getFunctionEnd();
2804
Craig Topper353eda42014-04-24 06:44:33 +00002805 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002806}
2807
Reid Kleckner70f5bc92016-01-14 19:25:04 +00002808void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002809 DebugHandlerBase::beginInstruction(MI);
2810
Shiva Chen801bf7e2018-05-09 02:42:00 +00002811 // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
2812 if (!Asm || !CurFn || MI->isDebugInstr() ||
David Majnemer67f684e2016-07-28 05:03:22 +00002813 MI->getFlag(MachineInstr::FrameSetup))
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002814 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002815
2816 // If the first instruction of a new MBB has no location, find the first
2817 // instruction with a location and use that.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002818 DebugLoc DL = MI->getDebugLoc();
Reid Kleckner45a74622017-06-30 21:33:44 +00002819 if (!DL && MI->getParent() != PrevInstBB) {
2820 for (const auto &NextMI : *MI->getParent()) {
Shiva Chen801bf7e2018-05-09 02:42:00 +00002821 if (NextMI.isDebugInstr())
Reid Kleckner2de471d2017-07-31 21:03:08 +00002822 continue;
Reid Kleckner45a74622017-06-30 21:33:44 +00002823 DL = NextMI.getDebugLoc();
2824 if (DL)
2825 break;
2826 }
2827 }
2828 PrevInstBB = MI->getParent();
2829
2830 // If we still don't have a debug location, don't record a location.
2831 if (!DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002832 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002833
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002834 maybeRecordLocation(DL, Asm->MF);
2835}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002836
Zachary Turner8c099fe2017-05-30 16:36:15 +00002837MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002838 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2839 *EndLabel = MMI->getContext().createTempSymbol();
2840 OS.EmitIntValue(unsigned(Kind), 4);
2841 OS.AddComment("Subsection size");
2842 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2843 OS.EmitLabel(BeginLabel);
2844 return EndLabel;
2845}
2846
2847void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2848 OS.EmitLabel(EndLabel);
2849 // Every subsection must be aligned to a 4-byte boundary.
2850 OS.EmitValueToAlignment(4);
2851}
2852
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002853static StringRef getSymbolName(SymbolKind SymKind) {
2854 for (const EnumEntry<SymbolKind> &EE : getSymbolTypeNames())
2855 if (EE.Value == SymKind)
2856 return EE.Name;
2857 return "";
2858}
2859
2860MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) {
2861 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2862 *EndLabel = MMI->getContext().createTempSymbol();
2863 OS.AddComment("Record length");
2864 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
2865 OS.EmitLabel(BeginLabel);
2866 if (OS.isVerboseAsm())
2867 OS.AddComment("Record kind: " + getSymbolName(SymKind));
2868 OS.EmitIntValue(unsigned(SymKind), 2);
2869 return EndLabel;
2870}
2871
2872void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) {
Reid Kleckner4ab50b82018-12-18 01:36:06 +00002873 // MSVC does not pad out symbol records to four bytes, but LLVM does to avoid
2874 // an extra copy of every symbol record in LLD. This increases object file
2875 // size by less than 1% in the clang build, and is compatible with the Visual
2876 // C++ linker.
Reid Kleckner53ce0592018-12-18 01:14:05 +00002877 OS.EmitValueToAlignment(4);
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002878 OS.EmitLabel(SymEnd);
2879}
2880
2881void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) {
2882 OS.AddComment("Record length");
2883 OS.EmitIntValue(2, 2);
2884 if (OS.isVerboseAsm())
2885 OS.AddComment("Record kind: " + getSymbolName(EndKind));
2886 OS.EmitIntValue(unsigned(EndKind), 2); // Record Kind
2887}
2888
David Majnemer3128b102016-06-15 18:00:01 +00002889void CodeViewDebug::emitDebugInfoForUDTs(
Zachary Turnera7b04172017-08-28 18:49:04 +00002890 ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
2891 for (const auto &UDT : UDTs) {
2892 const DIType *T = UDT.second;
2893 assert(shouldEmitUdt(T));
2894
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002895 MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT);
David Majnemer3128b102016-06-15 18:00:01 +00002896 OS.AddComment("Type");
Zachary Turnera7b04172017-08-28 18:49:04 +00002897 OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
David Majnemer3128b102016-06-15 18:00:01 +00002898 emitNullTerminatedSymbolName(OS, UDT.first);
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002899 endSymbolRecord(UDTRecordEnd);
David Majnemer3128b102016-06-15 18:00:01 +00002900 }
2901}
2902
Brock Wymab17464e2018-12-20 17:33:45 +00002903void CodeViewDebug::collectGlobalVariableInfo() {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002904 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2905 GlobalMap;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002906 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002907 SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2908 GV.getDebugInfo(GVEs);
2909 for (const auto *GVE : GVEs)
2910 GlobalMap[GVE] = &GV;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002911 }
2912
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002913 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2914 for (const MDNode *Node : CUs->operands()) {
2915 const auto *CU = cast<DICompileUnit>(Node);
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002916 for (const auto *GVE : CU->getGlobalVariables()) {
Brock Wymab17464e2018-12-20 17:33:45 +00002917 const auto *GV = GlobalMap.lookup(GVE);
2918 if (!GV || GV->isDeclarationForLinker())
2919 continue;
2920 const DIGlobalVariable *DIGV = GVE->getVariable();
2921 DIScope *Scope = DIGV->getScope();
2922 SmallVector<CVGlobalVariable, 1> *VariableList;
2923 if (Scope && isa<DILocalScope>(Scope)) {
2924 // Locate a global variable list for this scope, creating one if
2925 // necessary.
2926 auto Insertion = ScopeGlobals.insert(
2927 {Scope, std::unique_ptr<GlobalVariableList>()});
2928 if (Insertion.second)
2929 Insertion.first->second = llvm::make_unique<GlobalVariableList>();
2930 VariableList = Insertion.first->second.get();
2931 } else if (GV->hasComdat())
2932 // Emit this global variable into a COMDAT section.
2933 VariableList = &ComdatVariables;
2934 else
2935 // Emit this globla variable in a single global symbol section.
2936 VariableList = &GlobalVariables;
2937 CVGlobalVariable CVGV = {DIGV, GV};
2938 VariableList->emplace_back(std::move(CVGV));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002939 }
Brock Wymab17464e2018-12-20 17:33:45 +00002940 }
2941}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002942
Brock Wymab17464e2018-12-20 17:33:45 +00002943void CodeViewDebug::emitDebugInfoForGlobals() {
2944 // First, emit all globals that are not in a comdat in a single symbol
2945 // substream. MSVC doesn't like it if the substream is empty, so only open
2946 // it if we have at least one global to emit.
2947 switchToDebugSectionForSymbol(nullptr);
2948 if (!GlobalVariables.empty()) {
2949 OS.AddComment("Symbol subsection for globals");
2950 MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
2951 emitGlobalVariableList(GlobalVariables);
2952 endCVSubsection(EndLabel);
2953 }
2954
2955 // Second, emit each global that is in a comdat into its own .debug$S
2956 // section along with its own symbol substream.
2957 for (const CVGlobalVariable &CVGV : ComdatVariables) {
2958 MCSymbol *GVSym = Asm->getSymbol(CVGV.GV);
2959 OS.AddComment("Symbol subsection for " +
2960 Twine(GlobalValue::dropLLVMManglingEscape(CVGV.GV->getName())));
2961 switchToDebugSectionForSymbol(GVSym);
2962 MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
2963 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2964 emitDebugInfoForGlobal(CVGV.DIGV, CVGV.GV, GVSym);
2965 endCVSubsection(EndLabel);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002966 }
2967}
2968
Hans Wennborgb510b452016-06-23 16:33:53 +00002969void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2970 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2971 for (const MDNode *Node : CUs->operands()) {
2972 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2973 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2974 getTypeIndex(RT);
2975 // FIXME: Add to global/local DTU list.
2976 }
2977 }
2978 }
2979}
2980
Brock Wymab17464e2018-12-20 17:33:45 +00002981// Emit each global variable in the specified array.
2982void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) {
2983 for (const CVGlobalVariable &CVGV : Globals) {
2984 MCSymbol *GVSym = Asm->getSymbol(CVGV.GV);
2985 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2986 emitDebugInfoForGlobal(CVGV.DIGV, CVGV.GV, GVSym);
2987 }
2988}
2989
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002990void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002991 const GlobalVariable *GV,
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002992 MCSymbol *GVSym) {
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002993 // DataSym record, see SymbolRecord.h for more info. Thread local data
2994 // happens to have the same format as global data.
2995 SymbolKind DataSym = GV->isThreadLocal()
2996 ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32
2997 : SymbolKind::S_GTHREAD32)
2998 : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32
2999 : SymbolKind::S_GDATA32);
3000 MCSymbol *DataEnd = beginSymbolRecord(DataSym);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00003001 OS.AddComment("Type");
3002 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
3003 OS.AddComment("DataOffset");
Keno Fischerf7d84ee2017-01-02 03:00:19 +00003004 OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00003005 OS.AddComment("Segment");
3006 OS.EmitCOFFSectionIndex(GVSym);
3007 OS.AddComment("Name");
Reid Kleckner5bf71d12018-12-14 22:40:28 +00003008 const unsigned LengthOfDataRecord = 12;
3009 emitNullTerminatedSymbolName(OS, DIGV->getName(), LengthOfDataRecord);
3010 endSymbolRecord(DataEnd);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00003011}