blob: a57f0f52fed17a96b19d3207f1b45d88bf352d01 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00006//
7//===----------------------------------------------------------------------===//
8//
Reid Kleckner70f5bc92016-01-14 19:25:04 +00009// This file contains support for writing Microsoft CodeView debug info.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000010//
11//===----------------------------------------------------------------------===//
12
Reid Kleckner70f5bc92016-01-14 19:25:04 +000013#include "CodeViewDebug.h"
Adrian Prantl032d2382017-08-01 21:45:24 +000014#include "DwarfExpression.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000015#include "llvm/ADT/APSInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/MapVector.h"
20#include "llvm/ADT/None.h"
21#include "llvm/ADT/Optional.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000022#include "llvm/ADT/STLExtras.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000023#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/SmallVector.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000025#include "llvm/ADT/StringRef.h"
Reid Kleckner156a7232016-06-22 18:31:14 +000026#include "llvm/ADT/TinyPtrVector.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000027#include "llvm/ADT/Triple.h"
28#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000029#include "llvm/BinaryFormat/COFF.h"
30#include "llvm/BinaryFormat/Dwarf.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000031#include "llvm/CodeGen/AsmPrinter.h"
32#include "llvm/CodeGen/LexicalScopes.h"
Reid Kleckner9ea2c012018-10-01 21:59:45 +000033#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000034#include "llvm/CodeGen/MachineFunction.h"
35#include "llvm/CodeGen/MachineInstr.h"
36#include "llvm/CodeGen/MachineModuleInfo.h"
37#include "llvm/CodeGen/MachineOperand.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000038#include "llvm/CodeGen/TargetFrameLowering.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000039#include "llvm/CodeGen/TargetRegisterInfo.h"
40#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000041#include "llvm/Config/llvm-config.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000042#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000043#include "llvm/DebugInfo/CodeView/CodeView.h"
Zachary Turner6900de12017-11-28 18:33:17 +000044#include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h"
Zachary Turner8c099fe2017-05-30 16:36:15 +000045#include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
Reid Kleckner5bf71d12018-12-14 22:40:28 +000046#include "llvm/DebugInfo/CodeView/EnumTables.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000047#include "llvm/DebugInfo/CodeView/Line.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000048#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
Zachary Turner629cb7d2017-01-11 23:24:22 +000049#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000050#include "llvm/DebugInfo/CodeView/TypeIndex.h"
51#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Zachary Turner526f4f22017-05-19 19:26:58 +000052#include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
David Majnemer9319cbc2016-06-30 03:00:20 +000053#include "llvm/IR/Constants.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000054#include "llvm/IR/DataLayout.h"
55#include "llvm/IR/DebugInfoMetadata.h"
56#include "llvm/IR/DebugLoc.h"
57#include "llvm/IR/Function.h"
58#include "llvm/IR/GlobalValue.h"
59#include "llvm/IR/GlobalVariable.h"
60#include "llvm/IR/Metadata.h"
61#include "llvm/IR/Module.h"
Reid Kleckner46cb48c2016-07-27 16:03:57 +000062#include "llvm/MC/MCAsmInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000063#include "llvm/MC/MCContext.h"
Reid Kleckner5d122f82016-05-25 23:16:12 +000064#include "llvm/MC/MCSectionCOFF.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000065#include "llvm/MC/MCStreamer.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000066#include "llvm/MC/MCSymbol.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000067#include "llvm/Support/BinaryByteStream.h"
68#include "llvm/Support/BinaryStreamReader.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000069#include "llvm/Support/Casting.h"
Zachary Turner048f8f92017-12-13 22:33:58 +000070#include "llvm/Support/CommandLine.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000071#include "llvm/Support/Compiler.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000072#include "llvm/Support/Endian.h"
73#include "llvm/Support/Error.h"
74#include "llvm/Support/ErrorHandling.h"
Zachary Turner048f8f92017-12-13 22:33:58 +000075#include "llvm/Support/FormatVariadic.h"
Zachary Turner5bba1ca2018-10-12 17:26:19 +000076#include "llvm/Support/Path.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000077#include "llvm/Support/SMLoc.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000078#include "llvm/Support/ScopedPrinter.h"
David Blaikie6054e652018-03-23 23:58:19 +000079#include "llvm/Target/TargetLoweringObjectFile.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000080#include "llvm/Target/TargetMachine.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000081#include <algorithm>
82#include <cassert>
83#include <cctype>
84#include <cstddef>
85#include <cstdint>
86#include <iterator>
87#include <limits>
88#include <string>
89#include <utility>
90#include <vector>
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000091
Reid Klecknerf9c275f2016-02-10 20:55:49 +000092using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000093using namespace llvm::codeview;
94
Reid Kleckner9ea2c012018-10-01 21:59:45 +000095static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
96 switch (Type) {
97 case Triple::ArchType::x86:
98 return CPUType::Pentium3;
99 case Triple::ArchType::x86_64:
100 return CPUType::X64;
101 case Triple::ArchType::thumb:
102 return CPUType::Thumb;
103 case Triple::ArchType::aarch64:
104 return CPUType::ARM64;
105 default:
106 report_fatal_error("target architecture doesn't map to a CodeView CPUType");
107 }
108}
109
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000110CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000111 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000112 // If module doesn't have named metadata anchors or COFF debug section
113 // is not available, skip any debug info related stuff.
114 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
115 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
116 Asm = nullptr;
Matthias Braun8763c0c2018-10-31 17:18:41 +0000117 MMI->setDebugInfoAvailability(false);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000118 return;
119 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000120 // Tell MMI that we have debug info.
121 MMI->setDebugInfoAvailability(true);
Reid Kleckner9ea2c012018-10-01 21:59:45 +0000122
123 TheCPU =
124 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
Reid Kleckner75557712018-11-16 18:47:41 +0000125
Brock Wymab17464e2018-12-20 17:33:45 +0000126 collectGlobalVariableInfo();
127
Reid Kleckner75557712018-11-16 18:47:41 +0000128 // Check if we should emit type record hashes.
129 ConstantInt *GH = mdconst::extract_or_null<ConstantInt>(
130 MMI->getModule()->getModuleFlag("CodeViewGHash"));
131 EmitDebugGlobalHashes = GH && !GH->isZero();
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000132}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000133
Reid Kleckner9533af42016-01-16 00:09:09 +0000134StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
135 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000136 if (!Filepath.empty())
137 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000138
Reid Kleckner9533af42016-01-16 00:09:09 +0000139 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
140
Peter Collingbournecb8a6662018-04-11 18:24:03 +0000141 // If this is a Unix-style path, just use it as is. Don't try to canonicalize
142 // it textually because one of the path components could be a symlink.
Zachary Turner5bba1ca2018-10-12 17:26:19 +0000143 if (Dir.startswith("/") || Filename.startswith("/")) {
144 if (llvm::sys::path::is_absolute(Filename, llvm::sys::path::Style::posix))
145 return Filename;
Peter Collingbournecb8a6662018-04-11 18:24:03 +0000146 Filepath = Dir;
147 if (Dir.back() != '/')
148 Filepath += '/';
149 Filepath += Filename;
150 return Filepath;
151 }
152
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000153 // Clang emits directory and relative filename info into the IR, but CodeView
154 // operates on full paths. We could change Clang to emit full paths too, but
155 // that would increase the IR size and probably not needed for other users.
156 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000157 if (Filename.find(':') == 1)
158 Filepath = Filename;
159 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +0000160 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000161
162 // Canonicalize the path. We have to do it textually because we may no longer
163 // have access the file in the filesystem.
164 // First, replace all slashes with backslashes.
165 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
166
167 // Remove all "\.\" with "\".
168 size_t Cursor = 0;
169 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
170 Filepath.erase(Cursor, 2);
171
172 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
173 // path should be well-formatted, e.g. start with a drive letter, etc.
174 Cursor = 0;
175 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
176 // Something's wrong if the path starts with "\..\", abort.
177 if (Cursor == 0)
178 break;
179
180 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
181 if (PrevSlash == std::string::npos)
182 // Something's wrong, abort.
183 break;
184
185 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
186 // The next ".." might be following the one we've just erased.
187 Cursor = PrevSlash;
188 }
189
190 // Remove all duplicate backslashes.
191 Cursor = 0;
192 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
193 Filepath.erase(Cursor, 1);
194
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000195 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000196}
197
Reid Kleckner2214ed82016-01-29 00:49:42 +0000198unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
Reid Klecknerbc6f52d2017-10-31 21:52:15 +0000199 StringRef FullPath = getFullFilepath(F);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000200 unsigned NextId = FileIdMap.size() + 1;
Reid Klecknerbc6f52d2017-10-31 21:52:15 +0000201 auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
Reid Kleckner2214ed82016-01-29 00:49:42 +0000202 if (Insertion.second) {
203 // We have to compute the full filepath and emit a .cv_file directive.
Scott Linder71603842018-02-12 19:45:54 +0000204 ArrayRef<uint8_t> ChecksumAsBytes;
205 FileChecksumKind CSKind = FileChecksumKind::None;
206 if (F->getChecksum()) {
207 std::string Checksum = fromHex(F->getChecksum()->Value);
208 void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
209 memcpy(CKMem, Checksum.data(), Checksum.size());
210 ChecksumAsBytes = ArrayRef<uint8_t>(
211 reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
212 switch (F->getChecksum()->Kind) {
213 case DIFile::CSK_MD5: CSKind = FileChecksumKind::MD5; break;
214 case DIFile::CSK_SHA1: CSKind = FileChecksumKind::SHA1; break;
215 }
216 }
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000217 bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
Scott Linder71603842018-02-12 19:45:54 +0000218 static_cast<unsigned>(CSKind));
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000219 (void)Success;
220 assert(Success && ".cv_file directive failed");
Reid Kleckner2214ed82016-01-29 00:49:42 +0000221 }
222 return Insertion.first->second;
223}
224
Reid Kleckner876330d2016-02-12 21:48:30 +0000225CodeViewDebug::InlineSite &
226CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
227 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000228 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
229 InlineSite *Site = &SiteInsertion.first->second;
230 if (SiteInsertion.second) {
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000231 unsigned ParentFuncId = CurFn->FuncId;
232 if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
233 ParentFuncId =
234 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
235 .SiteFuncId;
236
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000237 Site->SiteFuncId = NextFuncId++;
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000238 OS.EmitCVInlineSiteIdDirective(
239 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
240 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
Reid Kleckner876330d2016-02-12 21:48:30 +0000241 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000242 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000243 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000244 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000245 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000246}
247
David Majnemer6bdc24e2016-07-01 23:12:45 +0000248static StringRef getPrettyScopeName(const DIScope *Scope) {
249 StringRef ScopeName = Scope->getName();
250 if (!ScopeName.empty())
251 return ScopeName;
252
253 switch (Scope->getTag()) {
254 case dwarf::DW_TAG_enumeration_type:
255 case dwarf::DW_TAG_class_type:
256 case dwarf::DW_TAG_structure_type:
257 case dwarf::DW_TAG_union_type:
258 return "<unnamed-tag>";
259 case dwarf::DW_TAG_namespace:
260 return "`anonymous namespace'";
261 }
262
263 return StringRef();
264}
265
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000266static const DISubprogram *getQualifiedNameComponents(
267 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
268 const DISubprogram *ClosestSubprogram = nullptr;
269 while (Scope != nullptr) {
270 if (ClosestSubprogram == nullptr)
271 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
David Majnemer6bdc24e2016-07-01 23:12:45 +0000272 StringRef ScopeName = getPrettyScopeName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000273 if (!ScopeName.empty())
274 QualifiedNameComponents.push_back(ScopeName);
275 Scope = Scope->getScope().resolve();
276 }
277 return ClosestSubprogram;
278}
279
280static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
281 StringRef TypeName) {
282 std::string FullyQualifiedName;
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000283 for (StringRef QualifiedNameComponent :
284 llvm::reverse(QualifiedNameComponents)) {
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000285 FullyQualifiedName.append(QualifiedNameComponent);
286 FullyQualifiedName.append("::");
287 }
288 FullyQualifiedName.append(TypeName);
289 return FullyQualifiedName;
290}
291
292static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
293 SmallVector<StringRef, 5> QualifiedNameComponents;
294 getQualifiedNameComponents(Scope, QualifiedNameComponents);
295 return getQualifiedName(QualifiedNameComponents, Name);
296}
297
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000298struct CodeViewDebug::TypeLoweringScope {
299 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
300 ~TypeLoweringScope() {
301 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
302 // inner TypeLoweringScopes don't attempt to emit deferred types.
303 if (CVD.TypeEmissionLevel == 1)
304 CVD.emitDeferredCompleteTypes();
305 --CVD.TypeEmissionLevel;
306 }
307 CodeViewDebug &CVD;
308};
309
David Majnemer6bdc24e2016-07-01 23:12:45 +0000310static std::string getFullyQualifiedName(const DIScope *Ty) {
311 const DIScope *Scope = Ty->getScope().resolve();
312 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
313}
314
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000315TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
316 // No scope means global scope and that uses the zero index.
317 if (!Scope || isa<DIFile>(Scope))
318 return TypeIndex();
319
320 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
321
322 // Check if we've already translated this scope.
323 auto I = TypeIndices.find({Scope, nullptr});
324 if (I != TypeIndices.end())
325 return I->second;
326
327 // Build the fully qualified name of the scope.
David Majnemer6bdc24e2016-07-01 23:12:45 +0000328 std::string ScopeName = getFullyQualifiedName(Scope);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000329 StringIdRecord SID(TypeIndex(), ScopeName);
Zachary Turner6900de12017-11-28 18:33:17 +0000330 auto TI = TypeTable.writeLeafType(SID);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000331 return recordTypeIndexForDINode(Scope, TI);
332}
333
David Majnemer75c3ebf2016-06-02 17:13:53 +0000334TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
David Majnemer67f684e2016-07-28 05:03:22 +0000335 assert(SP);
Reid Kleckner2280f932016-05-23 20:23:46 +0000336
David Majnemer75c3ebf2016-06-02 17:13:53 +0000337 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000338 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000339 if (I != TypeIndices.end())
340 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000341
Reid Klecknerac945e22016-06-17 16:11:20 +0000342 // The display name includes function template arguments. Drop them to match
343 // MSVC.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000344 StringRef DisplayName = SP->getName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000345
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000346 const DIScope *Scope = SP->getScope().resolve();
347 TypeIndex TI;
348 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
349 // If the scope is a DICompositeType, then this must be a method. Member
350 // function types take some special handling, and require access to the
351 // subprogram.
352 TypeIndex ClassType = getTypeIndex(Class);
353 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
354 DisplayName);
Zachary Turner6900de12017-11-28 18:33:17 +0000355 TI = TypeTable.writeLeafType(MFuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000356 } else {
357 // Otherwise, this must be a free function.
358 TypeIndex ParentScope = getScopeIndex(Scope);
359 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Zachary Turner6900de12017-11-28 18:33:17 +0000360 TI = TypeTable.writeLeafType(FuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000361 }
362
363 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000364}
365
Aaron Smith1d5f8632019-02-26 03:23:56 +0000366static bool isNonTrivial(const DICompositeType *DCTy) {
367 return ((DCTy->getFlags() & DINode::FlagNonTrivial) == DINode::FlagNonTrivial);
Aaron Smith802b0332018-10-02 20:21:05 +0000368}
369
370static FunctionOptions
371getFunctionOptions(const DISubroutineType *Ty,
372 const DICompositeType *ClassTy = nullptr,
373 StringRef SPName = StringRef("")) {
374 FunctionOptions FO = FunctionOptions::None;
375 const DIType *ReturnTy = nullptr;
376 if (auto TypeArray = Ty->getTypeArray()) {
377 if (TypeArray.size())
378 ReturnTy = TypeArray[0].resolve();
379 }
380
381 if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy)) {
Aaron Smith1d5f8632019-02-26 03:23:56 +0000382 if (isNonTrivial(ReturnDCTy))
Aaron Smith802b0332018-10-02 20:21:05 +0000383 FO |= FunctionOptions::CxxReturnUdt;
384 }
385
386 // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison.
Aaron Smith1d5f8632019-02-26 03:23:56 +0000387 if (ClassTy && isNonTrivial(ClassTy) && SPName == ClassTy->getName()) {
Aaron Smith802b0332018-10-02 20:21:05 +0000388 FO |= FunctionOptions::Constructor;
389
390 // TODO: put the FunctionOptions::ConstructorWithVirtualBases flag.
391
392 }
393 return FO;
394}
395
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000396TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
397 const DICompositeType *Class) {
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000398 // Always use the method declaration as the key for the function type. The
399 // method declaration contains the this adjustment.
400 if (SP->getDeclaration())
401 SP = SP->getDeclaration();
402 assert(!SP->getDeclaration() && "should use declaration as key");
403
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000404 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
405 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000406 auto I = TypeIndices.find({SP, Class});
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000407 if (I != TypeIndices.end())
408 return I->second;
409
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000410 // Make sure complete type info for the class is emitted *after* the member
411 // function type, as the complete class type is likely to reference this
412 // member function type.
413 TypeLoweringScope S(*this);
Adrian McCarthyd91bf392017-09-13 20:53:55 +0000414 const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
Aaron Smith802b0332018-10-02 20:21:05 +0000415
416 FunctionOptions FO = getFunctionOptions(SP->getType(), Class, SP->getName());
Adrian McCarthyd91bf392017-09-13 20:53:55 +0000417 TypeIndex TI = lowerTypeMemberFunction(
Aaron Smith802b0332018-10-02 20:21:05 +0000418 SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000419 return recordTypeIndexForDINode(SP, TI, Class);
420}
421
Amjad Aboudacee5682016-07-12 12:06:34 +0000422TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
423 TypeIndex TI,
424 const DIType *ClassTy) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000425 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000426 (void)InsertResult;
427 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000428 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000429}
430
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000431unsigned CodeViewDebug::getPointerSizeInBytes() {
432 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
433}
434
Reid Kleckner876330d2016-02-12 21:48:30 +0000435void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
Reid Kleckner5a791ee2018-03-15 21:24:04 +0000436 const LexicalScope *LS) {
437 if (const DILocation *InlinedAt = LS->getInlinedAt()) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000438 // This variable was inlined. Associate it with the InlineSite.
439 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
440 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
441 Site.InlinedLocals.emplace_back(Var);
442 } else {
Reid Kleckner5a791ee2018-03-15 21:24:04 +0000443 // This variable goes into the corresponding lexical scope.
444 ScopeVariables[LS].emplace_back(Var);
Reid Kleckner876330d2016-02-12 21:48:30 +0000445 }
446}
447
Reid Kleckner829365a2016-02-11 19:41:47 +0000448static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
449 const DILocation *Loc) {
450 auto B = Locs.begin(), E = Locs.end();
451 if (std::find(B, E, Loc) == E)
452 Locs.push_back(Loc);
453}
454
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000455void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000456 const MachineFunction *MF) {
457 // Skip this instruction if it has the same location as the previous one.
Reid Kleckner45a74622017-06-30 21:33:44 +0000458 if (!DL || DL == PrevInstLoc)
Reid Kleckner9533af42016-01-16 00:09:09 +0000459 return;
460
461 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000462 if (!Scope)
463 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000464
David Majnemerc3340db2016-01-13 01:05:23 +0000465 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000466 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
467 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
468 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000469 return;
470
Reid Kleckner2214ed82016-01-29 00:49:42 +0000471 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
472 if (CI.getStartColumn() != DL.getCol())
473 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000474
Reid Kleckner2214ed82016-01-29 00:49:42 +0000475 if (!CurFn->HaveLineInfo)
476 CurFn->HaveLineInfo = true;
477 unsigned FileId = 0;
Reid Kleckner45a74622017-06-30 21:33:44 +0000478 if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
Reid Kleckner2214ed82016-01-29 00:49:42 +0000479 FileId = CurFn->LastFileId;
480 else
481 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
Reid Kleckner45a74622017-06-30 21:33:44 +0000482 PrevInstLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000483
484 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000485 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000486 const DILocation *Loc = DL.get();
487
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000488 // If this location was actually inlined from somewhere else, give it the ID
489 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000490 FuncId =
491 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000492
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000493 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000494 bool FirstLoc = true;
495 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000496 InlineSite &Site =
497 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000498 if (!FirstLoc)
499 addLocIfNotPresent(Site.ChildSites, Loc);
500 FirstLoc = false;
501 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000502 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000503 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000504 }
505
Reid Klecknerdac21b42016-02-03 21:15:48 +0000506 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000507 /*PrologueEnd=*/false, /*IsStmt=*/false,
508 DL->getFilename(), SMLoc());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000509}
510
Reid Kleckner5d122f82016-05-25 23:16:12 +0000511void CodeViewDebug::emitCodeViewMagicVersion() {
512 OS.EmitValueToAlignment(4);
513 OS.AddComment("Debug section magic");
514 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
515}
516
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000517void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000518 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000519 return;
520
521 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000522
523 // The COFF .debug$S section consists of several subsections, each starting
524 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
525 // of the payload followed by the payload itself. The subsections are 4-byte
526 // aligned.
527
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000528 // Use the generic .debug$S section, and make a subsection for all the inlined
529 // subprograms.
530 switchToDebugSectionForSymbol(nullptr);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000531
Zachary Turner8c099fe2017-05-30 16:36:15 +0000532 MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000533 emitCompilerInformation();
534 endCVSubsection(CompilerInfo);
535
Reid Kleckner5d122f82016-05-25 23:16:12 +0000536 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000537
Reid Kleckner2214ed82016-01-29 00:49:42 +0000538 // Emit per-function debug information.
539 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000540 if (!P.first->isDeclarationForLinker())
Reid Kleckner55baeef2018-03-15 21:12:21 +0000541 emitDebugInfoForFunction(P.first, *P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000542
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000543 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000544 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000545 emitDebugInfoForGlobals();
546
Hans Wennborgb510b452016-06-23 16:33:53 +0000547 // Emit retained types.
548 emitDebugInfoForRetainedTypes();
549
Reid Kleckner5d122f82016-05-25 23:16:12 +0000550 // Switch back to the generic .debug$S section after potentially processing
551 // comdat symbol sections.
552 switchToDebugSectionForSymbol(nullptr);
553
David Majnemer3128b102016-06-15 18:00:01 +0000554 // Emit UDT records for any types used by global variables.
555 if (!GlobalUDTs.empty()) {
Zachary Turner8c099fe2017-05-30 16:36:15 +0000556 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
David Majnemer3128b102016-06-15 18:00:01 +0000557 emitDebugInfoForUDTs(GlobalUDTs);
558 endCVSubsection(SymbolsEnd);
559 }
560
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000561 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000562 OS.AddComment("File index to string table offset subsection");
563 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000564
565 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000566 OS.AddComment("String table");
567 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000568
Reid Kleckner810687c2018-10-12 18:19:06 +0000569 // Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol
570 // subsection in the generic .debug$S section at the end. There is no
571 // particular reason for this ordering other than to match MSVC.
572 emitBuildInfo();
573
Zachary Turner048f8f92017-12-13 22:33:58 +0000574 // Emit type information and hashes last, so that any types we translate while
575 // emitting function info are included.
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000576 emitTypeInformation();
577
Zachary Turner048f8f92017-12-13 22:33:58 +0000578 if (EmitDebugGlobalHashes)
579 emitTypeGlobalHashes();
580
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000581 clear();
582}
583
Brock Wyma19e17b32018-02-11 21:26:46 +0000584static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S,
585 unsigned MaxFixedRecordLength = 0xF00) {
Reid Klecknerbb96df62016-10-05 22:36:07 +0000586 // The maximum CV record length is 0xFF00. Most of the strings we emit appear
587 // after a fixed length portion of the record. The fixed length portion should
588 // always be less than 0xF00 (3840) bytes, so truncate the string so that the
589 // overall record size is less than the maximum allowed.
Reid Klecknerbb96df62016-10-05 22:36:07 +0000590 SmallString<32> NullTerminatedString(
591 S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
David Majnemerb9456a52016-03-14 05:15:09 +0000592 NullTerminatedString.push_back('\0');
593 OS.EmitBytes(NullTerminatedString);
594}
595
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000596void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000597 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000598 return;
599
Alexandre Ganead9e96742018-04-09 20:17:56 +0000600 // Start the .debug$T or .debug$P section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000601 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000602 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000603
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000604 SmallString<8> CommentPrefix;
605 if (OS.isVerboseAsm()) {
606 CommentPrefix += '\t';
607 CommentPrefix += Asm->MAI->getCommentString();
608 CommentPrefix += ' ';
609 }
610
Zachary Turner526f4f22017-05-19 19:26:58 +0000611 TypeTableCollection Table(TypeTable.records());
612 Optional<TypeIndex> B = Table.getFirst();
613 while (B) {
614 // This will fail if the record data is invalid.
615 CVType Record = Table.getType(*B);
616
Zachary Turner4efa0a42016-11-08 22:24:53 +0000617 if (OS.isVerboseAsm()) {
618 // Emit a block comment describing the type record for readability.
619 SmallString<512> CommentBlock;
620 raw_svector_ostream CommentOS(CommentBlock);
621 ScopedPrinter SP(CommentOS);
622 SP.setPrefix(CommentPrefix);
Zachary Turner526f4f22017-05-19 19:26:58 +0000623 TypeDumpVisitor TDV(Table, &SP, false);
624
625 Error E = codeview::visitTypeRecord(Record, *B, TDV);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000626 if (E) {
627 logAllUnhandledErrors(std::move(E), errs(), "error: ");
628 llvm_unreachable("produced malformed type record");
629 }
630 // emitRawComment will insert its own tab and comment string before
631 // the first line, so strip off our first one. It also prints its own
632 // newline.
633 OS.emitRawComment(
634 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
Zachary Turner4efa0a42016-11-08 22:24:53 +0000635 }
Zachary Turner526f4f22017-05-19 19:26:58 +0000636 OS.EmitBinaryData(Record.str_data());
637 B = Table.getNext(*B);
638 }
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000639}
640
Zachary Turner048f8f92017-12-13 22:33:58 +0000641void CodeViewDebug::emitTypeGlobalHashes() {
642 if (TypeTable.empty())
643 return;
644
645 // Start the .debug$H section with the version and hash algorithm, currently
646 // hardcoded to version 0, SHA1.
647 OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
648
649 OS.EmitValueToAlignment(4);
650 OS.AddComment("Magic");
651 OS.EmitIntValue(COFF::DEBUG_HASHES_SECTION_MAGIC, 4);
652 OS.AddComment("Section Version");
653 OS.EmitIntValue(0, 2);
654 OS.AddComment("Hash Algorithm");
Zachary Turnerc7626662018-05-17 22:55:15 +0000655 OS.EmitIntValue(uint16_t(GlobalTypeHashAlg::SHA1_8), 2);
Zachary Turner048f8f92017-12-13 22:33:58 +0000656
657 TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
658 for (const auto &GHR : TypeTable.hashes()) {
659 if (OS.isVerboseAsm()) {
660 // Emit an EOL-comment describing which TypeIndex this hash corresponds
661 // to, as well as the stringified SHA1 hash.
662 SmallString<32> Comment;
663 raw_svector_ostream CommentOS(Comment);
664 CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
665 OS.AddComment(Comment);
666 ++TI;
667 }
Zachary Turnerc7626662018-05-17 22:55:15 +0000668 assert(GHR.Hash.size() == 8);
Zachary Turner048f8f92017-12-13 22:33:58 +0000669 StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
670 GHR.Hash.size());
671 OS.EmitBinaryData(S);
672 }
673}
674
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000675static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
676 switch (DWLang) {
677 case dwarf::DW_LANG_C:
678 case dwarf::DW_LANG_C89:
679 case dwarf::DW_LANG_C99:
680 case dwarf::DW_LANG_C11:
681 case dwarf::DW_LANG_ObjC:
682 return SourceLanguage::C;
683 case dwarf::DW_LANG_C_plus_plus:
684 case dwarf::DW_LANG_C_plus_plus_03:
685 case dwarf::DW_LANG_C_plus_plus_11:
686 case dwarf::DW_LANG_C_plus_plus_14:
687 return SourceLanguage::Cpp;
688 case dwarf::DW_LANG_Fortran77:
689 case dwarf::DW_LANG_Fortran90:
690 case dwarf::DW_LANG_Fortran03:
691 case dwarf::DW_LANG_Fortran08:
692 return SourceLanguage::Fortran;
693 case dwarf::DW_LANG_Pascal83:
694 return SourceLanguage::Pascal;
695 case dwarf::DW_LANG_Cobol74:
696 case dwarf::DW_LANG_Cobol85:
697 return SourceLanguage::Cobol;
698 case dwarf::DW_LANG_Java:
699 return SourceLanguage::Java;
Reid Kleckner898ddf62017-07-24 16:16:42 +0000700 case dwarf::DW_LANG_D:
701 return SourceLanguage::D;
Nathan Lanzacc51dc62019-03-11 23:27:59 +0000702 case dwarf::DW_LANG_Swift:
703 return SourceLanguage::Swift;
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000704 default:
705 // There's no CodeView representation for this language, and CV doesn't
706 // have an "unknown" option for the language field, so we'll use MASM,
707 // as it's very low level.
708 return SourceLanguage::Masm;
709 }
710}
711
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000712namespace {
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000713struct Version {
714 int Part[4];
715};
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000716} // end anonymous namespace
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000717
718// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
719// the version number.
720static Version parseVersion(StringRef Name) {
Adrian McCarthyad8ac542016-09-20 17:42:13 +0000721 Version V = {{0}};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000722 int N = 0;
723 for (const char C : Name) {
724 if (isdigit(C)) {
725 V.Part[N] *= 10;
726 V.Part[N] += C - '0';
727 } else if (C == '.') {
728 ++N;
729 if (N >= 4)
730 return V;
731 } else if (N > 0)
732 return V;
733 }
734 return V;
735}
736
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000737void CodeViewDebug::emitCompilerInformation() {
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000738 MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_COMPILE3);
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000739 uint32_t Flags = 0;
740
741 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
742 const MDNode *Node = *CUs->operands().begin();
743 const auto *CU = cast<DICompileUnit>(Node);
744
745 // The low byte of the flags indicates the source language.
746 Flags = MapDWLangToCVLang(CU->getSourceLanguage());
747 // TODO: Figure out which other flags need to be set.
748
749 OS.AddComment("Flags and language");
750 OS.EmitIntValue(Flags, 4);
751
752 OS.AddComment("CPUType");
Reid Kleckner9ea2c012018-10-01 21:59:45 +0000753 OS.EmitIntValue(static_cast<uint64_t>(TheCPU), 2);
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000754
755 StringRef CompilerVersion = CU->getProducer();
756 Version FrontVer = parseVersion(CompilerVersion);
757 OS.AddComment("Frontend version");
758 for (int N = 0; N < 4; ++N)
759 OS.EmitIntValue(FrontVer.Part[N], 2);
760
761 // Some Microsoft tools, like Binscope, expect a backend version number of at
762 // least 8.something, so we'll coerce the LLVM version into a form that
763 // guarantees it'll be big enough without really lying about the version.
Adrian McCarthyd1185fc2016-09-29 20:28:25 +0000764 int Major = 1000 * LLVM_VERSION_MAJOR +
765 10 * LLVM_VERSION_MINOR +
766 LLVM_VERSION_PATCH;
767 // Clamp it for builds that use unusually large version numbers.
768 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
769 Version BackVer = {{ Major, 0, 0, 0 }};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000770 OS.AddComment("Backend version");
771 for (int N = 0; N < 4; ++N)
772 OS.EmitIntValue(BackVer.Part[N], 2);
773
774 OS.AddComment("Null-terminated compiler version string");
775 emitNullTerminatedSymbolName(OS, CompilerVersion);
776
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000777 endSymbolRecord(CompilerEnd);
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000778}
779
Reid Kleckner810687c2018-10-12 18:19:06 +0000780static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable,
781 StringRef S) {
782 StringIdRecord SIR(TypeIndex(0x0), S);
783 return TypeTable.writeLeafType(SIR);
784}
785
786void CodeViewDebug::emitBuildInfo() {
787 // First, make LF_BUILDINFO. It's a sequence of strings with various bits of
788 // build info. The known prefix is:
789 // - Absolute path of current directory
790 // - Compiler path
791 // - Main source file path, relative to CWD or absolute
792 // - Type server PDB file
793 // - Canonical compiler command line
794 // If frontend and backend compilation are separated (think llc or LTO), it's
795 // not clear if the compiler path should refer to the executable for the
796 // frontend or the backend. Leave it blank for now.
797 TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {};
798 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
799 const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs.
800 const auto *CU = cast<DICompileUnit>(Node);
801 const DIFile *MainSourceFile = CU->getFile();
802 BuildInfoArgs[BuildInfoRecord::CurrentDirectory] =
803 getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory());
804 BuildInfoArgs[BuildInfoRecord::SourceFile] =
805 getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename());
806 // FIXME: Path to compiler and command line. PDB is intentionally blank unless
807 // we implement /Zi type servers.
808 BuildInfoRecord BIR(BuildInfoArgs);
809 TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR);
810
811 // Make a new .debug$S subsection for the S_BUILDINFO record, which points
812 // from the module symbols into the type stream.
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000813 MCSymbol *BISubsecEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
814 MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO);
Reid Kleckner810687c2018-10-12 18:19:06 +0000815 OS.AddComment("LF_BUILDINFO index");
816 OS.EmitIntValue(BuildInfoIndex.getIndex(), 4);
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000817 endSymbolRecord(BIEnd);
818 endCVSubsection(BISubsecEnd);
Reid Kleckner810687c2018-10-12 18:19:06 +0000819}
820
Reid Kleckner5d122f82016-05-25 23:16:12 +0000821void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000822 if (InlinedSubprograms.empty())
823 return;
824
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000825 OS.AddComment("Inlinee lines subsection");
Zachary Turner8c099fe2017-05-30 16:36:15 +0000826 MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000827
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000828 // We emit the checksum info for files. This is used by debuggers to
829 // determine if a pdb matches the source before loading it. Visual Studio,
830 // for instance, will display a warning that the breakpoints are not valid if
831 // the pdb does not match the source.
David Majnemer30579ec2016-02-02 23:18:23 +0000832 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000833 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
834
835 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000836 assert(TypeIndices.count({SP, nullptr}));
837 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000838
David Majnemer30579ec2016-02-02 23:18:23 +0000839 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000840 unsigned FileId = maybeRecordFile(SP->getFile());
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000841 OS.AddComment("Inlined function " + SP->getName() + " starts at " +
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000842 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000843 OS.AddBlankLine();
David Majnemer30579ec2016-02-02 23:18:23 +0000844 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000845 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000846 OS.AddComment("Offset into filechecksum table");
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000847 OS.EmitCVFileChecksumOffsetDirective(FileId);
David Majnemer30579ec2016-02-02 23:18:23 +0000848 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000849 OS.EmitIntValue(SP->getLine(), 4);
850 }
851
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000852 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000853}
854
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000855void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
856 const DILocation *InlinedAt,
857 const InlineSite &Site) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000858 assert(TypeIndices.count({Site.Inlinee, nullptr}));
859 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000860
861 // SymbolRecord
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000862 MCSymbol *InlineEnd = beginSymbolRecord(SymbolKind::S_INLINESITE);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000863
Reid Klecknerdac21b42016-02-03 21:15:48 +0000864 OS.AddComment("PtrParent");
865 OS.EmitIntValue(0, 4);
866 OS.AddComment("PtrEnd");
867 OS.EmitIntValue(0, 4);
868 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000869 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000870
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000871 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
872 unsigned StartLineNum = Site.Inlinee->getLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000873
874 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000875 FI.Begin, FI.End);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000876
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000877 endSymbolRecord(InlineEnd);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000878
Reid Kleckner9ea2c012018-10-01 21:59:45 +0000879 emitLocalVariableList(FI, Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000880
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000881 // Recurse on child inlined call sites before closing the scope.
882 for (const DILocation *ChildSite : Site.ChildSites) {
883 auto I = FI.InlineSites.find(ChildSite);
884 assert(I != FI.InlineSites.end() &&
885 "child site not in function inline site map");
886 emitInlinedCallSite(FI, ChildSite, I->second);
887 }
888
889 // Close the scope.
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000890 emitEndSymbolRecord(SymbolKind::S_INLINESITE_END);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000891}
892
Reid Kleckner5d122f82016-05-25 23:16:12 +0000893void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
894 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
895 // comdat key. A section may be comdat because of -ffunction-sections or
896 // because it is comdat in the IR.
897 MCSectionCOFF *GVSec =
898 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
899 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
900
901 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
902 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
903 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
904
905 OS.SwitchSection(DebugSec);
906
907 // Emit the magic version number if this is the first time we've switched to
908 // this section.
909 if (ComdatDebugSections.insert(DebugSec).second)
910 emitCodeViewMagicVersion();
911}
912
Brock Wyma94ece8f2018-04-16 16:53:57 +0000913// Emit an S_THUNK32/S_END symbol pair for a thunk routine.
914// The only supported thunk ordinal is currently the standard type.
915void CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
916 FunctionInfo &FI,
917 const MCSymbol *Fn) {
918 std::string FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
919 const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
920
921 OS.AddComment("Symbol subsection for " + Twine(FuncName));
922 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
923
924 // Emit S_THUNK32
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000925 MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32);
Brock Wyma94ece8f2018-04-16 16:53:57 +0000926 OS.AddComment("PtrParent");
927 OS.EmitIntValue(0, 4);
928 OS.AddComment("PtrEnd");
929 OS.EmitIntValue(0, 4);
930 OS.AddComment("PtrNext");
931 OS.EmitIntValue(0, 4);
932 OS.AddComment("Thunk section relative address");
933 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
934 OS.AddComment("Thunk section index");
935 OS.EmitCOFFSectionIndex(Fn);
936 OS.AddComment("Code size");
937 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
938 OS.AddComment("Ordinal");
939 OS.EmitIntValue(unsigned(ordinal), 1);
940 OS.AddComment("Function name");
941 emitNullTerminatedSymbolName(OS, FuncName);
942 // Additional fields specific to the thunk ordinal would go here.
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000943 endSymbolRecord(ThunkRecordEnd);
Brock Wyma94ece8f2018-04-16 16:53:57 +0000944
945 // Local variables/inlined routines are purposely omitted here. The point of
946 // marking this as a thunk is so Visual Studio will NOT stop in this routine.
947
948 // Emit S_PROC_ID_END
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000949 emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
Brock Wyma94ece8f2018-04-16 16:53:57 +0000950
951 endCVSubsection(SymbolsEnd);
952}
953
Reid Kleckner2214ed82016-01-29 00:49:42 +0000954void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
955 FunctionInfo &FI) {
Brock Wyma31cc1eb2018-01-30 13:16:50 +0000956 // For each function there is a separate subsection which holds the PC to
957 // file:line table.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000958 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000959 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000960
Reid Kleckner5d122f82016-05-25 23:16:12 +0000961 // Switch to the to a comdat section, if appropriate.
962 switchToDebugSectionForSymbol(Fn);
963
Reid Klecknerac945e22016-06-17 16:11:20 +0000964 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000965 auto *SP = GV->getSubprogram();
David Majnemer67f684e2016-07-28 05:03:22 +0000966 assert(SP);
David Majnemer3128b102016-06-15 18:00:01 +0000967 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000968
Brock Wyma94ece8f2018-04-16 16:53:57 +0000969 if (SP->isThunk()) {
970 emitDebugInfoForThunk(GV, FI, Fn);
971 return;
972 }
973
Reid Klecknerac945e22016-06-17 16:11:20 +0000974 // If we have a display name, build the fully qualified name by walking the
975 // chain of scopes.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000976 if (!SP->getName().empty())
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000977 FuncName =
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000978 getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000979
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000980 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000981 if (FuncName.empty())
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +0000982 FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000983
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000984 // Emit FPO data, but only on 32-bit x86. No other platforms use it.
985 if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
986 OS.EmitCVFPOData(Fn);
987
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000988 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000989 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Zachary Turner8c099fe2017-05-30 16:36:15 +0000990 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000991 {
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000992 SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID
993 : SymbolKind::S_GPROC32_ID;
994 MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind);
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000995
David Majnemer30579ec2016-02-02 23:18:23 +0000996 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000997 OS.AddComment("PtrParent");
998 OS.EmitIntValue(0, 4);
999 OS.AddComment("PtrEnd");
1000 OS.EmitIntValue(0, 4);
1001 OS.AddComment("PtrNext");
1002 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001003 // This is the important bit that tells the debugger where the function
1004 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +00001005 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +00001006 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +00001007 OS.AddComment("Offset after prologue");
1008 OS.EmitIntValue(0, 4);
1009 OS.AddComment("Offset before epilogue");
1010 OS.EmitIntValue(0, 4);
1011 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +00001012 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +00001013 OS.AddComment("Function section relative address");
Keno Fischerf7d84ee2017-01-02 03:00:19 +00001014 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
Reid Klecknerdac21b42016-02-03 21:15:48 +00001015 OS.AddComment("Function section index");
1016 OS.EmitCOFFSectionIndex(Fn);
1017 OS.AddComment("Flags");
1018 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +00001019 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +00001020 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +00001021 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00001022 emitNullTerminatedSymbolName(OS, FuncName);
Reid Kleckner5bf71d12018-12-14 22:40:28 +00001023 endSymbolRecord(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001024
Reid Kleckner5bf71d12018-12-14 22:40:28 +00001025 MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC);
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001026 // Subtract out the CSR size since MSVC excludes that and we include it.
1027 OS.AddComment("FrameSize");
1028 OS.EmitIntValue(FI.FrameSize - FI.CSRSize, 4);
1029 OS.AddComment("Padding");
1030 OS.EmitIntValue(0, 4);
1031 OS.AddComment("Offset of padding");
1032 OS.EmitIntValue(0, 4);
1033 OS.AddComment("Bytes of callee saved registers");
1034 OS.EmitIntValue(FI.CSRSize, 4);
1035 OS.AddComment("Exception handler offset");
1036 OS.EmitIntValue(0, 4);
1037 OS.AddComment("Exception handler section");
1038 OS.EmitIntValue(0, 2);
1039 OS.AddComment("Flags (defines frame register)");
1040 OS.EmitIntValue(uint32_t(FI.FrameProcOpts), 4);
Reid Kleckner5bf71d12018-12-14 22:40:28 +00001041 endSymbolRecord(FrameProcEnd);
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001042
1043 emitLocalVariableList(FI, FI.Locals);
Brock Wymab17464e2018-12-20 17:33:45 +00001044 emitGlobalVariableList(FI.Globals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00001045 emitLexicalBlockList(FI.ChildBlocks, FI);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001046
Reid Klecknerf3b9ba42016-01-29 18:16:43 +00001047 // Emit inlined call site information. Only emit functions inlined directly
1048 // into the parent function. We'll emit the other sites recursively as part
1049 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001050 for (const DILocation *InlinedAt : FI.ChildSites) {
1051 auto I = FI.InlineSites.find(InlinedAt);
1052 assert(I != FI.InlineSites.end() &&
1053 "child site not in function inline site map");
1054 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +00001055 }
1056
Reid Klecknere33c94f2017-09-05 20:14:58 +00001057 for (auto Annot : FI.Annotations) {
1058 MCSymbol *Label = Annot.first;
1059 MDTuple *Strs = cast<MDTuple>(Annot.second);
Reid Kleckner5bf71d12018-12-14 22:40:28 +00001060 MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION);
Reid Klecknere33c94f2017-09-05 20:14:58 +00001061 OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
1062 // FIXME: Make sure we don't overflow the max record size.
1063 OS.EmitCOFFSectionIndex(Label);
1064 OS.EmitIntValue(Strs->getNumOperands(), 2);
1065 for (Metadata *MD : Strs->operands()) {
1066 // MDStrings are null terminated, so we can do EmitBytes and get the
1067 // nice .asciz directive.
1068 StringRef Str = cast<MDString>(MD)->getString();
1069 assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
1070 OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
1071 }
Reid Kleckner5bf71d12018-12-14 22:40:28 +00001072 endSymbolRecord(AnnotEnd);
Reid Klecknere33c94f2017-09-05 20:14:58 +00001073 }
1074
David Majnemer3128b102016-06-15 18:00:01 +00001075 if (SP != nullptr)
1076 emitDebugInfoForUDTs(LocalUDTs);
1077
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001078 // We're done with this function.
Reid Kleckner5bf71d12018-12-14 22:40:28 +00001079 emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001080 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001081 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001082
Reid Kleckner2214ed82016-01-29 00:49:42 +00001083 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +00001084 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001085}
1086
Reid Kleckner876330d2016-02-12 21:48:30 +00001087CodeViewDebug::LocalVarDefRange
1088CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
1089 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +00001090 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +00001091 DR.DataOffset = Offset;
1092 assert(DR.DataOffset == Offset && "truncation");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00001093 DR.IsSubfield = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +00001094 DR.StructOffset = 0;
1095 DR.CVRegister = CVRegister;
1096 return DR;
1097}
1098
Matthias Braunef331ef2016-11-30 23:48:50 +00001099void CodeViewDebug::collectVariableInfoFromMFTable(
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001100 DenseSet<InlinedEntity> &Processed) {
Matthias Braunef331ef2016-11-30 23:48:50 +00001101 const MachineFunction &MF = *Asm->MF;
1102 const TargetSubtargetInfo &TSI = MF.getSubtarget();
Reid Kleckner876330d2016-02-12 21:48:30 +00001103 const TargetFrameLowering *TFI = TSI.getFrameLowering();
1104 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1105
Matthias Braunef331ef2016-11-30 23:48:50 +00001106 for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001107 if (!VI.Var)
1108 continue;
1109 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1110 "Expected inlined-at fields to agree");
1111
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001112 Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001113 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1114
1115 // If variable scope is not found then skip this variable.
1116 if (!Scope)
1117 continue;
1118
Reid Klecknerb5fced72017-05-09 19:59:29 +00001119 // If the variable has an attached offset expression, extract it.
1120 // FIXME: Try to handle DW_OP_deref as well.
1121 int64_t ExprOffset = 0;
1122 if (VI.Expr)
1123 if (!VI.Expr->extractIfOffset(ExprOffset))
1124 continue;
1125
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001126 // Get the frame register used and the offset.
1127 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +00001128 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
1129 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001130
1131 // Calculate the label ranges.
Reid Klecknerb5fced72017-05-09 19:59:29 +00001132 LocalVarDefRange DefRange =
1133 createDefRangeMem(CVReg, FrameOffset + ExprOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001134 for (const InsnRange &Range : Scope->getRanges()) {
1135 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1136 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +00001137 End = End ? End : Asm->getFunctionEnd();
1138 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001139 }
1140
Reid Kleckner876330d2016-02-12 21:48:30 +00001141 LocalVariable Var;
1142 Var.DIVar = VI.Var;
1143 Var.DefRanges.emplace_back(std::move(DefRange));
Reid Kleckner5a791ee2018-03-15 21:24:04 +00001144 recordLocalVariable(std::move(Var), Scope);
Reid Kleckner876330d2016-02-12 21:48:30 +00001145 }
1146}
1147
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001148static bool canUseReferenceType(const DbgVariableLocation &Loc) {
1149 return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
1150}
1151
1152static bool needsReferenceType(const DbgVariableLocation &Loc) {
1153 return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
1154}
1155
Bob Haarman223303c2017-08-29 20:59:25 +00001156void CodeViewDebug::calculateRanges(
1157 LocalVariable &Var, const DbgValueHistoryMap::InstrRanges &Ranges) {
1158 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1159
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001160 // Calculate the definition ranges.
Bob Haarman223303c2017-08-29 20:59:25 +00001161 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1162 const InsnRange &Range = *I;
1163 const MachineInstr *DVInst = Range.first;
1164 assert(DVInst->isDebugValue() && "Invalid History entry");
1165 // FIXME: Find a way to represent constant variables, since they are
1166 // relatively common.
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001167 Optional<DbgVariableLocation> Location =
1168 DbgVariableLocation::extractFromMachineInstruction(*DVInst);
1169 if (!Location)
Bob Haarmana88bce12017-08-29 21:01:55 +00001170 continue;
Bob Haarman223303c2017-08-29 20:59:25 +00001171
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001172 // CodeView can only express variables in register and variables in memory
1173 // at a constant offset from a register. However, for variables passed
1174 // indirectly by pointer, it is common for that pointer to be spilled to a
1175 // stack location. For the special case of one offseted load followed by a
1176 // zero offset load (a pointer spilled to the stack), we change the type of
1177 // the local variable from a value type to a reference type. This tricks the
1178 // debugger into doing the load for us.
1179 if (Var.UseReferenceType) {
1180 // We're using a reference type. Drop the last zero offset load.
1181 if (canUseReferenceType(*Location))
1182 Location->LoadChain.pop_back();
1183 else
1184 continue;
1185 } else if (needsReferenceType(*Location)) {
1186 // This location can't be expressed without switching to a reference type.
1187 // Start over using that.
1188 Var.UseReferenceType = true;
Bob Haarman223303c2017-08-29 20:59:25 +00001189 Var.DefRanges.clear();
1190 calculateRanges(Var, Ranges);
1191 return;
1192 }
1193
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001194 // We can only handle a register or an offseted load of a register.
1195 if (Location->Register == 0 || Location->LoadChain.size() > 1)
Bob Haarman223303c2017-08-29 20:59:25 +00001196 continue;
Bob Haarman223303c2017-08-29 20:59:25 +00001197 {
1198 LocalVarDefRange DR;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001199 DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001200 DR.InMemory = !Location->LoadChain.empty();
1201 DR.DataOffset =
1202 !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001203 if (Location->FragmentInfo) {
Bob Haarman223303c2017-08-29 20:59:25 +00001204 DR.IsSubfield = true;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001205 DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
Bob Haarman223303c2017-08-29 20:59:25 +00001206 } else {
1207 DR.IsSubfield = false;
1208 DR.StructOffset = 0;
1209 }
1210
1211 if (Var.DefRanges.empty() ||
1212 Var.DefRanges.back().isDifferentLocation(DR)) {
1213 Var.DefRanges.emplace_back(std::move(DR));
1214 }
1215 }
1216
1217 // Compute the label range.
1218 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1219 const MCSymbol *End = getLabelAfterInsn(Range.second);
1220 if (!End) {
1221 // This range is valid until the next overlapping bitpiece. In the
1222 // common case, ranges will not be bitpieces, so they will overlap.
1223 auto J = std::next(I);
1224 const DIExpression *DIExpr = DVInst->getDebugExpression();
1225 while (J != E &&
Bjorn Petterssona223f8152018-03-12 18:02:39 +00001226 !DIExpr->fragmentsOverlap(J->first->getDebugExpression()))
Bob Haarman223303c2017-08-29 20:59:25 +00001227 ++J;
1228 if (J != E)
1229 End = getLabelBeforeInsn(J->first);
1230 else
1231 End = Asm->getFunctionEnd();
1232 }
1233
1234 // If the last range end is our begin, just extend the last range.
1235 // Otherwise make a new range.
1236 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1237 Var.DefRanges.back().Ranges;
1238 if (!R.empty() && R.back().second == Begin)
1239 R.back().second = End;
1240 else
1241 R.emplace_back(Begin, End);
1242
1243 // FIXME: Do more range combining.
1244 }
1245}
1246
Reid Kleckner876330d2016-02-12 21:48:30 +00001247void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001248 DenseSet<InlinedEntity> Processed;
Reid Kleckner876330d2016-02-12 21:48:30 +00001249 // Grab the variable info that was squirreled away in the MMI side-table.
Matthias Braunef331ef2016-11-30 23:48:50 +00001250 collectVariableInfoFromMFTable(Processed);
Reid Kleckner876330d2016-02-12 21:48:30 +00001251
Reid Kleckner876330d2016-02-12 21:48:30 +00001252 for (const auto &I : DbgValues) {
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001253 InlinedEntity IV = I.first;
Reid Kleckner876330d2016-02-12 21:48:30 +00001254 if (Processed.count(IV))
1255 continue;
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001256 const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
Reid Kleckner876330d2016-02-12 21:48:30 +00001257 const DILocation *InlinedAt = IV.second;
1258
1259 // Instruction ranges, specifying where IV is accessible.
1260 const auto &Ranges = I.second;
1261
1262 LexicalScope *Scope = nullptr;
1263 if (InlinedAt)
1264 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1265 else
1266 Scope = LScopes.findLexicalScope(DIVar->getScope());
1267 // If variable scope is not found then skip this variable.
1268 if (!Scope)
1269 continue;
1270
1271 LocalVariable Var;
1272 Var.DIVar = DIVar;
1273
Bob Haarman223303c2017-08-29 20:59:25 +00001274 calculateRanges(Var, Ranges);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00001275 recordLocalVariable(std::move(Var), Scope);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001276 }
1277}
1278
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001279void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001280 const TargetSubtargetInfo &TSI = MF->getSubtarget();
1281 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1282 const MachineFrameInfo &MFI = MF->getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00001283 const Function &GV = MF->getFunction();
Reid Kleckner55baeef2018-03-15 21:12:21 +00001284 auto Insertion = FnDebugInfo.insert({&GV, llvm::make_unique<FunctionInfo>()});
Reid Klecknere9dc30d2018-03-15 21:18:42 +00001285 assert(Insertion.second && "function already has info");
Reid Kleckner55baeef2018-03-15 21:12:21 +00001286 CurFn = Insertion.first->second.get();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001287 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +00001288 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001289
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001290 // The S_FRAMEPROC record reports the stack size, and how many bytes of
1291 // callee-saved registers were used. For targets that don't use a PUSH
1292 // instruction (AArch64), this will be zero.
1293 CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
1294 CurFn->FrameSize = MFI.getStackSize();
Reid Kleckner2bcb2882018-11-03 00:41:52 +00001295 CurFn->OffsetAdjustment = MFI.getOffsetAdjustment();
Reid Klecknerd5e4ec72018-10-02 16:43:52 +00001296 CurFn->HasStackRealignment = TRI->needsStackRealignment(*MF);
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001297
1298 // For this function S_FRAMEPROC record, figure out which codeview register
1299 // will be the frame pointer.
1300 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
1301 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
1302 if (CurFn->FrameSize > 0) {
1303 if (!TSI.getFrameLowering()->hasFP(*MF)) {
1304 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1305 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
1306 } else {
1307 // If there is an FP, parameters are always relative to it.
1308 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
Reid Klecknerd5e4ec72018-10-02 16:43:52 +00001309 if (CurFn->HasStackRealignment) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001310 // If the stack needs realignment, locals are relative to SP or VFRAME.
1311 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1312 } else {
1313 // Otherwise, locals are relative to EBP, and we probably have VLAs or
1314 // other stack adjustments.
1315 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
1316 }
1317 }
1318 }
1319
1320 // Compute other frame procedure options.
1321 FrameProcedureOptions FPO = FrameProcedureOptions::None;
1322 if (MFI.hasVarSizedObjects())
1323 FPO |= FrameProcedureOptions::HasAlloca;
1324 if (MF->exposesReturnsTwice())
1325 FPO |= FrameProcedureOptions::HasSetJmp;
1326 // FIXME: Set HasLongJmp if we ever track that info.
1327 if (MF->hasInlineAsm())
1328 FPO |= FrameProcedureOptions::HasInlineAssembly;
1329 if (GV.hasPersonalityFn()) {
1330 if (isAsynchronousEHPersonality(
1331 classifyEHPersonality(GV.getPersonalityFn())))
1332 FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
1333 else
1334 FPO |= FrameProcedureOptions::HasExceptionHandling;
1335 }
1336 if (GV.hasFnAttribute(Attribute::InlineHint))
1337 FPO |= FrameProcedureOptions::MarkedInline;
1338 if (GV.hasFnAttribute(Attribute::Naked))
1339 FPO |= FrameProcedureOptions::Naked;
1340 if (MFI.hasStackProtectorIndex())
1341 FPO |= FrameProcedureOptions::SecurityChecks;
1342 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
1343 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
Evandro Menezes7c711cc2019-04-03 21:27:03 +00001344 if (Asm->TM.getOptLevel() != CodeGenOpt::None &&
Evandro Menezes85bd3972019-04-04 22:40:06 +00001345 !GV.hasOptSize() && !GV.hasOptNone())
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001346 FPO |= FrameProcedureOptions::OptimizedForSpeed;
1347 // FIXME: Set GuardCfg when it is implemented.
1348 CurFn->FrameProcOpts = FPO;
1349
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001350 OS.EmitCVFuncIdDirective(CurFn->FuncId);
1351
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001352 // Find the end of the function prolog. First known non-DBG_VALUE and
1353 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001354 // FIXME: is there a simpler a way to do this? Can we just search
1355 // for the first instruction of the function, not the last of the prolog?
1356 DebugLoc PrologEndLoc;
1357 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001358 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001359 for (const auto &MI : MBB) {
Adrian Prantlfb31da12017-05-22 20:47:09 +00001360 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001361 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001362 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001363 break;
Adrian Prantlfb31da12017-05-22 20:47:09 +00001364 } else if (!MI.isMetaInstruction()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001365 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001366 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001367 }
1368 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001369
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001370 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001371 if (PrologEndLoc && !EmptyPrologue) {
1372 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001373 maybeRecordLocation(FnStartDL, MF);
1374 }
1375}
1376
Zachary Turnera7b04172017-08-28 18:49:04 +00001377static bool shouldEmitUdt(const DIType *T) {
Zachary Turner37c74742017-09-05 22:06:39 +00001378 if (!T)
1379 return false;
1380
1381 // MSVC does not emit UDTs for typedefs that are scoped to classes.
1382 if (T->getTag() == dwarf::DW_TAG_typedef) {
1383 if (DIScope *Scope = T->getScope().resolve()) {
1384 switch (Scope->getTag()) {
1385 case dwarf::DW_TAG_structure_type:
1386 case dwarf::DW_TAG_class_type:
1387 case dwarf::DW_TAG_union_type:
1388 return false;
1389 }
1390 }
1391 }
1392
Zachary Turnera7b04172017-08-28 18:49:04 +00001393 while (true) {
1394 if (!T || T->isForwardDecl())
1395 return false;
1396
1397 const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
1398 if (!DT)
1399 return true;
1400 T = DT->getBaseType().resolve();
1401 }
1402 return true;
1403}
1404
1405void CodeViewDebug::addToUDTs(const DIType *Ty) {
Reid Klecknerad56ea32016-07-01 22:24:51 +00001406 // Don't record empty UDTs.
1407 if (Ty->getName().empty())
1408 return;
Zachary Turnera7b04172017-08-28 18:49:04 +00001409 if (!shouldEmitUdt(Ty))
1410 return;
Reid Klecknerad56ea32016-07-01 22:24:51 +00001411
Hans Wennborg4b63a982016-06-23 22:57:25 +00001412 SmallVector<StringRef, 5> QualifiedNameComponents;
1413 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1414 Ty->getScope().resolve(), QualifiedNameComponents);
1415
1416 std::string FullyQualifiedName =
David Majnemer6bdc24e2016-07-01 23:12:45 +00001417 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
Hans Wennborg4b63a982016-06-23 22:57:25 +00001418
Zachary Turnera7b04172017-08-28 18:49:04 +00001419 if (ClosestSubprogram == nullptr) {
1420 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1421 } else if (ClosestSubprogram == CurrentSubprogram) {
1422 LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1423 }
Hans Wennborg4b63a982016-06-23 22:57:25 +00001424
1425 // TODO: What if the ClosestSubprogram is neither null or the current
1426 // subprogram? Currently, the UDT just gets dropped on the floor.
1427 //
1428 // The current behavior is not desirable. To get maximal fidelity, we would
1429 // need to perform all type translation before beginning emission of .debug$S
1430 // and then make LocalUDTs a member of FunctionInfo
1431}
1432
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001433TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001434 // Generic dispatch for lowering an unknown type.
1435 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001436 case dwarf::DW_TAG_array_type:
1437 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +00001438 case dwarf::DW_TAG_typedef:
1439 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001440 case dwarf::DW_TAG_base_type:
1441 return lowerTypeBasic(cast<DIBasicType>(Ty));
1442 case dwarf::DW_TAG_pointer_type:
Reid Kleckner9dac4732016-08-31 15:59:30 +00001443 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1444 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1445 LLVM_FALLTHROUGH;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001446 case dwarf::DW_TAG_reference_type:
1447 case dwarf::DW_TAG_rvalue_reference_type:
1448 return lowerTypePointer(cast<DIDerivedType>(Ty));
1449 case dwarf::DW_TAG_ptr_to_member_type:
1450 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
Reid Kleckner3acdc672018-02-27 22:08:15 +00001451 case dwarf::DW_TAG_restrict_type:
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001452 case dwarf::DW_TAG_const_type:
1453 case dwarf::DW_TAG_volatile_type:
Victor Leschuke1156c22016-10-31 19:09:38 +00001454 // TODO: add support for DW_TAG_atomic_type here
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001455 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +00001456 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001457 if (ClassTy) {
1458 // The member function type of a member function pointer has no
1459 // ThisAdjustment.
1460 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001461 /*ThisAdjustment=*/0,
1462 /*IsStaticMethod=*/false);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001463 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001464 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +00001465 case dwarf::DW_TAG_enumeration_type:
1466 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +00001467 case dwarf::DW_TAG_class_type:
1468 case dwarf::DW_TAG_structure_type:
1469 return lowerTypeClass(cast<DICompositeType>(Ty));
1470 case dwarf::DW_TAG_union_type:
1471 return lowerTypeUnion(cast<DICompositeType>(Ty));
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001472 case dwarf::DW_TAG_unspecified_type:
Zachary Turner56a5a0c2018-11-01 04:02:41 +00001473 if (Ty->getName() == "decltype(nullptr)")
1474 return TypeIndex::NullptrT();
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001475 return TypeIndex::None();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001476 default:
1477 // Use the null type index.
1478 return TypeIndex();
1479 }
1480}
1481
David Majnemerd065e232016-06-02 06:21:37 +00001482TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +00001483 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1484 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +00001485 StringRef TypeName = Ty->getName();
1486
Zachary Turnera7b04172017-08-28 18:49:04 +00001487 addToUDTs(Ty);
David Majnemer3128b102016-06-15 18:00:01 +00001488
David Majnemerd065e232016-06-02 06:21:37 +00001489 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +00001490 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +00001491 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +00001492 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +00001493 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +00001494 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001495
David Majnemerd065e232016-06-02 06:21:37 +00001496 return UnderlyingTypeIndex;
1497}
1498
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001499TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1500 DITypeRef ElementTypeRef = Ty->getBaseType();
1501 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1502 // IndexType is size_t, which depends on the bitness of the target.
Matt Arsenault41e5ac42018-03-14 00:36:23 +00001503 TypeIndex IndexType = getPointerSizeInBytes() == 8
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001504 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1505 : TypeIndex(SimpleTypeKind::UInt32Long);
Amjad Aboudacee5682016-07-12 12:06:34 +00001506
1507 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1508
Amjad Aboudacee5682016-07-12 12:06:34 +00001509 // Add subranges to array type.
1510 DINodeArray Elements = Ty->getElements();
1511 for (int i = Elements.size() - 1; i >= 0; --i) {
1512 const DINode *Element = Elements[i];
1513 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1514
1515 const DISubrange *Subrange = cast<DISubrange>(Element);
1516 assert(Subrange->getLowerBound() == 0 &&
1517 "codeview doesn't support subranges with lower bounds");
Sander de Smalenfdf40912018-01-24 09:56:07 +00001518 int64_t Count = -1;
1519 if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>())
1520 Count = CI->getSExtValue();
Amjad Aboudacee5682016-07-12 12:06:34 +00001521
Reid Klecknercd7bba02017-09-13 23:30:01 +00001522 // Forward declarations of arrays without a size and VLAs use a count of -1.
1523 // Emit a count of zero in these cases to match what MSVC does for arrays
1524 // without a size. MSVC doesn't support VLAs, so it's not clear what we
1525 // should do for them even if we could distinguish them.
Reid Kleckner6b78e162017-03-24 23:28:42 +00001526 if (Count == -1)
Reid Kleckner89af1122017-09-13 21:54:20 +00001527 Count = 0;
Amjad Aboudacee5682016-07-12 12:06:34 +00001528
Amjad Aboudacee5682016-07-12 12:06:34 +00001529 // Update the element size and element type index for subsequent subranges.
1530 ElementSize *= Count;
Reid Kleckner10762882016-09-09 17:29:36 +00001531
1532 // If this is the outermost array, use the size from the array. It will be
Reid Kleckner6b78e162017-03-24 23:28:42 +00001533 // more accurate if we had a VLA or an incomplete element type size.
Reid Kleckner10762882016-09-09 17:29:36 +00001534 uint64_t ArraySize =
1535 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1536
1537 StringRef Name = (i == 0) ? Ty->getName() : "";
Zachary Turner4efa0a42016-11-08 22:24:53 +00001538 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
Zachary Turner6900de12017-11-28 18:33:17 +00001539 ElementTypeIndex = TypeTable.writeLeafType(AR);
Amjad Aboudacee5682016-07-12 12:06:34 +00001540 }
1541
Amjad Aboudacee5682016-07-12 12:06:34 +00001542 return ElementTypeIndex;
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001543}
1544
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001545TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1546 TypeIndex Index;
1547 dwarf::TypeKind Kind;
1548 uint32_t ByteSize;
1549
1550 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +00001551 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001552
1553 SimpleTypeKind STK = SimpleTypeKind::None;
1554 switch (Kind) {
1555 case dwarf::DW_ATE_address:
1556 // FIXME: Translate
1557 break;
1558 case dwarf::DW_ATE_boolean:
1559 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001560 case 1: STK = SimpleTypeKind::Boolean8; break;
1561 case 2: STK = SimpleTypeKind::Boolean16; break;
1562 case 4: STK = SimpleTypeKind::Boolean32; break;
1563 case 8: STK = SimpleTypeKind::Boolean64; break;
1564 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001565 }
1566 break;
1567 case dwarf::DW_ATE_complex_float:
1568 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001569 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001570 case 4: STK = SimpleTypeKind::Complex32; break;
1571 case 8: STK = SimpleTypeKind::Complex64; break;
1572 case 10: STK = SimpleTypeKind::Complex80; break;
1573 case 16: STK = SimpleTypeKind::Complex128; break;
1574 }
1575 break;
1576 case dwarf::DW_ATE_float:
1577 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001578 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001579 case 4: STK = SimpleTypeKind::Float32; break;
1580 case 6: STK = SimpleTypeKind::Float48; break;
1581 case 8: STK = SimpleTypeKind::Float64; break;
1582 case 10: STK = SimpleTypeKind::Float80; break;
1583 case 16: STK = SimpleTypeKind::Float128; break;
1584 }
1585 break;
1586 case dwarf::DW_ATE_signed:
1587 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001588 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1589 case 2: STK = SimpleTypeKind::Int16Short; break;
1590 case 4: STK = SimpleTypeKind::Int32; break;
1591 case 8: STK = SimpleTypeKind::Int64Quad; break;
1592 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001593 }
1594 break;
1595 case dwarf::DW_ATE_unsigned:
1596 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001597 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1598 case 2: STK = SimpleTypeKind::UInt16Short; break;
1599 case 4: STK = SimpleTypeKind::UInt32; break;
1600 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1601 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001602 }
1603 break;
1604 case dwarf::DW_ATE_UTF:
1605 switch (ByteSize) {
1606 case 2: STK = SimpleTypeKind::Character16; break;
1607 case 4: STK = SimpleTypeKind::Character32; break;
1608 }
1609 break;
1610 case dwarf::DW_ATE_signed_char:
1611 if (ByteSize == 1)
1612 STK = SimpleTypeKind::SignedCharacter;
1613 break;
1614 case dwarf::DW_ATE_unsigned_char:
1615 if (ByteSize == 1)
1616 STK = SimpleTypeKind::UnsignedCharacter;
1617 break;
1618 default:
1619 break;
1620 }
1621
1622 // Apply some fixups based on the source-level type name.
1623 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1624 STK = SimpleTypeKind::Int32Long;
1625 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1626 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001627 if (STK == SimpleTypeKind::UInt16Short &&
1628 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001629 STK = SimpleTypeKind::WideCharacter;
1630 if ((STK == SimpleTypeKind::SignedCharacter ||
1631 STK == SimpleTypeKind::UnsignedCharacter) &&
1632 Ty->getName() == "char")
1633 STK = SimpleTypeKind::NarrowCharacter;
1634
1635 return TypeIndex(STK);
1636}
1637
Reid Kleckner3acdc672018-02-27 22:08:15 +00001638TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
1639 PointerOptions PO) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001640 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1641
Reid Kleckner3acdc672018-02-27 22:08:15 +00001642 // Pointers to simple types without any options can use SimpleTypeMode, rather
1643 // than having a dedicated pointer type record.
1644 if (PointeeTI.isSimple() && PO == PointerOptions::None &&
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001645 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1646 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1647 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1648 ? SimpleTypeMode::NearPointer64
1649 : SimpleTypeMode::NearPointer32;
1650 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1651 }
1652
1653 PointerKind PK =
1654 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1655 PointerMode PM = PointerMode::Pointer;
1656 switch (Ty->getTag()) {
1657 default: llvm_unreachable("not a pointer tag type");
1658 case dwarf::DW_TAG_pointer_type:
1659 PM = PointerMode::Pointer;
1660 break;
1661 case dwarf::DW_TAG_reference_type:
1662 PM = PointerMode::LValueReference;
1663 break;
1664 case dwarf::DW_TAG_rvalue_reference_type:
1665 PM = PointerMode::RValueReference;
1666 break;
1667 }
Reid Kleckner3acdc672018-02-27 22:08:15 +00001668
Zachary Turner38265662018-11-20 22:13:23 +00001669 if (Ty->isObjectPointer())
1670 PO |= PointerOptions::Const;
1671
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001672 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00001673 return TypeTable.writeLeafType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001674}
1675
Reid Kleckner6fa15462016-06-17 22:14:39 +00001676static PointerToMemberRepresentation
1677translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1678 // SizeInBytes being zero generally implies that the member pointer type was
1679 // incomplete, which can happen if it is part of a function prototype. In this
1680 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001681 if (IsPMF) {
1682 switch (Flags & DINode::FlagPtrToMemberRep) {
1683 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001684 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1685 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001686 case DINode::FlagSingleInheritance:
1687 return PointerToMemberRepresentation::SingleInheritanceFunction;
1688 case DINode::FlagMultipleInheritance:
1689 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1690 case DINode::FlagVirtualInheritance:
1691 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1692 }
1693 } else {
1694 switch (Flags & DINode::FlagPtrToMemberRep) {
1695 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001696 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1697 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001698 case DINode::FlagSingleInheritance:
1699 return PointerToMemberRepresentation::SingleInheritanceData;
1700 case DINode::FlagMultipleInheritance:
1701 return PointerToMemberRepresentation::MultipleInheritanceData;
1702 case DINode::FlagVirtualInheritance:
1703 return PointerToMemberRepresentation::VirtualInheritanceData;
1704 }
1705 }
1706 llvm_unreachable("invalid ptr to member representation");
1707}
1708
Reid Kleckner3acdc672018-02-27 22:08:15 +00001709TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
1710 PointerOptions PO) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001711 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1712 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001713 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Matt Arsenault41e5ac42018-03-14 00:36:23 +00001714 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1715 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001716 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1717 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1718 : PointerMode::PointerToDataMember;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001719
Reid Kleckner6fa15462016-06-17 22:14:39 +00001720 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1721 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1722 MemberPointerInfo MPI(
1723 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001724 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Zachary Turner6900de12017-11-28 18:33:17 +00001725 return TypeTable.writeLeafType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001726}
1727
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001728/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1729/// have a translation, use the NearC convention.
1730static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1731 switch (DwarfCC) {
1732 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1733 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1734 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1735 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1736 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1737 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1738 }
1739 return CallingConvention::NearC;
1740}
1741
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001742TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1743 ModifierOptions Mods = ModifierOptions::None;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001744 PointerOptions PO = PointerOptions::None;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001745 bool IsModifier = true;
1746 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001747 while (IsModifier && BaseTy) {
Victor Leschuke1156c22016-10-31 19:09:38 +00001748 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001749 switch (BaseTy->getTag()) {
1750 case dwarf::DW_TAG_const_type:
1751 Mods |= ModifierOptions::Const;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001752 PO |= PointerOptions::Const;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001753 break;
1754 case dwarf::DW_TAG_volatile_type:
1755 Mods |= ModifierOptions::Volatile;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001756 PO |= PointerOptions::Volatile;
1757 break;
1758 case dwarf::DW_TAG_restrict_type:
1759 // Only pointer types be marked with __restrict. There is no known flag
1760 // for __restrict in LF_MODIFIER records.
1761 PO |= PointerOptions::Restrict;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001762 break;
1763 default:
1764 IsModifier = false;
1765 break;
1766 }
1767 if (IsModifier)
1768 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1769 }
Reid Kleckner3acdc672018-02-27 22:08:15 +00001770
1771 // Check if the inner type will use an LF_POINTER record. If so, the
1772 // qualifiers will go in the LF_POINTER record. This comes up for types like
1773 // 'int *const' and 'int *__restrict', not the more common cases like 'const
1774 // char *'.
1775 if (BaseTy) {
1776 switch (BaseTy->getTag()) {
1777 case dwarf::DW_TAG_pointer_type:
1778 case dwarf::DW_TAG_reference_type:
1779 case dwarf::DW_TAG_rvalue_reference_type:
1780 return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
1781 case dwarf::DW_TAG_ptr_to_member_type:
1782 return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
1783 default:
1784 break;
1785 }
1786 }
1787
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001788 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Reid Kleckner3acdc672018-02-27 22:08:15 +00001789
1790 // Return the base type index if there aren't any modifiers. For example, the
1791 // metadata could contain restrict wrappers around non-pointer types.
1792 if (Mods == ModifierOptions::None)
1793 return ModifiedTI;
1794
Zachary Turner4efa0a42016-11-08 22:24:53 +00001795 ModifierRecord MR(ModifiedTI, Mods);
Zachary Turner6900de12017-11-28 18:33:17 +00001796 return TypeTable.writeLeafType(MR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001797}
1798
David Majnemer75c3ebf2016-06-02 17:13:53 +00001799TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1800 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1801 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1802 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1803
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001804 // MSVC uses type none for variadic argument.
1805 if (ReturnAndArgTypeIndices.size() > 1 &&
1806 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1807 ReturnAndArgTypeIndices.back() = TypeIndex::None();
1808 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001809 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1810 ArrayRef<TypeIndex> ArgTypeIndices = None;
1811 if (!ReturnAndArgTypeIndices.empty()) {
1812 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1813 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1814 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1815 }
1816
1817 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner6900de12017-11-28 18:33:17 +00001818 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001819
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001820 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1821
Aaron Smith802b0332018-10-02 20:21:05 +00001822 FunctionOptions FO = getFunctionOptions(Ty);
1823 ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
1824 ArgListIndex);
Zachary Turner6900de12017-11-28 18:33:17 +00001825 return TypeTable.writeLeafType(Procedure);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001826}
1827
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001828TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001829 const DIType *ClassTy,
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001830 int ThisAdjustment,
Aaron Smith802b0332018-10-02 20:21:05 +00001831 bool IsStaticMethod,
1832 FunctionOptions FO) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001833 // Lower the containing class type.
1834 TypeIndex ClassType = getTypeIndex(ClassTy);
1835
Zachary Turnerc68f8952018-11-20 22:13:43 +00001836 DITypeRefArray ReturnAndArgs = Ty->getTypeArray();
1837
1838 unsigned Index = 0;
1839 SmallVector<TypeIndex, 8> ArgTypeIndices;
Josh Stone7a3108f2019-01-23 00:53:22 +00001840 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1841 if (ReturnAndArgs.size() > Index) {
1842 ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]);
1843 }
Zachary Turnerc68f8952018-11-20 22:13:43 +00001844
Reid Klecknerc168c6f2018-12-26 21:52:17 +00001845 // If the first argument is a pointer type and this isn't a static method,
1846 // treat it as the special 'this' parameter, which is encoded separately from
1847 // the arguments.
Zachary Turnerc68f8952018-11-20 22:13:43 +00001848 TypeIndex ThisTypeIndex;
Reid Klecknerc168c6f2018-12-26 21:52:17 +00001849 if (!IsStaticMethod && ReturnAndArgs.size() > Index) {
1850 if (const DIDerivedType *PtrTy =
1851 dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index].resolve())) {
1852 if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) {
1853 ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty);
1854 Index++;
1855 }
1856 }
1857 }
Zachary Turnerc68f8952018-11-20 22:13:43 +00001858
1859 while (Index < ReturnAndArgs.size())
1860 ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++]));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001861
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001862 // MSVC uses type none for variadic argument.
Zachary Turnerc68f8952018-11-20 22:13:43 +00001863 if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void())
1864 ArgTypeIndices.back() = TypeIndex::None();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001865
1866 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner6900de12017-11-28 18:33:17 +00001867 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001868
1869 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1870
Aaron Smith802b0332018-10-02 20:21:05 +00001871 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
1872 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
Zachary Turner6900de12017-11-28 18:33:17 +00001873 return TypeTable.writeLeafType(MFR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001874}
1875
Reid Kleckner9dac4732016-08-31 15:59:30 +00001876TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001877 unsigned VSlotCount =
1878 Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
Reid Kleckner9dac4732016-08-31 15:59:30 +00001879 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001880
1881 VFTableShapeRecord VFTSR(Slots);
Zachary Turner6900de12017-11-28 18:33:17 +00001882 return TypeTable.writeLeafType(VFTSR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001883}
1884
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001885static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1886 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001887 case DINode::FlagPrivate: return MemberAccess::Private;
1888 case DINode::FlagPublic: return MemberAccess::Public;
1889 case DINode::FlagProtected: return MemberAccess::Protected;
1890 case 0:
1891 // If there was no explicit access control, provide the default for the tag.
1892 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1893 : MemberAccess::Public;
1894 }
1895 llvm_unreachable("access flags are exclusive");
1896}
1897
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001898static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1899 if (SP->isArtificial())
1900 return MethodOptions::CompilerGenerated;
1901
1902 // FIXME: Handle other MethodOptions.
1903
1904 return MethodOptions::None;
1905}
1906
1907static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1908 bool Introduced) {
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001909 if (SP->getFlags() & DINode::FlagStaticMember)
1910 return MethodKind::Static;
1911
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001912 switch (SP->getVirtuality()) {
1913 case dwarf::DW_VIRTUALITY_none:
1914 break;
1915 case dwarf::DW_VIRTUALITY_virtual:
1916 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1917 case dwarf::DW_VIRTUALITY_pure_virtual:
1918 return Introduced ? MethodKind::PureIntroducingVirtual
1919 : MethodKind::PureVirtual;
1920 default:
1921 llvm_unreachable("unhandled virtuality case");
1922 }
1923
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001924 return MethodKind::Vanilla;
1925}
1926
Reid Klecknera8d57402016-06-03 15:58:20 +00001927static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1928 switch (Ty->getTag()) {
1929 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1930 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1931 }
1932 llvm_unreachable("unexpected tag");
1933}
1934
Reid Klecknere092dad2016-07-02 00:11:07 +00001935/// Return ClassOptions that should be present on both the forward declaration
1936/// and the defintion of a tag type.
1937static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1938 ClassOptions CO = ClassOptions::None;
1939
1940 // MSVC always sets this flag, even for local types. Clang doesn't always
Reid Klecknera8d57402016-06-03 15:58:20 +00001941 // appear to give every type a linkage name, which may be problematic for us.
1942 // FIXME: Investigate the consequences of not following them here.
Reid Klecknere092dad2016-07-02 00:11:07 +00001943 if (!Ty->getIdentifier().empty())
1944 CO |= ClassOptions::HasUniqueName;
1945
1946 // Put the Nested flag on a type if it appears immediately inside a tag type.
1947 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1948 // here. That flag is only set on definitions, and not forward declarations.
1949 const DIScope *ImmediateScope = Ty->getScope().resolve();
1950 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1951 CO |= ClassOptions::Nested;
1952
Aaron Smithda0602c2018-10-02 20:28:15 +00001953 // Put the Scoped flag on function-local types. MSVC puts this flag for enum
Zachary Turnerc68f8952018-11-20 22:13:43 +00001954 // type only when it has an immediate function scope. Clang never puts enums
1955 // inside DILexicalBlock scopes. Enum types, as generated by clang, are
Aaron Smithda0602c2018-10-02 20:28:15 +00001956 // always in function, class, or file scopes.
1957 if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
1958 if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
Reid Klecknere092dad2016-07-02 00:11:07 +00001959 CO |= ClassOptions::Scoped;
Aaron Smithda0602c2018-10-02 20:28:15 +00001960 } else {
1961 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1962 Scope = Scope->getScope().resolve()) {
1963 if (isa<DISubprogram>(Scope)) {
1964 CO |= ClassOptions::Scoped;
1965 break;
1966 }
Reid Klecknere092dad2016-07-02 00:11:07 +00001967 }
1968 }
1969
1970 return CO;
Reid Klecknera8d57402016-06-03 15:58:20 +00001971}
1972
Aaron Smith122d9e72018-03-06 18:20:22 +00001973void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
1974 switch (Ty->getTag()) {
1975 case dwarf::DW_TAG_class_type:
1976 case dwarf::DW_TAG_structure_type:
1977 case dwarf::DW_TAG_union_type:
1978 case dwarf::DW_TAG_enumeration_type:
1979 break;
1980 default:
1981 return;
1982 }
1983
1984 if (const auto *File = Ty->getFile()) {
1985 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
1986 TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
1987
1988 UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
1989 TypeTable.writeLeafType(USLR);
1990 }
1991}
1992
David Majnemer979cb882016-06-16 21:32:16 +00001993TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
Reid Klecknere092dad2016-07-02 00:11:07 +00001994 ClassOptions CO = getCommonClassOptions(Ty);
David Majnemer979cb882016-06-16 21:32:16 +00001995 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001996 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001997
David Majnemerda9548f2016-06-17 16:13:21 +00001998 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001999 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00002000 } else {
Zachary Turner6900de12017-11-28 18:33:17 +00002001 ContinuationRecordBuilder ContinuationBuilder;
2002 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
David Majnemerda9548f2016-06-17 16:13:21 +00002003 for (const DINode *Element : Ty->getElements()) {
2004 // We assume that the frontend provides all members in source declaration
2005 // order, which is what MSVC does.
2006 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00002007 EnumeratorRecord ER(MemberAccess::Public,
2008 APSInt::getUnsigned(Enumerator->getValue()),
2009 Enumerator->getName());
Zachary Turner6900de12017-11-28 18:33:17 +00002010 ContinuationBuilder.writeMemberType(ER);
David Majnemerda9548f2016-06-17 16:13:21 +00002011 EnumeratorCount++;
2012 }
2013 }
Zachary Turner6900de12017-11-28 18:33:17 +00002014 FTI = TypeTable.insertRecord(ContinuationBuilder);
David Majnemerda9548f2016-06-17 16:13:21 +00002015 }
David Majnemer979cb882016-06-16 21:32:16 +00002016
David Majnemer6bdc24e2016-07-01 23:12:45 +00002017 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00002018
Zachary Turner4efa0a42016-11-08 22:24:53 +00002019 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
2020 getTypeIndex(Ty->getBaseType()));
Aaron Smith122d9e72018-03-06 18:20:22 +00002021 TypeIndex EnumTI = TypeTable.writeLeafType(ER);
2022
2023 addUDTSrcLine(Ty, EnumTI);
2024
2025 return EnumTI;
David Majnemer979cb882016-06-16 21:32:16 +00002026}
2027
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002028//===----------------------------------------------------------------------===//
2029// ClassInfo
2030//===----------------------------------------------------------------------===//
2031
2032struct llvm::ClassInfo {
2033 struct MemberInfo {
2034 const DIDerivedType *MemberTypeNode;
David Majnemer08bd7442016-07-01 23:12:48 +00002035 uint64_t BaseOffset;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002036 };
2037 // [MemberInfo]
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002038 using MemberList = std::vector<MemberInfo>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002039
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002040 using MethodsList = TinyPtrVector<const DISubprogram *>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002041 // MethodName -> MethodsList
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002042 using MethodsMap = MapVector<MDString *, MethodsList>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002043
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002044 /// Base classes.
2045 std::vector<const DIDerivedType *> Inheritance;
2046
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002047 /// Direct members.
2048 MemberList Members;
2049 // Direct overloaded methods gathered by name.
2050 MethodsMap Methods;
Adrian McCarthy820ca542016-07-06 19:49:51 +00002051
Reid Kleckner9dac4732016-08-31 15:59:30 +00002052 TypeIndex VShapeTI;
2053
Reid Klecknere2e82062017-08-08 20:30:14 +00002054 std::vector<const DIType *> NestedTypes;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002055};
2056
2057void CodeViewDebug::clear() {
2058 assert(CurFn == nullptr);
2059 FileIdMap.clear();
2060 FnDebugInfo.clear();
2061 FileToFilepathMap.clear();
2062 LocalUDTs.clear();
2063 GlobalUDTs.clear();
2064 TypeIndices.clear();
2065 CompleteTypeIndices.clear();
Brock Wymab17464e2018-12-20 17:33:45 +00002066 ScopeGlobals.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002067}
2068
2069void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
2070 const DIDerivedType *DDTy) {
2071 if (!DDTy->getName().empty()) {
2072 Info.Members.push_back({DDTy, 0});
2073 return;
2074 }
Shoaib Meenai03303a32018-02-27 21:48:41 +00002075
2076 // An unnamed member may represent a nested struct or union. Attempt to
2077 // interpret the unnamed member as a DICompositeType possibly wrapped in
2078 // qualifier types. Add all the indirect fields to the current record if that
2079 // succeeds, and drop the member if that fails.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002080 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
David Majnemer08bd7442016-07-01 23:12:48 +00002081 uint64_t Offset = DDTy->getOffsetInBits();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002082 const DIType *Ty = DDTy->getBaseType().resolve();
Shoaib Meenai03303a32018-02-27 21:48:41 +00002083 bool FullyResolved = false;
2084 while (!FullyResolved) {
2085 switch (Ty->getTag()) {
2086 case dwarf::DW_TAG_const_type:
2087 case dwarf::DW_TAG_volatile_type:
2088 // FIXME: we should apply the qualifier types to the indirect fields
2089 // rather than dropping them.
2090 Ty = cast<DIDerivedType>(Ty)->getBaseType().resolve();
2091 break;
2092 default:
2093 FullyResolved = true;
2094 break;
2095 }
2096 }
2097
2098 const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
2099 if (!DCTy)
2100 return;
2101
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002102 ClassInfo NestedInfo = collectClassInfo(DCTy);
2103 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002104 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002105 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002106}
2107
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002108ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
2109 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002110 // Add elements to structure type.
2111 DINodeArray Elements = Ty->getElements();
2112 for (auto *Element : Elements) {
2113 // We assume that the frontend provides all members in source declaration
2114 // order, which is what MSVC does.
2115 if (!Element)
2116 continue;
2117 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00002118 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002119 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002120 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002121 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002122 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
2123 Info.Inheritance.push_back(DDTy);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002124 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
2125 DDTy->getName() == "__vtbl_ptr_type") {
2126 Info.VShapeTI = getTypeIndex(DDTy);
Reid Klecknere2e82062017-08-08 20:30:14 +00002127 } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
2128 Info.NestedTypes.push_back(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002129 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
2130 // Ignore friend members. It appears that MSVC emitted info about
2131 // friends in the past, but modern versions do not.
2132 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00002133 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
Reid Klecknere2e82062017-08-08 20:30:14 +00002134 Info.NestedTypes.push_back(Composite);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002135 }
2136 // Skip other unrecognized kinds of elements.
2137 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002138 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002139}
2140
Brock Wymab60532f2018-06-11 01:39:34 +00002141static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) {
2142 // This routine is used by lowerTypeClass and lowerTypeUnion to determine
2143 // if a complete type should be emitted instead of a forward reference.
2144 return Ty->getName().empty() && Ty->getIdentifier().empty() &&
2145 !Ty->isForwardDecl();
2146}
2147
Reid Klecknera8d57402016-06-03 15:58:20 +00002148TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
Brock Wymab60532f2018-06-11 01:39:34 +00002149 // Emit the complete type for unnamed structs. C++ classes with methods
2150 // which have a circular reference back to the class type are expected to
2151 // be named by the front-end and should not be "unnamed". C unnamed
2152 // structs should not have circular references.
2153 if (shouldAlwaysEmitCompleteClassType(Ty)) {
2154 // If this unnamed complete type is already in the process of being defined
2155 // then the description of the type is malformed and cannot be emitted
2156 // into CodeView correctly so report a fatal error.
2157 auto I = CompleteTypeIndices.find(Ty);
2158 if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
2159 report_fatal_error("cannot debug circular reference to unnamed type");
2160 return getCompleteTypeIndex(Ty);
2161 }
2162
Reid Klecknera8d57402016-06-03 15:58:20 +00002163 // First, construct the forward decl. Don't look into Ty to compute the
2164 // forward decl options, since it might not be available in all TUs.
2165 TypeRecordKind Kind = getRecordKind(Ty);
2166 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00002167 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00002168 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00002169 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
2170 FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002171 TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
Reid Kleckner643dd832016-06-22 17:15:28 +00002172 if (!Ty->isForwardDecl())
2173 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00002174 return FwdDeclTI;
2175}
2176
2177TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
2178 // Construct the field list and complete type record.
2179 TypeRecordKind Kind = getRecordKind(Ty);
Reid Klecknere092dad2016-07-02 00:11:07 +00002180 ClassOptions CO = getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002181 TypeIndex FieldTI;
2182 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002183 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00002184 bool ContainsNestedClass;
2185 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
2186 lowerRecordFieldList(Ty);
2187
2188 if (ContainsNestedClass)
2189 CO |= ClassOptions::ContainsNestedClass;
Reid Klecknera8d57402016-06-03 15:58:20 +00002190
Aaron Smith1d5f8632019-02-26 03:23:56 +00002191 // MSVC appears to set this flag by searching any destructor or method with
2192 // FunctionOptions::Constructor among the emitted members. Clang AST has all
2193 // the members, however special member functions are not yet emitted into
2194 // debug information. For now checking a class's non-triviality seems enough.
2195 // FIXME: not true for a nested unnamed struct.
2196 if (isNonTrivial(Ty))
2197 CO |= ClassOptions::HasConstructorOrDestructor;
2198
David Majnemer6bdc24e2016-07-01 23:12:45 +00002199 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00002200
Reid Klecknera8d57402016-06-03 15:58:20 +00002201 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00002202
Zachary Turner4efa0a42016-11-08 22:24:53 +00002203 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
2204 SizeInBytes, FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002205 TypeIndex ClassTI = TypeTable.writeLeafType(CR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002206
Aaron Smith122d9e72018-03-06 18:20:22 +00002207 addUDTSrcLine(Ty, ClassTI);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002208
Zachary Turnera7b04172017-08-28 18:49:04 +00002209 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00002210
Hans Wennborg9a519a02016-06-22 21:22:13 +00002211 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002212}
2213
2214TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
Brock Wymab60532f2018-06-11 01:39:34 +00002215 // Emit the complete type for unnamed unions.
2216 if (shouldAlwaysEmitCompleteClassType(Ty))
2217 return getCompleteTypeIndex(Ty);
2218
Reid Klecknera8d57402016-06-03 15:58:20 +00002219 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00002220 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00002221 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00002222 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002223 TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
Reid Kleckner643dd832016-06-22 17:15:28 +00002224 if (!Ty->isForwardDecl())
2225 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00002226 return FwdDeclTI;
2227}
2228
2229TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
David Majnemere1e73722016-07-06 21:07:42 +00002230 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002231 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002232 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00002233 bool ContainsNestedClass;
2234 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
2235 lowerRecordFieldList(Ty);
2236
2237 if (ContainsNestedClass)
2238 CO |= ClassOptions::ContainsNestedClass;
2239
Reid Klecknera8d57402016-06-03 15:58:20 +00002240 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
David Majnemer6bdc24e2016-07-01 23:12:45 +00002241 std::string FullName = getFullyQualifiedName(Ty);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002242
Zachary Turner4efa0a42016-11-08 22:24:53 +00002243 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
2244 Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002245 TypeIndex UnionTI = TypeTable.writeLeafType(UR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002246
Aaron Smith122d9e72018-03-06 18:20:22 +00002247 addUDTSrcLine(Ty, UnionTI);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002248
Zachary Turnera7b04172017-08-28 18:49:04 +00002249 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00002250
Hans Wennborg9a519a02016-06-22 21:22:13 +00002251 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002252}
2253
Adrian McCarthy820ca542016-07-06 19:49:51 +00002254std::tuple<TypeIndex, TypeIndex, unsigned, bool>
Reid Klecknera8d57402016-06-03 15:58:20 +00002255CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
2256 // Manually count members. MSVC appears to count everything that generates a
2257 // field list record. Each individual overload in a method overload group
2258 // contributes to this count, even though the overload group is a single field
2259 // list record.
2260 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002261 ClassInfo Info = collectClassInfo(Ty);
Zachary Turner6900de12017-11-28 18:33:17 +00002262 ContinuationRecordBuilder ContinuationBuilder;
2263 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002264
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002265 // Create base classes.
2266 for (const DIDerivedType *I : Info.Inheritance) {
2267 if (I->getFlags() & DINode::FlagVirtual) {
2268 // Virtual base.
Brock Wyma3db2b102018-05-14 21:21:22 +00002269 unsigned VBPtrOffset = I->getVBPtrOffset();
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002270 // FIXME: Despite the accessor name, the offset is really in bytes.
2271 unsigned VBTableIndex = I->getOffsetInBits() / 4;
Bob Haarman26a87bd2016-10-25 22:11:52 +00002272 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
2273 ? TypeRecordKind::IndirectVirtualBaseClass
2274 : TypeRecordKind::VirtualBaseClass;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002275 VirtualBaseClassRecord VBCR(
Bob Haarman26a87bd2016-10-25 22:11:52 +00002276 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002277 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
Zachary Turner4efa0a42016-11-08 22:24:53 +00002278 VBTableIndex);
2279
Zachary Turner6900de12017-11-28 18:33:17 +00002280 ContinuationBuilder.writeMemberType(VBCR);
Brock Wyma4536c1f2018-02-01 20:37:38 +00002281 MemberCount++;
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002282 } else {
2283 assert(I->getOffsetInBits() % 8 == 0 &&
2284 "bases must be on byte boundaries");
Zachary Turner4efa0a42016-11-08 22:24:53 +00002285 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
2286 getTypeIndex(I->getBaseType()),
2287 I->getOffsetInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00002288 ContinuationBuilder.writeMemberType(BCR);
Brock Wyma4536c1f2018-02-01 20:37:38 +00002289 MemberCount++;
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002290 }
2291 }
2292
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002293 // Create members.
2294 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
2295 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
2296 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00002297 StringRef MemberName = Member->getName();
2298 MemberAccess Access =
2299 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002300
2301 if (Member->isStaticMember()) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00002302 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
Zachary Turner6900de12017-11-28 18:33:17 +00002303 ContinuationBuilder.writeMemberType(SDMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002304 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00002305 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00002306 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002307
Reid Kleckner9dac4732016-08-31 15:59:30 +00002308 // Virtual function pointer member.
2309 if ((Member->getFlags() & DINode::FlagArtificial) &&
2310 Member->getName().startswith("_vptr$")) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00002311 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
Zachary Turner6900de12017-11-28 18:33:17 +00002312 ContinuationBuilder.writeMemberType(VFPR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002313 MemberCount++;
2314 continue;
2315 }
2316
David Majnemer9319cbc2016-06-30 03:00:20 +00002317 // Data member.
David Majnemer08bd7442016-07-01 23:12:48 +00002318 uint64_t MemberOffsetInBits =
2319 Member->getOffsetInBits() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00002320 if (Member->isBitField()) {
2321 uint64_t StartBitOffset = MemberOffsetInBits;
2322 if (const auto *CI =
2323 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
David Majnemer08bd7442016-07-01 23:12:48 +00002324 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00002325 }
2326 StartBitOffset -= MemberOffsetInBits;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002327 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2328 StartBitOffset);
Zachary Turner6900de12017-11-28 18:33:17 +00002329 MemberBaseType = TypeTable.writeLeafType(BFR);
David Majnemer9319cbc2016-06-30 03:00:20 +00002330 }
2331 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002332 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2333 MemberName);
Zachary Turner6900de12017-11-28 18:33:17 +00002334 ContinuationBuilder.writeMemberType(DMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002335 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00002336 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002337
2338 // Create methods
2339 for (auto &MethodItr : Info.Methods) {
2340 StringRef Name = MethodItr.first->getString();
2341
2342 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00002343 for (const DISubprogram *SP : MethodItr.second) {
2344 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2345 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002346
2347 unsigned VFTableOffset = -1;
2348 if (Introduced)
2349 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2350
Zachary Turner7251ede2016-11-02 17:05:19 +00002351 Methods.push_back(OneMethodRecord(
2352 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
2353 translateMethodKindFlags(SP, Introduced),
2354 translateMethodOptionFlags(SP), VFTableOffset, Name));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002355 MemberCount++;
2356 }
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002357 assert(!Methods.empty() && "Empty methods map entry");
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002358 if (Methods.size() == 1)
Zachary Turner6900de12017-11-28 18:33:17 +00002359 ContinuationBuilder.writeMemberType(Methods[0]);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002360 else {
Zachary Turner6900de12017-11-28 18:33:17 +00002361 // FIXME: Make this use its own ContinuationBuilder so that
2362 // MethodOverloadList can be split correctly.
Zachary Turner4efa0a42016-11-08 22:24:53 +00002363 MethodOverloadListRecord MOLR(Methods);
Zachary Turner6900de12017-11-28 18:33:17 +00002364 TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
2365
Zachary Turner4efa0a42016-11-08 22:24:53 +00002366 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
Zachary Turner6900de12017-11-28 18:33:17 +00002367 ContinuationBuilder.writeMemberType(OMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002368 }
2369 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00002370
2371 // Create nested classes.
Reid Klecknere2e82062017-08-08 20:30:14 +00002372 for (const DIType *Nested : Info.NestedTypes) {
Adrian McCarthy820ca542016-07-06 19:49:51 +00002373 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
Zachary Turner6900de12017-11-28 18:33:17 +00002374 ContinuationBuilder.writeMemberType(R);
Adrian McCarthy820ca542016-07-06 19:49:51 +00002375 MemberCount++;
2376 }
2377
Zachary Turner6900de12017-11-28 18:33:17 +00002378 TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002379 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
Reid Klecknere2e82062017-08-08 20:30:14 +00002380 !Info.NestedTypes.empty());
Reid Klecknera8d57402016-06-03 15:58:20 +00002381}
2382
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002383TypeIndex CodeViewDebug::getVBPTypeIndex() {
2384 if (!VBPType.getIndex()) {
2385 // Make a 'const int *' type.
2386 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
Zachary Turner6900de12017-11-28 18:33:17 +00002387 TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002388
2389 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2390 : PointerKind::Near32;
2391 PointerMode PM = PointerMode::Pointer;
2392 PointerOptions PO = PointerOptions::None;
2393 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
Zachary Turner6900de12017-11-28 18:33:17 +00002394 VBPType = TypeTable.writeLeafType(PR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002395 }
2396
2397 return VBPType;
2398}
2399
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002400TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002401 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002402 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002403
2404 // The null DIType is the void type. Don't try to hash it.
2405 if (!Ty)
2406 return TypeIndex::Void();
2407
Reid Klecknera8d57402016-06-03 15:58:20 +00002408 // Check if we've already translated this type. Don't try to do a
2409 // get-or-create style insertion that caches the hash lookup across the
2410 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002411 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002412 if (I != TypeIndices.end())
2413 return I->second;
2414
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002415 TypeLoweringScope S(*this);
2416 TypeIndex TI = lowerType(Ty, ClassTy);
2417 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00002418}
2419
Zachary Turnerc68f8952018-11-20 22:13:43 +00002420codeview::TypeIndex
Reid Klecknerc168c6f2018-12-26 21:52:17 +00002421CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy,
Zachary Turnerc68f8952018-11-20 22:13:43 +00002422 const DISubroutineType *SubroutineTy) {
Reid Klecknerc168c6f2018-12-26 21:52:17 +00002423 assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type &&
2424 "this type must be a pointer type");
Zachary Turnerc68f8952018-11-20 22:13:43 +00002425
2426 PointerOptions Options = PointerOptions::None;
2427 if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference)
2428 Options = PointerOptions::LValueRefThisPointer;
2429 else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference)
2430 Options = PointerOptions::RValueRefThisPointer;
2431
2432 // Check if we've already translated this type. If there is no ref qualifier
2433 // on the function then we look up this pointer type with no associated class
2434 // so that the TypeIndex for the this pointer can be shared with the type
2435 // index for other pointers to this class type. If there is a ref qualifier
2436 // then we lookup the pointer using the subroutine as the parent type.
Reid Klecknerc168c6f2018-12-26 21:52:17 +00002437 auto I = TypeIndices.find({PtrTy, SubroutineTy});
Zachary Turnerc68f8952018-11-20 22:13:43 +00002438 if (I != TypeIndices.end())
2439 return I->second;
2440
2441 TypeLoweringScope S(*this);
Reid Klecknerc168c6f2018-12-26 21:52:17 +00002442 TypeIndex TI = lowerTypePointer(PtrTy, Options);
2443 return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy);
Zachary Turnerc68f8952018-11-20 22:13:43 +00002444}
2445
Bob Haarman223303c2017-08-29 20:59:25 +00002446TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(DITypeRef TypeRef) {
2447 DIType *Ty = TypeRef.resolve();
2448 PointerRecord PR(getTypeIndex(Ty),
2449 getPointerSizeInBytes() == 8 ? PointerKind::Near64
2450 : PointerKind::Near32,
2451 PointerMode::LValueReference, PointerOptions::None,
2452 Ty->getSizeInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00002453 return TypeTable.writeLeafType(PR);
Bob Haarman223303c2017-08-29 20:59:25 +00002454}
2455
Reid Klecknera8d57402016-06-03 15:58:20 +00002456TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
2457 const DIType *Ty = TypeRef.resolve();
2458
2459 // The null DIType is the void type. Don't try to hash it.
2460 if (!Ty)
2461 return TypeIndex::Void();
2462
Reid Kleckner9571c802018-12-11 23:07:39 +00002463 // Look through typedefs when getting the complete type index. Call
2464 // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are
2465 // emitted only once.
2466 if (Ty->getTag() == dwarf::DW_TAG_typedef)
2467 (void)getTypeIndex(Ty);
2468 while (Ty->getTag() == dwarf::DW_TAG_typedef)
2469 Ty = cast<DIDerivedType>(Ty)->getBaseType().resolve();
2470
Reid Klecknera8d57402016-06-03 15:58:20 +00002471 // If this is a non-record type, the complete type index is the same as the
2472 // normal type index. Just call getTypeIndex.
2473 switch (Ty->getTag()) {
2474 case dwarf::DW_TAG_class_type:
2475 case dwarf::DW_TAG_structure_type:
2476 case dwarf::DW_TAG_union_type:
2477 break;
2478 default:
2479 return getTypeIndex(Ty);
2480 }
2481
Brock Wymab60532f2018-06-11 01:39:34 +00002482 // Check if we've already translated the complete record type.
Reid Klecknera8d57402016-06-03 15:58:20 +00002483 const auto *CTy = cast<DICompositeType>(Ty);
2484 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
2485 if (!InsertResult.second)
2486 return InsertResult.first->second;
2487
Reid Kleckner643dd832016-06-22 17:15:28 +00002488 TypeLoweringScope S(*this);
2489
Reid Klecknera8d57402016-06-03 15:58:20 +00002490 // Make sure the forward declaration is emitted first. It's unclear if this
2491 // is necessary, but MSVC does it, and we should follow suit until we can show
2492 // otherwise.
Brock Wymab60532f2018-06-11 01:39:34 +00002493 // We only emit a forward declaration for named types.
2494 if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
2495 TypeIndex FwdDeclTI = getTypeIndex(CTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00002496
Brock Wymab60532f2018-06-11 01:39:34 +00002497 // Just use the forward decl if we don't have complete type info. This
2498 // might happen if the frontend is using modules and expects the complete
2499 // definition to be emitted elsewhere.
2500 if (CTy->isForwardDecl())
2501 return FwdDeclTI;
2502 }
Reid Klecknera8d57402016-06-03 15:58:20 +00002503
2504 TypeIndex TI;
2505 switch (CTy->getTag()) {
2506 case dwarf::DW_TAG_class_type:
2507 case dwarf::DW_TAG_structure_type:
2508 TI = lowerCompleteTypeClass(CTy);
2509 break;
2510 case dwarf::DW_TAG_union_type:
2511 TI = lowerCompleteTypeUnion(CTy);
2512 break;
2513 default:
2514 llvm_unreachable("not a record");
2515 }
2516
Brock Wymab60532f2018-06-11 01:39:34 +00002517 // Update the type index associated with this CompositeType. This cannot
2518 // use the 'InsertResult' iterator above because it is potentially
2519 // invalidated by map insertions which can occur while lowering the class
2520 // type above.
2521 CompleteTypeIndices[CTy] = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002522 return TI;
2523}
2524
Reid Kleckner643dd832016-06-22 17:15:28 +00002525/// Emit all the deferred complete record types. Try to do this in FIFO order,
Amjad Aboudacee5682016-07-12 12:06:34 +00002526/// and do this until fixpoint, as each complete record type typically
2527/// references
Reid Kleckner643dd832016-06-22 17:15:28 +00002528/// many other record types.
2529void CodeViewDebug::emitDeferredCompleteTypes() {
2530 SmallVector<const DICompositeType *, 4> TypesToEmit;
2531 while (!DeferredCompleteTypes.empty()) {
2532 std::swap(DeferredCompleteTypes, TypesToEmit);
2533 for (const DICompositeType *RecordTy : TypesToEmit)
2534 getCompleteTypeIndex(RecordTy);
2535 TypesToEmit.clear();
2536 }
2537}
2538
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002539void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
2540 ArrayRef<LocalVariable> Locals) {
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002541 // Get the sorted list of parameters and emit them first.
2542 SmallVector<const LocalVariable *, 6> Params;
2543 for (const LocalVariable &L : Locals)
2544 if (L.DIVar->isParameter())
2545 Params.push_back(&L);
Fangrui Song0cac7262018-09-27 02:13:45 +00002546 llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
2547 return L->DIVar->getArg() < R->DIVar->getArg();
2548 });
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002549 for (const LocalVariable *L : Params)
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002550 emitLocalVariable(FI, *L);
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002551
2552 // Next emit all non-parameters in the order that we found them.
2553 for (const LocalVariable &L : Locals)
2554 if (!L.DIVar->isParameter())
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002555 emitLocalVariable(FI, L);
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002556}
2557
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002558/// Only call this on endian-specific types like ulittle16_t and little32_t, or
2559/// structs composed of them.
2560template <typename T>
2561static void copyBytesForDefRange(SmallString<20> &BytePrefix,
2562 SymbolKind SymKind, const T &DefRangeHeader) {
2563 BytePrefix.resize(2 + sizeof(T));
2564 ulittle16_t SymKindLE = ulittle16_t(SymKind);
2565 memcpy(&BytePrefix[0], &SymKindLE, 2);
2566 memcpy(&BytePrefix[2], &DefRangeHeader, sizeof(T));
2567}
2568
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002569void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
2570 const LocalVariable &Var) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002571 // LocalSym record, see SymbolRecord.h for more info.
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002572 MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002573
Zachary Turner63a28462016-05-17 23:50:21 +00002574 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002575 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00002576 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00002577 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00002578 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002579
2580 OS.AddComment("TypeIndex");
Reid Kleckner08f5fd52017-08-31 15:56:49 +00002581 TypeIndex TI = Var.UseReferenceType
2582 ? getTypeIndexForReferenceTo(Var.DIVar->getType())
2583 : getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002584 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002585 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00002586 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00002587 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00002588 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002589 endSymbolRecord(LocalEnd);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002590
Reid Kleckner876330d2016-02-12 21:48:30 +00002591 // Calculate the on disk prefix of the appropriate def range record. The
2592 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2593 // should be big enough to hold all forms without memory allocation.
2594 SmallString<20> BytePrefix;
2595 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2596 BytePrefix.clear();
Reid Kleckner876330d2016-02-12 21:48:30 +00002597 if (DefRange.InMemory) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002598 int Offset = DefRange.DataOffset;
2599 unsigned Reg = DefRange.CVRegister;
2600
Reid Klecknerd5e4ec72018-10-02 16:43:52 +00002601 // 32-bit x86 call sequences often use PUSH instructions, which disrupt
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002602 // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
Reid Kleckner2bcb2882018-11-03 00:41:52 +00002603 // instead. In frames without stack realignment, $T0 will be the CFA.
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002604 if (RegisterId(Reg) == RegisterId::ESP) {
2605 Reg = unsigned(RegisterId::VFRAME);
Reid Kleckner2bcb2882018-11-03 00:41:52 +00002606 Offset += FI.OffsetAdjustment;
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002607 }
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002608
2609 // If we can use the chosen frame pointer for the frame and this isn't a
2610 // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
2611 // Otherwise, use S_DEFRANGE_REGISTER_REL.
2612 EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU);
2613 if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
2614 (bool(Flags & LocalSymFlags::IsParameter)
2615 ? (EncFP == FI.EncodedParamFramePtrReg)
2616 : (EncFP == FI.EncodedLocalFramePtrReg))) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002617 little32_t FPOffset = little32_t(Offset);
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002618 copyBytesForDefRange(BytePrefix, S_DEFRANGE_FRAMEPOINTER_REL, FPOffset);
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002619 } else {
2620 uint16_t RegRelFlags = 0;
2621 if (DefRange.IsSubfield) {
2622 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2623 (DefRange.StructOffset
2624 << DefRangeRegisterRelSym::OffsetInParentShift);
2625 }
2626 DefRangeRegisterRelSym::Header DRHdr;
2627 DRHdr.Register = Reg;
2628 DRHdr.Flags = RegRelFlags;
2629 DRHdr.BasePointerOffset = Offset;
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002630 copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER_REL, DRHdr);
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002631 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002632 } else {
2633 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002634 if (DefRange.IsSubfield) {
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002635 DefRangeSubfieldRegisterSym::Header DRHdr;
2636 DRHdr.Register = DefRange.CVRegister;
2637 DRHdr.MayHaveNoName = 0;
2638 DRHdr.OffsetInParent = DefRange.StructOffset;
2639 copyBytesForDefRange(BytePrefix, S_DEFRANGE_SUBFIELD_REGISTER, DRHdr);
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002640 } else {
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002641 DefRangeRegisterSym::Header DRHdr;
2642 DRHdr.Register = DefRange.CVRegister;
2643 DRHdr.MayHaveNoName = 0;
2644 copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER, DRHdr);
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002645 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002646 }
2647 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2648 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002649}
2650
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002651void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
2652 const FunctionInfo& FI) {
2653 for (LexicalBlock *Block : Blocks)
2654 emitLexicalBlock(*Block, FI);
2655}
2656
2657/// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
2658/// lexical block scope.
2659void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
2660 const FunctionInfo& FI) {
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002661 MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002662 OS.AddComment("PtrParent");
2663 OS.EmitIntValue(0, 4); // PtrParent
2664 OS.AddComment("PtrEnd");
2665 OS.EmitIntValue(0, 4); // PtrEnd
2666 OS.AddComment("Code size");
2667 OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4); // Code Size
2668 OS.AddComment("Function section relative address");
2669 OS.EmitCOFFSecRel32(Block.Begin, /*Offset=*/0); // Func Offset
2670 OS.AddComment("Function section index");
2671 OS.EmitCOFFSectionIndex(FI.Begin); // Func Symbol
2672 OS.AddComment("Lexical block name");
2673 emitNullTerminatedSymbolName(OS, Block.Name); // Name
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002674 endSymbolRecord(RecordEnd);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002675
2676 // Emit variables local to this lexical block.
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002677 emitLocalVariableList(FI, Block.Locals);
Brock Wymab17464e2018-12-20 17:33:45 +00002678 emitGlobalVariableList(Block.Globals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002679
2680 // Emit lexical blocks contained within this block.
2681 emitLexicalBlockList(Block.Children, FI);
2682
2683 // Close the lexical block scope.
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002684 emitEndSymbolRecord(SymbolKind::S_END);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002685}
2686
2687/// Convenience routine for collecting lexical block information for a list
2688/// of lexical scopes.
2689void CodeViewDebug::collectLexicalBlockInfo(
2690 SmallVectorImpl<LexicalScope *> &Scopes,
2691 SmallVectorImpl<LexicalBlock *> &Blocks,
Brock Wymab17464e2018-12-20 17:33:45 +00002692 SmallVectorImpl<LocalVariable> &Locals,
2693 SmallVectorImpl<CVGlobalVariable> &Globals) {
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002694 for (LexicalScope *Scope : Scopes)
Brock Wymab17464e2018-12-20 17:33:45 +00002695 collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002696}
2697
2698/// Populate the lexical blocks and local variable lists of the parent with
2699/// information about the specified lexical scope.
2700void CodeViewDebug::collectLexicalBlockInfo(
2701 LexicalScope &Scope,
2702 SmallVectorImpl<LexicalBlock *> &ParentBlocks,
Brock Wymab17464e2018-12-20 17:33:45 +00002703 SmallVectorImpl<LocalVariable> &ParentLocals,
2704 SmallVectorImpl<CVGlobalVariable> &ParentGlobals) {
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002705 if (Scope.isAbstractScope())
2706 return;
2707
Brock Wymab17464e2018-12-20 17:33:45 +00002708 // Gather information about the lexical scope including local variables,
2709 // global variables, and address ranges.
2710 bool IgnoreScope = false;
2711 auto LI = ScopeVariables.find(&Scope);
2712 SmallVectorImpl<LocalVariable> *Locals =
2713 LI != ScopeVariables.end() ? &LI->second : nullptr;
2714 auto GI = ScopeGlobals.find(Scope.getScopeNode());
2715 SmallVectorImpl<CVGlobalVariable> *Globals =
2716 GI != ScopeGlobals.end() ? GI->second.get() : nullptr;
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002717 const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002718 const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
Brock Wymab17464e2018-12-20 17:33:45 +00002719
2720 // Ignore lexical scopes which do not contain variables.
2721 if (!Locals && !Globals)
2722 IgnoreScope = true;
2723
2724 // Ignore lexical scopes which are not lexical blocks.
2725 if (!DILB)
2726 IgnoreScope = true;
2727
2728 // Ignore scopes which have too many address ranges to represent in the
2729 // current CodeView format or do not have a valid address range.
2730 //
2731 // For lexical scopes with multiple address ranges you may be tempted to
2732 // construct a single range covering every instruction where the block is
2733 // live and everything in between. Unfortunately, Visual Studio only
2734 // displays variables from the first matching lexical block scope. If the
2735 // first lexical block contains exception handling code or cold code which
2736 // is moved to the bottom of the routine creating a single range covering
2737 // nearly the entire routine, then it will hide all other lexical blocks
2738 // and the variables they contain.
2739 if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second))
2740 IgnoreScope = true;
2741
2742 if (IgnoreScope) {
2743 // This scope can be safely ignored and eliminating it will reduce the
2744 // size of the debug information. Be sure to collect any variable and scope
2745 // information from the this scope or any of its children and collapse them
2746 // into the parent scope.
2747 if (Locals)
2748 ParentLocals.append(Locals->begin(), Locals->end());
2749 if (Globals)
2750 ParentGlobals.append(Globals->begin(), Globals->end());
2751 collectLexicalBlockInfo(Scope.getChildren(),
2752 ParentBlocks,
2753 ParentLocals,
2754 ParentGlobals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002755 return;
2756 }
2757
2758 // Create a new CodeView lexical block for this lexical scope. If we've
2759 // seen this DILexicalBlock before then the scope tree is malformed and
2760 // we can handle this gracefully by not processing it a second time.
2761 auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
2762 if (!BlockInsertion.second)
2763 return;
2764
Brock Wymab17464e2018-12-20 17:33:45 +00002765 // Create a lexical block containing the variables and collect the the
2766 // lexical block information for the children.
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002767 const InsnRange &Range = Ranges.front();
2768 assert(Range.first && Range.second);
2769 LexicalBlock &Block = BlockInsertion.first->second;
2770 Block.Begin = getLabelBeforeInsn(Range.first);
2771 Block.End = getLabelAfterInsn(Range.second);
2772 assert(Block.Begin && "missing label for scope begin");
2773 assert(Block.End && "missing label for scope end");
2774 Block.Name = DILB->getName();
Brock Wymab17464e2018-12-20 17:33:45 +00002775 if (Locals)
2776 Block.Locals = std::move(*Locals);
2777 if (Globals)
2778 Block.Globals = std::move(*Globals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002779 ParentBlocks.push_back(&Block);
Brock Wymab17464e2018-12-20 17:33:45 +00002780 collectLexicalBlockInfo(Scope.getChildren(),
2781 Block.Children,
2782 Block.Locals,
2783 Block.Globals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002784}
2785
David Blaikieb2fbb4b2017-02-16 18:48:33 +00002786void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002787 const Function &GV = MF->getFunction();
2788 assert(FnDebugInfo.count(&GV));
Reid Kleckner55baeef2018-03-15 21:12:21 +00002789 assert(CurFn == FnDebugInfo[&GV].get());
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002790
Matthias Braunf1caa282017-12-15 22:22:58 +00002791 collectVariableInfo(GV.getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00002792
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002793 // Build the lexical block structure to emit for this routine.
2794 if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
Brock Wymab17464e2018-12-20 17:33:45 +00002795 collectLexicalBlockInfo(*CFS,
2796 CurFn->ChildBlocks,
2797 CurFn->Locals,
2798 CurFn->Globals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002799
2800 // Clear the scope and variable information from the map which will not be
2801 // valid after we have finished processing this routine. This also prepares
2802 // the map for the subsequent routine.
2803 ScopeVariables.clear();
2804
Reid Kleckner2214ed82016-01-29 00:49:42 +00002805 // Don't emit anything if we don't have any line tables.
Brock Wyma94ece8f2018-04-16 16:53:57 +00002806 // Thunks are compiler-generated and probably won't have source correlation.
2807 if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002808 FnDebugInfo.erase(&GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002809 CurFn = nullptr;
2810 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00002811 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002812
Reid Klecknere33c94f2017-09-05 20:14:58 +00002813 CurFn->Annotations = MF->getCodeViewAnnotations();
2814
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002815 CurFn->End = Asm->getFunctionEnd();
2816
Craig Topper353eda42014-04-24 06:44:33 +00002817 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002818}
2819
Reid Kleckner70f5bc92016-01-14 19:25:04 +00002820void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002821 DebugHandlerBase::beginInstruction(MI);
2822
Shiva Chen801bf7e2018-05-09 02:42:00 +00002823 // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
2824 if (!Asm || !CurFn || MI->isDebugInstr() ||
David Majnemer67f684e2016-07-28 05:03:22 +00002825 MI->getFlag(MachineInstr::FrameSetup))
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002826 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002827
2828 // If the first instruction of a new MBB has no location, find the first
2829 // instruction with a location and use that.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002830 DebugLoc DL = MI->getDebugLoc();
Reid Kleckner45a74622017-06-30 21:33:44 +00002831 if (!DL && MI->getParent() != PrevInstBB) {
2832 for (const auto &NextMI : *MI->getParent()) {
Shiva Chen801bf7e2018-05-09 02:42:00 +00002833 if (NextMI.isDebugInstr())
Reid Kleckner2de471d2017-07-31 21:03:08 +00002834 continue;
Reid Kleckner45a74622017-06-30 21:33:44 +00002835 DL = NextMI.getDebugLoc();
2836 if (DL)
2837 break;
2838 }
2839 }
2840 PrevInstBB = MI->getParent();
2841
2842 // If we still don't have a debug location, don't record a location.
2843 if (!DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002844 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002845
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002846 maybeRecordLocation(DL, Asm->MF);
2847}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002848
Zachary Turner8c099fe2017-05-30 16:36:15 +00002849MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002850 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2851 *EndLabel = MMI->getContext().createTempSymbol();
2852 OS.EmitIntValue(unsigned(Kind), 4);
2853 OS.AddComment("Subsection size");
2854 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2855 OS.EmitLabel(BeginLabel);
2856 return EndLabel;
2857}
2858
2859void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2860 OS.EmitLabel(EndLabel);
2861 // Every subsection must be aligned to a 4-byte boundary.
2862 OS.EmitValueToAlignment(4);
2863}
2864
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002865static StringRef getSymbolName(SymbolKind SymKind) {
2866 for (const EnumEntry<SymbolKind> &EE : getSymbolTypeNames())
2867 if (EE.Value == SymKind)
2868 return EE.Name;
2869 return "";
2870}
2871
2872MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) {
2873 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2874 *EndLabel = MMI->getContext().createTempSymbol();
2875 OS.AddComment("Record length");
2876 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
2877 OS.EmitLabel(BeginLabel);
2878 if (OS.isVerboseAsm())
2879 OS.AddComment("Record kind: " + getSymbolName(SymKind));
2880 OS.EmitIntValue(unsigned(SymKind), 2);
2881 return EndLabel;
2882}
2883
2884void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) {
Reid Kleckner4ab50b82018-12-18 01:36:06 +00002885 // MSVC does not pad out symbol records to four bytes, but LLVM does to avoid
2886 // an extra copy of every symbol record in LLD. This increases object file
2887 // size by less than 1% in the clang build, and is compatible with the Visual
2888 // C++ linker.
Reid Kleckner53ce0592018-12-18 01:14:05 +00002889 OS.EmitValueToAlignment(4);
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002890 OS.EmitLabel(SymEnd);
2891}
2892
2893void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) {
2894 OS.AddComment("Record length");
2895 OS.EmitIntValue(2, 2);
2896 if (OS.isVerboseAsm())
2897 OS.AddComment("Record kind: " + getSymbolName(EndKind));
2898 OS.EmitIntValue(unsigned(EndKind), 2); // Record Kind
2899}
2900
David Majnemer3128b102016-06-15 18:00:01 +00002901void CodeViewDebug::emitDebugInfoForUDTs(
Zachary Turnera7b04172017-08-28 18:49:04 +00002902 ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
2903 for (const auto &UDT : UDTs) {
2904 const DIType *T = UDT.second;
2905 assert(shouldEmitUdt(T));
2906
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002907 MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT);
David Majnemer3128b102016-06-15 18:00:01 +00002908 OS.AddComment("Type");
Zachary Turnera7b04172017-08-28 18:49:04 +00002909 OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
David Majnemer3128b102016-06-15 18:00:01 +00002910 emitNullTerminatedSymbolName(OS, UDT.first);
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002911 endSymbolRecord(UDTRecordEnd);
David Majnemer3128b102016-06-15 18:00:01 +00002912 }
2913}
2914
Brock Wymab17464e2018-12-20 17:33:45 +00002915void CodeViewDebug::collectGlobalVariableInfo() {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002916 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2917 GlobalMap;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002918 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002919 SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2920 GV.getDebugInfo(GVEs);
2921 for (const auto *GVE : GVEs)
2922 GlobalMap[GVE] = &GV;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002923 }
2924
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002925 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2926 for (const MDNode *Node : CUs->operands()) {
2927 const auto *CU = cast<DICompileUnit>(Node);
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002928 for (const auto *GVE : CU->getGlobalVariables()) {
Brock Wymab17464e2018-12-20 17:33:45 +00002929 const auto *GV = GlobalMap.lookup(GVE);
2930 if (!GV || GV->isDeclarationForLinker())
2931 continue;
2932 const DIGlobalVariable *DIGV = GVE->getVariable();
2933 DIScope *Scope = DIGV->getScope();
2934 SmallVector<CVGlobalVariable, 1> *VariableList;
2935 if (Scope && isa<DILocalScope>(Scope)) {
2936 // Locate a global variable list for this scope, creating one if
2937 // necessary.
2938 auto Insertion = ScopeGlobals.insert(
2939 {Scope, std::unique_ptr<GlobalVariableList>()});
2940 if (Insertion.second)
2941 Insertion.first->second = llvm::make_unique<GlobalVariableList>();
2942 VariableList = Insertion.first->second.get();
2943 } else if (GV->hasComdat())
2944 // Emit this global variable into a COMDAT section.
2945 VariableList = &ComdatVariables;
2946 else
2947 // Emit this globla variable in a single global symbol section.
2948 VariableList = &GlobalVariables;
2949 CVGlobalVariable CVGV = {DIGV, GV};
2950 VariableList->emplace_back(std::move(CVGV));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002951 }
Brock Wymab17464e2018-12-20 17:33:45 +00002952 }
2953}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002954
Brock Wymab17464e2018-12-20 17:33:45 +00002955void CodeViewDebug::emitDebugInfoForGlobals() {
2956 // First, emit all globals that are not in a comdat in a single symbol
2957 // substream. MSVC doesn't like it if the substream is empty, so only open
2958 // it if we have at least one global to emit.
2959 switchToDebugSectionForSymbol(nullptr);
2960 if (!GlobalVariables.empty()) {
2961 OS.AddComment("Symbol subsection for globals");
2962 MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
2963 emitGlobalVariableList(GlobalVariables);
2964 endCVSubsection(EndLabel);
2965 }
2966
2967 // Second, emit each global that is in a comdat into its own .debug$S
2968 // section along with its own symbol substream.
2969 for (const CVGlobalVariable &CVGV : ComdatVariables) {
2970 MCSymbol *GVSym = Asm->getSymbol(CVGV.GV);
2971 OS.AddComment("Symbol subsection for " +
2972 Twine(GlobalValue::dropLLVMManglingEscape(CVGV.GV->getName())));
2973 switchToDebugSectionForSymbol(GVSym);
2974 MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
2975 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2976 emitDebugInfoForGlobal(CVGV.DIGV, CVGV.GV, GVSym);
2977 endCVSubsection(EndLabel);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002978 }
2979}
2980
Hans Wennborgb510b452016-06-23 16:33:53 +00002981void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2982 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2983 for (const MDNode *Node : CUs->operands()) {
2984 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2985 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2986 getTypeIndex(RT);
2987 // FIXME: Add to global/local DTU list.
2988 }
2989 }
2990 }
2991}
2992
Brock Wymab17464e2018-12-20 17:33:45 +00002993// Emit each global variable in the specified array.
2994void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) {
2995 for (const CVGlobalVariable &CVGV : Globals) {
2996 MCSymbol *GVSym = Asm->getSymbol(CVGV.GV);
2997 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2998 emitDebugInfoForGlobal(CVGV.DIGV, CVGV.GV, GVSym);
2999 }
3000}
3001
Reid Kleckner6f3406d2016-06-07 00:02:03 +00003002void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
Peter Collingbourned4135bb2016-09-13 01:12:59 +00003003 const GlobalVariable *GV,
Reid Kleckner6f3406d2016-06-07 00:02:03 +00003004 MCSymbol *GVSym) {
Reid Kleckner5bf71d12018-12-14 22:40:28 +00003005 // DataSym record, see SymbolRecord.h for more info. Thread local data
3006 // happens to have the same format as global data.
3007 SymbolKind DataSym = GV->isThreadLocal()
3008 ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32
3009 : SymbolKind::S_GTHREAD32)
3010 : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32
3011 : SymbolKind::S_GDATA32);
3012 MCSymbol *DataEnd = beginSymbolRecord(DataSym);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00003013 OS.AddComment("Type");
3014 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
3015 OS.AddComment("DataOffset");
Keno Fischerf7d84ee2017-01-02 03:00:19 +00003016 OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00003017 OS.AddComment("Segment");
3018 OS.EmitCOFFSectionIndex(GVSym);
3019 OS.AddComment("Name");
Reid Kleckner5bf71d12018-12-14 22:40:28 +00003020 const unsigned LengthOfDataRecord = 12;
3021 emitNullTerminatedSymbolName(OS, DIGV->getName(), LengthOfDataRecord);
3022 endSymbolRecord(DataEnd);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00003023}