blob: 42259d4a62d97c481826f7680305bfa867ae12e6 [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 Kleckner2214ed82016-01-29 00:49:42 +000047#include "llvm/DebugInfo/CodeView/Line.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000048#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
Zachary Turner629cb7d2017-01-11 23:24:22 +000049#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000050#include "llvm/DebugInfo/CodeView/TypeIndex.h"
51#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Zachary Turner526f4f22017-05-19 19:26:58 +000052#include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
David Majnemer9319cbc2016-06-30 03:00:20 +000053#include "llvm/IR/Constants.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000054#include "llvm/IR/DataLayout.h"
55#include "llvm/IR/DebugInfoMetadata.h"
56#include "llvm/IR/DebugLoc.h"
57#include "llvm/IR/Function.h"
58#include "llvm/IR/GlobalValue.h"
59#include "llvm/IR/GlobalVariable.h"
60#include "llvm/IR/Metadata.h"
61#include "llvm/IR/Module.h"
Reid Kleckner46cb48c2016-07-27 16:03:57 +000062#include "llvm/MC/MCAsmInfo.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000063#include "llvm/MC/MCContext.h"
Reid Kleckner5d122f82016-05-25 23:16:12 +000064#include "llvm/MC/MCSectionCOFF.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000065#include "llvm/MC/MCStreamer.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000066#include "llvm/MC/MCSymbol.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000067#include "llvm/Support/BinaryByteStream.h"
68#include "llvm/Support/BinaryStreamReader.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000069#include "llvm/Support/Casting.h"
Zachary Turner048f8f92017-12-13 22:33:58 +000070#include "llvm/Support/CommandLine.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000071#include "llvm/Support/Compiler.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000072#include "llvm/Support/Endian.h"
73#include "llvm/Support/Error.h"
74#include "llvm/Support/ErrorHandling.h"
Zachary Turner048f8f92017-12-13 22:33:58 +000075#include "llvm/Support/FormatVariadic.h"
Zachary Turner5bba1ca2018-10-12 17:26:19 +000076#include "llvm/Support/Path.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000077#include "llvm/Support/SMLoc.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000078#include "llvm/Support/ScopedPrinter.h"
David Blaikie6054e652018-03-23 23:58:19 +000079#include "llvm/Target/TargetLoweringObjectFile.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000080#include "llvm/Target/TargetMachine.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000081#include <algorithm>
82#include <cassert>
83#include <cctype>
84#include <cstddef>
85#include <cstdint>
86#include <iterator>
87#include <limits>
88#include <string>
89#include <utility>
90#include <vector>
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000091
Reid Klecknerf9c275f2016-02-10 20:55:49 +000092using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000093using namespace llvm::codeview;
94
Zachary Turner048f8f92017-12-13 22:33:58 +000095static cl::opt<bool> EmitDebugGlobalHashes("emit-codeview-ghash-section",
96 cl::ReallyHidden, cl::init(false));
97
Reid Kleckner9ea2c012018-10-01 21:59:45 +000098static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
99 switch (Type) {
100 case Triple::ArchType::x86:
101 return CPUType::Pentium3;
102 case Triple::ArchType::x86_64:
103 return CPUType::X64;
104 case Triple::ArchType::thumb:
105 return CPUType::Thumb;
106 case Triple::ArchType::aarch64:
107 return CPUType::ARM64;
108 default:
109 report_fatal_error("target architecture doesn't map to a CodeView CPUType");
110 }
111}
112
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000113CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000114 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000115 // If module doesn't have named metadata anchors or COFF debug section
116 // is not available, skip any debug info related stuff.
117 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
118 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
119 Asm = nullptr;
Matthias Braun8763c0c2018-10-31 17:18:41 +0000120 MMI->setDebugInfoAvailability(false);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000121 return;
122 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000123 // Tell MMI that we have debug info.
124 MMI->setDebugInfoAvailability(true);
Reid Kleckner9ea2c012018-10-01 21:59:45 +0000125
126 TheCPU =
127 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000128}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000129
Reid Kleckner9533af42016-01-16 00:09:09 +0000130StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
131 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000132 if (!Filepath.empty())
133 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000134
Reid Kleckner9533af42016-01-16 00:09:09 +0000135 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
136
Peter Collingbournecb8a6662018-04-11 18:24:03 +0000137 // If this is a Unix-style path, just use it as is. Don't try to canonicalize
138 // it textually because one of the path components could be a symlink.
Zachary Turner5bba1ca2018-10-12 17:26:19 +0000139 if (Dir.startswith("/") || Filename.startswith("/")) {
140 if (llvm::sys::path::is_absolute(Filename, llvm::sys::path::Style::posix))
141 return Filename;
Peter Collingbournecb8a6662018-04-11 18:24:03 +0000142 Filepath = Dir;
143 if (Dir.back() != '/')
144 Filepath += '/';
145 Filepath += Filename;
146 return Filepath;
147 }
148
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000149 // Clang emits directory and relative filename info into the IR, but CodeView
150 // operates on full paths. We could change Clang to emit full paths too, but
151 // that would increase the IR size and probably not needed for other users.
152 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000153 if (Filename.find(':') == 1)
154 Filepath = Filename;
155 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +0000156 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000157
158 // Canonicalize the path. We have to do it textually because we may no longer
159 // have access the file in the filesystem.
160 // First, replace all slashes with backslashes.
161 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
162
163 // Remove all "\.\" with "\".
164 size_t Cursor = 0;
165 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
166 Filepath.erase(Cursor, 2);
167
168 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
169 // path should be well-formatted, e.g. start with a drive letter, etc.
170 Cursor = 0;
171 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
172 // Something's wrong if the path starts with "\..\", abort.
173 if (Cursor == 0)
174 break;
175
176 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
177 if (PrevSlash == std::string::npos)
178 // Something's wrong, abort.
179 break;
180
181 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
182 // The next ".." might be following the one we've just erased.
183 Cursor = PrevSlash;
184 }
185
186 // Remove all duplicate backslashes.
187 Cursor = 0;
188 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
189 Filepath.erase(Cursor, 1);
190
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000191 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000192}
193
Reid Kleckner2214ed82016-01-29 00:49:42 +0000194unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
Reid Klecknerbc6f52d2017-10-31 21:52:15 +0000195 StringRef FullPath = getFullFilepath(F);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000196 unsigned NextId = FileIdMap.size() + 1;
Reid Klecknerbc6f52d2017-10-31 21:52:15 +0000197 auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
Reid Kleckner2214ed82016-01-29 00:49:42 +0000198 if (Insertion.second) {
199 // We have to compute the full filepath and emit a .cv_file directive.
Scott Linder71603842018-02-12 19:45:54 +0000200 ArrayRef<uint8_t> ChecksumAsBytes;
201 FileChecksumKind CSKind = FileChecksumKind::None;
202 if (F->getChecksum()) {
203 std::string Checksum = fromHex(F->getChecksum()->Value);
204 void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
205 memcpy(CKMem, Checksum.data(), Checksum.size());
206 ChecksumAsBytes = ArrayRef<uint8_t>(
207 reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
208 switch (F->getChecksum()->Kind) {
209 case DIFile::CSK_MD5: CSKind = FileChecksumKind::MD5; break;
210 case DIFile::CSK_SHA1: CSKind = FileChecksumKind::SHA1; break;
211 }
212 }
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000213 bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
Scott Linder71603842018-02-12 19:45:54 +0000214 static_cast<unsigned>(CSKind));
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000215 (void)Success;
216 assert(Success && ".cv_file directive failed");
Reid Kleckner2214ed82016-01-29 00:49:42 +0000217 }
218 return Insertion.first->second;
219}
220
Reid Kleckner876330d2016-02-12 21:48:30 +0000221CodeViewDebug::InlineSite &
222CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
223 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000224 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
225 InlineSite *Site = &SiteInsertion.first->second;
226 if (SiteInsertion.second) {
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000227 unsigned ParentFuncId = CurFn->FuncId;
228 if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
229 ParentFuncId =
230 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
231 .SiteFuncId;
232
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000233 Site->SiteFuncId = NextFuncId++;
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000234 OS.EmitCVInlineSiteIdDirective(
235 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
236 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
Reid Kleckner876330d2016-02-12 21:48:30 +0000237 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000238 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000239 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000240 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000241 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000242}
243
David Majnemer6bdc24e2016-07-01 23:12:45 +0000244static StringRef getPrettyScopeName(const DIScope *Scope) {
245 StringRef ScopeName = Scope->getName();
246 if (!ScopeName.empty())
247 return ScopeName;
248
249 switch (Scope->getTag()) {
250 case dwarf::DW_TAG_enumeration_type:
251 case dwarf::DW_TAG_class_type:
252 case dwarf::DW_TAG_structure_type:
253 case dwarf::DW_TAG_union_type:
254 return "<unnamed-tag>";
255 case dwarf::DW_TAG_namespace:
256 return "`anonymous namespace'";
257 }
258
259 return StringRef();
260}
261
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000262static const DISubprogram *getQualifiedNameComponents(
263 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
264 const DISubprogram *ClosestSubprogram = nullptr;
265 while (Scope != nullptr) {
266 if (ClosestSubprogram == nullptr)
267 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
David Majnemer6bdc24e2016-07-01 23:12:45 +0000268 StringRef ScopeName = getPrettyScopeName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000269 if (!ScopeName.empty())
270 QualifiedNameComponents.push_back(ScopeName);
271 Scope = Scope->getScope().resolve();
272 }
273 return ClosestSubprogram;
274}
275
276static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
277 StringRef TypeName) {
278 std::string FullyQualifiedName;
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000279 for (StringRef QualifiedNameComponent :
280 llvm::reverse(QualifiedNameComponents)) {
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000281 FullyQualifiedName.append(QualifiedNameComponent);
282 FullyQualifiedName.append("::");
283 }
284 FullyQualifiedName.append(TypeName);
285 return FullyQualifiedName;
286}
287
288static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
289 SmallVector<StringRef, 5> QualifiedNameComponents;
290 getQualifiedNameComponents(Scope, QualifiedNameComponents);
291 return getQualifiedName(QualifiedNameComponents, Name);
292}
293
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000294struct CodeViewDebug::TypeLoweringScope {
295 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
296 ~TypeLoweringScope() {
297 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
298 // inner TypeLoweringScopes don't attempt to emit deferred types.
299 if (CVD.TypeEmissionLevel == 1)
300 CVD.emitDeferredCompleteTypes();
301 --CVD.TypeEmissionLevel;
302 }
303 CodeViewDebug &CVD;
304};
305
David Majnemer6bdc24e2016-07-01 23:12:45 +0000306static std::string getFullyQualifiedName(const DIScope *Ty) {
307 const DIScope *Scope = Ty->getScope().resolve();
308 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
309}
310
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000311TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
312 // No scope means global scope and that uses the zero index.
313 if (!Scope || isa<DIFile>(Scope))
314 return TypeIndex();
315
316 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
317
318 // Check if we've already translated this scope.
319 auto I = TypeIndices.find({Scope, nullptr});
320 if (I != TypeIndices.end())
321 return I->second;
322
323 // Build the fully qualified name of the scope.
David Majnemer6bdc24e2016-07-01 23:12:45 +0000324 std::string ScopeName = getFullyQualifiedName(Scope);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000325 StringIdRecord SID(TypeIndex(), ScopeName);
Zachary Turner6900de12017-11-28 18:33:17 +0000326 auto TI = TypeTable.writeLeafType(SID);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000327 return recordTypeIndexForDINode(Scope, TI);
328}
329
David Majnemer75c3ebf2016-06-02 17:13:53 +0000330TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
David Majnemer67f684e2016-07-28 05:03:22 +0000331 assert(SP);
Reid Kleckner2280f932016-05-23 20:23:46 +0000332
David Majnemer75c3ebf2016-06-02 17:13:53 +0000333 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000334 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000335 if (I != TypeIndices.end())
336 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000337
Reid Klecknerac945e22016-06-17 16:11:20 +0000338 // The display name includes function template arguments. Drop them to match
339 // MSVC.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000340 StringRef DisplayName = SP->getName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000341
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000342 const DIScope *Scope = SP->getScope().resolve();
343 TypeIndex TI;
344 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
345 // If the scope is a DICompositeType, then this must be a method. Member
346 // function types take some special handling, and require access to the
347 // subprogram.
348 TypeIndex ClassType = getTypeIndex(Class);
349 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
350 DisplayName);
Zachary Turner6900de12017-11-28 18:33:17 +0000351 TI = TypeTable.writeLeafType(MFuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000352 } else {
353 // Otherwise, this must be a free function.
354 TypeIndex ParentScope = getScopeIndex(Scope);
355 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Zachary Turner6900de12017-11-28 18:33:17 +0000356 TI = TypeTable.writeLeafType(FuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000357 }
358
359 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000360}
361
Aaron Smith802b0332018-10-02 20:21:05 +0000362static bool isTrivial(const DICompositeType *DCTy) {
363 return ((DCTy->getFlags() & DINode::FlagTrivial) == DINode::FlagTrivial);
364}
365
366static FunctionOptions
367getFunctionOptions(const DISubroutineType *Ty,
368 const DICompositeType *ClassTy = nullptr,
369 StringRef SPName = StringRef("")) {
370 FunctionOptions FO = FunctionOptions::None;
371 const DIType *ReturnTy = nullptr;
372 if (auto TypeArray = Ty->getTypeArray()) {
373 if (TypeArray.size())
374 ReturnTy = TypeArray[0].resolve();
375 }
376
377 if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy)) {
378 if (!isTrivial(ReturnDCTy))
379 FO |= FunctionOptions::CxxReturnUdt;
380 }
381
382 // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison.
383 if (ClassTy && !isTrivial(ClassTy) && SPName == ClassTy->getName()) {
384 FO |= FunctionOptions::Constructor;
385
386 // TODO: put the FunctionOptions::ConstructorWithVirtualBases flag.
387
388 }
389 return FO;
390}
391
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000392TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
393 const DICompositeType *Class) {
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000394 // Always use the method declaration as the key for the function type. The
395 // method declaration contains the this adjustment.
396 if (SP->getDeclaration())
397 SP = SP->getDeclaration();
398 assert(!SP->getDeclaration() && "should use declaration as key");
399
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000400 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
401 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000402 auto I = TypeIndices.find({SP, Class});
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000403 if (I != TypeIndices.end())
404 return I->second;
405
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000406 // Make sure complete type info for the class is emitted *after* the member
407 // function type, as the complete class type is likely to reference this
408 // member function type.
409 TypeLoweringScope S(*this);
Adrian McCarthyd91bf392017-09-13 20:53:55 +0000410 const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
Aaron Smith802b0332018-10-02 20:21:05 +0000411
412 FunctionOptions FO = getFunctionOptions(SP->getType(), Class, SP->getName());
Adrian McCarthyd91bf392017-09-13 20:53:55 +0000413 TypeIndex TI = lowerTypeMemberFunction(
Aaron Smith802b0332018-10-02 20:21:05 +0000414 SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000415 return recordTypeIndexForDINode(SP, TI, Class);
416}
417
Amjad Aboudacee5682016-07-12 12:06:34 +0000418TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
419 TypeIndex TI,
420 const DIType *ClassTy) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000421 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000422 (void)InsertResult;
423 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000424 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000425}
426
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000427unsigned CodeViewDebug::getPointerSizeInBytes() {
428 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
429}
430
Reid Kleckner876330d2016-02-12 21:48:30 +0000431void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
Reid Kleckner5a791ee2018-03-15 21:24:04 +0000432 const LexicalScope *LS) {
433 if (const DILocation *InlinedAt = LS->getInlinedAt()) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000434 // This variable was inlined. Associate it with the InlineSite.
435 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
436 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
437 Site.InlinedLocals.emplace_back(Var);
438 } else {
Reid Kleckner5a791ee2018-03-15 21:24:04 +0000439 // This variable goes into the corresponding lexical scope.
440 ScopeVariables[LS].emplace_back(Var);
Reid Kleckner876330d2016-02-12 21:48:30 +0000441 }
442}
443
Reid Kleckner829365a2016-02-11 19:41:47 +0000444static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
445 const DILocation *Loc) {
446 auto B = Locs.begin(), E = Locs.end();
447 if (std::find(B, E, Loc) == E)
448 Locs.push_back(Loc);
449}
450
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000451void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000452 const MachineFunction *MF) {
453 // Skip this instruction if it has the same location as the previous one.
Reid Kleckner45a74622017-06-30 21:33:44 +0000454 if (!DL || DL == PrevInstLoc)
Reid Kleckner9533af42016-01-16 00:09:09 +0000455 return;
456
457 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000458 if (!Scope)
459 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000460
David Majnemerc3340db2016-01-13 01:05:23 +0000461 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000462 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
463 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
464 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000465 return;
466
Reid Kleckner2214ed82016-01-29 00:49:42 +0000467 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
468 if (CI.getStartColumn() != DL.getCol())
469 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000470
Reid Kleckner2214ed82016-01-29 00:49:42 +0000471 if (!CurFn->HaveLineInfo)
472 CurFn->HaveLineInfo = true;
473 unsigned FileId = 0;
Reid Kleckner45a74622017-06-30 21:33:44 +0000474 if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
Reid Kleckner2214ed82016-01-29 00:49:42 +0000475 FileId = CurFn->LastFileId;
476 else
477 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
Reid Kleckner45a74622017-06-30 21:33:44 +0000478 PrevInstLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000479
480 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000481 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000482 const DILocation *Loc = DL.get();
483
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000484 // If this location was actually inlined from somewhere else, give it the ID
485 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000486 FuncId =
487 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000488
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000489 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000490 bool FirstLoc = true;
491 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000492 InlineSite &Site =
493 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000494 if (!FirstLoc)
495 addLocIfNotPresent(Site.ChildSites, Loc);
496 FirstLoc = false;
497 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000498 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000499 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000500 }
501
Reid Klecknerdac21b42016-02-03 21:15:48 +0000502 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000503 /*PrologueEnd=*/false, /*IsStmt=*/false,
504 DL->getFilename(), SMLoc());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000505}
506
Reid Kleckner5d122f82016-05-25 23:16:12 +0000507void CodeViewDebug::emitCodeViewMagicVersion() {
508 OS.EmitValueToAlignment(4);
509 OS.AddComment("Debug section magic");
510 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
511}
512
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000513void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000514 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000515 return;
516
517 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000518
519 // The COFF .debug$S section consists of several subsections, each starting
520 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
521 // of the payload followed by the payload itself. The subsections are 4-byte
522 // aligned.
523
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000524 // Use the generic .debug$S section, and make a subsection for all the inlined
525 // subprograms.
526 switchToDebugSectionForSymbol(nullptr);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000527
Zachary Turner8c099fe2017-05-30 16:36:15 +0000528 MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000529 emitCompilerInformation();
530 endCVSubsection(CompilerInfo);
531
Reid Kleckner5d122f82016-05-25 23:16:12 +0000532 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000533
Reid Kleckner2214ed82016-01-29 00:49:42 +0000534 // Emit per-function debug information.
535 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000536 if (!P.first->isDeclarationForLinker())
Reid Kleckner55baeef2018-03-15 21:12:21 +0000537 emitDebugInfoForFunction(P.first, *P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000538
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000539 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000540 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000541 emitDebugInfoForGlobals();
542
Hans Wennborgb510b452016-06-23 16:33:53 +0000543 // Emit retained types.
544 emitDebugInfoForRetainedTypes();
545
Reid Kleckner5d122f82016-05-25 23:16:12 +0000546 // Switch back to the generic .debug$S section after potentially processing
547 // comdat symbol sections.
548 switchToDebugSectionForSymbol(nullptr);
549
David Majnemer3128b102016-06-15 18:00:01 +0000550 // Emit UDT records for any types used by global variables.
551 if (!GlobalUDTs.empty()) {
Zachary Turner8c099fe2017-05-30 16:36:15 +0000552 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
David Majnemer3128b102016-06-15 18:00:01 +0000553 emitDebugInfoForUDTs(GlobalUDTs);
554 endCVSubsection(SymbolsEnd);
555 }
556
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000557 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000558 OS.AddComment("File index to string table offset subsection");
559 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000560
561 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000562 OS.AddComment("String table");
563 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000564
Reid Kleckner810687c2018-10-12 18:19:06 +0000565 // Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol
566 // subsection in the generic .debug$S section at the end. There is no
567 // particular reason for this ordering other than to match MSVC.
568 emitBuildInfo();
569
Zachary Turner048f8f92017-12-13 22:33:58 +0000570 // Emit type information and hashes last, so that any types we translate while
571 // emitting function info are included.
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000572 emitTypeInformation();
573
Zachary Turner048f8f92017-12-13 22:33:58 +0000574 if (EmitDebugGlobalHashes)
575 emitTypeGlobalHashes();
576
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000577 clear();
578}
579
Brock Wyma19e17b32018-02-11 21:26:46 +0000580static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S,
581 unsigned MaxFixedRecordLength = 0xF00) {
Reid Klecknerbb96df62016-10-05 22:36:07 +0000582 // The maximum CV record length is 0xFF00. Most of the strings we emit appear
583 // after a fixed length portion of the record. The fixed length portion should
584 // always be less than 0xF00 (3840) bytes, so truncate the string so that the
585 // overall record size is less than the maximum allowed.
Reid Klecknerbb96df62016-10-05 22:36:07 +0000586 SmallString<32> NullTerminatedString(
587 S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
David Majnemerb9456a52016-03-14 05:15:09 +0000588 NullTerminatedString.push_back('\0');
589 OS.EmitBytes(NullTerminatedString);
590}
591
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000592void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000593 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000594 return;
595
Alexandre Ganead9e96742018-04-09 20:17:56 +0000596 // Start the .debug$T or .debug$P section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000597 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000598 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000599
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000600 SmallString<8> CommentPrefix;
601 if (OS.isVerboseAsm()) {
602 CommentPrefix += '\t';
603 CommentPrefix += Asm->MAI->getCommentString();
604 CommentPrefix += ' ';
605 }
606
Zachary Turner526f4f22017-05-19 19:26:58 +0000607 TypeTableCollection Table(TypeTable.records());
608 Optional<TypeIndex> B = Table.getFirst();
609 while (B) {
610 // This will fail if the record data is invalid.
611 CVType Record = Table.getType(*B);
612
Zachary Turner4efa0a42016-11-08 22:24:53 +0000613 if (OS.isVerboseAsm()) {
614 // Emit a block comment describing the type record for readability.
615 SmallString<512> CommentBlock;
616 raw_svector_ostream CommentOS(CommentBlock);
617 ScopedPrinter SP(CommentOS);
618 SP.setPrefix(CommentPrefix);
Zachary Turner526f4f22017-05-19 19:26:58 +0000619 TypeDumpVisitor TDV(Table, &SP, false);
620
621 Error E = codeview::visitTypeRecord(Record, *B, TDV);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000622 if (E) {
623 logAllUnhandledErrors(std::move(E), errs(), "error: ");
624 llvm_unreachable("produced malformed type record");
625 }
626 // emitRawComment will insert its own tab and comment string before
627 // the first line, so strip off our first one. It also prints its own
628 // newline.
629 OS.emitRawComment(
630 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
Zachary Turner4efa0a42016-11-08 22:24:53 +0000631 }
Zachary Turner526f4f22017-05-19 19:26:58 +0000632 OS.EmitBinaryData(Record.str_data());
633 B = Table.getNext(*B);
634 }
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000635}
636
Zachary Turner048f8f92017-12-13 22:33:58 +0000637void CodeViewDebug::emitTypeGlobalHashes() {
638 if (TypeTable.empty())
639 return;
640
641 // Start the .debug$H section with the version and hash algorithm, currently
642 // hardcoded to version 0, SHA1.
643 OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
644
645 OS.EmitValueToAlignment(4);
646 OS.AddComment("Magic");
647 OS.EmitIntValue(COFF::DEBUG_HASHES_SECTION_MAGIC, 4);
648 OS.AddComment("Section Version");
649 OS.EmitIntValue(0, 2);
650 OS.AddComment("Hash Algorithm");
Zachary Turnerc7626662018-05-17 22:55:15 +0000651 OS.EmitIntValue(uint16_t(GlobalTypeHashAlg::SHA1_8), 2);
Zachary Turner048f8f92017-12-13 22:33:58 +0000652
653 TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
654 for (const auto &GHR : TypeTable.hashes()) {
655 if (OS.isVerboseAsm()) {
656 // Emit an EOL-comment describing which TypeIndex this hash corresponds
657 // to, as well as the stringified SHA1 hash.
658 SmallString<32> Comment;
659 raw_svector_ostream CommentOS(Comment);
660 CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
661 OS.AddComment(Comment);
662 ++TI;
663 }
Zachary Turnerc7626662018-05-17 22:55:15 +0000664 assert(GHR.Hash.size() == 8);
Zachary Turner048f8f92017-12-13 22:33:58 +0000665 StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
666 GHR.Hash.size());
667 OS.EmitBinaryData(S);
668 }
669}
670
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000671static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
672 switch (DWLang) {
673 case dwarf::DW_LANG_C:
674 case dwarf::DW_LANG_C89:
675 case dwarf::DW_LANG_C99:
676 case dwarf::DW_LANG_C11:
677 case dwarf::DW_LANG_ObjC:
678 return SourceLanguage::C;
679 case dwarf::DW_LANG_C_plus_plus:
680 case dwarf::DW_LANG_C_plus_plus_03:
681 case dwarf::DW_LANG_C_plus_plus_11:
682 case dwarf::DW_LANG_C_plus_plus_14:
683 return SourceLanguage::Cpp;
684 case dwarf::DW_LANG_Fortran77:
685 case dwarf::DW_LANG_Fortran90:
686 case dwarf::DW_LANG_Fortran03:
687 case dwarf::DW_LANG_Fortran08:
688 return SourceLanguage::Fortran;
689 case dwarf::DW_LANG_Pascal83:
690 return SourceLanguage::Pascal;
691 case dwarf::DW_LANG_Cobol74:
692 case dwarf::DW_LANG_Cobol85:
693 return SourceLanguage::Cobol;
694 case dwarf::DW_LANG_Java:
695 return SourceLanguage::Java;
Reid Kleckner898ddf62017-07-24 16:16:42 +0000696 case dwarf::DW_LANG_D:
697 return SourceLanguage::D;
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000698 default:
699 // There's no CodeView representation for this language, and CV doesn't
700 // have an "unknown" option for the language field, so we'll use MASM,
701 // as it's very low level.
702 return SourceLanguage::Masm;
703 }
704}
705
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000706namespace {
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000707struct Version {
708 int Part[4];
709};
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000710} // end anonymous namespace
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000711
712// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
713// the version number.
714static Version parseVersion(StringRef Name) {
Adrian McCarthyad8ac542016-09-20 17:42:13 +0000715 Version V = {{0}};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000716 int N = 0;
717 for (const char C : Name) {
718 if (isdigit(C)) {
719 V.Part[N] *= 10;
720 V.Part[N] += C - '0';
721 } else if (C == '.') {
722 ++N;
723 if (N >= 4)
724 return V;
725 } else if (N > 0)
726 return V;
727 }
728 return V;
729}
730
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000731void CodeViewDebug::emitCompilerInformation() {
732 MCContext &Context = MMI->getContext();
733 MCSymbol *CompilerBegin = Context.createTempSymbol(),
734 *CompilerEnd = Context.createTempSymbol();
735 OS.AddComment("Record length");
736 OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
737 OS.EmitLabel(CompilerBegin);
738 OS.AddComment("Record kind: S_COMPILE3");
739 OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
740 uint32_t Flags = 0;
741
742 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
743 const MDNode *Node = *CUs->operands().begin();
744 const auto *CU = cast<DICompileUnit>(Node);
745
746 // The low byte of the flags indicates the source language.
747 Flags = MapDWLangToCVLang(CU->getSourceLanguage());
748 // TODO: Figure out which other flags need to be set.
749
750 OS.AddComment("Flags and language");
751 OS.EmitIntValue(Flags, 4);
752
753 OS.AddComment("CPUType");
Reid Kleckner9ea2c012018-10-01 21:59:45 +0000754 OS.EmitIntValue(static_cast<uint64_t>(TheCPU), 2);
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000755
756 StringRef CompilerVersion = CU->getProducer();
757 Version FrontVer = parseVersion(CompilerVersion);
758 OS.AddComment("Frontend version");
759 for (int N = 0; N < 4; ++N)
760 OS.EmitIntValue(FrontVer.Part[N], 2);
761
762 // Some Microsoft tools, like Binscope, expect a backend version number of at
763 // least 8.something, so we'll coerce the LLVM version into a form that
764 // guarantees it'll be big enough without really lying about the version.
Adrian McCarthyd1185fc2016-09-29 20:28:25 +0000765 int Major = 1000 * LLVM_VERSION_MAJOR +
766 10 * LLVM_VERSION_MINOR +
767 LLVM_VERSION_PATCH;
768 // Clamp it for builds that use unusually large version numbers.
769 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
770 Version BackVer = {{ Major, 0, 0, 0 }};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000771 OS.AddComment("Backend version");
772 for (int N = 0; N < 4; ++N)
773 OS.EmitIntValue(BackVer.Part[N], 2);
774
775 OS.AddComment("Null-terminated compiler version string");
776 emitNullTerminatedSymbolName(OS, CompilerVersion);
777
778 OS.EmitLabel(CompilerEnd);
779}
780
Reid Kleckner810687c2018-10-12 18:19:06 +0000781static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable,
782 StringRef S) {
783 StringIdRecord SIR(TypeIndex(0x0), S);
784 return TypeTable.writeLeafType(SIR);
785}
786
787void CodeViewDebug::emitBuildInfo() {
788 // First, make LF_BUILDINFO. It's a sequence of strings with various bits of
789 // build info. The known prefix is:
790 // - Absolute path of current directory
791 // - Compiler path
792 // - Main source file path, relative to CWD or absolute
793 // - Type server PDB file
794 // - Canonical compiler command line
795 // If frontend and backend compilation are separated (think llc or LTO), it's
796 // not clear if the compiler path should refer to the executable for the
797 // frontend or the backend. Leave it blank for now.
798 TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {};
799 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
800 const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs.
801 const auto *CU = cast<DICompileUnit>(Node);
802 const DIFile *MainSourceFile = CU->getFile();
803 BuildInfoArgs[BuildInfoRecord::CurrentDirectory] =
804 getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory());
805 BuildInfoArgs[BuildInfoRecord::SourceFile] =
806 getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename());
807 // FIXME: Path to compiler and command line. PDB is intentionally blank unless
808 // we implement /Zi type servers.
809 BuildInfoRecord BIR(BuildInfoArgs);
810 TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR);
811
812 // Make a new .debug$S subsection for the S_BUILDINFO record, which points
813 // from the module symbols into the type stream.
814 MCSymbol *BuildInfoEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
815 OS.AddComment("Record length");
816 OS.EmitIntValue(6, 2);
817 OS.AddComment("Record kind: S_BUILDINFO");
818 OS.EmitIntValue(unsigned(SymbolKind::S_BUILDINFO), 2);
819 OS.AddComment("LF_BUILDINFO index");
820 OS.EmitIntValue(BuildInfoIndex.getIndex(), 4);
821 endCVSubsection(BuildInfoEnd);
822}
823
Reid Kleckner5d122f82016-05-25 23:16:12 +0000824void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000825 if (InlinedSubprograms.empty())
826 return;
827
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000828 OS.AddComment("Inlinee lines subsection");
Zachary Turner8c099fe2017-05-30 16:36:15 +0000829 MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000830
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000831 // We emit the checksum info for files. This is used by debuggers to
832 // determine if a pdb matches the source before loading it. Visual Studio,
833 // for instance, will display a warning that the breakpoints are not valid if
834 // the pdb does not match the source.
David Majnemer30579ec2016-02-02 23:18:23 +0000835 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000836 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
837
838 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000839 assert(TypeIndices.count({SP, nullptr}));
840 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000841
David Majnemer30579ec2016-02-02 23:18:23 +0000842 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000843 unsigned FileId = maybeRecordFile(SP->getFile());
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000844 OS.AddComment("Inlined function " + SP->getName() + " starts at " +
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000845 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000846 OS.AddBlankLine();
David Majnemer30579ec2016-02-02 23:18:23 +0000847 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000848 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000849 OS.AddComment("Offset into filechecksum table");
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000850 OS.EmitCVFileChecksumOffsetDirective(FileId);
David Majnemer30579ec2016-02-02 23:18:23 +0000851 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000852 OS.EmitIntValue(SP->getLine(), 4);
853 }
854
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000855 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000856}
857
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000858void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
859 const DILocation *InlinedAt,
860 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000861 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
862 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000863
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000864 assert(TypeIndices.count({Site.Inlinee, nullptr}));
865 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000866
867 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000868 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000869 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000870 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000871 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000872 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000873
Reid Klecknerdac21b42016-02-03 21:15:48 +0000874 OS.AddComment("PtrParent");
875 OS.EmitIntValue(0, 4);
876 OS.AddComment("PtrEnd");
877 OS.EmitIntValue(0, 4);
878 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000879 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000880
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000881 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
882 unsigned StartLineNum = Site.Inlinee->getLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000883
884 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000885 FI.Begin, FI.End);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000886
887 OS.EmitLabel(InlineEnd);
888
Reid Kleckner9ea2c012018-10-01 21:59:45 +0000889 emitLocalVariableList(FI, Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000890
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000891 // Recurse on child inlined call sites before closing the scope.
892 for (const DILocation *ChildSite : Site.ChildSites) {
893 auto I = FI.InlineSites.find(ChildSite);
894 assert(I != FI.InlineSites.end() &&
895 "child site not in function inline site map");
896 emitInlinedCallSite(FI, ChildSite, I->second);
897 }
898
899 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000900 OS.AddComment("Record length");
901 OS.EmitIntValue(2, 2); // RecordLength
902 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000903 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000904}
905
Reid Kleckner5d122f82016-05-25 23:16:12 +0000906void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
907 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
908 // comdat key. A section may be comdat because of -ffunction-sections or
909 // because it is comdat in the IR.
910 MCSectionCOFF *GVSec =
911 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
912 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
913
914 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
915 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
916 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
917
918 OS.SwitchSection(DebugSec);
919
920 // Emit the magic version number if this is the first time we've switched to
921 // this section.
922 if (ComdatDebugSections.insert(DebugSec).second)
923 emitCodeViewMagicVersion();
924}
925
Brock Wyma94ece8f2018-04-16 16:53:57 +0000926// Emit an S_THUNK32/S_END symbol pair for a thunk routine.
927// The only supported thunk ordinal is currently the standard type.
928void CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
929 FunctionInfo &FI,
930 const MCSymbol *Fn) {
931 std::string FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
932 const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
933
934 OS.AddComment("Symbol subsection for " + Twine(FuncName));
935 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
936
937 // Emit S_THUNK32
938 MCSymbol *ThunkRecordBegin = MMI->getContext().createTempSymbol(),
939 *ThunkRecordEnd = MMI->getContext().createTempSymbol();
940 OS.AddComment("Record length");
941 OS.emitAbsoluteSymbolDiff(ThunkRecordEnd, ThunkRecordBegin, 2);
942 OS.EmitLabel(ThunkRecordBegin);
943 OS.AddComment("Record kind: S_THUNK32");
944 OS.EmitIntValue(unsigned(SymbolKind::S_THUNK32), 2);
945 OS.AddComment("PtrParent");
946 OS.EmitIntValue(0, 4);
947 OS.AddComment("PtrEnd");
948 OS.EmitIntValue(0, 4);
949 OS.AddComment("PtrNext");
950 OS.EmitIntValue(0, 4);
951 OS.AddComment("Thunk section relative address");
952 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
953 OS.AddComment("Thunk section index");
954 OS.EmitCOFFSectionIndex(Fn);
955 OS.AddComment("Code size");
956 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
957 OS.AddComment("Ordinal");
958 OS.EmitIntValue(unsigned(ordinal), 1);
959 OS.AddComment("Function name");
960 emitNullTerminatedSymbolName(OS, FuncName);
961 // Additional fields specific to the thunk ordinal would go here.
962 OS.EmitLabel(ThunkRecordEnd);
963
964 // Local variables/inlined routines are purposely omitted here. The point of
965 // marking this as a thunk is so Visual Studio will NOT stop in this routine.
966
967 // Emit S_PROC_ID_END
968 const unsigned RecordLengthForSymbolEnd = 2;
969 OS.AddComment("Record length");
970 OS.EmitIntValue(RecordLengthForSymbolEnd, 2);
971 OS.AddComment("Record kind: S_PROC_ID_END");
972 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
973
974 endCVSubsection(SymbolsEnd);
975}
976
Reid Kleckner2214ed82016-01-29 00:49:42 +0000977void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
978 FunctionInfo &FI) {
Brock Wyma31cc1eb2018-01-30 13:16:50 +0000979 // For each function there is a separate subsection which holds the PC to
980 // file:line table.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000981 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000982 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000983
Reid Kleckner5d122f82016-05-25 23:16:12 +0000984 // Switch to the to a comdat section, if appropriate.
985 switchToDebugSectionForSymbol(Fn);
986
Reid Klecknerac945e22016-06-17 16:11:20 +0000987 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000988 auto *SP = GV->getSubprogram();
David Majnemer67f684e2016-07-28 05:03:22 +0000989 assert(SP);
David Majnemer3128b102016-06-15 18:00:01 +0000990 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000991
Brock Wyma94ece8f2018-04-16 16:53:57 +0000992 if (SP->isThunk()) {
993 emitDebugInfoForThunk(GV, FI, Fn);
994 return;
995 }
996
Reid Klecknerac945e22016-06-17 16:11:20 +0000997 // If we have a display name, build the fully qualified name by walking the
998 // chain of scopes.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000999 if (!SP->getName().empty())
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001000 FuncName =
Adrian Prantl9d2f0192017-04-26 23:59:52 +00001001 getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +00001002
Reid Kleckner3c0ff982016-01-14 00:12:54 +00001003 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +00001004 if (FuncName.empty())
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00001005 FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +00001006
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00001007 // Emit FPO data, but only on 32-bit x86. No other platforms use it.
1008 if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
1009 OS.EmitCVFPOData(Fn);
1010
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001011 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +00001012 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Zachary Turner8c099fe2017-05-30 16:36:15 +00001013 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001014 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001015 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
1016 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +00001017 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +00001018 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +00001019 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001020
Reid Kleckner4ad127f2016-09-14 21:49:21 +00001021 if (GV->hasLocalLinkage()) {
1022 OS.AddComment("Record kind: S_LPROC32_ID");
1023 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
1024 } else {
1025 OS.AddComment("Record kind: S_GPROC32_ID");
1026 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
1027 }
Reid Kleckner6b3faef2016-01-13 23:44:57 +00001028
David Majnemer30579ec2016-02-02 23:18:23 +00001029 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +00001030 OS.AddComment("PtrParent");
1031 OS.EmitIntValue(0, 4);
1032 OS.AddComment("PtrEnd");
1033 OS.EmitIntValue(0, 4);
1034 OS.AddComment("PtrNext");
1035 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001036 // This is the important bit that tells the debugger where the function
1037 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +00001038 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +00001039 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +00001040 OS.AddComment("Offset after prologue");
1041 OS.EmitIntValue(0, 4);
1042 OS.AddComment("Offset before epilogue");
1043 OS.EmitIntValue(0, 4);
1044 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +00001045 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +00001046 OS.AddComment("Function section relative address");
Keno Fischerf7d84ee2017-01-02 03:00:19 +00001047 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
Reid Klecknerdac21b42016-02-03 21:15:48 +00001048 OS.AddComment("Function section index");
1049 OS.EmitCOFFSectionIndex(Fn);
1050 OS.AddComment("Flags");
1051 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +00001052 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +00001053 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +00001054 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00001055 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +00001056 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001057
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001058 MCSymbol *FrameProcBegin = MMI->getContext().createTempSymbol(),
1059 *FrameProcEnd = MMI->getContext().createTempSymbol();
1060 OS.AddComment("Record length");
1061 OS.emitAbsoluteSymbolDiff(FrameProcEnd, FrameProcBegin, 2);
1062 OS.EmitLabel(FrameProcBegin);
1063 OS.AddComment("Record kind: S_FRAMEPROC");
1064 OS.EmitIntValue(unsigned(SymbolKind::S_FRAMEPROC), 2);
1065 // Subtract out the CSR size since MSVC excludes that and we include it.
1066 OS.AddComment("FrameSize");
1067 OS.EmitIntValue(FI.FrameSize - FI.CSRSize, 4);
1068 OS.AddComment("Padding");
1069 OS.EmitIntValue(0, 4);
1070 OS.AddComment("Offset of padding");
1071 OS.EmitIntValue(0, 4);
1072 OS.AddComment("Bytes of callee saved registers");
1073 OS.EmitIntValue(FI.CSRSize, 4);
1074 OS.AddComment("Exception handler offset");
1075 OS.EmitIntValue(0, 4);
1076 OS.AddComment("Exception handler section");
1077 OS.EmitIntValue(0, 2);
1078 OS.AddComment("Flags (defines frame register)");
1079 OS.EmitIntValue(uint32_t(FI.FrameProcOpts), 4);
1080 OS.EmitLabel(FrameProcEnd);
1081
1082 emitLocalVariableList(FI, FI.Locals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00001083 emitLexicalBlockList(FI.ChildBlocks, FI);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001084
Reid Klecknerf3b9ba42016-01-29 18:16:43 +00001085 // Emit inlined call site information. Only emit functions inlined directly
1086 // into the parent function. We'll emit the other sites recursively as part
1087 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001088 for (const DILocation *InlinedAt : FI.ChildSites) {
1089 auto I = FI.InlineSites.find(InlinedAt);
1090 assert(I != FI.InlineSites.end() &&
1091 "child site not in function inline site map");
1092 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +00001093 }
1094
Reid Klecknere33c94f2017-09-05 20:14:58 +00001095 for (auto Annot : FI.Annotations) {
1096 MCSymbol *Label = Annot.first;
1097 MDTuple *Strs = cast<MDTuple>(Annot.second);
1098 MCSymbol *AnnotBegin = MMI->getContext().createTempSymbol(),
1099 *AnnotEnd = MMI->getContext().createTempSymbol();
1100 OS.AddComment("Record length");
1101 OS.emitAbsoluteSymbolDiff(AnnotEnd, AnnotBegin, 2);
1102 OS.EmitLabel(AnnotBegin);
1103 OS.AddComment("Record kind: S_ANNOTATION");
1104 OS.EmitIntValue(SymbolKind::S_ANNOTATION, 2);
1105 OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
1106 // FIXME: Make sure we don't overflow the max record size.
1107 OS.EmitCOFFSectionIndex(Label);
1108 OS.EmitIntValue(Strs->getNumOperands(), 2);
1109 for (Metadata *MD : Strs->operands()) {
1110 // MDStrings are null terminated, so we can do EmitBytes and get the
1111 // nice .asciz directive.
1112 StringRef Str = cast<MDString>(MD)->getString();
1113 assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
1114 OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
1115 }
1116 OS.EmitLabel(AnnotEnd);
1117 }
1118
David Majnemer3128b102016-06-15 18:00:01 +00001119 if (SP != nullptr)
1120 emitDebugInfoForUDTs(LocalUDTs);
1121
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001122 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +00001123 OS.AddComment("Record length");
1124 OS.EmitIntValue(0x0002, 2);
1125 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +00001126 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001127 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001128 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001129
Reid Kleckner2214ed82016-01-29 00:49:42 +00001130 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +00001131 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001132}
1133
Reid Kleckner876330d2016-02-12 21:48:30 +00001134CodeViewDebug::LocalVarDefRange
1135CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
1136 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +00001137 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +00001138 DR.DataOffset = Offset;
1139 assert(DR.DataOffset == Offset && "truncation");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00001140 DR.IsSubfield = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +00001141 DR.StructOffset = 0;
1142 DR.CVRegister = CVRegister;
1143 return DR;
1144}
1145
Matthias Braunef331ef2016-11-30 23:48:50 +00001146void CodeViewDebug::collectVariableInfoFromMFTable(
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001147 DenseSet<InlinedEntity> &Processed) {
Matthias Braunef331ef2016-11-30 23:48:50 +00001148 const MachineFunction &MF = *Asm->MF;
1149 const TargetSubtargetInfo &TSI = MF.getSubtarget();
Reid Kleckner876330d2016-02-12 21:48:30 +00001150 const TargetFrameLowering *TFI = TSI.getFrameLowering();
1151 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1152
Matthias Braunef331ef2016-11-30 23:48:50 +00001153 for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001154 if (!VI.Var)
1155 continue;
1156 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1157 "Expected inlined-at fields to agree");
1158
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001159 Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001160 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1161
1162 // If variable scope is not found then skip this variable.
1163 if (!Scope)
1164 continue;
1165
Reid Klecknerb5fced72017-05-09 19:59:29 +00001166 // If the variable has an attached offset expression, extract it.
1167 // FIXME: Try to handle DW_OP_deref as well.
1168 int64_t ExprOffset = 0;
1169 if (VI.Expr)
1170 if (!VI.Expr->extractIfOffset(ExprOffset))
1171 continue;
1172
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001173 // Get the frame register used and the offset.
1174 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +00001175 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
1176 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001177
1178 // Calculate the label ranges.
Reid Klecknerb5fced72017-05-09 19:59:29 +00001179 LocalVarDefRange DefRange =
1180 createDefRangeMem(CVReg, FrameOffset + ExprOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001181 for (const InsnRange &Range : Scope->getRanges()) {
1182 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1183 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +00001184 End = End ? End : Asm->getFunctionEnd();
1185 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001186 }
1187
Reid Kleckner876330d2016-02-12 21:48:30 +00001188 LocalVariable Var;
1189 Var.DIVar = VI.Var;
1190 Var.DefRanges.emplace_back(std::move(DefRange));
Reid Kleckner5a791ee2018-03-15 21:24:04 +00001191 recordLocalVariable(std::move(Var), Scope);
Reid Kleckner876330d2016-02-12 21:48:30 +00001192 }
1193}
1194
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001195static bool canUseReferenceType(const DbgVariableLocation &Loc) {
1196 return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
1197}
1198
1199static bool needsReferenceType(const DbgVariableLocation &Loc) {
1200 return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
1201}
1202
Bob Haarman223303c2017-08-29 20:59:25 +00001203void CodeViewDebug::calculateRanges(
1204 LocalVariable &Var, const DbgValueHistoryMap::InstrRanges &Ranges) {
1205 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1206
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001207 // Calculate the definition ranges.
Bob Haarman223303c2017-08-29 20:59:25 +00001208 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1209 const InsnRange &Range = *I;
1210 const MachineInstr *DVInst = Range.first;
1211 assert(DVInst->isDebugValue() && "Invalid History entry");
1212 // FIXME: Find a way to represent constant variables, since they are
1213 // relatively common.
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001214 Optional<DbgVariableLocation> Location =
1215 DbgVariableLocation::extractFromMachineInstruction(*DVInst);
1216 if (!Location)
Bob Haarmana88bce12017-08-29 21:01:55 +00001217 continue;
Bob Haarman223303c2017-08-29 20:59:25 +00001218
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001219 // CodeView can only express variables in register and variables in memory
1220 // at a constant offset from a register. However, for variables passed
1221 // indirectly by pointer, it is common for that pointer to be spilled to a
1222 // stack location. For the special case of one offseted load followed by a
1223 // zero offset load (a pointer spilled to the stack), we change the type of
1224 // the local variable from a value type to a reference type. This tricks the
1225 // debugger into doing the load for us.
1226 if (Var.UseReferenceType) {
1227 // We're using a reference type. Drop the last zero offset load.
1228 if (canUseReferenceType(*Location))
1229 Location->LoadChain.pop_back();
1230 else
1231 continue;
1232 } else if (needsReferenceType(*Location)) {
1233 // This location can't be expressed without switching to a reference type.
1234 // Start over using that.
1235 Var.UseReferenceType = true;
Bob Haarman223303c2017-08-29 20:59:25 +00001236 Var.DefRanges.clear();
1237 calculateRanges(Var, Ranges);
1238 return;
1239 }
1240
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001241 // We can only handle a register or an offseted load of a register.
1242 if (Location->Register == 0 || Location->LoadChain.size() > 1)
Bob Haarman223303c2017-08-29 20:59:25 +00001243 continue;
Bob Haarman223303c2017-08-29 20:59:25 +00001244 {
1245 LocalVarDefRange DR;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001246 DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001247 DR.InMemory = !Location->LoadChain.empty();
1248 DR.DataOffset =
1249 !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001250 if (Location->FragmentInfo) {
Bob Haarman223303c2017-08-29 20:59:25 +00001251 DR.IsSubfield = true;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001252 DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
Bob Haarman223303c2017-08-29 20:59:25 +00001253 } else {
1254 DR.IsSubfield = false;
1255 DR.StructOffset = 0;
1256 }
1257
1258 if (Var.DefRanges.empty() ||
1259 Var.DefRanges.back().isDifferentLocation(DR)) {
1260 Var.DefRanges.emplace_back(std::move(DR));
1261 }
1262 }
1263
1264 // Compute the label range.
1265 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1266 const MCSymbol *End = getLabelAfterInsn(Range.second);
1267 if (!End) {
1268 // This range is valid until the next overlapping bitpiece. In the
1269 // common case, ranges will not be bitpieces, so they will overlap.
1270 auto J = std::next(I);
1271 const DIExpression *DIExpr = DVInst->getDebugExpression();
1272 while (J != E &&
Bjorn Petterssona223f8152018-03-12 18:02:39 +00001273 !DIExpr->fragmentsOverlap(J->first->getDebugExpression()))
Bob Haarman223303c2017-08-29 20:59:25 +00001274 ++J;
1275 if (J != E)
1276 End = getLabelBeforeInsn(J->first);
1277 else
1278 End = Asm->getFunctionEnd();
1279 }
1280
1281 // If the last range end is our begin, just extend the last range.
1282 // Otherwise make a new range.
1283 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1284 Var.DefRanges.back().Ranges;
1285 if (!R.empty() && R.back().second == Begin)
1286 R.back().second = End;
1287 else
1288 R.emplace_back(Begin, End);
1289
1290 // FIXME: Do more range combining.
1291 }
1292}
1293
Reid Kleckner876330d2016-02-12 21:48:30 +00001294void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001295 DenseSet<InlinedEntity> Processed;
Reid Kleckner876330d2016-02-12 21:48:30 +00001296 // Grab the variable info that was squirreled away in the MMI side-table.
Matthias Braunef331ef2016-11-30 23:48:50 +00001297 collectVariableInfoFromMFTable(Processed);
Reid Kleckner876330d2016-02-12 21:48:30 +00001298
Reid Kleckner876330d2016-02-12 21:48:30 +00001299 for (const auto &I : DbgValues) {
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001300 InlinedEntity IV = I.first;
Reid Kleckner876330d2016-02-12 21:48:30 +00001301 if (Processed.count(IV))
1302 continue;
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001303 const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
Reid Kleckner876330d2016-02-12 21:48:30 +00001304 const DILocation *InlinedAt = IV.second;
1305
1306 // Instruction ranges, specifying where IV is accessible.
1307 const auto &Ranges = I.second;
1308
1309 LexicalScope *Scope = nullptr;
1310 if (InlinedAt)
1311 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1312 else
1313 Scope = LScopes.findLexicalScope(DIVar->getScope());
1314 // If variable scope is not found then skip this variable.
1315 if (!Scope)
1316 continue;
1317
1318 LocalVariable Var;
1319 Var.DIVar = DIVar;
1320
Bob Haarman223303c2017-08-29 20:59:25 +00001321 calculateRanges(Var, Ranges);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00001322 recordLocalVariable(std::move(Var), Scope);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001323 }
1324}
1325
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001326void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001327 const TargetSubtargetInfo &TSI = MF->getSubtarget();
1328 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1329 const MachineFrameInfo &MFI = MF->getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00001330 const Function &GV = MF->getFunction();
Reid Kleckner55baeef2018-03-15 21:12:21 +00001331 auto Insertion = FnDebugInfo.insert({&GV, llvm::make_unique<FunctionInfo>()});
Reid Klecknere9dc30d2018-03-15 21:18:42 +00001332 assert(Insertion.second && "function already has info");
Reid Kleckner55baeef2018-03-15 21:12:21 +00001333 CurFn = Insertion.first->second.get();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001334 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +00001335 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001336
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001337 // The S_FRAMEPROC record reports the stack size, and how many bytes of
1338 // callee-saved registers were used. For targets that don't use a PUSH
1339 // instruction (AArch64), this will be zero.
1340 CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
1341 CurFn->FrameSize = MFI.getStackSize();
Reid Klecknerd5e4ec72018-10-02 16:43:52 +00001342 CurFn->HasStackRealignment = TRI->needsStackRealignment(*MF);
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001343
1344 // For this function S_FRAMEPROC record, figure out which codeview register
1345 // will be the frame pointer.
1346 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
1347 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
1348 if (CurFn->FrameSize > 0) {
1349 if (!TSI.getFrameLowering()->hasFP(*MF)) {
1350 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1351 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
1352 } else {
1353 // If there is an FP, parameters are always relative to it.
1354 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
Reid Klecknerd5e4ec72018-10-02 16:43:52 +00001355 if (CurFn->HasStackRealignment) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001356 // If the stack needs realignment, locals are relative to SP or VFRAME.
1357 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1358 } else {
1359 // Otherwise, locals are relative to EBP, and we probably have VLAs or
1360 // other stack adjustments.
1361 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
1362 }
1363 }
1364 }
1365
1366 // Compute other frame procedure options.
1367 FrameProcedureOptions FPO = FrameProcedureOptions::None;
1368 if (MFI.hasVarSizedObjects())
1369 FPO |= FrameProcedureOptions::HasAlloca;
1370 if (MF->exposesReturnsTwice())
1371 FPO |= FrameProcedureOptions::HasSetJmp;
1372 // FIXME: Set HasLongJmp if we ever track that info.
1373 if (MF->hasInlineAsm())
1374 FPO |= FrameProcedureOptions::HasInlineAssembly;
1375 if (GV.hasPersonalityFn()) {
1376 if (isAsynchronousEHPersonality(
1377 classifyEHPersonality(GV.getPersonalityFn())))
1378 FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
1379 else
1380 FPO |= FrameProcedureOptions::HasExceptionHandling;
1381 }
1382 if (GV.hasFnAttribute(Attribute::InlineHint))
1383 FPO |= FrameProcedureOptions::MarkedInline;
1384 if (GV.hasFnAttribute(Attribute::Naked))
1385 FPO |= FrameProcedureOptions::Naked;
1386 if (MFI.hasStackProtectorIndex())
1387 FPO |= FrameProcedureOptions::SecurityChecks;
1388 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
1389 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
1390 if (Asm->TM.getOptLevel() != CodeGenOpt::None && !GV.optForSize() &&
1391 !GV.hasFnAttribute(Attribute::OptimizeNone))
1392 FPO |= FrameProcedureOptions::OptimizedForSpeed;
1393 // FIXME: Set GuardCfg when it is implemented.
1394 CurFn->FrameProcOpts = FPO;
1395
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001396 OS.EmitCVFuncIdDirective(CurFn->FuncId);
1397
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001398 // Find the end of the function prolog. First known non-DBG_VALUE and
1399 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001400 // FIXME: is there a simpler a way to do this? Can we just search
1401 // for the first instruction of the function, not the last of the prolog?
1402 DebugLoc PrologEndLoc;
1403 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001404 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001405 for (const auto &MI : MBB) {
Adrian Prantlfb31da12017-05-22 20:47:09 +00001406 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001407 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001408 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001409 break;
Adrian Prantlfb31da12017-05-22 20:47:09 +00001410 } else if (!MI.isMetaInstruction()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001411 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001412 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001413 }
1414 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001415
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001416 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001417 if (PrologEndLoc && !EmptyPrologue) {
1418 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001419 maybeRecordLocation(FnStartDL, MF);
1420 }
1421}
1422
Zachary Turnera7b04172017-08-28 18:49:04 +00001423static bool shouldEmitUdt(const DIType *T) {
Zachary Turner37c74742017-09-05 22:06:39 +00001424 if (!T)
1425 return false;
1426
1427 // MSVC does not emit UDTs for typedefs that are scoped to classes.
1428 if (T->getTag() == dwarf::DW_TAG_typedef) {
1429 if (DIScope *Scope = T->getScope().resolve()) {
1430 switch (Scope->getTag()) {
1431 case dwarf::DW_TAG_structure_type:
1432 case dwarf::DW_TAG_class_type:
1433 case dwarf::DW_TAG_union_type:
1434 return false;
1435 }
1436 }
1437 }
1438
Zachary Turnera7b04172017-08-28 18:49:04 +00001439 while (true) {
1440 if (!T || T->isForwardDecl())
1441 return false;
1442
1443 const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
1444 if (!DT)
1445 return true;
1446 T = DT->getBaseType().resolve();
1447 }
1448 return true;
1449}
1450
1451void CodeViewDebug::addToUDTs(const DIType *Ty) {
Reid Klecknerad56ea32016-07-01 22:24:51 +00001452 // Don't record empty UDTs.
1453 if (Ty->getName().empty())
1454 return;
Zachary Turnera7b04172017-08-28 18:49:04 +00001455 if (!shouldEmitUdt(Ty))
1456 return;
Reid Klecknerad56ea32016-07-01 22:24:51 +00001457
Hans Wennborg4b63a982016-06-23 22:57:25 +00001458 SmallVector<StringRef, 5> QualifiedNameComponents;
1459 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1460 Ty->getScope().resolve(), QualifiedNameComponents);
1461
1462 std::string FullyQualifiedName =
David Majnemer6bdc24e2016-07-01 23:12:45 +00001463 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
Hans Wennborg4b63a982016-06-23 22:57:25 +00001464
Zachary Turnera7b04172017-08-28 18:49:04 +00001465 if (ClosestSubprogram == nullptr) {
1466 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1467 } else if (ClosestSubprogram == CurrentSubprogram) {
1468 LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1469 }
Hans Wennborg4b63a982016-06-23 22:57:25 +00001470
1471 // TODO: What if the ClosestSubprogram is neither null or the current
1472 // subprogram? Currently, the UDT just gets dropped on the floor.
1473 //
1474 // The current behavior is not desirable. To get maximal fidelity, we would
1475 // need to perform all type translation before beginning emission of .debug$S
1476 // and then make LocalUDTs a member of FunctionInfo
1477}
1478
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001479TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001480 // Generic dispatch for lowering an unknown type.
1481 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001482 case dwarf::DW_TAG_array_type:
1483 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +00001484 case dwarf::DW_TAG_typedef:
1485 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001486 case dwarf::DW_TAG_base_type:
1487 return lowerTypeBasic(cast<DIBasicType>(Ty));
1488 case dwarf::DW_TAG_pointer_type:
Reid Kleckner9dac4732016-08-31 15:59:30 +00001489 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1490 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1491 LLVM_FALLTHROUGH;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001492 case dwarf::DW_TAG_reference_type:
1493 case dwarf::DW_TAG_rvalue_reference_type:
1494 return lowerTypePointer(cast<DIDerivedType>(Ty));
1495 case dwarf::DW_TAG_ptr_to_member_type:
1496 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
Reid Kleckner3acdc672018-02-27 22:08:15 +00001497 case dwarf::DW_TAG_restrict_type:
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001498 case dwarf::DW_TAG_const_type:
1499 case dwarf::DW_TAG_volatile_type:
Victor Leschuke1156c22016-10-31 19:09:38 +00001500 // TODO: add support for DW_TAG_atomic_type here
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001501 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +00001502 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001503 if (ClassTy) {
1504 // The member function type of a member function pointer has no
1505 // ThisAdjustment.
1506 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001507 /*ThisAdjustment=*/0,
1508 /*IsStaticMethod=*/false);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001509 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001510 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +00001511 case dwarf::DW_TAG_enumeration_type:
1512 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +00001513 case dwarf::DW_TAG_class_type:
1514 case dwarf::DW_TAG_structure_type:
1515 return lowerTypeClass(cast<DICompositeType>(Ty));
1516 case dwarf::DW_TAG_union_type:
1517 return lowerTypeUnion(cast<DICompositeType>(Ty));
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001518 case dwarf::DW_TAG_unspecified_type:
1519 return TypeIndex::None();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001520 default:
1521 // Use the null type index.
1522 return TypeIndex();
1523 }
1524}
1525
David Majnemerd065e232016-06-02 06:21:37 +00001526TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +00001527 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1528 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +00001529 StringRef TypeName = Ty->getName();
1530
Zachary Turnera7b04172017-08-28 18:49:04 +00001531 addToUDTs(Ty);
David Majnemer3128b102016-06-15 18:00:01 +00001532
David Majnemerd065e232016-06-02 06:21:37 +00001533 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +00001534 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +00001535 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +00001536 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +00001537 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +00001538 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001539
David Majnemerd065e232016-06-02 06:21:37 +00001540 return UnderlyingTypeIndex;
1541}
1542
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001543TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1544 DITypeRef ElementTypeRef = Ty->getBaseType();
1545 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1546 // IndexType is size_t, which depends on the bitness of the target.
Matt Arsenault41e5ac42018-03-14 00:36:23 +00001547 TypeIndex IndexType = getPointerSizeInBytes() == 8
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001548 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1549 : TypeIndex(SimpleTypeKind::UInt32Long);
Amjad Aboudacee5682016-07-12 12:06:34 +00001550
1551 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1552
Amjad Aboudacee5682016-07-12 12:06:34 +00001553 // Add subranges to array type.
1554 DINodeArray Elements = Ty->getElements();
1555 for (int i = Elements.size() - 1; i >= 0; --i) {
1556 const DINode *Element = Elements[i];
1557 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1558
1559 const DISubrange *Subrange = cast<DISubrange>(Element);
1560 assert(Subrange->getLowerBound() == 0 &&
1561 "codeview doesn't support subranges with lower bounds");
Sander de Smalenfdf40912018-01-24 09:56:07 +00001562 int64_t Count = -1;
1563 if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>())
1564 Count = CI->getSExtValue();
Amjad Aboudacee5682016-07-12 12:06:34 +00001565
Reid Klecknercd7bba02017-09-13 23:30:01 +00001566 // Forward declarations of arrays without a size and VLAs use a count of -1.
1567 // Emit a count of zero in these cases to match what MSVC does for arrays
1568 // without a size. MSVC doesn't support VLAs, so it's not clear what we
1569 // should do for them even if we could distinguish them.
Reid Kleckner6b78e162017-03-24 23:28:42 +00001570 if (Count == -1)
Reid Kleckner89af1122017-09-13 21:54:20 +00001571 Count = 0;
Amjad Aboudacee5682016-07-12 12:06:34 +00001572
Amjad Aboudacee5682016-07-12 12:06:34 +00001573 // Update the element size and element type index for subsequent subranges.
1574 ElementSize *= Count;
Reid Kleckner10762882016-09-09 17:29:36 +00001575
1576 // If this is the outermost array, use the size from the array. It will be
Reid Kleckner6b78e162017-03-24 23:28:42 +00001577 // more accurate if we had a VLA or an incomplete element type size.
Reid Kleckner10762882016-09-09 17:29:36 +00001578 uint64_t ArraySize =
1579 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1580
1581 StringRef Name = (i == 0) ? Ty->getName() : "";
Zachary Turner4efa0a42016-11-08 22:24:53 +00001582 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
Zachary Turner6900de12017-11-28 18:33:17 +00001583 ElementTypeIndex = TypeTable.writeLeafType(AR);
Amjad Aboudacee5682016-07-12 12:06:34 +00001584 }
1585
Amjad Aboudacee5682016-07-12 12:06:34 +00001586 return ElementTypeIndex;
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001587}
1588
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001589TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1590 TypeIndex Index;
1591 dwarf::TypeKind Kind;
1592 uint32_t ByteSize;
1593
1594 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +00001595 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001596
1597 SimpleTypeKind STK = SimpleTypeKind::None;
1598 switch (Kind) {
1599 case dwarf::DW_ATE_address:
1600 // FIXME: Translate
1601 break;
1602 case dwarf::DW_ATE_boolean:
1603 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001604 case 1: STK = SimpleTypeKind::Boolean8; break;
1605 case 2: STK = SimpleTypeKind::Boolean16; break;
1606 case 4: STK = SimpleTypeKind::Boolean32; break;
1607 case 8: STK = SimpleTypeKind::Boolean64; break;
1608 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001609 }
1610 break;
1611 case dwarf::DW_ATE_complex_float:
1612 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001613 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001614 case 4: STK = SimpleTypeKind::Complex32; break;
1615 case 8: STK = SimpleTypeKind::Complex64; break;
1616 case 10: STK = SimpleTypeKind::Complex80; break;
1617 case 16: STK = SimpleTypeKind::Complex128; break;
1618 }
1619 break;
1620 case dwarf::DW_ATE_float:
1621 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001622 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001623 case 4: STK = SimpleTypeKind::Float32; break;
1624 case 6: STK = SimpleTypeKind::Float48; break;
1625 case 8: STK = SimpleTypeKind::Float64; break;
1626 case 10: STK = SimpleTypeKind::Float80; break;
1627 case 16: STK = SimpleTypeKind::Float128; break;
1628 }
1629 break;
1630 case dwarf::DW_ATE_signed:
1631 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001632 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1633 case 2: STK = SimpleTypeKind::Int16Short; break;
1634 case 4: STK = SimpleTypeKind::Int32; break;
1635 case 8: STK = SimpleTypeKind::Int64Quad; break;
1636 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001637 }
1638 break;
1639 case dwarf::DW_ATE_unsigned:
1640 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001641 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1642 case 2: STK = SimpleTypeKind::UInt16Short; break;
1643 case 4: STK = SimpleTypeKind::UInt32; break;
1644 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1645 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001646 }
1647 break;
1648 case dwarf::DW_ATE_UTF:
1649 switch (ByteSize) {
1650 case 2: STK = SimpleTypeKind::Character16; break;
1651 case 4: STK = SimpleTypeKind::Character32; break;
1652 }
1653 break;
1654 case dwarf::DW_ATE_signed_char:
1655 if (ByteSize == 1)
1656 STK = SimpleTypeKind::SignedCharacter;
1657 break;
1658 case dwarf::DW_ATE_unsigned_char:
1659 if (ByteSize == 1)
1660 STK = SimpleTypeKind::UnsignedCharacter;
1661 break;
1662 default:
1663 break;
1664 }
1665
1666 // Apply some fixups based on the source-level type name.
1667 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1668 STK = SimpleTypeKind::Int32Long;
1669 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1670 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001671 if (STK == SimpleTypeKind::UInt16Short &&
1672 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001673 STK = SimpleTypeKind::WideCharacter;
1674 if ((STK == SimpleTypeKind::SignedCharacter ||
1675 STK == SimpleTypeKind::UnsignedCharacter) &&
1676 Ty->getName() == "char")
1677 STK = SimpleTypeKind::NarrowCharacter;
1678
1679 return TypeIndex(STK);
1680}
1681
Reid Kleckner3acdc672018-02-27 22:08:15 +00001682TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
1683 PointerOptions PO) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001684 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1685
Reid Kleckner3acdc672018-02-27 22:08:15 +00001686 // Pointers to simple types without any options can use SimpleTypeMode, rather
1687 // than having a dedicated pointer type record.
1688 if (PointeeTI.isSimple() && PO == PointerOptions::None &&
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001689 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1690 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1691 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1692 ? SimpleTypeMode::NearPointer64
1693 : SimpleTypeMode::NearPointer32;
1694 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1695 }
1696
1697 PointerKind PK =
1698 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1699 PointerMode PM = PointerMode::Pointer;
1700 switch (Ty->getTag()) {
1701 default: llvm_unreachable("not a pointer tag type");
1702 case dwarf::DW_TAG_pointer_type:
1703 PM = PointerMode::Pointer;
1704 break;
1705 case dwarf::DW_TAG_reference_type:
1706 PM = PointerMode::LValueReference;
1707 break;
1708 case dwarf::DW_TAG_rvalue_reference_type:
1709 PM = PointerMode::RValueReference;
1710 break;
1711 }
Reid Kleckner3acdc672018-02-27 22:08:15 +00001712
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001713 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00001714 return TypeTable.writeLeafType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001715}
1716
Reid Kleckner6fa15462016-06-17 22:14:39 +00001717static PointerToMemberRepresentation
1718translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1719 // SizeInBytes being zero generally implies that the member pointer type was
1720 // incomplete, which can happen if it is part of a function prototype. In this
1721 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001722 if (IsPMF) {
1723 switch (Flags & DINode::FlagPtrToMemberRep) {
1724 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001725 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1726 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001727 case DINode::FlagSingleInheritance:
1728 return PointerToMemberRepresentation::SingleInheritanceFunction;
1729 case DINode::FlagMultipleInheritance:
1730 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1731 case DINode::FlagVirtualInheritance:
1732 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1733 }
1734 } else {
1735 switch (Flags & DINode::FlagPtrToMemberRep) {
1736 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001737 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1738 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001739 case DINode::FlagSingleInheritance:
1740 return PointerToMemberRepresentation::SingleInheritanceData;
1741 case DINode::FlagMultipleInheritance:
1742 return PointerToMemberRepresentation::MultipleInheritanceData;
1743 case DINode::FlagVirtualInheritance:
1744 return PointerToMemberRepresentation::VirtualInheritanceData;
1745 }
1746 }
1747 llvm_unreachable("invalid ptr to member representation");
1748}
1749
Reid Kleckner3acdc672018-02-27 22:08:15 +00001750TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
1751 PointerOptions PO) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001752 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1753 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001754 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Matt Arsenault41e5ac42018-03-14 00:36:23 +00001755 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1756 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001757 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1758 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1759 : PointerMode::PointerToDataMember;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001760
Reid Kleckner6fa15462016-06-17 22:14:39 +00001761 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1762 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1763 MemberPointerInfo MPI(
1764 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001765 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Zachary Turner6900de12017-11-28 18:33:17 +00001766 return TypeTable.writeLeafType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001767}
1768
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001769/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1770/// have a translation, use the NearC convention.
1771static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1772 switch (DwarfCC) {
1773 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1774 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1775 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1776 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1777 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1778 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1779 }
1780 return CallingConvention::NearC;
1781}
1782
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001783TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1784 ModifierOptions Mods = ModifierOptions::None;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001785 PointerOptions PO = PointerOptions::None;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001786 bool IsModifier = true;
1787 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001788 while (IsModifier && BaseTy) {
Victor Leschuke1156c22016-10-31 19:09:38 +00001789 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001790 switch (BaseTy->getTag()) {
1791 case dwarf::DW_TAG_const_type:
1792 Mods |= ModifierOptions::Const;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001793 PO |= PointerOptions::Const;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001794 break;
1795 case dwarf::DW_TAG_volatile_type:
1796 Mods |= ModifierOptions::Volatile;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001797 PO |= PointerOptions::Volatile;
1798 break;
1799 case dwarf::DW_TAG_restrict_type:
1800 // Only pointer types be marked with __restrict. There is no known flag
1801 // for __restrict in LF_MODIFIER records.
1802 PO |= PointerOptions::Restrict;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001803 break;
1804 default:
1805 IsModifier = false;
1806 break;
1807 }
1808 if (IsModifier)
1809 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1810 }
Reid Kleckner3acdc672018-02-27 22:08:15 +00001811
1812 // Check if the inner type will use an LF_POINTER record. If so, the
1813 // qualifiers will go in the LF_POINTER record. This comes up for types like
1814 // 'int *const' and 'int *__restrict', not the more common cases like 'const
1815 // char *'.
1816 if (BaseTy) {
1817 switch (BaseTy->getTag()) {
1818 case dwarf::DW_TAG_pointer_type:
1819 case dwarf::DW_TAG_reference_type:
1820 case dwarf::DW_TAG_rvalue_reference_type:
1821 return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
1822 case dwarf::DW_TAG_ptr_to_member_type:
1823 return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
1824 default:
1825 break;
1826 }
1827 }
1828
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001829 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Reid Kleckner3acdc672018-02-27 22:08:15 +00001830
1831 // Return the base type index if there aren't any modifiers. For example, the
1832 // metadata could contain restrict wrappers around non-pointer types.
1833 if (Mods == ModifierOptions::None)
1834 return ModifiedTI;
1835
Zachary Turner4efa0a42016-11-08 22:24:53 +00001836 ModifierRecord MR(ModifiedTI, Mods);
Zachary Turner6900de12017-11-28 18:33:17 +00001837 return TypeTable.writeLeafType(MR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001838}
1839
David Majnemer75c3ebf2016-06-02 17:13:53 +00001840TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1841 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1842 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1843 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1844
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001845 // MSVC uses type none for variadic argument.
1846 if (ReturnAndArgTypeIndices.size() > 1 &&
1847 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1848 ReturnAndArgTypeIndices.back() = TypeIndex::None();
1849 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001850 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1851 ArrayRef<TypeIndex> ArgTypeIndices = None;
1852 if (!ReturnAndArgTypeIndices.empty()) {
1853 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1854 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1855 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1856 }
1857
1858 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner6900de12017-11-28 18:33:17 +00001859 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001860
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001861 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1862
Aaron Smith802b0332018-10-02 20:21:05 +00001863 FunctionOptions FO = getFunctionOptions(Ty);
1864 ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
1865 ArgListIndex);
Zachary Turner6900de12017-11-28 18:33:17 +00001866 return TypeTable.writeLeafType(Procedure);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001867}
1868
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001869TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001870 const DIType *ClassTy,
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001871 int ThisAdjustment,
Aaron Smith802b0332018-10-02 20:21:05 +00001872 bool IsStaticMethod,
1873 FunctionOptions FO) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001874 // Lower the containing class type.
1875 TypeIndex ClassType = getTypeIndex(ClassTy);
1876
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001877 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1878 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1879 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1880
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001881 // MSVC uses type none for variadic argument.
1882 if (ReturnAndArgTypeIndices.size() > 1 &&
1883 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1884 ReturnAndArgTypeIndices.back() = TypeIndex::None();
1885 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001886 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1887 ArrayRef<TypeIndex> ArgTypeIndices = None;
1888 if (!ReturnAndArgTypeIndices.empty()) {
1889 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1890 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1891 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1892 }
Reid Kleckner87288b92017-09-15 00:59:07 +00001893 TypeIndex ThisTypeIndex;
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001894 if (!IsStaticMethod && !ArgTypeIndices.empty()) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001895 ThisTypeIndex = ArgTypeIndices.front();
1896 ArgTypeIndices = ArgTypeIndices.drop_front();
1897 }
1898
1899 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner6900de12017-11-28 18:33:17 +00001900 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001901
1902 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1903
Aaron Smith802b0332018-10-02 20:21:05 +00001904 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
1905 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
Zachary Turner6900de12017-11-28 18:33:17 +00001906 return TypeTable.writeLeafType(MFR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001907}
1908
Reid Kleckner9dac4732016-08-31 15:59:30 +00001909TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001910 unsigned VSlotCount =
1911 Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
Reid Kleckner9dac4732016-08-31 15:59:30 +00001912 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001913
1914 VFTableShapeRecord VFTSR(Slots);
Zachary Turner6900de12017-11-28 18:33:17 +00001915 return TypeTable.writeLeafType(VFTSR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001916}
1917
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001918static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1919 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001920 case DINode::FlagPrivate: return MemberAccess::Private;
1921 case DINode::FlagPublic: return MemberAccess::Public;
1922 case DINode::FlagProtected: return MemberAccess::Protected;
1923 case 0:
1924 // If there was no explicit access control, provide the default for the tag.
1925 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1926 : MemberAccess::Public;
1927 }
1928 llvm_unreachable("access flags are exclusive");
1929}
1930
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001931static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1932 if (SP->isArtificial())
1933 return MethodOptions::CompilerGenerated;
1934
1935 // FIXME: Handle other MethodOptions.
1936
1937 return MethodOptions::None;
1938}
1939
1940static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1941 bool Introduced) {
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001942 if (SP->getFlags() & DINode::FlagStaticMember)
1943 return MethodKind::Static;
1944
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001945 switch (SP->getVirtuality()) {
1946 case dwarf::DW_VIRTUALITY_none:
1947 break;
1948 case dwarf::DW_VIRTUALITY_virtual:
1949 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1950 case dwarf::DW_VIRTUALITY_pure_virtual:
1951 return Introduced ? MethodKind::PureIntroducingVirtual
1952 : MethodKind::PureVirtual;
1953 default:
1954 llvm_unreachable("unhandled virtuality case");
1955 }
1956
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001957 return MethodKind::Vanilla;
1958}
1959
Reid Klecknera8d57402016-06-03 15:58:20 +00001960static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1961 switch (Ty->getTag()) {
1962 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1963 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1964 }
1965 llvm_unreachable("unexpected tag");
1966}
1967
Reid Klecknere092dad2016-07-02 00:11:07 +00001968/// Return ClassOptions that should be present on both the forward declaration
1969/// and the defintion of a tag type.
1970static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1971 ClassOptions CO = ClassOptions::None;
1972
1973 // MSVC always sets this flag, even for local types. Clang doesn't always
Reid Klecknera8d57402016-06-03 15:58:20 +00001974 // appear to give every type a linkage name, which may be problematic for us.
1975 // FIXME: Investigate the consequences of not following them here.
Reid Klecknere092dad2016-07-02 00:11:07 +00001976 if (!Ty->getIdentifier().empty())
1977 CO |= ClassOptions::HasUniqueName;
1978
1979 // Put the Nested flag on a type if it appears immediately inside a tag type.
1980 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1981 // here. That flag is only set on definitions, and not forward declarations.
1982 const DIScope *ImmediateScope = Ty->getScope().resolve();
1983 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1984 CO |= ClassOptions::Nested;
1985
Aaron Smithda0602c2018-10-02 20:28:15 +00001986 // Put the Scoped flag on function-local types. MSVC puts this flag for enum
1987 // type only when it has an immediate function scope. Clang never puts enums
1988 // inside DILexicalBlock scopes. Enum types, as generated by clang, are
1989 // always in function, class, or file scopes.
1990 if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
1991 if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
Reid Klecknere092dad2016-07-02 00:11:07 +00001992 CO |= ClassOptions::Scoped;
Aaron Smithda0602c2018-10-02 20:28:15 +00001993 } else {
1994 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1995 Scope = Scope->getScope().resolve()) {
1996 if (isa<DISubprogram>(Scope)) {
1997 CO |= ClassOptions::Scoped;
1998 break;
1999 }
Reid Klecknere092dad2016-07-02 00:11:07 +00002000 }
2001 }
2002
2003 return CO;
Reid Klecknera8d57402016-06-03 15:58:20 +00002004}
2005
Aaron Smith122d9e72018-03-06 18:20:22 +00002006void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
2007 switch (Ty->getTag()) {
2008 case dwarf::DW_TAG_class_type:
2009 case dwarf::DW_TAG_structure_type:
2010 case dwarf::DW_TAG_union_type:
2011 case dwarf::DW_TAG_enumeration_type:
2012 break;
2013 default:
2014 return;
2015 }
2016
2017 if (const auto *File = Ty->getFile()) {
2018 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
2019 TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
2020
2021 UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
2022 TypeTable.writeLeafType(USLR);
2023 }
2024}
2025
David Majnemer979cb882016-06-16 21:32:16 +00002026TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
Reid Klecknere092dad2016-07-02 00:11:07 +00002027 ClassOptions CO = getCommonClassOptions(Ty);
David Majnemer979cb882016-06-16 21:32:16 +00002028 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00002029 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00002030
David Majnemerda9548f2016-06-17 16:13:21 +00002031 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00002032 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00002033 } else {
Zachary Turner6900de12017-11-28 18:33:17 +00002034 ContinuationRecordBuilder ContinuationBuilder;
2035 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
David Majnemerda9548f2016-06-17 16:13:21 +00002036 for (const DINode *Element : Ty->getElements()) {
2037 // We assume that the frontend provides all members in source declaration
2038 // order, which is what MSVC does.
2039 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00002040 EnumeratorRecord ER(MemberAccess::Public,
2041 APSInt::getUnsigned(Enumerator->getValue()),
2042 Enumerator->getName());
Zachary Turner6900de12017-11-28 18:33:17 +00002043 ContinuationBuilder.writeMemberType(ER);
David Majnemerda9548f2016-06-17 16:13:21 +00002044 EnumeratorCount++;
2045 }
2046 }
Zachary Turner6900de12017-11-28 18:33:17 +00002047 FTI = TypeTable.insertRecord(ContinuationBuilder);
David Majnemerda9548f2016-06-17 16:13:21 +00002048 }
David Majnemer979cb882016-06-16 21:32:16 +00002049
David Majnemer6bdc24e2016-07-01 23:12:45 +00002050 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00002051
Zachary Turner4efa0a42016-11-08 22:24:53 +00002052 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
2053 getTypeIndex(Ty->getBaseType()));
Aaron Smith122d9e72018-03-06 18:20:22 +00002054 TypeIndex EnumTI = TypeTable.writeLeafType(ER);
2055
2056 addUDTSrcLine(Ty, EnumTI);
2057
2058 return EnumTI;
David Majnemer979cb882016-06-16 21:32:16 +00002059}
2060
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002061//===----------------------------------------------------------------------===//
2062// ClassInfo
2063//===----------------------------------------------------------------------===//
2064
2065struct llvm::ClassInfo {
2066 struct MemberInfo {
2067 const DIDerivedType *MemberTypeNode;
David Majnemer08bd7442016-07-01 23:12:48 +00002068 uint64_t BaseOffset;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002069 };
2070 // [MemberInfo]
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002071 using MemberList = std::vector<MemberInfo>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002072
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002073 using MethodsList = TinyPtrVector<const DISubprogram *>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002074 // MethodName -> MethodsList
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002075 using MethodsMap = MapVector<MDString *, MethodsList>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002076
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002077 /// Base classes.
2078 std::vector<const DIDerivedType *> Inheritance;
2079
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002080 /// Direct members.
2081 MemberList Members;
2082 // Direct overloaded methods gathered by name.
2083 MethodsMap Methods;
Adrian McCarthy820ca542016-07-06 19:49:51 +00002084
Reid Kleckner9dac4732016-08-31 15:59:30 +00002085 TypeIndex VShapeTI;
2086
Reid Klecknere2e82062017-08-08 20:30:14 +00002087 std::vector<const DIType *> NestedTypes;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002088};
2089
2090void CodeViewDebug::clear() {
2091 assert(CurFn == nullptr);
2092 FileIdMap.clear();
2093 FnDebugInfo.clear();
2094 FileToFilepathMap.clear();
2095 LocalUDTs.clear();
2096 GlobalUDTs.clear();
2097 TypeIndices.clear();
2098 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002099}
2100
2101void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
2102 const DIDerivedType *DDTy) {
2103 if (!DDTy->getName().empty()) {
2104 Info.Members.push_back({DDTy, 0});
2105 return;
2106 }
Shoaib Meenai03303a32018-02-27 21:48:41 +00002107
2108 // An unnamed member may represent a nested struct or union. Attempt to
2109 // interpret the unnamed member as a DICompositeType possibly wrapped in
2110 // qualifier types. Add all the indirect fields to the current record if that
2111 // succeeds, and drop the member if that fails.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002112 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
David Majnemer08bd7442016-07-01 23:12:48 +00002113 uint64_t Offset = DDTy->getOffsetInBits();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002114 const DIType *Ty = DDTy->getBaseType().resolve();
Shoaib Meenai03303a32018-02-27 21:48:41 +00002115 bool FullyResolved = false;
2116 while (!FullyResolved) {
2117 switch (Ty->getTag()) {
2118 case dwarf::DW_TAG_const_type:
2119 case dwarf::DW_TAG_volatile_type:
2120 // FIXME: we should apply the qualifier types to the indirect fields
2121 // rather than dropping them.
2122 Ty = cast<DIDerivedType>(Ty)->getBaseType().resolve();
2123 break;
2124 default:
2125 FullyResolved = true;
2126 break;
2127 }
2128 }
2129
2130 const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
2131 if (!DCTy)
2132 return;
2133
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002134 ClassInfo NestedInfo = collectClassInfo(DCTy);
2135 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002136 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002137 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002138}
2139
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002140ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
2141 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002142 // Add elements to structure type.
2143 DINodeArray Elements = Ty->getElements();
2144 for (auto *Element : Elements) {
2145 // We assume that the frontend provides all members in source declaration
2146 // order, which is what MSVC does.
2147 if (!Element)
2148 continue;
2149 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00002150 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002151 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002152 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002153 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002154 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
2155 Info.Inheritance.push_back(DDTy);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002156 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
2157 DDTy->getName() == "__vtbl_ptr_type") {
2158 Info.VShapeTI = getTypeIndex(DDTy);
Reid Klecknere2e82062017-08-08 20:30:14 +00002159 } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
2160 Info.NestedTypes.push_back(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002161 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
2162 // Ignore friend members. It appears that MSVC emitted info about
2163 // friends in the past, but modern versions do not.
2164 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00002165 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
Reid Klecknere2e82062017-08-08 20:30:14 +00002166 Info.NestedTypes.push_back(Composite);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002167 }
2168 // Skip other unrecognized kinds of elements.
2169 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002170 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002171}
2172
Brock Wymab60532f2018-06-11 01:39:34 +00002173static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) {
2174 // This routine is used by lowerTypeClass and lowerTypeUnion to determine
2175 // if a complete type should be emitted instead of a forward reference.
2176 return Ty->getName().empty() && Ty->getIdentifier().empty() &&
2177 !Ty->isForwardDecl();
2178}
2179
Reid Klecknera8d57402016-06-03 15:58:20 +00002180TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
Brock Wymab60532f2018-06-11 01:39:34 +00002181 // Emit the complete type for unnamed structs. C++ classes with methods
2182 // which have a circular reference back to the class type are expected to
2183 // be named by the front-end and should not be "unnamed". C unnamed
2184 // structs should not have circular references.
2185 if (shouldAlwaysEmitCompleteClassType(Ty)) {
2186 // If this unnamed complete type is already in the process of being defined
2187 // then the description of the type is malformed and cannot be emitted
2188 // into CodeView correctly so report a fatal error.
2189 auto I = CompleteTypeIndices.find(Ty);
2190 if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
2191 report_fatal_error("cannot debug circular reference to unnamed type");
2192 return getCompleteTypeIndex(Ty);
2193 }
2194
Reid Klecknera8d57402016-06-03 15:58:20 +00002195 // First, construct the forward decl. Don't look into Ty to compute the
2196 // forward decl options, since it might not be available in all TUs.
2197 TypeRecordKind Kind = getRecordKind(Ty);
2198 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00002199 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00002200 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00002201 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
2202 FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002203 TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
Reid Kleckner643dd832016-06-22 17:15:28 +00002204 if (!Ty->isForwardDecl())
2205 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00002206 return FwdDeclTI;
2207}
2208
2209TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
2210 // Construct the field list and complete type record.
2211 TypeRecordKind Kind = getRecordKind(Ty);
Reid Klecknere092dad2016-07-02 00:11:07 +00002212 ClassOptions CO = getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002213 TypeIndex FieldTI;
2214 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002215 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00002216 bool ContainsNestedClass;
2217 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
2218 lowerRecordFieldList(Ty);
2219
2220 if (ContainsNestedClass)
2221 CO |= ClassOptions::ContainsNestedClass;
Reid Klecknera8d57402016-06-03 15:58:20 +00002222
David Majnemer6bdc24e2016-07-01 23:12:45 +00002223 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00002224
Reid Klecknera8d57402016-06-03 15:58:20 +00002225 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00002226
Zachary Turner4efa0a42016-11-08 22:24:53 +00002227 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
2228 SizeInBytes, FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002229 TypeIndex ClassTI = TypeTable.writeLeafType(CR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002230
Aaron Smith122d9e72018-03-06 18:20:22 +00002231 addUDTSrcLine(Ty, ClassTI);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002232
Zachary Turnera7b04172017-08-28 18:49:04 +00002233 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00002234
Hans Wennborg9a519a02016-06-22 21:22:13 +00002235 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002236}
2237
2238TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
Brock Wymab60532f2018-06-11 01:39:34 +00002239 // Emit the complete type for unnamed unions.
2240 if (shouldAlwaysEmitCompleteClassType(Ty))
2241 return getCompleteTypeIndex(Ty);
2242
Reid Klecknera8d57402016-06-03 15:58:20 +00002243 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00002244 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00002245 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00002246 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002247 TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
Reid Kleckner643dd832016-06-22 17:15:28 +00002248 if (!Ty->isForwardDecl())
2249 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00002250 return FwdDeclTI;
2251}
2252
2253TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
David Majnemere1e73722016-07-06 21:07:42 +00002254 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002255 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002256 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00002257 bool ContainsNestedClass;
2258 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
2259 lowerRecordFieldList(Ty);
2260
2261 if (ContainsNestedClass)
2262 CO |= ClassOptions::ContainsNestedClass;
2263
Reid Klecknera8d57402016-06-03 15:58:20 +00002264 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
David Majnemer6bdc24e2016-07-01 23:12:45 +00002265 std::string FullName = getFullyQualifiedName(Ty);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002266
Zachary Turner4efa0a42016-11-08 22:24:53 +00002267 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
2268 Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002269 TypeIndex UnionTI = TypeTable.writeLeafType(UR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002270
Aaron Smith122d9e72018-03-06 18:20:22 +00002271 addUDTSrcLine(Ty, UnionTI);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002272
Zachary Turnera7b04172017-08-28 18:49:04 +00002273 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00002274
Hans Wennborg9a519a02016-06-22 21:22:13 +00002275 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002276}
2277
Adrian McCarthy820ca542016-07-06 19:49:51 +00002278std::tuple<TypeIndex, TypeIndex, unsigned, bool>
Reid Klecknera8d57402016-06-03 15:58:20 +00002279CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
2280 // Manually count members. MSVC appears to count everything that generates a
2281 // field list record. Each individual overload in a method overload group
2282 // contributes to this count, even though the overload group is a single field
2283 // list record.
2284 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002285 ClassInfo Info = collectClassInfo(Ty);
Zachary Turner6900de12017-11-28 18:33:17 +00002286 ContinuationRecordBuilder ContinuationBuilder;
2287 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002288
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002289 // Create base classes.
2290 for (const DIDerivedType *I : Info.Inheritance) {
2291 if (I->getFlags() & DINode::FlagVirtual) {
2292 // Virtual base.
Brock Wyma3db2b102018-05-14 21:21:22 +00002293 unsigned VBPtrOffset = I->getVBPtrOffset();
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002294 // FIXME: Despite the accessor name, the offset is really in bytes.
2295 unsigned VBTableIndex = I->getOffsetInBits() / 4;
Bob Haarman26a87bd2016-10-25 22:11:52 +00002296 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
2297 ? TypeRecordKind::IndirectVirtualBaseClass
2298 : TypeRecordKind::VirtualBaseClass;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002299 VirtualBaseClassRecord VBCR(
Bob Haarman26a87bd2016-10-25 22:11:52 +00002300 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002301 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
Zachary Turner4efa0a42016-11-08 22:24:53 +00002302 VBTableIndex);
2303
Zachary Turner6900de12017-11-28 18:33:17 +00002304 ContinuationBuilder.writeMemberType(VBCR);
Brock Wyma4536c1f2018-02-01 20:37:38 +00002305 MemberCount++;
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002306 } else {
2307 assert(I->getOffsetInBits() % 8 == 0 &&
2308 "bases must be on byte boundaries");
Zachary Turner4efa0a42016-11-08 22:24:53 +00002309 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
2310 getTypeIndex(I->getBaseType()),
2311 I->getOffsetInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00002312 ContinuationBuilder.writeMemberType(BCR);
Brock Wyma4536c1f2018-02-01 20:37:38 +00002313 MemberCount++;
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002314 }
2315 }
2316
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002317 // Create members.
2318 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
2319 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
2320 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00002321 StringRef MemberName = Member->getName();
2322 MemberAccess Access =
2323 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002324
2325 if (Member->isStaticMember()) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00002326 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
Zachary Turner6900de12017-11-28 18:33:17 +00002327 ContinuationBuilder.writeMemberType(SDMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002328 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00002329 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00002330 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002331
Reid Kleckner9dac4732016-08-31 15:59:30 +00002332 // Virtual function pointer member.
2333 if ((Member->getFlags() & DINode::FlagArtificial) &&
2334 Member->getName().startswith("_vptr$")) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00002335 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
Zachary Turner6900de12017-11-28 18:33:17 +00002336 ContinuationBuilder.writeMemberType(VFPR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002337 MemberCount++;
2338 continue;
2339 }
2340
David Majnemer9319cbc2016-06-30 03:00:20 +00002341 // Data member.
David Majnemer08bd7442016-07-01 23:12:48 +00002342 uint64_t MemberOffsetInBits =
2343 Member->getOffsetInBits() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00002344 if (Member->isBitField()) {
2345 uint64_t StartBitOffset = MemberOffsetInBits;
2346 if (const auto *CI =
2347 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
David Majnemer08bd7442016-07-01 23:12:48 +00002348 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00002349 }
2350 StartBitOffset -= MemberOffsetInBits;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002351 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2352 StartBitOffset);
Zachary Turner6900de12017-11-28 18:33:17 +00002353 MemberBaseType = TypeTable.writeLeafType(BFR);
David Majnemer9319cbc2016-06-30 03:00:20 +00002354 }
2355 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002356 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2357 MemberName);
Zachary Turner6900de12017-11-28 18:33:17 +00002358 ContinuationBuilder.writeMemberType(DMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002359 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00002360 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002361
2362 // Create methods
2363 for (auto &MethodItr : Info.Methods) {
2364 StringRef Name = MethodItr.first->getString();
2365
2366 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00002367 for (const DISubprogram *SP : MethodItr.second) {
2368 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2369 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002370
2371 unsigned VFTableOffset = -1;
2372 if (Introduced)
2373 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2374
Zachary Turner7251ede2016-11-02 17:05:19 +00002375 Methods.push_back(OneMethodRecord(
2376 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
2377 translateMethodKindFlags(SP, Introduced),
2378 translateMethodOptionFlags(SP), VFTableOffset, Name));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002379 MemberCount++;
2380 }
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002381 assert(!Methods.empty() && "Empty methods map entry");
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002382 if (Methods.size() == 1)
Zachary Turner6900de12017-11-28 18:33:17 +00002383 ContinuationBuilder.writeMemberType(Methods[0]);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002384 else {
Zachary Turner6900de12017-11-28 18:33:17 +00002385 // FIXME: Make this use its own ContinuationBuilder so that
2386 // MethodOverloadList can be split correctly.
Zachary Turner4efa0a42016-11-08 22:24:53 +00002387 MethodOverloadListRecord MOLR(Methods);
Zachary Turner6900de12017-11-28 18:33:17 +00002388 TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
2389
Zachary Turner4efa0a42016-11-08 22:24:53 +00002390 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
Zachary Turner6900de12017-11-28 18:33:17 +00002391 ContinuationBuilder.writeMemberType(OMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002392 }
2393 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00002394
2395 // Create nested classes.
Reid Klecknere2e82062017-08-08 20:30:14 +00002396 for (const DIType *Nested : Info.NestedTypes) {
Adrian McCarthy820ca542016-07-06 19:49:51 +00002397 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
Zachary Turner6900de12017-11-28 18:33:17 +00002398 ContinuationBuilder.writeMemberType(R);
Adrian McCarthy820ca542016-07-06 19:49:51 +00002399 MemberCount++;
2400 }
2401
Zachary Turner6900de12017-11-28 18:33:17 +00002402 TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002403 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
Reid Klecknere2e82062017-08-08 20:30:14 +00002404 !Info.NestedTypes.empty());
Reid Klecknera8d57402016-06-03 15:58:20 +00002405}
2406
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002407TypeIndex CodeViewDebug::getVBPTypeIndex() {
2408 if (!VBPType.getIndex()) {
2409 // Make a 'const int *' type.
2410 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
Zachary Turner6900de12017-11-28 18:33:17 +00002411 TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002412
2413 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2414 : PointerKind::Near32;
2415 PointerMode PM = PointerMode::Pointer;
2416 PointerOptions PO = PointerOptions::None;
2417 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
Zachary Turner6900de12017-11-28 18:33:17 +00002418 VBPType = TypeTable.writeLeafType(PR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002419 }
2420
2421 return VBPType;
2422}
2423
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002424TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002425 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002426 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002427
2428 // The null DIType is the void type. Don't try to hash it.
2429 if (!Ty)
2430 return TypeIndex::Void();
2431
Reid Klecknera8d57402016-06-03 15:58:20 +00002432 // Check if we've already translated this type. Don't try to do a
2433 // get-or-create style insertion that caches the hash lookup across the
2434 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002435 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002436 if (I != TypeIndices.end())
2437 return I->second;
2438
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002439 TypeLoweringScope S(*this);
2440 TypeIndex TI = lowerType(Ty, ClassTy);
2441 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00002442}
2443
Bob Haarman223303c2017-08-29 20:59:25 +00002444TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(DITypeRef TypeRef) {
2445 DIType *Ty = TypeRef.resolve();
2446 PointerRecord PR(getTypeIndex(Ty),
2447 getPointerSizeInBytes() == 8 ? PointerKind::Near64
2448 : PointerKind::Near32,
2449 PointerMode::LValueReference, PointerOptions::None,
2450 Ty->getSizeInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00002451 return TypeTable.writeLeafType(PR);
Bob Haarman223303c2017-08-29 20:59:25 +00002452}
2453
Reid Klecknera8d57402016-06-03 15:58:20 +00002454TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
2455 const DIType *Ty = TypeRef.resolve();
2456
2457 // The null DIType is the void type. Don't try to hash it.
2458 if (!Ty)
2459 return TypeIndex::Void();
2460
2461 // If this is a non-record type, the complete type index is the same as the
2462 // normal type index. Just call getTypeIndex.
2463 switch (Ty->getTag()) {
2464 case dwarf::DW_TAG_class_type:
2465 case dwarf::DW_TAG_structure_type:
2466 case dwarf::DW_TAG_union_type:
2467 break;
2468 default:
2469 return getTypeIndex(Ty);
2470 }
2471
Brock Wymab60532f2018-06-11 01:39:34 +00002472 // Check if we've already translated the complete record type.
Reid Klecknera8d57402016-06-03 15:58:20 +00002473 const auto *CTy = cast<DICompositeType>(Ty);
2474 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
2475 if (!InsertResult.second)
2476 return InsertResult.first->second;
2477
Reid Kleckner643dd832016-06-22 17:15:28 +00002478 TypeLoweringScope S(*this);
2479
Reid Klecknera8d57402016-06-03 15:58:20 +00002480 // Make sure the forward declaration is emitted first. It's unclear if this
2481 // is necessary, but MSVC does it, and we should follow suit until we can show
2482 // otherwise.
Brock Wymab60532f2018-06-11 01:39:34 +00002483 // We only emit a forward declaration for named types.
2484 if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
2485 TypeIndex FwdDeclTI = getTypeIndex(CTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00002486
Brock Wymab60532f2018-06-11 01:39:34 +00002487 // Just use the forward decl if we don't have complete type info. This
2488 // might happen if the frontend is using modules and expects the complete
2489 // definition to be emitted elsewhere.
2490 if (CTy->isForwardDecl())
2491 return FwdDeclTI;
2492 }
Reid Klecknera8d57402016-06-03 15:58:20 +00002493
2494 TypeIndex TI;
2495 switch (CTy->getTag()) {
2496 case dwarf::DW_TAG_class_type:
2497 case dwarf::DW_TAG_structure_type:
2498 TI = lowerCompleteTypeClass(CTy);
2499 break;
2500 case dwarf::DW_TAG_union_type:
2501 TI = lowerCompleteTypeUnion(CTy);
2502 break;
2503 default:
2504 llvm_unreachable("not a record");
2505 }
2506
Brock Wymab60532f2018-06-11 01:39:34 +00002507 // Update the type index associated with this CompositeType. This cannot
2508 // use the 'InsertResult' iterator above because it is potentially
2509 // invalidated by map insertions which can occur while lowering the class
2510 // type above.
2511 CompleteTypeIndices[CTy] = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002512 return TI;
2513}
2514
Reid Kleckner643dd832016-06-22 17:15:28 +00002515/// Emit all the deferred complete record types. Try to do this in FIFO order,
Amjad Aboudacee5682016-07-12 12:06:34 +00002516/// and do this until fixpoint, as each complete record type typically
2517/// references
Reid Kleckner643dd832016-06-22 17:15:28 +00002518/// many other record types.
2519void CodeViewDebug::emitDeferredCompleteTypes() {
2520 SmallVector<const DICompositeType *, 4> TypesToEmit;
2521 while (!DeferredCompleteTypes.empty()) {
2522 std::swap(DeferredCompleteTypes, TypesToEmit);
2523 for (const DICompositeType *RecordTy : TypesToEmit)
2524 getCompleteTypeIndex(RecordTy);
2525 TypesToEmit.clear();
2526 }
2527}
2528
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002529void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
2530 ArrayRef<LocalVariable> Locals) {
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002531 // Get the sorted list of parameters and emit them first.
2532 SmallVector<const LocalVariable *, 6> Params;
2533 for (const LocalVariable &L : Locals)
2534 if (L.DIVar->isParameter())
2535 Params.push_back(&L);
Fangrui Song0cac7262018-09-27 02:13:45 +00002536 llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
2537 return L->DIVar->getArg() < R->DIVar->getArg();
2538 });
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002539 for (const LocalVariable *L : Params)
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002540 emitLocalVariable(FI, *L);
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002541
2542 // Next emit all non-parameters in the order that we found them.
2543 for (const LocalVariable &L : Locals)
2544 if (!L.DIVar->isParameter())
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002545 emitLocalVariable(FI, L);
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002546}
2547
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002548/// Only call this on endian-specific types like ulittle16_t and little32_t, or
2549/// structs composed of them.
2550template <typename T>
2551static void copyBytesForDefRange(SmallString<20> &BytePrefix,
2552 SymbolKind SymKind, const T &DefRangeHeader) {
2553 BytePrefix.resize(2 + sizeof(T));
2554 ulittle16_t SymKindLE = ulittle16_t(SymKind);
2555 memcpy(&BytePrefix[0], &SymKindLE, 2);
2556 memcpy(&BytePrefix[2], &DefRangeHeader, sizeof(T));
2557}
2558
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002559void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
2560 const LocalVariable &Var) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002561 // LocalSym record, see SymbolRecord.h for more info.
2562 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
2563 *LocalEnd = MMI->getContext().createTempSymbol();
2564 OS.AddComment("Record length");
2565 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
2566 OS.EmitLabel(LocalBegin);
2567
2568 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00002569 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002570
Zachary Turner63a28462016-05-17 23:50:21 +00002571 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002572 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00002573 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00002574 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00002575 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002576
2577 OS.AddComment("TypeIndex");
Reid Kleckner08f5fd52017-08-31 15:56:49 +00002578 TypeIndex TI = Var.UseReferenceType
2579 ? getTypeIndexForReferenceTo(Var.DIVar->getType())
2580 : getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002581 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002582 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00002583 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00002584 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00002585 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002586 OS.EmitLabel(LocalEnd);
2587
Reid Kleckner876330d2016-02-12 21:48:30 +00002588 // Calculate the on disk prefix of the appropriate def range record. The
2589 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2590 // should be big enough to hold all forms without memory allocation.
2591 SmallString<20> BytePrefix;
2592 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2593 BytePrefix.clear();
Reid Kleckner876330d2016-02-12 21:48:30 +00002594 if (DefRange.InMemory) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002595 int Offset = DefRange.DataOffset;
2596 unsigned Reg = DefRange.CVRegister;
2597
Reid Klecknerd5e4ec72018-10-02 16:43:52 +00002598 // 32-bit x86 call sequences often use PUSH instructions, which disrupt
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002599 // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
Reid Klecknerd5e4ec72018-10-02 16:43:52 +00002600 // instead. In simple cases, $T0 will be the CFA.
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002601 if (RegisterId(Reg) == RegisterId::ESP) {
2602 Reg = unsigned(RegisterId::VFRAME);
2603 Offset -= FI.FrameSize;
Reid Klecknerd5e4ec72018-10-02 16:43:52 +00002604
2605 // If the frame requires realignment, VFRAME will be ESP after it is
2606 // aligned. We have to remove the ESP adjustments made to push CSRs and
2607 // EBP. EBP is not included in CSRSize.
2608 if (FI.HasStackRealignment)
2609 Offset += FI.CSRSize + 4;
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002610 }
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002611
2612 // If we can use the chosen frame pointer for the frame and this isn't a
2613 // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
2614 // Otherwise, use S_DEFRANGE_REGISTER_REL.
2615 EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU);
2616 if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
2617 (bool(Flags & LocalSymFlags::IsParameter)
2618 ? (EncFP == FI.EncodedParamFramePtrReg)
2619 : (EncFP == FI.EncodedLocalFramePtrReg))) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002620 little32_t FPOffset = little32_t(Offset);
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002621 copyBytesForDefRange(BytePrefix, S_DEFRANGE_FRAMEPOINTER_REL, FPOffset);
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002622 } else {
2623 uint16_t RegRelFlags = 0;
2624 if (DefRange.IsSubfield) {
2625 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2626 (DefRange.StructOffset
2627 << DefRangeRegisterRelSym::OffsetInParentShift);
2628 }
2629 DefRangeRegisterRelSym::Header DRHdr;
2630 DRHdr.Register = Reg;
2631 DRHdr.Flags = RegRelFlags;
2632 DRHdr.BasePointerOffset = Offset;
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002633 copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER_REL, DRHdr);
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002634 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002635 } else {
2636 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002637 if (DefRange.IsSubfield) {
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002638 DefRangeSubfieldRegisterSym::Header DRHdr;
2639 DRHdr.Register = DefRange.CVRegister;
2640 DRHdr.MayHaveNoName = 0;
2641 DRHdr.OffsetInParent = DefRange.StructOffset;
2642 copyBytesForDefRange(BytePrefix, S_DEFRANGE_SUBFIELD_REGISTER, DRHdr);
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002643 } else {
Reid Kleckner8d7c4212018-10-01 22:25:49 +00002644 DefRangeRegisterSym::Header DRHdr;
2645 DRHdr.Register = DefRange.CVRegister;
2646 DRHdr.MayHaveNoName = 0;
2647 copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER, DRHdr);
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002648 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002649 }
2650 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2651 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002652}
2653
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002654void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
2655 const FunctionInfo& FI) {
2656 for (LexicalBlock *Block : Blocks)
2657 emitLexicalBlock(*Block, FI);
2658}
2659
2660/// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
2661/// lexical block scope.
2662void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
2663 const FunctionInfo& FI) {
2664 MCSymbol *RecordBegin = MMI->getContext().createTempSymbol(),
2665 *RecordEnd = MMI->getContext().createTempSymbol();
2666
2667 // Lexical block symbol record.
2668 OS.AddComment("Record length");
2669 OS.emitAbsoluteSymbolDiff(RecordEnd, RecordBegin, 2); // Record Length
2670 OS.EmitLabel(RecordBegin);
2671 OS.AddComment("Record kind: S_BLOCK32");
2672 OS.EmitIntValue(SymbolKind::S_BLOCK32, 2); // Record Kind
2673 OS.AddComment("PtrParent");
2674 OS.EmitIntValue(0, 4); // PtrParent
2675 OS.AddComment("PtrEnd");
2676 OS.EmitIntValue(0, 4); // PtrEnd
2677 OS.AddComment("Code size");
2678 OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4); // Code Size
2679 OS.AddComment("Function section relative address");
2680 OS.EmitCOFFSecRel32(Block.Begin, /*Offset=*/0); // Func Offset
2681 OS.AddComment("Function section index");
2682 OS.EmitCOFFSectionIndex(FI.Begin); // Func Symbol
2683 OS.AddComment("Lexical block name");
2684 emitNullTerminatedSymbolName(OS, Block.Name); // Name
2685 OS.EmitLabel(RecordEnd);
2686
2687 // Emit variables local to this lexical block.
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002688 emitLocalVariableList(FI, Block.Locals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002689
2690 // Emit lexical blocks contained within this block.
2691 emitLexicalBlockList(Block.Children, FI);
2692
2693 // Close the lexical block scope.
2694 OS.AddComment("Record length");
2695 OS.EmitIntValue(2, 2); // Record Length
2696 OS.AddComment("Record kind: S_END");
2697 OS.EmitIntValue(SymbolKind::S_END, 2); // Record Kind
2698}
2699
2700/// Convenience routine for collecting lexical block information for a list
2701/// of lexical scopes.
2702void CodeViewDebug::collectLexicalBlockInfo(
2703 SmallVectorImpl<LexicalScope *> &Scopes,
2704 SmallVectorImpl<LexicalBlock *> &Blocks,
2705 SmallVectorImpl<LocalVariable> &Locals) {
2706 for (LexicalScope *Scope : Scopes)
2707 collectLexicalBlockInfo(*Scope, Blocks, Locals);
2708}
2709
2710/// Populate the lexical blocks and local variable lists of the parent with
2711/// information about the specified lexical scope.
2712void CodeViewDebug::collectLexicalBlockInfo(
2713 LexicalScope &Scope,
2714 SmallVectorImpl<LexicalBlock *> &ParentBlocks,
2715 SmallVectorImpl<LocalVariable> &ParentLocals) {
2716 if (Scope.isAbstractScope())
2717 return;
2718
2719 auto LocalsIter = ScopeVariables.find(&Scope);
2720 if (LocalsIter == ScopeVariables.end()) {
2721 // This scope does not contain variables and can be eliminated.
2722 collectLexicalBlockInfo(Scope.getChildren(), ParentBlocks, ParentLocals);
2723 return;
2724 }
2725 SmallVectorImpl<LocalVariable> &Locals = LocalsIter->second;
2726
2727 const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
2728 if (!DILB) {
2729 // This scope is not a lexical block and can be eliminated, but keep any
2730 // local variables it contains.
2731 ParentLocals.append(Locals.begin(), Locals.end());
2732 collectLexicalBlockInfo(Scope.getChildren(), ParentBlocks, ParentLocals);
2733 return;
2734 }
2735
2736 const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
2737 if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second)) {
2738 // This lexical block scope has too many address ranges to represent in the
2739 // current CodeView format or does not have a valid address range.
2740 // Eliminate this lexical scope and promote any locals it contains to the
2741 // parent scope.
2742 //
2743 // For lexical scopes with multiple address ranges you may be tempted to
2744 // construct a single range covering every instruction where the block is
2745 // live and everything in between. Unfortunately, Visual Studio only
2746 // displays variables from the first matching lexical block scope. If the
2747 // first lexical block contains exception handling code or cold code which
2748 // is moved to the bottom of the routine creating a single range covering
2749 // nearly the entire routine, then it will hide all other lexical blocks
2750 // and the variables they contain.
2751 //
2752 ParentLocals.append(Locals.begin(), Locals.end());
2753 collectLexicalBlockInfo(Scope.getChildren(), ParentBlocks, ParentLocals);
2754 return;
2755 }
2756
2757 // Create a new CodeView lexical block for this lexical scope. If we've
2758 // seen this DILexicalBlock before then the scope tree is malformed and
2759 // we can handle this gracefully by not processing it a second time.
2760 auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
2761 if (!BlockInsertion.second)
2762 return;
2763
2764 // Create a lexical block containing the local variables and collect the
2765 // the lexical block information for the children.
2766 const InsnRange &Range = Ranges.front();
2767 assert(Range.first && Range.second);
2768 LexicalBlock &Block = BlockInsertion.first->second;
2769 Block.Begin = getLabelBeforeInsn(Range.first);
2770 Block.End = getLabelAfterInsn(Range.second);
2771 assert(Block.Begin && "missing label for scope begin");
2772 assert(Block.End && "missing label for scope end");
2773 Block.Name = DILB->getName();
2774 Block.Locals = std::move(Locals);
2775 ParentBlocks.push_back(&Block);
2776 collectLexicalBlockInfo(Scope.getChildren(), Block.Children, Block.Locals);
2777}
2778
David Blaikieb2fbb4b2017-02-16 18:48:33 +00002779void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002780 const Function &GV = MF->getFunction();
2781 assert(FnDebugInfo.count(&GV));
Reid Kleckner55baeef2018-03-15 21:12:21 +00002782 assert(CurFn == FnDebugInfo[&GV].get());
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002783
Matthias Braunf1caa282017-12-15 22:22:58 +00002784 collectVariableInfo(GV.getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00002785
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002786 // Build the lexical block structure to emit for this routine.
2787 if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
2788 collectLexicalBlockInfo(*CFS, CurFn->ChildBlocks, CurFn->Locals);
2789
2790 // Clear the scope and variable information from the map which will not be
2791 // valid after we have finished processing this routine. This also prepares
2792 // the map for the subsequent routine.
2793 ScopeVariables.clear();
2794
Reid Kleckner2214ed82016-01-29 00:49:42 +00002795 // Don't emit anything if we don't have any line tables.
Brock Wyma94ece8f2018-04-16 16:53:57 +00002796 // Thunks are compiler-generated and probably won't have source correlation.
2797 if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002798 FnDebugInfo.erase(&GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002799 CurFn = nullptr;
2800 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00002801 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002802
Reid Klecknere33c94f2017-09-05 20:14:58 +00002803 CurFn->Annotations = MF->getCodeViewAnnotations();
2804
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002805 CurFn->End = Asm->getFunctionEnd();
2806
Craig Topper353eda42014-04-24 06:44:33 +00002807 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002808}
2809
Reid Kleckner70f5bc92016-01-14 19:25:04 +00002810void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002811 DebugHandlerBase::beginInstruction(MI);
2812
Shiva Chen801bf7e2018-05-09 02:42:00 +00002813 // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
2814 if (!Asm || !CurFn || MI->isDebugInstr() ||
David Majnemer67f684e2016-07-28 05:03:22 +00002815 MI->getFlag(MachineInstr::FrameSetup))
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002816 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002817
2818 // If the first instruction of a new MBB has no location, find the first
2819 // instruction with a location and use that.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002820 DebugLoc DL = MI->getDebugLoc();
Reid Kleckner45a74622017-06-30 21:33:44 +00002821 if (!DL && MI->getParent() != PrevInstBB) {
2822 for (const auto &NextMI : *MI->getParent()) {
Shiva Chen801bf7e2018-05-09 02:42:00 +00002823 if (NextMI.isDebugInstr())
Reid Kleckner2de471d2017-07-31 21:03:08 +00002824 continue;
Reid Kleckner45a74622017-06-30 21:33:44 +00002825 DL = NextMI.getDebugLoc();
2826 if (DL)
2827 break;
2828 }
2829 }
2830 PrevInstBB = MI->getParent();
2831
2832 // If we still don't have a debug location, don't record a location.
2833 if (!DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002834 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002835
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002836 maybeRecordLocation(DL, Asm->MF);
2837}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002838
Zachary Turner8c099fe2017-05-30 16:36:15 +00002839MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002840 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2841 *EndLabel = MMI->getContext().createTempSymbol();
2842 OS.EmitIntValue(unsigned(Kind), 4);
2843 OS.AddComment("Subsection size");
2844 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2845 OS.EmitLabel(BeginLabel);
2846 return EndLabel;
2847}
2848
2849void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2850 OS.EmitLabel(EndLabel);
2851 // Every subsection must be aligned to a 4-byte boundary.
2852 OS.EmitValueToAlignment(4);
2853}
2854
David Majnemer3128b102016-06-15 18:00:01 +00002855void CodeViewDebug::emitDebugInfoForUDTs(
Zachary Turnera7b04172017-08-28 18:49:04 +00002856 ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
2857 for (const auto &UDT : UDTs) {
2858 const DIType *T = UDT.second;
2859 assert(shouldEmitUdt(T));
2860
David Majnemer3128b102016-06-15 18:00:01 +00002861 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
2862 *UDTRecordEnd = MMI->getContext().createTempSymbol();
2863 OS.AddComment("Record length");
2864 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
2865 OS.EmitLabel(UDTRecordBegin);
2866
2867 OS.AddComment("Record kind: S_UDT");
2868 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
2869
2870 OS.AddComment("Type");
Zachary Turnera7b04172017-08-28 18:49:04 +00002871 OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
David Majnemer3128b102016-06-15 18:00:01 +00002872
2873 emitNullTerminatedSymbolName(OS, UDT.first);
2874 OS.EmitLabel(UDTRecordEnd);
2875 }
2876}
2877
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002878void CodeViewDebug::emitDebugInfoForGlobals() {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002879 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2880 GlobalMap;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002881 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002882 SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2883 GV.getDebugInfo(GVEs);
2884 for (const auto *GVE : GVEs)
2885 GlobalMap[GVE] = &GV;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002886 }
2887
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002888 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2889 for (const MDNode *Node : CUs->operands()) {
2890 const auto *CU = cast<DICompileUnit>(Node);
2891
2892 // First, emit all globals that are not in a comdat in a single symbol
2893 // substream. MSVC doesn't like it if the substream is empty, so only open
2894 // it if we have at least one global to emit.
2895 switchToDebugSectionForSymbol(nullptr);
2896 MCSymbol *EndLabel = nullptr;
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002897 for (const auto *GVE : CU->getGlobalVariables()) {
2898 if (const auto *GV = GlobalMap.lookup(GVE))
David Majnemer577be0f2016-06-15 00:19:52 +00002899 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002900 if (!EndLabel) {
2901 OS.AddComment("Symbol subsection for globals");
Zachary Turner8c099fe2017-05-30 16:36:15 +00002902 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002903 }
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002904 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2905 emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002906 }
2907 }
2908 if (EndLabel)
2909 endCVSubsection(EndLabel);
2910
2911 // Second, emit each global that is in a comdat into its own .debug$S
2912 // section along with its own symbol substream.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002913 for (const auto *GVE : CU->getGlobalVariables()) {
2914 if (const auto *GV = GlobalMap.lookup(GVE)) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002915 if (GV->hasComdat()) {
2916 MCSymbol *GVSym = Asm->getSymbol(GV);
2917 OS.AddComment("Symbol subsection for " +
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00002918 Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002919 switchToDebugSectionForSymbol(GVSym);
Zachary Turner8c099fe2017-05-30 16:36:15 +00002920 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002921 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2922 emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002923 endCVSubsection(EndLabel);
2924 }
2925 }
2926 }
2927 }
2928}
2929
Hans Wennborgb510b452016-06-23 16:33:53 +00002930void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2931 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2932 for (const MDNode *Node : CUs->operands()) {
2933 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2934 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2935 getTypeIndex(RT);
2936 // FIXME: Add to global/local DTU list.
2937 }
2938 }
2939 }
2940}
2941
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002942void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002943 const GlobalVariable *GV,
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002944 MCSymbol *GVSym) {
2945 // DataSym record, see SymbolRecord.h for more info.
2946 // FIXME: Thread local data, etc
2947 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2948 *DataEnd = MMI->getContext().createTempSymbol();
Brock Wyma19e17b32018-02-11 21:26:46 +00002949 const unsigned FixedLengthOfThisRecord = 12;
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002950 OS.AddComment("Record length");
2951 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2952 OS.EmitLabel(DataBegin);
David Majnemer7abd2692016-07-06 21:07:47 +00002953 if (DIGV->isLocalToUnit()) {
David Majnemera54fe1a2016-07-07 05:14:21 +00002954 if (GV->isThreadLocal()) {
2955 OS.AddComment("Record kind: S_LTHREAD32");
2956 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2957 } else {
2958 OS.AddComment("Record kind: S_LDATA32");
2959 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2960 }
David Majnemer7abd2692016-07-06 21:07:47 +00002961 } else {
David Majnemera54fe1a2016-07-07 05:14:21 +00002962 if (GV->isThreadLocal()) {
2963 OS.AddComment("Record kind: S_GTHREAD32");
2964 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2965 } else {
2966 OS.AddComment("Record kind: S_GDATA32");
2967 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2968 }
David Majnemer7abd2692016-07-06 21:07:47 +00002969 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002970 OS.AddComment("Type");
2971 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2972 OS.AddComment("DataOffset");
Keno Fischerf7d84ee2017-01-02 03:00:19 +00002973 OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002974 OS.AddComment("Segment");
2975 OS.EmitCOFFSectionIndex(GVSym);
2976 OS.AddComment("Name");
Brock Wyma19e17b32018-02-11 21:26:46 +00002977 emitNullTerminatedSymbolName(OS, DIGV->getName(), FixedLengthOfThisRecord);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002978 OS.EmitLabel(DataEnd);
2979}