blob: 78e5f5d215b3ff1a1be5b838c8d9775873a3a490 [file] [log] [blame]
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001//===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===//
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Reid Kleckner70f5bc92016-01-14 19:25:04 +000010// This file contains support for writing Microsoft CodeView debug info.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000011//
12//===----------------------------------------------------------------------===//
13
Reid Kleckner70f5bc92016-01-14 19:25:04 +000014#include "CodeViewDebug.h"
Adrian Prantl032d2382017-08-01 21:45:24 +000015#include "DwarfExpression.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000016#include "llvm/ADT/APSInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/DenseSet.h"
20#include "llvm/ADT/MapVector.h"
21#include "llvm/ADT/None.h"
22#include "llvm/ADT/Optional.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000023#include "llvm/ADT/STLExtras.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000024#include "llvm/ADT/SmallString.h"
25#include "llvm/ADT/SmallVector.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000026#include "llvm/ADT/StringRef.h"
Reid Kleckner156a7232016-06-22 18:31:14 +000027#include "llvm/ADT/TinyPtrVector.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000028#include "llvm/ADT/Triple.h"
29#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000030#include "llvm/BinaryFormat/COFF.h"
31#include "llvm/BinaryFormat/Dwarf.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000032#include "llvm/CodeGen/AsmPrinter.h"
33#include "llvm/CodeGen/LexicalScopes.h"
Reid Kleckner9ea2c012018-10-01 21:59:45 +000034#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000035#include "llvm/CodeGen/MachineFunction.h"
36#include "llvm/CodeGen/MachineInstr.h"
37#include "llvm/CodeGen/MachineModuleInfo.h"
38#include "llvm/CodeGen/MachineOperand.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000039#include "llvm/CodeGen/TargetFrameLowering.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000040#include "llvm/CodeGen/TargetRegisterInfo.h"
41#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000042#include "llvm/Config/llvm-config.h"
Reid Klecknerc92e9462016-07-01 18:05:56 +000043#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000044#include "llvm/DebugInfo/CodeView/CodeView.h"
Zachary Turner6900de12017-11-28 18:33:17 +000045#include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h"
Zachary Turner8c099fe2017-05-30 16:36:15 +000046#include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
Reid Kleckner5bf71d12018-12-14 22:40:28 +000047#include "llvm/DebugInfo/CodeView/EnumTables.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000048#include "llvm/DebugInfo/CodeView/Line.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000049#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
Zachary Turner629cb7d2017-01-11 23:24:22 +000050#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000051#include "llvm/DebugInfo/CodeView/TypeIndex.h"
52#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Zachary Turner526f4f22017-05-19 19:26:58 +000053#include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
David Majnemer9319cbc2016-06-30 03:00:20 +000054#include "llvm/IR/Constants.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000055#include "llvm/IR/DataLayout.h"
56#include "llvm/IR/DebugInfoMetadata.h"
57#include "llvm/IR/DebugLoc.h"
58#include "llvm/IR/Function.h"
59#include "llvm/IR/GlobalValue.h"
60#include "llvm/IR/GlobalVariable.h"
61#include "llvm/IR/Metadata.h"
62#include "llvm/IR/Module.h"
Reid Kleckner46cb48c2016-07-27 16:03:57 +000063#include "llvm/MC/MCAsmInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000064#include "llvm/MC/MCContext.h"
Reid Kleckner5d122f82016-05-25 23:16:12 +000065#include "llvm/MC/MCSectionCOFF.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000066#include "llvm/MC/MCStreamer.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000067#include "llvm/MC/MCSymbol.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000068#include "llvm/Support/BinaryByteStream.h"
69#include "llvm/Support/BinaryStreamReader.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000070#include "llvm/Support/Casting.h"
Zachary Turner048f8f92017-12-13 22:33:58 +000071#include "llvm/Support/CommandLine.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000072#include "llvm/Support/Compiler.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000073#include "llvm/Support/Endian.h"
74#include "llvm/Support/Error.h"
75#include "llvm/Support/ErrorHandling.h"
Zachary Turner048f8f92017-12-13 22:33:58 +000076#include "llvm/Support/FormatVariadic.h"
Zachary Turner5bba1ca2018-10-12 17:26:19 +000077#include "llvm/Support/Path.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000078#include "llvm/Support/SMLoc.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000079#include "llvm/Support/ScopedPrinter.h"
David Blaikie6054e652018-03-23 23:58:19 +000080#include "llvm/Target/TargetLoweringObjectFile.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000081#include "llvm/Target/TargetMachine.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000082#include <algorithm>
83#include <cassert>
84#include <cctype>
85#include <cstddef>
86#include <cstdint>
87#include <iterator>
88#include <limits>
89#include <string>
90#include <utility>
91#include <vector>
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000092
Reid Klecknerf9c275f2016-02-10 20:55:49 +000093using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000094using namespace llvm::codeview;
95
Reid Kleckner9ea2c012018-10-01 21:59:45 +000096static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
97 switch (Type) {
98 case Triple::ArchType::x86:
99 return CPUType::Pentium3;
100 case Triple::ArchType::x86_64:
101 return CPUType::X64;
102 case Triple::ArchType::thumb:
103 return CPUType::Thumb;
104 case Triple::ArchType::aarch64:
105 return CPUType::ARM64;
106 default:
107 report_fatal_error("target architecture doesn't map to a CodeView CPUType");
108 }
109}
110
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000111CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000112 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000113 // If module doesn't have named metadata anchors or COFF debug section
114 // is not available, skip any debug info related stuff.
115 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
116 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
117 Asm = nullptr;
Matthias Braun8763c0c2018-10-31 17:18:41 +0000118 MMI->setDebugInfoAvailability(false);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000119 return;
120 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000121 // Tell MMI that we have debug info.
122 MMI->setDebugInfoAvailability(true);
Reid Kleckner9ea2c012018-10-01 21:59:45 +0000123
124 TheCPU =
125 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
Reid Kleckner75557712018-11-16 18:47:41 +0000126
127 // Check if we should emit type record hashes.
128 ConstantInt *GH = mdconst::extract_or_null<ConstantInt>(
129 MMI->getModule()->getModuleFlag("CodeViewGHash"));
130 EmitDebugGlobalHashes = GH && !GH->isZero();
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000131}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000132
Reid Kleckner9533af42016-01-16 00:09:09 +0000133StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
134 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000135 if (!Filepath.empty())
136 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000137
Reid Kleckner9533af42016-01-16 00:09:09 +0000138 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
139
Peter Collingbournecb8a6662018-04-11 18:24:03 +0000140 // If this is a Unix-style path, just use it as is. Don't try to canonicalize
141 // it textually because one of the path components could be a symlink.
Zachary Turner5bba1ca2018-10-12 17:26:19 +0000142 if (Dir.startswith("/") || Filename.startswith("/")) {
143 if (llvm::sys::path::is_absolute(Filename, llvm::sys::path::Style::posix))
144 return Filename;
Peter Collingbournecb8a6662018-04-11 18:24:03 +0000145 Filepath = Dir;
146 if (Dir.back() != '/')
147 Filepath += '/';
148 Filepath += Filename;
149 return Filepath;
150 }
151
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000152 // Clang emits directory and relative filename info into the IR, but CodeView
153 // operates on full paths. We could change Clang to emit full paths too, but
154 // that would increase the IR size and probably not needed for other users.
155 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000156 if (Filename.find(':') == 1)
157 Filepath = Filename;
158 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +0000159 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000160
161 // Canonicalize the path. We have to do it textually because we may no longer
162 // have access the file in the filesystem.
163 // First, replace all slashes with backslashes.
164 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
165
166 // Remove all "\.\" with "\".
167 size_t Cursor = 0;
168 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
169 Filepath.erase(Cursor, 2);
170
171 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
172 // path should be well-formatted, e.g. start with a drive letter, etc.
173 Cursor = 0;
174 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
175 // Something's wrong if the path starts with "\..\", abort.
176 if (Cursor == 0)
177 break;
178
179 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
180 if (PrevSlash == std::string::npos)
181 // Something's wrong, abort.
182 break;
183
184 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
185 // The next ".." might be following the one we've just erased.
186 Cursor = PrevSlash;
187 }
188
189 // Remove all duplicate backslashes.
190 Cursor = 0;
191 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
192 Filepath.erase(Cursor, 1);
193
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000194 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000195}
196
Reid Kleckner2214ed82016-01-29 00:49:42 +0000197unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
Reid Klecknerbc6f52d2017-10-31 21:52:15 +0000198 StringRef FullPath = getFullFilepath(F);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000199 unsigned NextId = FileIdMap.size() + 1;
Reid Klecknerbc6f52d2017-10-31 21:52:15 +0000200 auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
Reid Kleckner2214ed82016-01-29 00:49:42 +0000201 if (Insertion.second) {
202 // We have to compute the full filepath and emit a .cv_file directive.
Scott Linder71603842018-02-12 19:45:54 +0000203 ArrayRef<uint8_t> ChecksumAsBytes;
204 FileChecksumKind CSKind = FileChecksumKind::None;
205 if (F->getChecksum()) {
206 std::string Checksum = fromHex(F->getChecksum()->Value);
207 void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
208 memcpy(CKMem, Checksum.data(), Checksum.size());
209 ChecksumAsBytes = ArrayRef<uint8_t>(
210 reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
211 switch (F->getChecksum()->Kind) {
212 case DIFile::CSK_MD5: CSKind = FileChecksumKind::MD5; break;
213 case DIFile::CSK_SHA1: CSKind = FileChecksumKind::SHA1; break;
214 }
215 }
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000216 bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
Scott Linder71603842018-02-12 19:45:54 +0000217 static_cast<unsigned>(CSKind));
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000218 (void)Success;
219 assert(Success && ".cv_file directive failed");
Reid Kleckner2214ed82016-01-29 00:49:42 +0000220 }
221 return Insertion.first->second;
222}
223
Reid Kleckner876330d2016-02-12 21:48:30 +0000224CodeViewDebug::InlineSite &
225CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
226 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000227 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
228 InlineSite *Site = &SiteInsertion.first->second;
229 if (SiteInsertion.second) {
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000230 unsigned ParentFuncId = CurFn->FuncId;
231 if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
232 ParentFuncId =
233 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
234 .SiteFuncId;
235
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000236 Site->SiteFuncId = NextFuncId++;
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000237 OS.EmitCVInlineSiteIdDirective(
238 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
239 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
Reid Kleckner876330d2016-02-12 21:48:30 +0000240 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000241 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000242 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000243 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000244 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000245}
246
David Majnemer6bdc24e2016-07-01 23:12:45 +0000247static StringRef getPrettyScopeName(const DIScope *Scope) {
248 StringRef ScopeName = Scope->getName();
249 if (!ScopeName.empty())
250 return ScopeName;
251
252 switch (Scope->getTag()) {
253 case dwarf::DW_TAG_enumeration_type:
254 case dwarf::DW_TAG_class_type:
255 case dwarf::DW_TAG_structure_type:
256 case dwarf::DW_TAG_union_type:
257 return "<unnamed-tag>";
258 case dwarf::DW_TAG_namespace:
259 return "`anonymous namespace'";
260 }
261
262 return StringRef();
263}
264
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000265static const DISubprogram *getQualifiedNameComponents(
266 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
267 const DISubprogram *ClosestSubprogram = nullptr;
268 while (Scope != nullptr) {
269 if (ClosestSubprogram == nullptr)
270 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
David Majnemer6bdc24e2016-07-01 23:12:45 +0000271 StringRef ScopeName = getPrettyScopeName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000272 if (!ScopeName.empty())
273 QualifiedNameComponents.push_back(ScopeName);
274 Scope = Scope->getScope().resolve();
275 }
276 return ClosestSubprogram;
277}
278
279static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
280 StringRef TypeName) {
281 std::string FullyQualifiedName;
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000282 for (StringRef QualifiedNameComponent :
283 llvm::reverse(QualifiedNameComponents)) {
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000284 FullyQualifiedName.append(QualifiedNameComponent);
285 FullyQualifiedName.append("::");
286 }
287 FullyQualifiedName.append(TypeName);
288 return FullyQualifiedName;
289}
290
291static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
292 SmallVector<StringRef, 5> QualifiedNameComponents;
293 getQualifiedNameComponents(Scope, QualifiedNameComponents);
294 return getQualifiedName(QualifiedNameComponents, Name);
295}
296
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000297struct CodeViewDebug::TypeLoweringScope {
298 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
299 ~TypeLoweringScope() {
300 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
301 // inner TypeLoweringScopes don't attempt to emit deferred types.
302 if (CVD.TypeEmissionLevel == 1)
303 CVD.emitDeferredCompleteTypes();
304 --CVD.TypeEmissionLevel;
305 }
306 CodeViewDebug &CVD;
307};
308
David Majnemer6bdc24e2016-07-01 23:12:45 +0000309static std::string getFullyQualifiedName(const DIScope *Ty) {
310 const DIScope *Scope = Ty->getScope().resolve();
311 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
312}
313
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000314TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
315 // No scope means global scope and that uses the zero index.
316 if (!Scope || isa<DIFile>(Scope))
317 return TypeIndex();
318
319 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
320
321 // Check if we've already translated this scope.
322 auto I = TypeIndices.find({Scope, nullptr});
323 if (I != TypeIndices.end())
324 return I->second;
325
326 // Build the fully qualified name of the scope.
David Majnemer6bdc24e2016-07-01 23:12:45 +0000327 std::string ScopeName = getFullyQualifiedName(Scope);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000328 StringIdRecord SID(TypeIndex(), ScopeName);
Zachary Turner6900de12017-11-28 18:33:17 +0000329 auto TI = TypeTable.writeLeafType(SID);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000330 return recordTypeIndexForDINode(Scope, TI);
331}
332
David Majnemer75c3ebf2016-06-02 17:13:53 +0000333TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
David Majnemer67f684e2016-07-28 05:03:22 +0000334 assert(SP);
Reid Kleckner2280f932016-05-23 20:23:46 +0000335
David Majnemer75c3ebf2016-06-02 17:13:53 +0000336 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000337 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000338 if (I != TypeIndices.end())
339 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000340
Reid Klecknerac945e22016-06-17 16:11:20 +0000341 // The display name includes function template arguments. Drop them to match
342 // MSVC.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000343 StringRef DisplayName = SP->getName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000344
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000345 const DIScope *Scope = SP->getScope().resolve();
346 TypeIndex TI;
347 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
348 // If the scope is a DICompositeType, then this must be a method. Member
349 // function types take some special handling, and require access to the
350 // subprogram.
351 TypeIndex ClassType = getTypeIndex(Class);
352 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
353 DisplayName);
Zachary Turner6900de12017-11-28 18:33:17 +0000354 TI = TypeTable.writeLeafType(MFuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000355 } else {
356 // Otherwise, this must be a free function.
357 TypeIndex ParentScope = getScopeIndex(Scope);
358 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Zachary Turner6900de12017-11-28 18:33:17 +0000359 TI = TypeTable.writeLeafType(FuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000360 }
361
362 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000363}
364
Aaron Smith802b0332018-10-02 20:21:05 +0000365static bool isTrivial(const DICompositeType *DCTy) {
366 return ((DCTy->getFlags() & DINode::FlagTrivial) == DINode::FlagTrivial);
367}
368
369static FunctionOptions
370getFunctionOptions(const DISubroutineType *Ty,
371 const DICompositeType *ClassTy = nullptr,
372 StringRef SPName = StringRef("")) {
373 FunctionOptions FO = FunctionOptions::None;
374 const DIType *ReturnTy = nullptr;
375 if (auto TypeArray = Ty->getTypeArray()) {
376 if (TypeArray.size())
377 ReturnTy = TypeArray[0].resolve();
378 }
379
380 if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy)) {
381 if (!isTrivial(ReturnDCTy))
382 FO |= FunctionOptions::CxxReturnUdt;
383 }
384
385 // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison.
386 if (ClassTy && !isTrivial(ClassTy) && SPName == ClassTy->getName()) {
387 FO |= FunctionOptions::Constructor;
388
389 // TODO: put the FunctionOptions::ConstructorWithVirtualBases flag.
390
391 }
392 return FO;
393}
394
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000395TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
396 const DICompositeType *Class) {
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000397 // Always use the method declaration as the key for the function type. The
398 // method declaration contains the this adjustment.
399 if (SP->getDeclaration())
400 SP = SP->getDeclaration();
401 assert(!SP->getDeclaration() && "should use declaration as key");
402
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000403 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
404 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000405 auto I = TypeIndices.find({SP, Class});
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000406 if (I != TypeIndices.end())
407 return I->second;
408
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000409 // Make sure complete type info for the class is emitted *after* the member
410 // function type, as the complete class type is likely to reference this
411 // member function type.
412 TypeLoweringScope S(*this);
Adrian McCarthyd91bf392017-09-13 20:53:55 +0000413 const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
Aaron Smith802b0332018-10-02 20:21:05 +0000414
415 FunctionOptions FO = getFunctionOptions(SP->getType(), Class, SP->getName());
Adrian McCarthyd91bf392017-09-13 20:53:55 +0000416 TypeIndex TI = lowerTypeMemberFunction(
Aaron Smith802b0332018-10-02 20:21:05 +0000417 SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000418 return recordTypeIndexForDINode(SP, TI, Class);
419}
420
Amjad Aboudacee5682016-07-12 12:06:34 +0000421TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
422 TypeIndex TI,
423 const DIType *ClassTy) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000424 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000425 (void)InsertResult;
426 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000427 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000428}
429
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000430unsigned CodeViewDebug::getPointerSizeInBytes() {
431 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
432}
433
Reid Kleckner876330d2016-02-12 21:48:30 +0000434void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
Reid Kleckner5a791ee2018-03-15 21:24:04 +0000435 const LexicalScope *LS) {
436 if (const DILocation *InlinedAt = LS->getInlinedAt()) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000437 // This variable was inlined. Associate it with the InlineSite.
438 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
439 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
440 Site.InlinedLocals.emplace_back(Var);
441 } else {
Reid Kleckner5a791ee2018-03-15 21:24:04 +0000442 // This variable goes into the corresponding lexical scope.
443 ScopeVariables[LS].emplace_back(Var);
Reid Kleckner876330d2016-02-12 21:48:30 +0000444 }
445}
446
Reid Kleckner829365a2016-02-11 19:41:47 +0000447static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
448 const DILocation *Loc) {
449 auto B = Locs.begin(), E = Locs.end();
450 if (std::find(B, E, Loc) == E)
451 Locs.push_back(Loc);
452}
453
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000454void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000455 const MachineFunction *MF) {
456 // Skip this instruction if it has the same location as the previous one.
Reid Kleckner45a74622017-06-30 21:33:44 +0000457 if (!DL || DL == PrevInstLoc)
Reid Kleckner9533af42016-01-16 00:09:09 +0000458 return;
459
460 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000461 if (!Scope)
462 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000463
David Majnemerc3340db2016-01-13 01:05:23 +0000464 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000465 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
466 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
467 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000468 return;
469
Reid Kleckner2214ed82016-01-29 00:49:42 +0000470 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
471 if (CI.getStartColumn() != DL.getCol())
472 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000473
Reid Kleckner2214ed82016-01-29 00:49:42 +0000474 if (!CurFn->HaveLineInfo)
475 CurFn->HaveLineInfo = true;
476 unsigned FileId = 0;
Reid Kleckner45a74622017-06-30 21:33:44 +0000477 if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
Reid Kleckner2214ed82016-01-29 00:49:42 +0000478 FileId = CurFn->LastFileId;
479 else
480 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
Reid Kleckner45a74622017-06-30 21:33:44 +0000481 PrevInstLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000482
483 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000484 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000485 const DILocation *Loc = DL.get();
486
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000487 // If this location was actually inlined from somewhere else, give it the ID
488 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000489 FuncId =
490 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000491
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000492 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000493 bool FirstLoc = true;
494 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000495 InlineSite &Site =
496 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000497 if (!FirstLoc)
498 addLocIfNotPresent(Site.ChildSites, Loc);
499 FirstLoc = false;
500 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000501 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000502 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000503 }
504
Reid Klecknerdac21b42016-02-03 21:15:48 +0000505 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000506 /*PrologueEnd=*/false, /*IsStmt=*/false,
507 DL->getFilename(), SMLoc());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000508}
509
Reid Kleckner5d122f82016-05-25 23:16:12 +0000510void CodeViewDebug::emitCodeViewMagicVersion() {
511 OS.EmitValueToAlignment(4);
512 OS.AddComment("Debug section magic");
513 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
514}
515
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000516void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000517 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000518 return;
519
520 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000521
522 // The COFF .debug$S section consists of several subsections, each starting
523 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
524 // of the payload followed by the payload itself. The subsections are 4-byte
525 // aligned.
526
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000527 // Use the generic .debug$S section, and make a subsection for all the inlined
528 // subprograms.
529 switchToDebugSectionForSymbol(nullptr);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000530
Zachary Turner8c099fe2017-05-30 16:36:15 +0000531 MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000532 emitCompilerInformation();
533 endCVSubsection(CompilerInfo);
534
Reid Kleckner5d122f82016-05-25 23:16:12 +0000535 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000536
Reid Kleckner2214ed82016-01-29 00:49:42 +0000537 // Emit per-function debug information.
538 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000539 if (!P.first->isDeclarationForLinker())
Reid Kleckner55baeef2018-03-15 21:12:21 +0000540 emitDebugInfoForFunction(P.first, *P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000541
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000542 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000543 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000544 emitDebugInfoForGlobals();
545
Hans Wennborgb510b452016-06-23 16:33:53 +0000546 // Emit retained types.
547 emitDebugInfoForRetainedTypes();
548
Reid Kleckner5d122f82016-05-25 23:16:12 +0000549 // Switch back to the generic .debug$S section after potentially processing
550 // comdat symbol sections.
551 switchToDebugSectionForSymbol(nullptr);
552
David Majnemer3128b102016-06-15 18:00:01 +0000553 // Emit UDT records for any types used by global variables.
554 if (!GlobalUDTs.empty()) {
Zachary Turner8c099fe2017-05-30 16:36:15 +0000555 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
David Majnemer3128b102016-06-15 18:00:01 +0000556 emitDebugInfoForUDTs(GlobalUDTs);
557 endCVSubsection(SymbolsEnd);
558 }
559
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000560 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000561 OS.AddComment("File index to string table offset subsection");
562 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000563
564 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000565 OS.AddComment("String table");
566 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000567
Reid Kleckner810687c2018-10-12 18:19:06 +0000568 // Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol
569 // subsection in the generic .debug$S section at the end. There is no
570 // particular reason for this ordering other than to match MSVC.
571 emitBuildInfo();
572
Zachary Turner048f8f92017-12-13 22:33:58 +0000573 // Emit type information and hashes last, so that any types we translate while
574 // emitting function info are included.
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000575 emitTypeInformation();
576
Zachary Turner048f8f92017-12-13 22:33:58 +0000577 if (EmitDebugGlobalHashes)
578 emitTypeGlobalHashes();
579
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000580 clear();
581}
582
Brock Wyma19e17b32018-02-11 21:26:46 +0000583static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S,
584 unsigned MaxFixedRecordLength = 0xF00) {
Reid Klecknerbb96df62016-10-05 22:36:07 +0000585 // The maximum CV record length is 0xFF00. Most of the strings we emit appear
586 // after a fixed length portion of the record. The fixed length portion should
587 // always be less than 0xF00 (3840) bytes, so truncate the string so that the
588 // overall record size is less than the maximum allowed.
Reid Klecknerbb96df62016-10-05 22:36:07 +0000589 SmallString<32> NullTerminatedString(
590 S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
David Majnemerb9456a52016-03-14 05:15:09 +0000591 NullTerminatedString.push_back('\0');
592 OS.EmitBytes(NullTerminatedString);
593}
594
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000595void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000596 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000597 return;
598
Alexandre Ganead9e96742018-04-09 20:17:56 +0000599 // Start the .debug$T or .debug$P section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000600 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000601 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000602
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000603 SmallString<8> CommentPrefix;
604 if (OS.isVerboseAsm()) {
605 CommentPrefix += '\t';
606 CommentPrefix += Asm->MAI->getCommentString();
607 CommentPrefix += ' ';
608 }
609
Zachary Turner526f4f22017-05-19 19:26:58 +0000610 TypeTableCollection Table(TypeTable.records());
611 Optional<TypeIndex> B = Table.getFirst();
612 while (B) {
613 // This will fail if the record data is invalid.
614 CVType Record = Table.getType(*B);
615
Zachary Turner4efa0a42016-11-08 22:24:53 +0000616 if (OS.isVerboseAsm()) {
617 // Emit a block comment describing the type record for readability.
618 SmallString<512> CommentBlock;
619 raw_svector_ostream CommentOS(CommentBlock);
620 ScopedPrinter SP(CommentOS);
621 SP.setPrefix(CommentPrefix);
Zachary Turner526f4f22017-05-19 19:26:58 +0000622 TypeDumpVisitor TDV(Table, &SP, false);
623
624 Error E = codeview::visitTypeRecord(Record, *B, TDV);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000625 if (E) {
626 logAllUnhandledErrors(std::move(E), errs(), "error: ");
627 llvm_unreachable("produced malformed type record");
628 }
629 // emitRawComment will insert its own tab and comment string before
630 // the first line, so strip off our first one. It also prints its own
631 // newline.
632 OS.emitRawComment(
633 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
Zachary Turner4efa0a42016-11-08 22:24:53 +0000634 }
Zachary Turner526f4f22017-05-19 19:26:58 +0000635 OS.EmitBinaryData(Record.str_data());
636 B = Table.getNext(*B);
637 }
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000638}
639
Zachary Turner048f8f92017-12-13 22:33:58 +0000640void CodeViewDebug::emitTypeGlobalHashes() {
641 if (TypeTable.empty())
642 return;
643
644 // Start the .debug$H section with the version and hash algorithm, currently
645 // hardcoded to version 0, SHA1.
646 OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
647
648 OS.EmitValueToAlignment(4);
649 OS.AddComment("Magic");
650 OS.EmitIntValue(COFF::DEBUG_HASHES_SECTION_MAGIC, 4);
651 OS.AddComment("Section Version");
652 OS.EmitIntValue(0, 2);
653 OS.AddComment("Hash Algorithm");
Zachary Turnerc7626662018-05-17 22:55:15 +0000654 OS.EmitIntValue(uint16_t(GlobalTypeHashAlg::SHA1_8), 2);
Zachary Turner048f8f92017-12-13 22:33:58 +0000655
656 TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
657 for (const auto &GHR : TypeTable.hashes()) {
658 if (OS.isVerboseAsm()) {
659 // Emit an EOL-comment describing which TypeIndex this hash corresponds
660 // to, as well as the stringified SHA1 hash.
661 SmallString<32> Comment;
662 raw_svector_ostream CommentOS(Comment);
663 CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
664 OS.AddComment(Comment);
665 ++TI;
666 }
Zachary Turnerc7626662018-05-17 22:55:15 +0000667 assert(GHR.Hash.size() == 8);
Zachary Turner048f8f92017-12-13 22:33:58 +0000668 StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
669 GHR.Hash.size());
670 OS.EmitBinaryData(S);
671 }
672}
673
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000674static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
675 switch (DWLang) {
676 case dwarf::DW_LANG_C:
677 case dwarf::DW_LANG_C89:
678 case dwarf::DW_LANG_C99:
679 case dwarf::DW_LANG_C11:
680 case dwarf::DW_LANG_ObjC:
681 return SourceLanguage::C;
682 case dwarf::DW_LANG_C_plus_plus:
683 case dwarf::DW_LANG_C_plus_plus_03:
684 case dwarf::DW_LANG_C_plus_plus_11:
685 case dwarf::DW_LANG_C_plus_plus_14:
686 return SourceLanguage::Cpp;
687 case dwarf::DW_LANG_Fortran77:
688 case dwarf::DW_LANG_Fortran90:
689 case dwarf::DW_LANG_Fortran03:
690 case dwarf::DW_LANG_Fortran08:
691 return SourceLanguage::Fortran;
692 case dwarf::DW_LANG_Pascal83:
693 return SourceLanguage::Pascal;
694 case dwarf::DW_LANG_Cobol74:
695 case dwarf::DW_LANG_Cobol85:
696 return SourceLanguage::Cobol;
697 case dwarf::DW_LANG_Java:
698 return SourceLanguage::Java;
Reid Kleckner898ddf62017-07-24 16:16:42 +0000699 case dwarf::DW_LANG_D:
700 return SourceLanguage::D;
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000701 default:
702 // There's no CodeView representation for this language, and CV doesn't
703 // have an "unknown" option for the language field, so we'll use MASM,
704 // as it's very low level.
705 return SourceLanguage::Masm;
706 }
707}
708
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000709namespace {
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000710struct Version {
711 int Part[4];
712};
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000713} // end anonymous namespace
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000714
715// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
716// the version number.
717static Version parseVersion(StringRef Name) {
Adrian McCarthyad8ac542016-09-20 17:42:13 +0000718 Version V = {{0}};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000719 int N = 0;
720 for (const char C : Name) {
721 if (isdigit(C)) {
722 V.Part[N] *= 10;
723 V.Part[N] += C - '0';
724 } else if (C == '.') {
725 ++N;
726 if (N >= 4)
727 return V;
728 } else if (N > 0)
729 return V;
730 }
731 return V;
732}
733
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000734void CodeViewDebug::emitCompilerInformation() {
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000735 MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_COMPILE3);
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000736 uint32_t Flags = 0;
737
738 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
739 const MDNode *Node = *CUs->operands().begin();
740 const auto *CU = cast<DICompileUnit>(Node);
741
742 // The low byte of the flags indicates the source language.
743 Flags = MapDWLangToCVLang(CU->getSourceLanguage());
744 // TODO: Figure out which other flags need to be set.
745
746 OS.AddComment("Flags and language");
747 OS.EmitIntValue(Flags, 4);
748
749 OS.AddComment("CPUType");
Reid Kleckner9ea2c012018-10-01 21:59:45 +0000750 OS.EmitIntValue(static_cast<uint64_t>(TheCPU), 2);
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000751
752 StringRef CompilerVersion = CU->getProducer();
753 Version FrontVer = parseVersion(CompilerVersion);
754 OS.AddComment("Frontend version");
755 for (int N = 0; N < 4; ++N)
756 OS.EmitIntValue(FrontVer.Part[N], 2);
757
758 // Some Microsoft tools, like Binscope, expect a backend version number of at
759 // least 8.something, so we'll coerce the LLVM version into a form that
760 // guarantees it'll be big enough without really lying about the version.
Adrian McCarthyd1185fc2016-09-29 20:28:25 +0000761 int Major = 1000 * LLVM_VERSION_MAJOR +
762 10 * LLVM_VERSION_MINOR +
763 LLVM_VERSION_PATCH;
764 // Clamp it for builds that use unusually large version numbers.
765 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
766 Version BackVer = {{ Major, 0, 0, 0 }};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000767 OS.AddComment("Backend version");
768 for (int N = 0; N < 4; ++N)
769 OS.EmitIntValue(BackVer.Part[N], 2);
770
771 OS.AddComment("Null-terminated compiler version string");
772 emitNullTerminatedSymbolName(OS, CompilerVersion);
773
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000774 endSymbolRecord(CompilerEnd);
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000775}
776
Reid Kleckner810687c2018-10-12 18:19:06 +0000777static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable,
778 StringRef S) {
779 StringIdRecord SIR(TypeIndex(0x0), S);
780 return TypeTable.writeLeafType(SIR);
781}
782
783void CodeViewDebug::emitBuildInfo() {
784 // First, make LF_BUILDINFO. It's a sequence of strings with various bits of
785 // build info. The known prefix is:
786 // - Absolute path of current directory
787 // - Compiler path
788 // - Main source file path, relative to CWD or absolute
789 // - Type server PDB file
790 // - Canonical compiler command line
791 // If frontend and backend compilation are separated (think llc or LTO), it's
792 // not clear if the compiler path should refer to the executable for the
793 // frontend or the backend. Leave it blank for now.
794 TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {};
795 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
796 const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs.
797 const auto *CU = cast<DICompileUnit>(Node);
798 const DIFile *MainSourceFile = CU->getFile();
799 BuildInfoArgs[BuildInfoRecord::CurrentDirectory] =
800 getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory());
801 BuildInfoArgs[BuildInfoRecord::SourceFile] =
802 getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename());
803 // FIXME: Path to compiler and command line. PDB is intentionally blank unless
804 // we implement /Zi type servers.
805 BuildInfoRecord BIR(BuildInfoArgs);
806 TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR);
807
808 // Make a new .debug$S subsection for the S_BUILDINFO record, which points
809 // from the module symbols into the type stream.
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000810 MCSymbol *BISubsecEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
811 MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO);
Reid Kleckner810687c2018-10-12 18:19:06 +0000812 OS.AddComment("LF_BUILDINFO index");
813 OS.EmitIntValue(BuildInfoIndex.getIndex(), 4);
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000814 endSymbolRecord(BIEnd);
815 endCVSubsection(BISubsecEnd);
Reid Kleckner810687c2018-10-12 18:19:06 +0000816}
817
Reid Kleckner5d122f82016-05-25 23:16:12 +0000818void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000819 if (InlinedSubprograms.empty())
820 return;
821
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000822 OS.AddComment("Inlinee lines subsection");
Zachary Turner8c099fe2017-05-30 16:36:15 +0000823 MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000824
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000825 // We emit the checksum info for files. This is used by debuggers to
826 // determine if a pdb matches the source before loading it. Visual Studio,
827 // for instance, will display a warning that the breakpoints are not valid if
828 // the pdb does not match the source.
David Majnemer30579ec2016-02-02 23:18:23 +0000829 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000830 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
831
832 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000833 assert(TypeIndices.count({SP, nullptr}));
834 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000835
David Majnemer30579ec2016-02-02 23:18:23 +0000836 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000837 unsigned FileId = maybeRecordFile(SP->getFile());
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000838 OS.AddComment("Inlined function " + SP->getName() + " starts at " +
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000839 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000840 OS.AddBlankLine();
David Majnemer30579ec2016-02-02 23:18:23 +0000841 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000842 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000843 OS.AddComment("Offset into filechecksum table");
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000844 OS.EmitCVFileChecksumOffsetDirective(FileId);
David Majnemer30579ec2016-02-02 23:18:23 +0000845 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000846 OS.EmitIntValue(SP->getLine(), 4);
847 }
848
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000849 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000850}
851
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000852void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
853 const DILocation *InlinedAt,
854 const InlineSite &Site) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000855 assert(TypeIndices.count({Site.Inlinee, nullptr}));
856 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000857
858 // SymbolRecord
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000859 MCSymbol *InlineEnd = beginSymbolRecord(SymbolKind::S_INLINESITE);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000860
Reid Klecknerdac21b42016-02-03 21:15:48 +0000861 OS.AddComment("PtrParent");
862 OS.EmitIntValue(0, 4);
863 OS.AddComment("PtrEnd");
864 OS.EmitIntValue(0, 4);
865 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000866 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000867
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000868 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
869 unsigned StartLineNum = Site.Inlinee->getLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000870
871 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000872 FI.Begin, FI.End);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000873
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000874 endSymbolRecord(InlineEnd);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000875
Reid Kleckner9ea2c012018-10-01 21:59:45 +0000876 emitLocalVariableList(FI, Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000877
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000878 // Recurse on child inlined call sites before closing the scope.
879 for (const DILocation *ChildSite : Site.ChildSites) {
880 auto I = FI.InlineSites.find(ChildSite);
881 assert(I != FI.InlineSites.end() &&
882 "child site not in function inline site map");
883 emitInlinedCallSite(FI, ChildSite, I->second);
884 }
885
886 // Close the scope.
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000887 emitEndSymbolRecord(SymbolKind::S_INLINESITE_END);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000888}
889
Reid Kleckner5d122f82016-05-25 23:16:12 +0000890void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
891 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
892 // comdat key. A section may be comdat because of -ffunction-sections or
893 // because it is comdat in the IR.
894 MCSectionCOFF *GVSec =
895 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
896 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
897
898 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
899 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
900 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
901
902 OS.SwitchSection(DebugSec);
903
904 // Emit the magic version number if this is the first time we've switched to
905 // this section.
906 if (ComdatDebugSections.insert(DebugSec).second)
907 emitCodeViewMagicVersion();
908}
909
Brock Wyma94ece8f2018-04-16 16:53:57 +0000910// Emit an S_THUNK32/S_END symbol pair for a thunk routine.
911// The only supported thunk ordinal is currently the standard type.
912void CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
913 FunctionInfo &FI,
914 const MCSymbol *Fn) {
915 std::string FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
916 const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
917
918 OS.AddComment("Symbol subsection for " + Twine(FuncName));
919 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
920
921 // Emit S_THUNK32
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000922 MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32);
Brock Wyma94ece8f2018-04-16 16:53:57 +0000923 OS.AddComment("PtrParent");
924 OS.EmitIntValue(0, 4);
925 OS.AddComment("PtrEnd");
926 OS.EmitIntValue(0, 4);
927 OS.AddComment("PtrNext");
928 OS.EmitIntValue(0, 4);
929 OS.AddComment("Thunk section relative address");
930 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
931 OS.AddComment("Thunk section index");
932 OS.EmitCOFFSectionIndex(Fn);
933 OS.AddComment("Code size");
934 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
935 OS.AddComment("Ordinal");
936 OS.EmitIntValue(unsigned(ordinal), 1);
937 OS.AddComment("Function name");
938 emitNullTerminatedSymbolName(OS, FuncName);
939 // Additional fields specific to the thunk ordinal would go here.
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000940 endSymbolRecord(ThunkRecordEnd);
Brock Wyma94ece8f2018-04-16 16:53:57 +0000941
942 // Local variables/inlined routines are purposely omitted here. The point of
943 // marking this as a thunk is so Visual Studio will NOT stop in this routine.
944
945 // Emit S_PROC_ID_END
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000946 emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
Brock Wyma94ece8f2018-04-16 16:53:57 +0000947
948 endCVSubsection(SymbolsEnd);
949}
950
Reid Kleckner2214ed82016-01-29 00:49:42 +0000951void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
952 FunctionInfo &FI) {
Brock Wyma31cc1eb2018-01-30 13:16:50 +0000953 // For each function there is a separate subsection which holds the PC to
954 // file:line table.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000955 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000956 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000957
Reid Kleckner5d122f82016-05-25 23:16:12 +0000958 // Switch to the to a comdat section, if appropriate.
959 switchToDebugSectionForSymbol(Fn);
960
Reid Klecknerac945e22016-06-17 16:11:20 +0000961 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000962 auto *SP = GV->getSubprogram();
David Majnemer67f684e2016-07-28 05:03:22 +0000963 assert(SP);
David Majnemer3128b102016-06-15 18:00:01 +0000964 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000965
Brock Wyma94ece8f2018-04-16 16:53:57 +0000966 if (SP->isThunk()) {
967 emitDebugInfoForThunk(GV, FI, Fn);
968 return;
969 }
970
Reid Klecknerac945e22016-06-17 16:11:20 +0000971 // If we have a display name, build the fully qualified name by walking the
972 // chain of scopes.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000973 if (!SP->getName().empty())
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000974 FuncName =
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000975 getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000976
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000977 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000978 if (FuncName.empty())
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +0000979 FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000980
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000981 // Emit FPO data, but only on 32-bit x86. No other platforms use it.
982 if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
983 OS.EmitCVFPOData(Fn);
984
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000985 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000986 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Zachary Turner8c099fe2017-05-30 16:36:15 +0000987 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000988 {
Reid Kleckner5bf71d12018-12-14 22:40:28 +0000989 SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID
990 : SymbolKind::S_GPROC32_ID;
991 MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind);
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000992
David Majnemer30579ec2016-02-02 23:18:23 +0000993 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000994 OS.AddComment("PtrParent");
995 OS.EmitIntValue(0, 4);
996 OS.AddComment("PtrEnd");
997 OS.EmitIntValue(0, 4);
998 OS.AddComment("PtrNext");
999 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001000 // This is the important bit that tells the debugger where the function
1001 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +00001002 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +00001003 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +00001004 OS.AddComment("Offset after prologue");
1005 OS.EmitIntValue(0, 4);
1006 OS.AddComment("Offset before epilogue");
1007 OS.EmitIntValue(0, 4);
1008 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +00001009 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +00001010 OS.AddComment("Function section relative address");
Keno Fischerf7d84ee2017-01-02 03:00:19 +00001011 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
Reid Klecknerdac21b42016-02-03 21:15:48 +00001012 OS.AddComment("Function section index");
1013 OS.EmitCOFFSectionIndex(Fn);
1014 OS.AddComment("Flags");
1015 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +00001016 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +00001017 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +00001018 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00001019 emitNullTerminatedSymbolName(OS, FuncName);
Reid Kleckner5bf71d12018-12-14 22:40:28 +00001020 endSymbolRecord(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001021
Reid Kleckner5bf71d12018-12-14 22:40:28 +00001022 MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC);
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001023 // Subtract out the CSR size since MSVC excludes that and we include it.
1024 OS.AddComment("FrameSize");
1025 OS.EmitIntValue(FI.FrameSize - FI.CSRSize, 4);
1026 OS.AddComment("Padding");
1027 OS.EmitIntValue(0, 4);
1028 OS.AddComment("Offset of padding");
1029 OS.EmitIntValue(0, 4);
1030 OS.AddComment("Bytes of callee saved registers");
1031 OS.EmitIntValue(FI.CSRSize, 4);
1032 OS.AddComment("Exception handler offset");
1033 OS.EmitIntValue(0, 4);
1034 OS.AddComment("Exception handler section");
1035 OS.EmitIntValue(0, 2);
1036 OS.AddComment("Flags (defines frame register)");
1037 OS.EmitIntValue(uint32_t(FI.FrameProcOpts), 4);
Reid Kleckner5bf71d12018-12-14 22:40:28 +00001038 endSymbolRecord(FrameProcEnd);
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001039
1040 emitLocalVariableList(FI, FI.Locals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00001041 emitLexicalBlockList(FI.ChildBlocks, FI);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001042
Reid Klecknerf3b9ba42016-01-29 18:16:43 +00001043 // Emit inlined call site information. Only emit functions inlined directly
1044 // into the parent function. We'll emit the other sites recursively as part
1045 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001046 for (const DILocation *InlinedAt : FI.ChildSites) {
1047 auto I = FI.InlineSites.find(InlinedAt);
1048 assert(I != FI.InlineSites.end() &&
1049 "child site not in function inline site map");
1050 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +00001051 }
1052
Reid Klecknere33c94f2017-09-05 20:14:58 +00001053 for (auto Annot : FI.Annotations) {
1054 MCSymbol *Label = Annot.first;
1055 MDTuple *Strs = cast<MDTuple>(Annot.second);
Reid Kleckner5bf71d12018-12-14 22:40:28 +00001056 MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION);
Reid Klecknere33c94f2017-09-05 20:14:58 +00001057 OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
1058 // FIXME: Make sure we don't overflow the max record size.
1059 OS.EmitCOFFSectionIndex(Label);
1060 OS.EmitIntValue(Strs->getNumOperands(), 2);
1061 for (Metadata *MD : Strs->operands()) {
1062 // MDStrings are null terminated, so we can do EmitBytes and get the
1063 // nice .asciz directive.
1064 StringRef Str = cast<MDString>(MD)->getString();
1065 assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
1066 OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
1067 }
Reid Kleckner5bf71d12018-12-14 22:40:28 +00001068 endSymbolRecord(AnnotEnd);
Reid Klecknere33c94f2017-09-05 20:14:58 +00001069 }
1070
David Majnemer3128b102016-06-15 18:00:01 +00001071 if (SP != nullptr)
1072 emitDebugInfoForUDTs(LocalUDTs);
1073
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001074 // We're done with this function.
Reid Kleckner5bf71d12018-12-14 22:40:28 +00001075 emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001076 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001077 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001078
Reid Kleckner2214ed82016-01-29 00:49:42 +00001079 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +00001080 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001081}
1082
Reid Kleckner876330d2016-02-12 21:48:30 +00001083CodeViewDebug::LocalVarDefRange
1084CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
1085 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +00001086 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +00001087 DR.DataOffset = Offset;
1088 assert(DR.DataOffset == Offset && "truncation");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00001089 DR.IsSubfield = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +00001090 DR.StructOffset = 0;
1091 DR.CVRegister = CVRegister;
1092 return DR;
1093}
1094
Matthias Braunef331ef2016-11-30 23:48:50 +00001095void CodeViewDebug::collectVariableInfoFromMFTable(
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001096 DenseSet<InlinedEntity> &Processed) {
Matthias Braunef331ef2016-11-30 23:48:50 +00001097 const MachineFunction &MF = *Asm->MF;
1098 const TargetSubtargetInfo &TSI = MF.getSubtarget();
Reid Kleckner876330d2016-02-12 21:48:30 +00001099 const TargetFrameLowering *TFI = TSI.getFrameLowering();
1100 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1101
Matthias Braunef331ef2016-11-30 23:48:50 +00001102 for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001103 if (!VI.Var)
1104 continue;
1105 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1106 "Expected inlined-at fields to agree");
1107
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001108 Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001109 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1110
1111 // If variable scope is not found then skip this variable.
1112 if (!Scope)
1113 continue;
1114
Reid Klecknerb5fced72017-05-09 19:59:29 +00001115 // If the variable has an attached offset expression, extract it.
1116 // FIXME: Try to handle DW_OP_deref as well.
1117 int64_t ExprOffset = 0;
1118 if (VI.Expr)
1119 if (!VI.Expr->extractIfOffset(ExprOffset))
1120 continue;
1121
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001122 // Get the frame register used and the offset.
1123 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +00001124 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
1125 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001126
1127 // Calculate the label ranges.
Reid Klecknerb5fced72017-05-09 19:59:29 +00001128 LocalVarDefRange DefRange =
1129 createDefRangeMem(CVReg, FrameOffset + ExprOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001130 for (const InsnRange &Range : Scope->getRanges()) {
1131 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1132 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +00001133 End = End ? End : Asm->getFunctionEnd();
1134 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001135 }
1136
Reid Kleckner876330d2016-02-12 21:48:30 +00001137 LocalVariable Var;
1138 Var.DIVar = VI.Var;
1139 Var.DefRanges.emplace_back(std::move(DefRange));
Reid Kleckner5a791ee2018-03-15 21:24:04 +00001140 recordLocalVariable(std::move(Var), Scope);
Reid Kleckner876330d2016-02-12 21:48:30 +00001141 }
1142}
1143
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001144static bool canUseReferenceType(const DbgVariableLocation &Loc) {
1145 return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
1146}
1147
1148static bool needsReferenceType(const DbgVariableLocation &Loc) {
1149 return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
1150}
1151
Bob Haarman223303c2017-08-29 20:59:25 +00001152void CodeViewDebug::calculateRanges(
1153 LocalVariable &Var, const DbgValueHistoryMap::InstrRanges &Ranges) {
1154 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1155
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001156 // Calculate the definition ranges.
Bob Haarman223303c2017-08-29 20:59:25 +00001157 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1158 const InsnRange &Range = *I;
1159 const MachineInstr *DVInst = Range.first;
1160 assert(DVInst->isDebugValue() && "Invalid History entry");
1161 // FIXME: Find a way to represent constant variables, since they are
1162 // relatively common.
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001163 Optional<DbgVariableLocation> Location =
1164 DbgVariableLocation::extractFromMachineInstruction(*DVInst);
1165 if (!Location)
Bob Haarmana88bce12017-08-29 21:01:55 +00001166 continue;
Bob Haarman223303c2017-08-29 20:59:25 +00001167
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001168 // CodeView can only express variables in register and variables in memory
1169 // at a constant offset from a register. However, for variables passed
1170 // indirectly by pointer, it is common for that pointer to be spilled to a
1171 // stack location. For the special case of one offseted load followed by a
1172 // zero offset load (a pointer spilled to the stack), we change the type of
1173 // the local variable from a value type to a reference type. This tricks the
1174 // debugger into doing the load for us.
1175 if (Var.UseReferenceType) {
1176 // We're using a reference type. Drop the last zero offset load.
1177 if (canUseReferenceType(*Location))
1178 Location->LoadChain.pop_back();
1179 else
1180 continue;
1181 } else if (needsReferenceType(*Location)) {
1182 // This location can't be expressed without switching to a reference type.
1183 // Start over using that.
1184 Var.UseReferenceType = true;
Bob Haarman223303c2017-08-29 20:59:25 +00001185 Var.DefRanges.clear();
1186 calculateRanges(Var, Ranges);
1187 return;
1188 }
1189
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001190 // We can only handle a register or an offseted load of a register.
1191 if (Location->Register == 0 || Location->LoadChain.size() > 1)
Bob Haarman223303c2017-08-29 20:59:25 +00001192 continue;
Bob Haarman223303c2017-08-29 20:59:25 +00001193 {
1194 LocalVarDefRange DR;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001195 DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001196 DR.InMemory = !Location->LoadChain.empty();
1197 DR.DataOffset =
1198 !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001199 if (Location->FragmentInfo) {
Bob Haarman223303c2017-08-29 20:59:25 +00001200 DR.IsSubfield = true;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001201 DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
Bob Haarman223303c2017-08-29 20:59:25 +00001202 } else {
1203 DR.IsSubfield = false;
1204 DR.StructOffset = 0;
1205 }
1206
1207 if (Var.DefRanges.empty() ||
1208 Var.DefRanges.back().isDifferentLocation(DR)) {
1209 Var.DefRanges.emplace_back(std::move(DR));
1210 }
1211 }
1212
1213 // Compute the label range.
1214 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1215 const MCSymbol *End = getLabelAfterInsn(Range.second);
1216 if (!End) {
1217 // This range is valid until the next overlapping bitpiece. In the
1218 // common case, ranges will not be bitpieces, so they will overlap.
1219 auto J = std::next(I);
1220 const DIExpression *DIExpr = DVInst->getDebugExpression();
1221 while (J != E &&
Bjorn Petterssona223f8152018-03-12 18:02:39 +00001222 !DIExpr->fragmentsOverlap(J->first->getDebugExpression()))
Bob Haarman223303c2017-08-29 20:59:25 +00001223 ++J;
1224 if (J != E)
1225 End = getLabelBeforeInsn(J->first);
1226 else
1227 End = Asm->getFunctionEnd();
1228 }
1229
1230 // If the last range end is our begin, just extend the last range.
1231 // Otherwise make a new range.
1232 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1233 Var.DefRanges.back().Ranges;
1234 if (!R.empty() && R.back().second == Begin)
1235 R.back().second = End;
1236 else
1237 R.emplace_back(Begin, End);
1238
1239 // FIXME: Do more range combining.
1240 }
1241}
1242
Reid Kleckner876330d2016-02-12 21:48:30 +00001243void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001244 DenseSet<InlinedEntity> Processed;
Reid Kleckner876330d2016-02-12 21:48:30 +00001245 // Grab the variable info that was squirreled away in the MMI side-table.
Matthias Braunef331ef2016-11-30 23:48:50 +00001246 collectVariableInfoFromMFTable(Processed);
Reid Kleckner876330d2016-02-12 21:48:30 +00001247
Reid Kleckner876330d2016-02-12 21:48:30 +00001248 for (const auto &I : DbgValues) {
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001249 InlinedEntity IV = I.first;
Reid Kleckner876330d2016-02-12 21:48:30 +00001250 if (Processed.count(IV))
1251 continue;
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001252 const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
Reid Kleckner876330d2016-02-12 21:48:30 +00001253 const DILocation *InlinedAt = IV.second;
1254
1255 // Instruction ranges, specifying where IV is accessible.
1256 const auto &Ranges = I.second;
1257
1258 LexicalScope *Scope = nullptr;
1259 if (InlinedAt)
1260 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1261 else
1262 Scope = LScopes.findLexicalScope(DIVar->getScope());
1263 // If variable scope is not found then skip this variable.
1264 if (!Scope)
1265 continue;
1266
1267 LocalVariable Var;
1268 Var.DIVar = DIVar;
1269
Bob Haarman223303c2017-08-29 20:59:25 +00001270 calculateRanges(Var, Ranges);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00001271 recordLocalVariable(std::move(Var), Scope);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001272 }
1273}
1274
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001275void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001276 const TargetSubtargetInfo &TSI = MF->getSubtarget();
1277 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1278 const MachineFrameInfo &MFI = MF->getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00001279 const Function &GV = MF->getFunction();
Reid Kleckner55baeef2018-03-15 21:12:21 +00001280 auto Insertion = FnDebugInfo.insert({&GV, llvm::make_unique<FunctionInfo>()});
Reid Klecknere9dc30d2018-03-15 21:18:42 +00001281 assert(Insertion.second && "function already has info");
Reid Kleckner55baeef2018-03-15 21:12:21 +00001282 CurFn = Insertion.first->second.get();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001283 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +00001284 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001285
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001286 // The S_FRAMEPROC record reports the stack size, and how many bytes of
1287 // callee-saved registers were used. For targets that don't use a PUSH
1288 // instruction (AArch64), this will be zero.
1289 CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
1290 CurFn->FrameSize = MFI.getStackSize();
Reid Kleckner2bcb2882018-11-03 00:41:52 +00001291 CurFn->OffsetAdjustment = MFI.getOffsetAdjustment();
Reid Klecknerd5e4ec72018-10-02 16:43:52 +00001292 CurFn->HasStackRealignment = TRI->needsStackRealignment(*MF);
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001293
1294 // For this function S_FRAMEPROC record, figure out which codeview register
1295 // will be the frame pointer.
1296 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
1297 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
1298 if (CurFn->FrameSize > 0) {
1299 if (!TSI.getFrameLowering()->hasFP(*MF)) {
1300 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1301 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
1302 } else {
1303 // If there is an FP, parameters are always relative to it.
1304 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
Reid Klecknerd5e4ec72018-10-02 16:43:52 +00001305 if (CurFn->HasStackRealignment) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001306 // If the stack needs realignment, locals are relative to SP or VFRAME.
1307 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1308 } else {
1309 // Otherwise, locals are relative to EBP, and we probably have VLAs or
1310 // other stack adjustments.
1311 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
1312 }
1313 }
1314 }
1315
1316 // Compute other frame procedure options.
1317 FrameProcedureOptions FPO = FrameProcedureOptions::None;
1318 if (MFI.hasVarSizedObjects())
1319 FPO |= FrameProcedureOptions::HasAlloca;
1320 if (MF->exposesReturnsTwice())
1321 FPO |= FrameProcedureOptions::HasSetJmp;
1322 // FIXME: Set HasLongJmp if we ever track that info.
1323 if (MF->hasInlineAsm())
1324 FPO |= FrameProcedureOptions::HasInlineAssembly;
1325 if (GV.hasPersonalityFn()) {
1326 if (isAsynchronousEHPersonality(
1327 classifyEHPersonality(GV.getPersonalityFn())))
1328 FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
1329 else
1330 FPO |= FrameProcedureOptions::HasExceptionHandling;
1331 }
1332 if (GV.hasFnAttribute(Attribute::InlineHint))
1333 FPO |= FrameProcedureOptions::MarkedInline;
1334 if (GV.hasFnAttribute(Attribute::Naked))
1335 FPO |= FrameProcedureOptions::Naked;
1336 if (MFI.hasStackProtectorIndex())
1337 FPO |= FrameProcedureOptions::SecurityChecks;
1338 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
1339 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
1340 if (Asm->TM.getOptLevel() != CodeGenOpt::None && !GV.optForSize() &&
1341 !GV.hasFnAttribute(Attribute::OptimizeNone))
1342 FPO |= FrameProcedureOptions::OptimizedForSpeed;
1343 // FIXME: Set GuardCfg when it is implemented.
1344 CurFn->FrameProcOpts = FPO;
1345
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001346 OS.EmitCVFuncIdDirective(CurFn->FuncId);
1347
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001348 // Find the end of the function prolog. First known non-DBG_VALUE and
1349 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001350 // FIXME: is there a simpler a way to do this? Can we just search
1351 // for the first instruction of the function, not the last of the prolog?
1352 DebugLoc PrologEndLoc;
1353 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001354 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001355 for (const auto &MI : MBB) {
Adrian Prantlfb31da12017-05-22 20:47:09 +00001356 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001357 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001358 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001359 break;
Adrian Prantlfb31da12017-05-22 20:47:09 +00001360 } else if (!MI.isMetaInstruction()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001361 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001362 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001363 }
1364 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001365
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001366 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001367 if (PrologEndLoc && !EmptyPrologue) {
1368 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001369 maybeRecordLocation(FnStartDL, MF);
1370 }
1371}
1372
Zachary Turnera7b04172017-08-28 18:49:04 +00001373static bool shouldEmitUdt(const DIType *T) {
Zachary Turner37c74742017-09-05 22:06:39 +00001374 if (!T)
1375 return false;
1376
1377 // MSVC does not emit UDTs for typedefs that are scoped to classes.
1378 if (T->getTag() == dwarf::DW_TAG_typedef) {
1379 if (DIScope *Scope = T->getScope().resolve()) {
1380 switch (Scope->getTag()) {
1381 case dwarf::DW_TAG_structure_type:
1382 case dwarf::DW_TAG_class_type:
1383 case dwarf::DW_TAG_union_type:
1384 return false;
1385 }
1386 }
1387 }
1388
Zachary Turnera7b04172017-08-28 18:49:04 +00001389 while (true) {
1390 if (!T || T->isForwardDecl())
1391 return false;
1392
1393 const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
1394 if (!DT)
1395 return true;
1396 T = DT->getBaseType().resolve();
1397 }
1398 return true;
1399}
1400
1401void CodeViewDebug::addToUDTs(const DIType *Ty) {
Reid Klecknerad56ea32016-07-01 22:24:51 +00001402 // Don't record empty UDTs.
1403 if (Ty->getName().empty())
1404 return;
Zachary Turnera7b04172017-08-28 18:49:04 +00001405 if (!shouldEmitUdt(Ty))
1406 return;
Reid Klecknerad56ea32016-07-01 22:24:51 +00001407
Hans Wennborg4b63a982016-06-23 22:57:25 +00001408 SmallVector<StringRef, 5> QualifiedNameComponents;
1409 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1410 Ty->getScope().resolve(), QualifiedNameComponents);
1411
1412 std::string FullyQualifiedName =
David Majnemer6bdc24e2016-07-01 23:12:45 +00001413 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
Hans Wennborg4b63a982016-06-23 22:57:25 +00001414
Zachary Turnera7b04172017-08-28 18:49:04 +00001415 if (ClosestSubprogram == nullptr) {
1416 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1417 } else if (ClosestSubprogram == CurrentSubprogram) {
1418 LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1419 }
Hans Wennborg4b63a982016-06-23 22:57:25 +00001420
1421 // TODO: What if the ClosestSubprogram is neither null or the current
1422 // subprogram? Currently, the UDT just gets dropped on the floor.
1423 //
1424 // The current behavior is not desirable. To get maximal fidelity, we would
1425 // need to perform all type translation before beginning emission of .debug$S
1426 // and then make LocalUDTs a member of FunctionInfo
1427}
1428
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001429TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001430 // Generic dispatch for lowering an unknown type.
1431 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001432 case dwarf::DW_TAG_array_type:
1433 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +00001434 case dwarf::DW_TAG_typedef:
1435 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001436 case dwarf::DW_TAG_base_type:
1437 return lowerTypeBasic(cast<DIBasicType>(Ty));
1438 case dwarf::DW_TAG_pointer_type:
Reid Kleckner9dac4732016-08-31 15:59:30 +00001439 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1440 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1441 LLVM_FALLTHROUGH;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001442 case dwarf::DW_TAG_reference_type:
1443 case dwarf::DW_TAG_rvalue_reference_type:
1444 return lowerTypePointer(cast<DIDerivedType>(Ty));
1445 case dwarf::DW_TAG_ptr_to_member_type:
1446 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
Reid Kleckner3acdc672018-02-27 22:08:15 +00001447 case dwarf::DW_TAG_restrict_type:
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001448 case dwarf::DW_TAG_const_type:
1449 case dwarf::DW_TAG_volatile_type:
Victor Leschuke1156c22016-10-31 19:09:38 +00001450 // TODO: add support for DW_TAG_atomic_type here
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001451 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +00001452 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001453 if (ClassTy) {
1454 // The member function type of a member function pointer has no
1455 // ThisAdjustment.
1456 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001457 /*ThisAdjustment=*/0,
1458 /*IsStaticMethod=*/false);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001459 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001460 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +00001461 case dwarf::DW_TAG_enumeration_type:
1462 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +00001463 case dwarf::DW_TAG_class_type:
1464 case dwarf::DW_TAG_structure_type:
1465 return lowerTypeClass(cast<DICompositeType>(Ty));
1466 case dwarf::DW_TAG_union_type:
1467 return lowerTypeUnion(cast<DICompositeType>(Ty));
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001468 case dwarf::DW_TAG_unspecified_type:
Zachary Turner56a5a0c2018-11-01 04:02:41 +00001469 if (Ty->getName() == "decltype(nullptr)")
1470 return TypeIndex::NullptrT();
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001471 return TypeIndex::None();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001472 default:
1473 // Use the null type index.
1474 return TypeIndex();
1475 }
1476}
1477
David Majnemerd065e232016-06-02 06:21:37 +00001478TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +00001479 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1480 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +00001481 StringRef TypeName = Ty->getName();
1482
Zachary Turnera7b04172017-08-28 18:49:04 +00001483 addToUDTs(Ty);
David Majnemer3128b102016-06-15 18:00:01 +00001484
David Majnemerd065e232016-06-02 06:21:37 +00001485 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +00001486 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +00001487 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +00001488 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +00001489 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +00001490 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001491
David Majnemerd065e232016-06-02 06:21:37 +00001492 return UnderlyingTypeIndex;
1493}
1494
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001495TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1496 DITypeRef ElementTypeRef = Ty->getBaseType();
1497 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1498 // IndexType is size_t, which depends on the bitness of the target.
Matt Arsenault41e5ac42018-03-14 00:36:23 +00001499 TypeIndex IndexType = getPointerSizeInBytes() == 8
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001500 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1501 : TypeIndex(SimpleTypeKind::UInt32Long);
Amjad Aboudacee5682016-07-12 12:06:34 +00001502
1503 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1504
Amjad Aboudacee5682016-07-12 12:06:34 +00001505 // Add subranges to array type.
1506 DINodeArray Elements = Ty->getElements();
1507 for (int i = Elements.size() - 1; i >= 0; --i) {
1508 const DINode *Element = Elements[i];
1509 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1510
1511 const DISubrange *Subrange = cast<DISubrange>(Element);
1512 assert(Subrange->getLowerBound() == 0 &&
1513 "codeview doesn't support subranges with lower bounds");
Sander de Smalenfdf40912018-01-24 09:56:07 +00001514 int64_t Count = -1;
1515 if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>())
1516 Count = CI->getSExtValue();
Amjad Aboudacee5682016-07-12 12:06:34 +00001517
Reid Klecknercd7bba02017-09-13 23:30:01 +00001518 // Forward declarations of arrays without a size and VLAs use a count of -1.
1519 // Emit a count of zero in these cases to match what MSVC does for arrays
1520 // without a size. MSVC doesn't support VLAs, so it's not clear what we
1521 // should do for them even if we could distinguish them.
Reid Kleckner6b78e162017-03-24 23:28:42 +00001522 if (Count == -1)
Reid Kleckner89af1122017-09-13 21:54:20 +00001523 Count = 0;
Amjad Aboudacee5682016-07-12 12:06:34 +00001524
Amjad Aboudacee5682016-07-12 12:06:34 +00001525 // Update the element size and element type index for subsequent subranges.
1526 ElementSize *= Count;
Reid Kleckner10762882016-09-09 17:29:36 +00001527
1528 // If this is the outermost array, use the size from the array. It will be
Reid Kleckner6b78e162017-03-24 23:28:42 +00001529 // more accurate if we had a VLA or an incomplete element type size.
Reid Kleckner10762882016-09-09 17:29:36 +00001530 uint64_t ArraySize =
1531 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1532
1533 StringRef Name = (i == 0) ? Ty->getName() : "";
Zachary Turner4efa0a42016-11-08 22:24:53 +00001534 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
Zachary Turner6900de12017-11-28 18:33:17 +00001535 ElementTypeIndex = TypeTable.writeLeafType(AR);
Amjad Aboudacee5682016-07-12 12:06:34 +00001536 }
1537
Amjad Aboudacee5682016-07-12 12:06:34 +00001538 return ElementTypeIndex;
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001539}
1540
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001541TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1542 TypeIndex Index;
1543 dwarf::TypeKind Kind;
1544 uint32_t ByteSize;
1545
1546 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +00001547 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001548
1549 SimpleTypeKind STK = SimpleTypeKind::None;
1550 switch (Kind) {
1551 case dwarf::DW_ATE_address:
1552 // FIXME: Translate
1553 break;
1554 case dwarf::DW_ATE_boolean:
1555 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001556 case 1: STK = SimpleTypeKind::Boolean8; break;
1557 case 2: STK = SimpleTypeKind::Boolean16; break;
1558 case 4: STK = SimpleTypeKind::Boolean32; break;
1559 case 8: STK = SimpleTypeKind::Boolean64; break;
1560 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001561 }
1562 break;
1563 case dwarf::DW_ATE_complex_float:
1564 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001565 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001566 case 4: STK = SimpleTypeKind::Complex32; break;
1567 case 8: STK = SimpleTypeKind::Complex64; break;
1568 case 10: STK = SimpleTypeKind::Complex80; break;
1569 case 16: STK = SimpleTypeKind::Complex128; break;
1570 }
1571 break;
1572 case dwarf::DW_ATE_float:
1573 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001574 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001575 case 4: STK = SimpleTypeKind::Float32; break;
1576 case 6: STK = SimpleTypeKind::Float48; break;
1577 case 8: STK = SimpleTypeKind::Float64; break;
1578 case 10: STK = SimpleTypeKind::Float80; break;
1579 case 16: STK = SimpleTypeKind::Float128; break;
1580 }
1581 break;
1582 case dwarf::DW_ATE_signed:
1583 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001584 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1585 case 2: STK = SimpleTypeKind::Int16Short; break;
1586 case 4: STK = SimpleTypeKind::Int32; break;
1587 case 8: STK = SimpleTypeKind::Int64Quad; break;
1588 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001589 }
1590 break;
1591 case dwarf::DW_ATE_unsigned:
1592 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001593 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1594 case 2: STK = SimpleTypeKind::UInt16Short; break;
1595 case 4: STK = SimpleTypeKind::UInt32; break;
1596 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1597 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001598 }
1599 break;
1600 case dwarf::DW_ATE_UTF:
1601 switch (ByteSize) {
1602 case 2: STK = SimpleTypeKind::Character16; break;
1603 case 4: STK = SimpleTypeKind::Character32; break;
1604 }
1605 break;
1606 case dwarf::DW_ATE_signed_char:
1607 if (ByteSize == 1)
1608 STK = SimpleTypeKind::SignedCharacter;
1609 break;
1610 case dwarf::DW_ATE_unsigned_char:
1611 if (ByteSize == 1)
1612 STK = SimpleTypeKind::UnsignedCharacter;
1613 break;
1614 default:
1615 break;
1616 }
1617
1618 // Apply some fixups based on the source-level type name.
1619 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1620 STK = SimpleTypeKind::Int32Long;
1621 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1622 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001623 if (STK == SimpleTypeKind::UInt16Short &&
1624 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001625 STK = SimpleTypeKind::WideCharacter;
1626 if ((STK == SimpleTypeKind::SignedCharacter ||
1627 STK == SimpleTypeKind::UnsignedCharacter) &&
1628 Ty->getName() == "char")
1629 STK = SimpleTypeKind::NarrowCharacter;
1630
1631 return TypeIndex(STK);
1632}
1633
Reid Kleckner3acdc672018-02-27 22:08:15 +00001634TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
1635 PointerOptions PO) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001636 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1637
Reid Kleckner3acdc672018-02-27 22:08:15 +00001638 // Pointers to simple types without any options can use SimpleTypeMode, rather
1639 // than having a dedicated pointer type record.
1640 if (PointeeTI.isSimple() && PO == PointerOptions::None &&
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001641 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1642 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1643 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1644 ? SimpleTypeMode::NearPointer64
1645 : SimpleTypeMode::NearPointer32;
1646 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1647 }
1648
1649 PointerKind PK =
1650 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1651 PointerMode PM = PointerMode::Pointer;
1652 switch (Ty->getTag()) {
1653 default: llvm_unreachable("not a pointer tag type");
1654 case dwarf::DW_TAG_pointer_type:
1655 PM = PointerMode::Pointer;
1656 break;
1657 case dwarf::DW_TAG_reference_type:
1658 PM = PointerMode::LValueReference;
1659 break;
1660 case dwarf::DW_TAG_rvalue_reference_type:
1661 PM = PointerMode::RValueReference;
1662 break;
1663 }
Reid Kleckner3acdc672018-02-27 22:08:15 +00001664
Zachary Turner38265662018-11-20 22:13:23 +00001665 if (Ty->isObjectPointer())
1666 PO |= PointerOptions::Const;
1667
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001668 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00001669 return TypeTable.writeLeafType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001670}
1671
Reid Kleckner6fa15462016-06-17 22:14:39 +00001672static PointerToMemberRepresentation
1673translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1674 // SizeInBytes being zero generally implies that the member pointer type was
1675 // incomplete, which can happen if it is part of a function prototype. In this
1676 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001677 if (IsPMF) {
1678 switch (Flags & DINode::FlagPtrToMemberRep) {
1679 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001680 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1681 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001682 case DINode::FlagSingleInheritance:
1683 return PointerToMemberRepresentation::SingleInheritanceFunction;
1684 case DINode::FlagMultipleInheritance:
1685 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1686 case DINode::FlagVirtualInheritance:
1687 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1688 }
1689 } else {
1690 switch (Flags & DINode::FlagPtrToMemberRep) {
1691 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001692 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1693 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001694 case DINode::FlagSingleInheritance:
1695 return PointerToMemberRepresentation::SingleInheritanceData;
1696 case DINode::FlagMultipleInheritance:
1697 return PointerToMemberRepresentation::MultipleInheritanceData;
1698 case DINode::FlagVirtualInheritance:
1699 return PointerToMemberRepresentation::VirtualInheritanceData;
1700 }
1701 }
1702 llvm_unreachable("invalid ptr to member representation");
1703}
1704
Reid Kleckner3acdc672018-02-27 22:08:15 +00001705TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
1706 PointerOptions PO) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001707 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1708 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001709 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Matt Arsenault41e5ac42018-03-14 00:36:23 +00001710 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1711 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001712 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1713 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1714 : PointerMode::PointerToDataMember;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001715
Reid Kleckner6fa15462016-06-17 22:14:39 +00001716 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1717 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1718 MemberPointerInfo MPI(
1719 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001720 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Zachary Turner6900de12017-11-28 18:33:17 +00001721 return TypeTable.writeLeafType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001722}
1723
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001724/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1725/// have a translation, use the NearC convention.
1726static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1727 switch (DwarfCC) {
1728 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1729 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1730 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1731 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1732 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1733 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1734 }
1735 return CallingConvention::NearC;
1736}
1737
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001738TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1739 ModifierOptions Mods = ModifierOptions::None;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001740 PointerOptions PO = PointerOptions::None;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001741 bool IsModifier = true;
1742 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001743 while (IsModifier && BaseTy) {
Victor Leschuke1156c22016-10-31 19:09:38 +00001744 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001745 switch (BaseTy->getTag()) {
1746 case dwarf::DW_TAG_const_type:
1747 Mods |= ModifierOptions::Const;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001748 PO |= PointerOptions::Const;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001749 break;
1750 case dwarf::DW_TAG_volatile_type:
1751 Mods |= ModifierOptions::Volatile;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001752 PO |= PointerOptions::Volatile;
1753 break;
1754 case dwarf::DW_TAG_restrict_type:
1755 // Only pointer types be marked with __restrict. There is no known flag
1756 // for __restrict in LF_MODIFIER records.
1757 PO |= PointerOptions::Restrict;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001758 break;
1759 default:
1760 IsModifier = false;
1761 break;
1762 }
1763 if (IsModifier)
1764 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1765 }
Reid Kleckner3acdc672018-02-27 22:08:15 +00001766
1767 // Check if the inner type will use an LF_POINTER record. If so, the
1768 // qualifiers will go in the LF_POINTER record. This comes up for types like
1769 // 'int *const' and 'int *__restrict', not the more common cases like 'const
1770 // char *'.
1771 if (BaseTy) {
1772 switch (BaseTy->getTag()) {
1773 case dwarf::DW_TAG_pointer_type:
1774 case dwarf::DW_TAG_reference_type:
1775 case dwarf::DW_TAG_rvalue_reference_type:
1776 return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
1777 case dwarf::DW_TAG_ptr_to_member_type:
1778 return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
1779 default:
1780 break;
1781 }
1782 }
1783
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001784 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Reid Kleckner3acdc672018-02-27 22:08:15 +00001785
1786 // Return the base type index if there aren't any modifiers. For example, the
1787 // metadata could contain restrict wrappers around non-pointer types.
1788 if (Mods == ModifierOptions::None)
1789 return ModifiedTI;
1790
Zachary Turner4efa0a42016-11-08 22:24:53 +00001791 ModifierRecord MR(ModifiedTI, Mods);
Zachary Turner6900de12017-11-28 18:33:17 +00001792 return TypeTable.writeLeafType(MR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001793}
1794
David Majnemer75c3ebf2016-06-02 17:13:53 +00001795TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1796 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1797 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1798 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1799
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001800 // MSVC uses type none for variadic argument.
1801 if (ReturnAndArgTypeIndices.size() > 1 &&
1802 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1803 ReturnAndArgTypeIndices.back() = TypeIndex::None();
1804 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001805 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1806 ArrayRef<TypeIndex> ArgTypeIndices = None;
1807 if (!ReturnAndArgTypeIndices.empty()) {
1808 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1809 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1810 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1811 }
1812
1813 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner6900de12017-11-28 18:33:17 +00001814 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001815
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001816 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1817
Aaron Smith802b0332018-10-02 20:21:05 +00001818 FunctionOptions FO = getFunctionOptions(Ty);
1819 ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
1820 ArgListIndex);
Zachary Turner6900de12017-11-28 18:33:17 +00001821 return TypeTable.writeLeafType(Procedure);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001822}
1823
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001824TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001825 const DIType *ClassTy,
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001826 int ThisAdjustment,
Aaron Smith802b0332018-10-02 20:21:05 +00001827 bool IsStaticMethod,
1828 FunctionOptions FO) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001829 // Lower the containing class type.
1830 TypeIndex ClassType = getTypeIndex(ClassTy);
1831
Zachary Turnerc68f8952018-11-20 22:13:43 +00001832 DITypeRefArray ReturnAndArgs = Ty->getTypeArray();
1833
1834 unsigned Index = 0;
1835 SmallVector<TypeIndex, 8> ArgTypeIndices;
1836 TypeIndex ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]);
1837
1838 TypeIndex ThisTypeIndex;
1839 if (!IsStaticMethod && ReturnAndArgs.size() > 1)
1840 ThisTypeIndex = getTypeIndexForThisPtr(ReturnAndArgs[Index++], Ty);
1841
1842 while (Index < ReturnAndArgs.size())
1843 ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++]));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001844
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001845 // MSVC uses type none for variadic argument.
Zachary Turnerc68f8952018-11-20 22:13:43 +00001846 if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void())
1847 ArgTypeIndices.back() = TypeIndex::None();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001848
1849 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner6900de12017-11-28 18:33:17 +00001850 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001851
1852 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1853
Aaron Smith802b0332018-10-02 20:21:05 +00001854 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
1855 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
Zachary Turner6900de12017-11-28 18:33:17 +00001856 return TypeTable.writeLeafType(MFR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001857}
1858
Reid Kleckner9dac4732016-08-31 15:59:30 +00001859TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001860 unsigned VSlotCount =
1861 Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
Reid Kleckner9dac4732016-08-31 15:59:30 +00001862 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001863
1864 VFTableShapeRecord VFTSR(Slots);
Zachary Turner6900de12017-11-28 18:33:17 +00001865 return TypeTable.writeLeafType(VFTSR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001866}
1867
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001868static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1869 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001870 case DINode::FlagPrivate: return MemberAccess::Private;
1871 case DINode::FlagPublic: return MemberAccess::Public;
1872 case DINode::FlagProtected: return MemberAccess::Protected;
1873 case 0:
1874 // If there was no explicit access control, provide the default for the tag.
1875 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1876 : MemberAccess::Public;
1877 }
1878 llvm_unreachable("access flags are exclusive");
1879}
1880
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001881static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1882 if (SP->isArtificial())
1883 return MethodOptions::CompilerGenerated;
1884
1885 // FIXME: Handle other MethodOptions.
1886
1887 return MethodOptions::None;
1888}
1889
1890static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1891 bool Introduced) {
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001892 if (SP->getFlags() & DINode::FlagStaticMember)
1893 return MethodKind::Static;
1894
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001895 switch (SP->getVirtuality()) {
1896 case dwarf::DW_VIRTUALITY_none:
1897 break;
1898 case dwarf::DW_VIRTUALITY_virtual:
1899 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1900 case dwarf::DW_VIRTUALITY_pure_virtual:
1901 return Introduced ? MethodKind::PureIntroducingVirtual
1902 : MethodKind::PureVirtual;
1903 default:
1904 llvm_unreachable("unhandled virtuality case");
1905 }
1906
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001907 return MethodKind::Vanilla;
1908}
1909
Reid Klecknera8d57402016-06-03 15:58:20 +00001910static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1911 switch (Ty->getTag()) {
1912 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1913 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1914 }
1915 llvm_unreachable("unexpected tag");
1916}
1917
Reid Klecknere092dad2016-07-02 00:11:07 +00001918/// Return ClassOptions that should be present on both the forward declaration
1919/// and the defintion of a tag type.
1920static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1921 ClassOptions CO = ClassOptions::None;
1922
1923 // MSVC always sets this flag, even for local types. Clang doesn't always
Reid Klecknera8d57402016-06-03 15:58:20 +00001924 // appear to give every type a linkage name, which may be problematic for us.
1925 // FIXME: Investigate the consequences of not following them here.
Reid Klecknere092dad2016-07-02 00:11:07 +00001926 if (!Ty->getIdentifier().empty())
1927 CO |= ClassOptions::HasUniqueName;
1928
1929 // Put the Nested flag on a type if it appears immediately inside a tag type.
1930 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1931 // here. That flag is only set on definitions, and not forward declarations.
1932 const DIScope *ImmediateScope = Ty->getScope().resolve();
1933 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1934 CO |= ClassOptions::Nested;
1935
Aaron Smithda0602c2018-10-02 20:28:15 +00001936 // Put the Scoped flag on function-local types. MSVC puts this flag for enum
Zachary Turnerc68f8952018-11-20 22:13:43 +00001937 // type only when it has an immediate function scope. Clang never puts enums
1938 // inside DILexicalBlock scopes. Enum types, as generated by clang, are
Aaron Smithda0602c2018-10-02 20:28:15 +00001939 // always in function, class, or file scopes.
1940 if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
1941 if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
Reid Klecknere092dad2016-07-02 00:11:07 +00001942 CO |= ClassOptions::Scoped;
Aaron Smithda0602c2018-10-02 20:28:15 +00001943 } else {
1944 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1945 Scope = Scope->getScope().resolve()) {
1946 if (isa<DISubprogram>(Scope)) {
1947 CO |= ClassOptions::Scoped;
1948 break;
1949 }
Reid Klecknere092dad2016-07-02 00:11:07 +00001950 }
1951 }
1952
1953 return CO;
Reid Klecknera8d57402016-06-03 15:58:20 +00001954}
1955
Aaron Smith122d9e72018-03-06 18:20:22 +00001956void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
1957 switch (Ty->getTag()) {
1958 case dwarf::DW_TAG_class_type:
1959 case dwarf::DW_TAG_structure_type:
1960 case dwarf::DW_TAG_union_type:
1961 case dwarf::DW_TAG_enumeration_type:
1962 break;
1963 default:
1964 return;
1965 }
1966
1967 if (const auto *File = Ty->getFile()) {
1968 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
1969 TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
1970
1971 UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
1972 TypeTable.writeLeafType(USLR);
1973 }
1974}
1975
David Majnemer979cb882016-06-16 21:32:16 +00001976TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
Reid Klecknere092dad2016-07-02 00:11:07 +00001977 ClassOptions CO = getCommonClassOptions(Ty);
David Majnemer979cb882016-06-16 21:32:16 +00001978 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001979 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001980
David Majnemerda9548f2016-06-17 16:13:21 +00001981 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001982 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001983 } else {
Zachary Turner6900de12017-11-28 18:33:17 +00001984 ContinuationRecordBuilder ContinuationBuilder;
1985 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
David Majnemerda9548f2016-06-17 16:13:21 +00001986 for (const DINode *Element : Ty->getElements()) {
1987 // We assume that the frontend provides all members in source declaration
1988 // order, which is what MSVC does.
1989 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001990 EnumeratorRecord ER(MemberAccess::Public,
1991 APSInt::getUnsigned(Enumerator->getValue()),
1992 Enumerator->getName());
Zachary Turner6900de12017-11-28 18:33:17 +00001993 ContinuationBuilder.writeMemberType(ER);
David Majnemerda9548f2016-06-17 16:13:21 +00001994 EnumeratorCount++;
1995 }
1996 }
Zachary Turner6900de12017-11-28 18:33:17 +00001997 FTI = TypeTable.insertRecord(ContinuationBuilder);
David Majnemerda9548f2016-06-17 16:13:21 +00001998 }
David Majnemer979cb882016-06-16 21:32:16 +00001999
David Majnemer6bdc24e2016-07-01 23:12:45 +00002000 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00002001
Zachary Turner4efa0a42016-11-08 22:24:53 +00002002 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
2003 getTypeIndex(Ty->getBaseType()));
Aaron Smith122d9e72018-03-06 18:20:22 +00002004 TypeIndex EnumTI = TypeTable.writeLeafType(ER);
2005
2006 addUDTSrcLine(Ty, EnumTI);
2007
2008 return EnumTI;
David Majnemer979cb882016-06-16 21:32:16 +00002009}
2010
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002011//===----------------------------------------------------------------------===//
2012// ClassInfo
2013//===----------------------------------------------------------------------===//
2014
2015struct llvm::ClassInfo {
2016 struct MemberInfo {
2017 const DIDerivedType *MemberTypeNode;
David Majnemer08bd7442016-07-01 23:12:48 +00002018 uint64_t BaseOffset;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002019 };
2020 // [MemberInfo]
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002021 using MemberList = std::vector<MemberInfo>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002022
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002023 using MethodsList = TinyPtrVector<const DISubprogram *>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002024 // MethodName -> MethodsList
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002025 using MethodsMap = MapVector<MDString *, MethodsList>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002026
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002027 /// Base classes.
2028 std::vector<const DIDerivedType *> Inheritance;
2029
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002030 /// Direct members.
2031 MemberList Members;
2032 // Direct overloaded methods gathered by name.
2033 MethodsMap Methods;
Adrian McCarthy820ca542016-07-06 19:49:51 +00002034
Reid Kleckner9dac4732016-08-31 15:59:30 +00002035 TypeIndex VShapeTI;
2036
Reid Klecknere2e82062017-08-08 20:30:14 +00002037 std::vector<const DIType *> NestedTypes;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002038};
2039
2040void CodeViewDebug::clear() {
2041 assert(CurFn == nullptr);
2042 FileIdMap.clear();
2043 FnDebugInfo.clear();
2044 FileToFilepathMap.clear();
2045 LocalUDTs.clear();
2046 GlobalUDTs.clear();
2047 TypeIndices.clear();
2048 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002049}
2050
2051void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
2052 const DIDerivedType *DDTy) {
2053 if (!DDTy->getName().empty()) {
2054 Info.Members.push_back({DDTy, 0});
2055 return;
2056 }
Shoaib Meenai03303a32018-02-27 21:48:41 +00002057
2058 // An unnamed member may represent a nested struct or union. Attempt to
2059 // interpret the unnamed member as a DICompositeType possibly wrapped in
2060 // qualifier types. Add all the indirect fields to the current record if that
2061 // succeeds, and drop the member if that fails.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002062 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
David Majnemer08bd7442016-07-01 23:12:48 +00002063 uint64_t Offset = DDTy->getOffsetInBits();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002064 const DIType *Ty = DDTy->getBaseType().resolve();
Shoaib Meenai03303a32018-02-27 21:48:41 +00002065 bool FullyResolved = false;
2066 while (!FullyResolved) {
2067 switch (Ty->getTag()) {
2068 case dwarf::DW_TAG_const_type:
2069 case dwarf::DW_TAG_volatile_type:
2070 // FIXME: we should apply the qualifier types to the indirect fields
2071 // rather than dropping them.
2072 Ty = cast<DIDerivedType>(Ty)->getBaseType().resolve();
2073 break;
2074 default:
2075 FullyResolved = true;
2076 break;
2077 }
2078 }
2079
2080 const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
2081 if (!DCTy)
2082 return;
2083
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002084 ClassInfo NestedInfo = collectClassInfo(DCTy);
2085 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002086 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002087 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002088}
2089
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002090ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
2091 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002092 // Add elements to structure type.
2093 DINodeArray Elements = Ty->getElements();
2094 for (auto *Element : Elements) {
2095 // We assume that the frontend provides all members in source declaration
2096 // order, which is what MSVC does.
2097 if (!Element)
2098 continue;
2099 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00002100 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002101 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002102 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002103 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002104 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
2105 Info.Inheritance.push_back(DDTy);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002106 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
2107 DDTy->getName() == "__vtbl_ptr_type") {
2108 Info.VShapeTI = getTypeIndex(DDTy);
Reid Klecknere2e82062017-08-08 20:30:14 +00002109 } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
2110 Info.NestedTypes.push_back(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002111 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
2112 // Ignore friend members. It appears that MSVC emitted info about
2113 // friends in the past, but modern versions do not.
2114 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00002115 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
Reid Klecknere2e82062017-08-08 20:30:14 +00002116 Info.NestedTypes.push_back(Composite);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002117 }
2118 // Skip other unrecognized kinds of elements.
2119 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002120 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002121}
2122
Brock Wymab60532f2018-06-11 01:39:34 +00002123static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) {
2124 // This routine is used by lowerTypeClass and lowerTypeUnion to determine
2125 // if a complete type should be emitted instead of a forward reference.
2126 return Ty->getName().empty() && Ty->getIdentifier().empty() &&
2127 !Ty->isForwardDecl();
2128}
2129
Reid Klecknera8d57402016-06-03 15:58:20 +00002130TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
Brock Wymab60532f2018-06-11 01:39:34 +00002131 // Emit the complete type for unnamed structs. C++ classes with methods
2132 // which have a circular reference back to the class type are expected to
2133 // be named by the front-end and should not be "unnamed". C unnamed
2134 // structs should not have circular references.
2135 if (shouldAlwaysEmitCompleteClassType(Ty)) {
2136 // If this unnamed complete type is already in the process of being defined
2137 // then the description of the type is malformed and cannot be emitted
2138 // into CodeView correctly so report a fatal error.
2139 auto I = CompleteTypeIndices.find(Ty);
2140 if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
2141 report_fatal_error("cannot debug circular reference to unnamed type");
2142 return getCompleteTypeIndex(Ty);
2143 }
2144
Reid Klecknera8d57402016-06-03 15:58:20 +00002145 // First, construct the forward decl. Don't look into Ty to compute the
2146 // forward decl options, since it might not be available in all TUs.
2147 TypeRecordKind Kind = getRecordKind(Ty);
2148 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00002149 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00002150 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00002151 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
2152 FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002153 TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
Reid Kleckner643dd832016-06-22 17:15:28 +00002154 if (!Ty->isForwardDecl())
2155 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00002156 return FwdDeclTI;
2157}
2158
2159TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
2160 // Construct the field list and complete type record.
2161 TypeRecordKind Kind = getRecordKind(Ty);
Reid Klecknere092dad2016-07-02 00:11:07 +00002162 ClassOptions CO = getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002163 TypeIndex FieldTI;
2164 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002165 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00002166 bool ContainsNestedClass;
2167 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
2168 lowerRecordFieldList(Ty);
2169
2170 if (ContainsNestedClass)
2171 CO |= ClassOptions::ContainsNestedClass;
Reid Klecknera8d57402016-06-03 15:58:20 +00002172
David Majnemer6bdc24e2016-07-01 23:12:45 +00002173 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00002174
Reid Klecknera8d57402016-06-03 15:58:20 +00002175 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00002176
Zachary Turner4efa0a42016-11-08 22:24:53 +00002177 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
2178 SizeInBytes, FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002179 TypeIndex ClassTI = TypeTable.writeLeafType(CR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002180
Aaron Smith122d9e72018-03-06 18:20:22 +00002181 addUDTSrcLine(Ty, ClassTI);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002182
Zachary Turnera7b04172017-08-28 18:49:04 +00002183 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00002184
Hans Wennborg9a519a02016-06-22 21:22:13 +00002185 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002186}
2187
2188TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
Brock Wymab60532f2018-06-11 01:39:34 +00002189 // Emit the complete type for unnamed unions.
2190 if (shouldAlwaysEmitCompleteClassType(Ty))
2191 return getCompleteTypeIndex(Ty);
2192
Reid Klecknera8d57402016-06-03 15:58:20 +00002193 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00002194 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00002195 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00002196 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002197 TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
Reid Kleckner643dd832016-06-22 17:15:28 +00002198 if (!Ty->isForwardDecl())
2199 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00002200 return FwdDeclTI;
2201}
2202
2203TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
David Majnemere1e73722016-07-06 21:07:42 +00002204 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002205 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002206 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00002207 bool ContainsNestedClass;
2208 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
2209 lowerRecordFieldList(Ty);
2210
2211 if (ContainsNestedClass)
2212 CO |= ClassOptions::ContainsNestedClass;
2213
Reid Klecknera8d57402016-06-03 15:58:20 +00002214 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
David Majnemer6bdc24e2016-07-01 23:12:45 +00002215 std::string FullName = getFullyQualifiedName(Ty);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002216
Zachary Turner4efa0a42016-11-08 22:24:53 +00002217 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
2218 Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002219 TypeIndex UnionTI = TypeTable.writeLeafType(UR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002220
Aaron Smith122d9e72018-03-06 18:20:22 +00002221 addUDTSrcLine(Ty, UnionTI);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002222
Zachary Turnera7b04172017-08-28 18:49:04 +00002223 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00002224
Hans Wennborg9a519a02016-06-22 21:22:13 +00002225 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002226}
2227
Adrian McCarthy820ca542016-07-06 19:49:51 +00002228std::tuple<TypeIndex, TypeIndex, unsigned, bool>
Reid Klecknera8d57402016-06-03 15:58:20 +00002229CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
2230 // Manually count members. MSVC appears to count everything that generates a
2231 // field list record. Each individual overload in a method overload group
2232 // contributes to this count, even though the overload group is a single field
2233 // list record.
2234 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002235 ClassInfo Info = collectClassInfo(Ty);
Zachary Turner6900de12017-11-28 18:33:17 +00002236 ContinuationRecordBuilder ContinuationBuilder;
2237 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002238
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002239 // Create base classes.
2240 for (const DIDerivedType *I : Info.Inheritance) {
2241 if (I->getFlags() & DINode::FlagVirtual) {
2242 // Virtual base.
Brock Wyma3db2b102018-05-14 21:21:22 +00002243 unsigned VBPtrOffset = I->getVBPtrOffset();
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002244 // FIXME: Despite the accessor name, the offset is really in bytes.
2245 unsigned VBTableIndex = I->getOffsetInBits() / 4;
Bob Haarman26a87bd2016-10-25 22:11:52 +00002246 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
2247 ? TypeRecordKind::IndirectVirtualBaseClass
2248 : TypeRecordKind::VirtualBaseClass;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002249 VirtualBaseClassRecord VBCR(
Bob Haarman26a87bd2016-10-25 22:11:52 +00002250 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002251 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
Zachary Turner4efa0a42016-11-08 22:24:53 +00002252 VBTableIndex);
2253
Zachary Turner6900de12017-11-28 18:33:17 +00002254 ContinuationBuilder.writeMemberType(VBCR);
Brock Wyma4536c1f2018-02-01 20:37:38 +00002255 MemberCount++;
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002256 } else {
2257 assert(I->getOffsetInBits() % 8 == 0 &&
2258 "bases must be on byte boundaries");
Zachary Turner4efa0a42016-11-08 22:24:53 +00002259 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
2260 getTypeIndex(I->getBaseType()),
2261 I->getOffsetInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00002262 ContinuationBuilder.writeMemberType(BCR);
Brock Wyma4536c1f2018-02-01 20:37:38 +00002263 MemberCount++;
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002264 }
2265 }
2266
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002267 // Create members.
2268 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
2269 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
2270 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00002271 StringRef MemberName = Member->getName();
2272 MemberAccess Access =
2273 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002274
2275 if (Member->isStaticMember()) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00002276 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
Zachary Turner6900de12017-11-28 18:33:17 +00002277 ContinuationBuilder.writeMemberType(SDMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002278 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00002279 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00002280 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002281
Reid Kleckner9dac4732016-08-31 15:59:30 +00002282 // Virtual function pointer member.
2283 if ((Member->getFlags() & DINode::FlagArtificial) &&
2284 Member->getName().startswith("_vptr$")) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00002285 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
Zachary Turner6900de12017-11-28 18:33:17 +00002286 ContinuationBuilder.writeMemberType(VFPR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002287 MemberCount++;
2288 continue;
2289 }
2290
David Majnemer9319cbc2016-06-30 03:00:20 +00002291 // Data member.
David Majnemer08bd7442016-07-01 23:12:48 +00002292 uint64_t MemberOffsetInBits =
2293 Member->getOffsetInBits() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00002294 if (Member->isBitField()) {
2295 uint64_t StartBitOffset = MemberOffsetInBits;
2296 if (const auto *CI =
2297 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
David Majnemer08bd7442016-07-01 23:12:48 +00002298 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00002299 }
2300 StartBitOffset -= MemberOffsetInBits;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002301 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2302 StartBitOffset);
Zachary Turner6900de12017-11-28 18:33:17 +00002303 MemberBaseType = TypeTable.writeLeafType(BFR);
David Majnemer9319cbc2016-06-30 03:00:20 +00002304 }
2305 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002306 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2307 MemberName);
Zachary Turner6900de12017-11-28 18:33:17 +00002308 ContinuationBuilder.writeMemberType(DMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002309 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00002310 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002311
2312 // Create methods
2313 for (auto &MethodItr : Info.Methods) {
2314 StringRef Name = MethodItr.first->getString();
2315
2316 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00002317 for (const DISubprogram *SP : MethodItr.second) {
2318 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2319 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002320
2321 unsigned VFTableOffset = -1;
2322 if (Introduced)
2323 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2324
Zachary Turner7251ede2016-11-02 17:05:19 +00002325 Methods.push_back(OneMethodRecord(
2326 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
2327 translateMethodKindFlags(SP, Introduced),
2328 translateMethodOptionFlags(SP), VFTableOffset, Name));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002329 MemberCount++;
2330 }
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002331 assert(!Methods.empty() && "Empty methods map entry");
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002332 if (Methods.size() == 1)
Zachary Turner6900de12017-11-28 18:33:17 +00002333 ContinuationBuilder.writeMemberType(Methods[0]);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002334 else {
Zachary Turner6900de12017-11-28 18:33:17 +00002335 // FIXME: Make this use its own ContinuationBuilder so that
2336 // MethodOverloadList can be split correctly.
Zachary Turner4efa0a42016-11-08 22:24:53 +00002337 MethodOverloadListRecord MOLR(Methods);
Zachary Turner6900de12017-11-28 18:33:17 +00002338 TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
2339
Zachary Turner4efa0a42016-11-08 22:24:53 +00002340 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
Zachary Turner6900de12017-11-28 18:33:17 +00002341 ContinuationBuilder.writeMemberType(OMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002342 }
2343 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00002344
2345 // Create nested classes.
Reid Klecknere2e82062017-08-08 20:30:14 +00002346 for (const DIType *Nested : Info.NestedTypes) {
Adrian McCarthy820ca542016-07-06 19:49:51 +00002347 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
Zachary Turner6900de12017-11-28 18:33:17 +00002348 ContinuationBuilder.writeMemberType(R);
Adrian McCarthy820ca542016-07-06 19:49:51 +00002349 MemberCount++;
2350 }
2351
Zachary Turner6900de12017-11-28 18:33:17 +00002352 TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002353 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
Reid Klecknere2e82062017-08-08 20:30:14 +00002354 !Info.NestedTypes.empty());
Reid Klecknera8d57402016-06-03 15:58:20 +00002355}
2356
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002357TypeIndex CodeViewDebug::getVBPTypeIndex() {
2358 if (!VBPType.getIndex()) {
2359 // Make a 'const int *' type.
2360 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
Zachary Turner6900de12017-11-28 18:33:17 +00002361 TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002362
2363 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2364 : PointerKind::Near32;
2365 PointerMode PM = PointerMode::Pointer;
2366 PointerOptions PO = PointerOptions::None;
2367 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
Zachary Turner6900de12017-11-28 18:33:17 +00002368 VBPType = TypeTable.writeLeafType(PR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002369 }
2370
2371 return VBPType;
2372}
2373
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002374TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002375 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002376 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002377
2378 // The null DIType is the void type. Don't try to hash it.
2379 if (!Ty)
2380 return TypeIndex::Void();
2381
Reid Klecknera8d57402016-06-03 15:58:20 +00002382 // Check if we've already translated this type. Don't try to do a
2383 // get-or-create style insertion that caches the hash lookup across the
2384 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002385 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002386 if (I != TypeIndices.end())
2387 return I->second;
2388
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002389 TypeLoweringScope S(*this);
2390 TypeIndex TI = lowerType(Ty, ClassTy);
2391 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00002392}
2393
Zachary Turnerc68f8952018-11-20 22:13:43 +00002394codeview::TypeIndex
2395CodeViewDebug::getTypeIndexForThisPtr(DITypeRef TypeRef,
2396 const DISubroutineType *SubroutineTy) {
2397 const DIType *Ty = TypeRef.resolve();
2398
2399 PointerOptions Options = PointerOptions::None;
2400 if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference)
2401 Options = PointerOptions::LValueRefThisPointer;
2402 else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference)
2403 Options = PointerOptions::RValueRefThisPointer;
2404
2405 // Check if we've already translated this type. If there is no ref qualifier
2406 // on the function then we look up this pointer type with no associated class
2407 // so that the TypeIndex for the this pointer can be shared with the type
2408 // index for other pointers to this class type. If there is a ref qualifier
2409 // then we lookup the pointer using the subroutine as the parent type.
Zachary Turnerc68f8952018-11-20 22:13:43 +00002410 auto I = TypeIndices.find({Ty, SubroutineTy});
2411 if (I != TypeIndices.end())
2412 return I->second;
2413
2414 TypeLoweringScope S(*this);
2415 TypeIndex TI = lowerTypePointer(cast<DIDerivedType>(Ty), Options);
2416 return recordTypeIndexForDINode(Ty, TI, SubroutineTy);
2417}
2418
Bob Haarman223303c2017-08-29 20:59:25 +00002419TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(DITypeRef TypeRef) {
2420 DIType *Ty = TypeRef.resolve();
2421 PointerRecord PR(getTypeIndex(Ty),
2422 getPointerSizeInBytes() == 8 ? PointerKind::Near64
2423 : PointerKind::Near32,
2424 PointerMode::LValueReference, PointerOptions::None,
2425 Ty->getSizeInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00002426 return TypeTable.writeLeafType(PR);
Bob Haarman223303c2017-08-29 20:59:25 +00002427}
2428
Reid Klecknera8d57402016-06-03 15:58:20 +00002429TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
2430 const DIType *Ty = TypeRef.resolve();
2431
2432 // The null DIType is the void type. Don't try to hash it.
2433 if (!Ty)
2434 return TypeIndex::Void();
2435
Reid Kleckner9571c802018-12-11 23:07:39 +00002436 // Look through typedefs when getting the complete type index. Call
2437 // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are
2438 // emitted only once.
2439 if (Ty->getTag() == dwarf::DW_TAG_typedef)
2440 (void)getTypeIndex(Ty);
2441 while (Ty->getTag() == dwarf::DW_TAG_typedef)
2442 Ty = cast<DIDerivedType>(Ty)->getBaseType().resolve();
2443
Reid Klecknera8d57402016-06-03 15:58:20 +00002444 // If this is a non-record type, the complete type index is the same as the
2445 // normal type index. Just call getTypeIndex.
2446 switch (Ty->getTag()) {
2447 case dwarf::DW_TAG_class_type:
2448 case dwarf::DW_TAG_structure_type:
2449 case dwarf::DW_TAG_union_type:
2450 break;
2451 default:
2452 return getTypeIndex(Ty);
2453 }
2454
Brock Wymab60532f2018-06-11 01:39:34 +00002455 // Check if we've already translated the complete record type.
Reid Klecknera8d57402016-06-03 15:58:20 +00002456 const auto *CTy = cast<DICompositeType>(Ty);
2457 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
2458 if (!InsertResult.second)
2459 return InsertResult.first->second;
2460
Reid Kleckner643dd832016-06-22 17:15:28 +00002461 TypeLoweringScope S(*this);
2462
Reid Klecknera8d57402016-06-03 15:58:20 +00002463 // Make sure the forward declaration is emitted first. It's unclear if this
2464 // is necessary, but MSVC does it, and we should follow suit until we can show
2465 // otherwise.
Brock Wymab60532f2018-06-11 01:39:34 +00002466 // We only emit a forward declaration for named types.
2467 if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
2468 TypeIndex FwdDeclTI = getTypeIndex(CTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00002469
Brock Wymab60532f2018-06-11 01:39:34 +00002470 // Just use the forward decl if we don't have complete type info. This
2471 // might happen if the frontend is using modules and expects the complete
2472 // definition to be emitted elsewhere.
2473 if (CTy->isForwardDecl())
2474 return FwdDeclTI;
2475 }
Reid Klecknera8d57402016-06-03 15:58:20 +00002476
2477 TypeIndex TI;
2478 switch (CTy->getTag()) {
2479 case dwarf::DW_TAG_class_type:
2480 case dwarf::DW_TAG_structure_type:
2481 TI = lowerCompleteTypeClass(CTy);
2482 break;
2483 case dwarf::DW_TAG_union_type:
2484 TI = lowerCompleteTypeUnion(CTy);
2485 break;
2486 default:
2487 llvm_unreachable("not a record");
2488 }
2489
Brock Wymab60532f2018-06-11 01:39:34 +00002490 // Update the type index associated with this CompositeType. This cannot
2491 // use the 'InsertResult' iterator above because it is potentially
2492 // invalidated by map insertions which can occur while lowering the class
2493 // type above.
2494 CompleteTypeIndices[CTy] = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002495 return TI;
2496}
2497
Reid Kleckner643dd832016-06-22 17:15:28 +00002498/// Emit all the deferred complete record types. Try to do this in FIFO order,
Amjad Aboudacee5682016-07-12 12:06:34 +00002499/// and do this until fixpoint, as each complete record type typically
2500/// references
Reid Kleckner643dd832016-06-22 17:15:28 +00002501/// many other record types.
2502void CodeViewDebug::emitDeferredCompleteTypes() {
2503 SmallVector<const DICompositeType *, 4> TypesToEmit;
2504 while (!DeferredCompleteTypes.empty()) {
2505 std::swap(DeferredCompleteTypes, TypesToEmit);
2506 for (const DICompositeType *RecordTy : TypesToEmit)
2507 getCompleteTypeIndex(RecordTy);
2508 TypesToEmit.clear();
2509 }
2510}
2511
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002512void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
2513 ArrayRef<LocalVariable> Locals) {
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002514 // Get the sorted list of parameters and emit them first.
2515 SmallVector<const LocalVariable *, 6> Params;
2516 for (const LocalVariable &L : Locals)
2517 if (L.DIVar->isParameter())
2518 Params.push_back(&L);
Fangrui Song0cac7262018-09-27 02:13:45 +00002519 llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
2520 return L->DIVar->getArg() < R->DIVar->getArg();
2521 });
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002522 for (const LocalVariable *L : Params)
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002523 emitLocalVariable(FI, *L);
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002524
2525 // Next emit all non-parameters in the order that we found them.
2526 for (const LocalVariable &L : Locals)
2527 if (!L.DIVar->isParameter())
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002528 emitLocalVariable(FI, L);
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002529}
2530
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002531/// Only call this on endian-specific types like ulittle16_t and little32_t, or
2532/// structs composed of them.
2533template <typename T>
2534static void copyBytesForDefRange(SmallString<20> &BytePrefix,
2535 SymbolKind SymKind, const T &DefRangeHeader) {
2536 BytePrefix.resize(2 + sizeof(T));
2537 ulittle16_t SymKindLE = ulittle16_t(SymKind);
2538 memcpy(&BytePrefix[0], &SymKindLE, 2);
2539 memcpy(&BytePrefix[2], &DefRangeHeader, sizeof(T));
2540}
2541
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002542void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
2543 const LocalVariable &Var) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002544 // LocalSym record, see SymbolRecord.h for more info.
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002545 MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002546
Zachary Turner63a28462016-05-17 23:50:21 +00002547 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002548 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00002549 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00002550 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00002551 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002552
2553 OS.AddComment("TypeIndex");
Reid Kleckner08f5fd52017-08-31 15:56:49 +00002554 TypeIndex TI = Var.UseReferenceType
2555 ? getTypeIndexForReferenceTo(Var.DIVar->getType())
2556 : getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002557 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002558 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00002559 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00002560 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00002561 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002562 endSymbolRecord(LocalEnd);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002563
Reid Kleckner876330d2016-02-12 21:48:30 +00002564 // Calculate the on disk prefix of the appropriate def range record. The
2565 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2566 // should be big enough to hold all forms without memory allocation.
2567 SmallString<20> BytePrefix;
2568 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2569 BytePrefix.clear();
Reid Kleckner876330d2016-02-12 21:48:30 +00002570 if (DefRange.InMemory) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002571 int Offset = DefRange.DataOffset;
2572 unsigned Reg = DefRange.CVRegister;
2573
Reid Klecknerd5e4ec72018-10-02 16:43:52 +00002574 // 32-bit x86 call sequences often use PUSH instructions, which disrupt
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002575 // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
Reid Kleckner2bcb2882018-11-03 00:41:52 +00002576 // instead. In frames without stack realignment, $T0 will be the CFA.
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002577 if (RegisterId(Reg) == RegisterId::ESP) {
2578 Reg = unsigned(RegisterId::VFRAME);
Reid Kleckner2bcb2882018-11-03 00:41:52 +00002579 Offset += FI.OffsetAdjustment;
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002580 }
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002581
2582 // If we can use the chosen frame pointer for the frame and this isn't a
2583 // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
2584 // Otherwise, use S_DEFRANGE_REGISTER_REL.
2585 EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU);
2586 if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
2587 (bool(Flags & LocalSymFlags::IsParameter)
2588 ? (EncFP == FI.EncodedParamFramePtrReg)
2589 : (EncFP == FI.EncodedLocalFramePtrReg))) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002590 little32_t FPOffset = little32_t(Offset);
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002591 copyBytesForDefRange(BytePrefix, S_DEFRANGE_FRAMEPOINTER_REL, FPOffset);
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002592 } else {
2593 uint16_t RegRelFlags = 0;
2594 if (DefRange.IsSubfield) {
2595 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2596 (DefRange.StructOffset
2597 << DefRangeRegisterRelSym::OffsetInParentShift);
2598 }
2599 DefRangeRegisterRelSym::Header DRHdr;
2600 DRHdr.Register = Reg;
2601 DRHdr.Flags = RegRelFlags;
2602 DRHdr.BasePointerOffset = Offset;
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002603 copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER_REL, DRHdr);
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002604 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002605 } else {
2606 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002607 if (DefRange.IsSubfield) {
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002608 DefRangeSubfieldRegisterSym::Header DRHdr;
2609 DRHdr.Register = DefRange.CVRegister;
2610 DRHdr.MayHaveNoName = 0;
2611 DRHdr.OffsetInParent = DefRange.StructOffset;
2612 copyBytesForDefRange(BytePrefix, S_DEFRANGE_SUBFIELD_REGISTER, DRHdr);
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002613 } else {
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002614 DefRangeRegisterSym::Header DRHdr;
2615 DRHdr.Register = DefRange.CVRegister;
2616 DRHdr.MayHaveNoName = 0;
2617 copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER, DRHdr);
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002618 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002619 }
2620 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2621 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002622}
2623
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002624void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
2625 const FunctionInfo& FI) {
2626 for (LexicalBlock *Block : Blocks)
2627 emitLexicalBlock(*Block, FI);
2628}
2629
2630/// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
2631/// lexical block scope.
2632void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
2633 const FunctionInfo& FI) {
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002634 MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002635 OS.AddComment("PtrParent");
2636 OS.EmitIntValue(0, 4); // PtrParent
2637 OS.AddComment("PtrEnd");
2638 OS.EmitIntValue(0, 4); // PtrEnd
2639 OS.AddComment("Code size");
2640 OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4); // Code Size
2641 OS.AddComment("Function section relative address");
2642 OS.EmitCOFFSecRel32(Block.Begin, /*Offset=*/0); // Func Offset
2643 OS.AddComment("Function section index");
2644 OS.EmitCOFFSectionIndex(FI.Begin); // Func Symbol
2645 OS.AddComment("Lexical block name");
2646 emitNullTerminatedSymbolName(OS, Block.Name); // Name
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002647 endSymbolRecord(RecordEnd);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002648
2649 // Emit variables local to this lexical block.
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002650 emitLocalVariableList(FI, Block.Locals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002651
2652 // Emit lexical blocks contained within this block.
2653 emitLexicalBlockList(Block.Children, FI);
2654
2655 // Close the lexical block scope.
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002656 emitEndSymbolRecord(SymbolKind::S_END);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002657}
2658
2659/// Convenience routine for collecting lexical block information for a list
2660/// of lexical scopes.
2661void CodeViewDebug::collectLexicalBlockInfo(
2662 SmallVectorImpl<LexicalScope *> &Scopes,
2663 SmallVectorImpl<LexicalBlock *> &Blocks,
2664 SmallVectorImpl<LocalVariable> &Locals) {
2665 for (LexicalScope *Scope : Scopes)
2666 collectLexicalBlockInfo(*Scope, Blocks, Locals);
2667}
2668
2669/// Populate the lexical blocks and local variable lists of the parent with
2670/// information about the specified lexical scope.
2671void CodeViewDebug::collectLexicalBlockInfo(
2672 LexicalScope &Scope,
2673 SmallVectorImpl<LexicalBlock *> &ParentBlocks,
2674 SmallVectorImpl<LocalVariable> &ParentLocals) {
2675 if (Scope.isAbstractScope())
2676 return;
2677
2678 auto LocalsIter = ScopeVariables.find(&Scope);
2679 if (LocalsIter == ScopeVariables.end()) {
2680 // This scope does not contain variables and can be eliminated.
2681 collectLexicalBlockInfo(Scope.getChildren(), ParentBlocks, ParentLocals);
2682 return;
2683 }
2684 SmallVectorImpl<LocalVariable> &Locals = LocalsIter->second;
2685
2686 const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
2687 if (!DILB) {
2688 // This scope is not a lexical block and can be eliminated, but keep any
2689 // local variables it contains.
2690 ParentLocals.append(Locals.begin(), Locals.end());
2691 collectLexicalBlockInfo(Scope.getChildren(), ParentBlocks, ParentLocals);
2692 return;
2693 }
2694
2695 const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
2696 if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second)) {
2697 // This lexical block scope has too many address ranges to represent in the
2698 // current CodeView format or does not have a valid address range.
2699 // Eliminate this lexical scope and promote any locals it contains to the
2700 // parent scope.
2701 //
2702 // For lexical scopes with multiple address ranges you may be tempted to
2703 // construct a single range covering every instruction where the block is
2704 // live and everything in between. Unfortunately, Visual Studio only
2705 // displays variables from the first matching lexical block scope. If the
2706 // first lexical block contains exception handling code or cold code which
2707 // is moved to the bottom of the routine creating a single range covering
2708 // nearly the entire routine, then it will hide all other lexical blocks
2709 // and the variables they contain.
2710 //
2711 ParentLocals.append(Locals.begin(), Locals.end());
2712 collectLexicalBlockInfo(Scope.getChildren(), ParentBlocks, ParentLocals);
2713 return;
2714 }
2715
2716 // Create a new CodeView lexical block for this lexical scope. If we've
2717 // seen this DILexicalBlock before then the scope tree is malformed and
2718 // we can handle this gracefully by not processing it a second time.
2719 auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
2720 if (!BlockInsertion.second)
2721 return;
2722
2723 // Create a lexical block containing the local variables and collect the
2724 // the lexical block information for the children.
2725 const InsnRange &Range = Ranges.front();
2726 assert(Range.first && Range.second);
2727 LexicalBlock &Block = BlockInsertion.first->second;
2728 Block.Begin = getLabelBeforeInsn(Range.first);
2729 Block.End = getLabelAfterInsn(Range.second);
2730 assert(Block.Begin && "missing label for scope begin");
2731 assert(Block.End && "missing label for scope end");
2732 Block.Name = DILB->getName();
2733 Block.Locals = std::move(Locals);
2734 ParentBlocks.push_back(&Block);
2735 collectLexicalBlockInfo(Scope.getChildren(), Block.Children, Block.Locals);
2736}
2737
David Blaikieb2fbb4b2017-02-16 18:48:33 +00002738void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002739 const Function &GV = MF->getFunction();
2740 assert(FnDebugInfo.count(&GV));
Reid Kleckner55baeef2018-03-15 21:12:21 +00002741 assert(CurFn == FnDebugInfo[&GV].get());
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002742
Matthias Braunf1caa282017-12-15 22:22:58 +00002743 collectVariableInfo(GV.getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00002744
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002745 // Build the lexical block structure to emit for this routine.
2746 if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
2747 collectLexicalBlockInfo(*CFS, CurFn->ChildBlocks, CurFn->Locals);
2748
2749 // Clear the scope and variable information from the map which will not be
2750 // valid after we have finished processing this routine. This also prepares
2751 // the map for the subsequent routine.
2752 ScopeVariables.clear();
2753
Reid Kleckner2214ed82016-01-29 00:49:42 +00002754 // Don't emit anything if we don't have any line tables.
Brock Wyma94ece8f2018-04-16 16:53:57 +00002755 // Thunks are compiler-generated and probably won't have source correlation.
2756 if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002757 FnDebugInfo.erase(&GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002758 CurFn = nullptr;
2759 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00002760 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002761
Reid Klecknere33c94f2017-09-05 20:14:58 +00002762 CurFn->Annotations = MF->getCodeViewAnnotations();
2763
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002764 CurFn->End = Asm->getFunctionEnd();
2765
Craig Topper353eda42014-04-24 06:44:33 +00002766 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002767}
2768
Reid Kleckner70f5bc92016-01-14 19:25:04 +00002769void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002770 DebugHandlerBase::beginInstruction(MI);
2771
Shiva Chen801bf7e2018-05-09 02:42:00 +00002772 // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
2773 if (!Asm || !CurFn || MI->isDebugInstr() ||
David Majnemer67f684e2016-07-28 05:03:22 +00002774 MI->getFlag(MachineInstr::FrameSetup))
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002775 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002776
2777 // If the first instruction of a new MBB has no location, find the first
2778 // instruction with a location and use that.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002779 DebugLoc DL = MI->getDebugLoc();
Reid Kleckner45a74622017-06-30 21:33:44 +00002780 if (!DL && MI->getParent() != PrevInstBB) {
2781 for (const auto &NextMI : *MI->getParent()) {
Shiva Chen801bf7e2018-05-09 02:42:00 +00002782 if (NextMI.isDebugInstr())
Reid Kleckner2de471d2017-07-31 21:03:08 +00002783 continue;
Reid Kleckner45a74622017-06-30 21:33:44 +00002784 DL = NextMI.getDebugLoc();
2785 if (DL)
2786 break;
2787 }
2788 }
2789 PrevInstBB = MI->getParent();
2790
2791 // If we still don't have a debug location, don't record a location.
2792 if (!DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002793 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002794
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002795 maybeRecordLocation(DL, Asm->MF);
2796}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002797
Zachary Turner8c099fe2017-05-30 16:36:15 +00002798MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002799 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2800 *EndLabel = MMI->getContext().createTempSymbol();
2801 OS.EmitIntValue(unsigned(Kind), 4);
2802 OS.AddComment("Subsection size");
2803 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2804 OS.EmitLabel(BeginLabel);
2805 return EndLabel;
2806}
2807
2808void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2809 OS.EmitLabel(EndLabel);
2810 // Every subsection must be aligned to a 4-byte boundary.
2811 OS.EmitValueToAlignment(4);
2812}
2813
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002814static StringRef getSymbolName(SymbolKind SymKind) {
2815 for (const EnumEntry<SymbolKind> &EE : getSymbolTypeNames())
2816 if (EE.Value == SymKind)
2817 return EE.Name;
2818 return "";
2819}
2820
2821MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) {
2822 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2823 *EndLabel = MMI->getContext().createTempSymbol();
2824 OS.AddComment("Record length");
2825 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
2826 OS.EmitLabel(BeginLabel);
2827 if (OS.isVerboseAsm())
2828 OS.AddComment("Record kind: " + getSymbolName(SymKind));
2829 OS.EmitIntValue(unsigned(SymKind), 2);
2830 return EndLabel;
2831}
2832
2833void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) {
2834 // Symbol records in object files are not aligned, although we are considering
2835 // it for linker performance reasons.
Reid Kleckner53ce0592018-12-18 01:14:05 +00002836 OS.EmitValueToAlignment(4);
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002837 OS.EmitLabel(SymEnd);
2838}
2839
2840void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) {
2841 OS.AddComment("Record length");
2842 OS.EmitIntValue(2, 2);
2843 if (OS.isVerboseAsm())
2844 OS.AddComment("Record kind: " + getSymbolName(EndKind));
2845 OS.EmitIntValue(unsigned(EndKind), 2); // Record Kind
2846}
2847
David Majnemer3128b102016-06-15 18:00:01 +00002848void CodeViewDebug::emitDebugInfoForUDTs(
Zachary Turnera7b04172017-08-28 18:49:04 +00002849 ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
2850 for (const auto &UDT : UDTs) {
2851 const DIType *T = UDT.second;
2852 assert(shouldEmitUdt(T));
2853
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002854 MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT);
David Majnemer3128b102016-06-15 18:00:01 +00002855 OS.AddComment("Type");
Zachary Turnera7b04172017-08-28 18:49:04 +00002856 OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
David Majnemer3128b102016-06-15 18:00:01 +00002857 emitNullTerminatedSymbolName(OS, UDT.first);
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002858 endSymbolRecord(UDTRecordEnd);
David Majnemer3128b102016-06-15 18:00:01 +00002859 }
2860}
2861
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002862void CodeViewDebug::emitDebugInfoForGlobals() {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002863 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2864 GlobalMap;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002865 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002866 SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2867 GV.getDebugInfo(GVEs);
2868 for (const auto *GVE : GVEs)
2869 GlobalMap[GVE] = &GV;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002870 }
2871
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002872 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2873 for (const MDNode *Node : CUs->operands()) {
2874 const auto *CU = cast<DICompileUnit>(Node);
2875
2876 // First, emit all globals that are not in a comdat in a single symbol
2877 // substream. MSVC doesn't like it if the substream is empty, so only open
2878 // it if we have at least one global to emit.
2879 switchToDebugSectionForSymbol(nullptr);
2880 MCSymbol *EndLabel = nullptr;
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002881 for (const auto *GVE : CU->getGlobalVariables()) {
2882 if (const auto *GV = GlobalMap.lookup(GVE))
David Majnemer577be0f2016-06-15 00:19:52 +00002883 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002884 if (!EndLabel) {
2885 OS.AddComment("Symbol subsection for globals");
Zachary Turner8c099fe2017-05-30 16:36:15 +00002886 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002887 }
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002888 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2889 emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002890 }
2891 }
2892 if (EndLabel)
2893 endCVSubsection(EndLabel);
2894
2895 // Second, emit each global that is in a comdat into its own .debug$S
2896 // section along with its own symbol substream.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002897 for (const auto *GVE : CU->getGlobalVariables()) {
2898 if (const auto *GV = GlobalMap.lookup(GVE)) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002899 if (GV->hasComdat()) {
2900 MCSymbol *GVSym = Asm->getSymbol(GV);
2901 OS.AddComment("Symbol subsection for " +
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00002902 Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002903 switchToDebugSectionForSymbol(GVSym);
Zachary Turner8c099fe2017-05-30 16:36:15 +00002904 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002905 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2906 emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002907 endCVSubsection(EndLabel);
2908 }
2909 }
2910 }
2911 }
2912}
2913
Hans Wennborgb510b452016-06-23 16:33:53 +00002914void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2915 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2916 for (const MDNode *Node : CUs->operands()) {
2917 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2918 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2919 getTypeIndex(RT);
2920 // FIXME: Add to global/local DTU list.
2921 }
2922 }
2923 }
2924}
2925
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002926void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002927 const GlobalVariable *GV,
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002928 MCSymbol *GVSym) {
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002929 // DataSym record, see SymbolRecord.h for more info. Thread local data
2930 // happens to have the same format as global data.
2931 SymbolKind DataSym = GV->isThreadLocal()
2932 ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32
2933 : SymbolKind::S_GTHREAD32)
2934 : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32
2935 : SymbolKind::S_GDATA32);
2936 MCSymbol *DataEnd = beginSymbolRecord(DataSym);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002937 OS.AddComment("Type");
2938 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2939 OS.AddComment("DataOffset");
Keno Fischerf7d84ee2017-01-02 03:00:19 +00002940 OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002941 OS.AddComment("Segment");
2942 OS.EmitCOFFSectionIndex(GVSym);
2943 OS.AddComment("Name");
Reid Kleckner5bf71d12018-12-14 22:40:28 +00002944 const unsigned LengthOfDataRecord = 12;
2945 emitNullTerminatedSymbolName(OS, DIGV->getName(), LengthOfDataRecord);
2946 endSymbolRecord(DataEnd);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002947}