blob: 1c67d765dadfc38044bf22989b88c5b89bedf4c1 [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"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000076#include "llvm/Support/SMLoc.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000077#include "llvm/Support/ScopedPrinter.h"
David Blaikie6054e652018-03-23 23:58:19 +000078#include "llvm/Target/TargetLoweringObjectFile.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000079#include "llvm/Target/TargetMachine.h"
Eugene Zelenkofb69e662017-06-06 22:22:41 +000080#include <algorithm>
81#include <cassert>
82#include <cctype>
83#include <cstddef>
84#include <cstdint>
85#include <iterator>
86#include <limits>
87#include <string>
88#include <utility>
89#include <vector>
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000090
Reid Klecknerf9c275f2016-02-10 20:55:49 +000091using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000092using namespace llvm::codeview;
93
Zachary Turner048f8f92017-12-13 22:33:58 +000094static cl::opt<bool> EmitDebugGlobalHashes("emit-codeview-ghash-section",
95 cl::ReallyHidden, cl::init(false));
96
Reid Kleckner9ea2c012018-10-01 21:59:45 +000097static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
98 switch (Type) {
99 case Triple::ArchType::x86:
100 return CPUType::Pentium3;
101 case Triple::ArchType::x86_64:
102 return CPUType::X64;
103 case Triple::ArchType::thumb:
104 return CPUType::Thumb;
105 case Triple::ArchType::aarch64:
106 return CPUType::ARM64;
107 default:
108 report_fatal_error("target architecture doesn't map to a CodeView CPUType");
109 }
110}
111
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000112CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000113 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000114 // If module doesn't have named metadata anchors or COFF debug section
115 // is not available, skip any debug info related stuff.
116 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
117 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
118 Asm = nullptr;
119 return;
120 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000121 // Tell MMI that we have debug info.
122 MMI->setDebugInfoAvailability(true);
Reid Kleckner9ea2c012018-10-01 21:59:45 +0000123
124 TheCPU =
125 mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000126}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000127
Reid Kleckner9533af42016-01-16 00:09:09 +0000128StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
129 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000130 if (!Filepath.empty())
131 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000132
Reid Kleckner9533af42016-01-16 00:09:09 +0000133 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
134
Peter Collingbournecb8a6662018-04-11 18:24:03 +0000135 // If this is a Unix-style path, just use it as is. Don't try to canonicalize
136 // it textually because one of the path components could be a symlink.
137 if (!Dir.empty() && Dir[0] == '/') {
138 Filepath = Dir;
139 if (Dir.back() != '/')
140 Filepath += '/';
141 Filepath += Filename;
142 return Filepath;
143 }
144
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000145 // Clang emits directory and relative filename info into the IR, but CodeView
146 // operates on full paths. We could change Clang to emit full paths too, but
147 // that would increase the IR size and probably not needed for other users.
148 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000149 if (Filename.find(':') == 1)
150 Filepath = Filename;
151 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +0000152 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000153
154 // Canonicalize the path. We have to do it textually because we may no longer
155 // have access the file in the filesystem.
156 // First, replace all slashes with backslashes.
157 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
158
159 // Remove all "\.\" with "\".
160 size_t Cursor = 0;
161 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
162 Filepath.erase(Cursor, 2);
163
164 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
165 // path should be well-formatted, e.g. start with a drive letter, etc.
166 Cursor = 0;
167 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
168 // Something's wrong if the path starts with "\..\", abort.
169 if (Cursor == 0)
170 break;
171
172 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
173 if (PrevSlash == std::string::npos)
174 // Something's wrong, abort.
175 break;
176
177 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
178 // The next ".." might be following the one we've just erased.
179 Cursor = PrevSlash;
180 }
181
182 // Remove all duplicate backslashes.
183 Cursor = 0;
184 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
185 Filepath.erase(Cursor, 1);
186
Reid Kleckner1f11b4e2015-12-02 22:34:30 +0000187 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000188}
189
Reid Kleckner2214ed82016-01-29 00:49:42 +0000190unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
Reid Klecknerbc6f52d2017-10-31 21:52:15 +0000191 StringRef FullPath = getFullFilepath(F);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000192 unsigned NextId = FileIdMap.size() + 1;
Reid Klecknerbc6f52d2017-10-31 21:52:15 +0000193 auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
Reid Kleckner2214ed82016-01-29 00:49:42 +0000194 if (Insertion.second) {
195 // We have to compute the full filepath and emit a .cv_file directive.
Scott Linder71603842018-02-12 19:45:54 +0000196 ArrayRef<uint8_t> ChecksumAsBytes;
197 FileChecksumKind CSKind = FileChecksumKind::None;
198 if (F->getChecksum()) {
199 std::string Checksum = fromHex(F->getChecksum()->Value);
200 void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
201 memcpy(CKMem, Checksum.data(), Checksum.size());
202 ChecksumAsBytes = ArrayRef<uint8_t>(
203 reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
204 switch (F->getChecksum()->Kind) {
205 case DIFile::CSK_MD5: CSKind = FileChecksumKind::MD5; break;
206 case DIFile::CSK_SHA1: CSKind = FileChecksumKind::SHA1; break;
207 }
208 }
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000209 bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
Scott Linder71603842018-02-12 19:45:54 +0000210 static_cast<unsigned>(CSKind));
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000211 (void)Success;
212 assert(Success && ".cv_file directive failed");
Reid Kleckner2214ed82016-01-29 00:49:42 +0000213 }
214 return Insertion.first->second;
215}
216
Reid Kleckner876330d2016-02-12 21:48:30 +0000217CodeViewDebug::InlineSite &
218CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
219 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000220 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
221 InlineSite *Site = &SiteInsertion.first->second;
222 if (SiteInsertion.second) {
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000223 unsigned ParentFuncId = CurFn->FuncId;
224 if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
225 ParentFuncId =
226 getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
227 .SiteFuncId;
228
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000229 Site->SiteFuncId = NextFuncId++;
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000230 OS.EmitCVInlineSiteIdDirective(
231 Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
232 InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
Reid Kleckner876330d2016-02-12 21:48:30 +0000233 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000234 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000235 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000236 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000237 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000238}
239
David Majnemer6bdc24e2016-07-01 23:12:45 +0000240static StringRef getPrettyScopeName(const DIScope *Scope) {
241 StringRef ScopeName = Scope->getName();
242 if (!ScopeName.empty())
243 return ScopeName;
244
245 switch (Scope->getTag()) {
246 case dwarf::DW_TAG_enumeration_type:
247 case dwarf::DW_TAG_class_type:
248 case dwarf::DW_TAG_structure_type:
249 case dwarf::DW_TAG_union_type:
250 return "<unnamed-tag>";
251 case dwarf::DW_TAG_namespace:
252 return "`anonymous namespace'";
253 }
254
255 return StringRef();
256}
257
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000258static const DISubprogram *getQualifiedNameComponents(
259 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
260 const DISubprogram *ClosestSubprogram = nullptr;
261 while (Scope != nullptr) {
262 if (ClosestSubprogram == nullptr)
263 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
David Majnemer6bdc24e2016-07-01 23:12:45 +0000264 StringRef ScopeName = getPrettyScopeName(Scope);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000265 if (!ScopeName.empty())
266 QualifiedNameComponents.push_back(ScopeName);
267 Scope = Scope->getScope().resolve();
268 }
269 return ClosestSubprogram;
270}
271
272static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
273 StringRef TypeName) {
274 std::string FullyQualifiedName;
Eugene Zelenkofb69e662017-06-06 22:22:41 +0000275 for (StringRef QualifiedNameComponent :
276 llvm::reverse(QualifiedNameComponents)) {
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000277 FullyQualifiedName.append(QualifiedNameComponent);
278 FullyQualifiedName.append("::");
279 }
280 FullyQualifiedName.append(TypeName);
281 return FullyQualifiedName;
282}
283
284static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
285 SmallVector<StringRef, 5> QualifiedNameComponents;
286 getQualifiedNameComponents(Scope, QualifiedNameComponents);
287 return getQualifiedName(QualifiedNameComponents, Name);
288}
289
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000290struct CodeViewDebug::TypeLoweringScope {
291 TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
292 ~TypeLoweringScope() {
293 // Don't decrement TypeEmissionLevel until after emitting deferred types, so
294 // inner TypeLoweringScopes don't attempt to emit deferred types.
295 if (CVD.TypeEmissionLevel == 1)
296 CVD.emitDeferredCompleteTypes();
297 --CVD.TypeEmissionLevel;
298 }
299 CodeViewDebug &CVD;
300};
301
David Majnemer6bdc24e2016-07-01 23:12:45 +0000302static std::string getFullyQualifiedName(const DIScope *Ty) {
303 const DIScope *Scope = Ty->getScope().resolve();
304 return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
305}
306
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000307TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
308 // No scope means global scope and that uses the zero index.
309 if (!Scope || isa<DIFile>(Scope))
310 return TypeIndex();
311
312 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
313
314 // Check if we've already translated this scope.
315 auto I = TypeIndices.find({Scope, nullptr});
316 if (I != TypeIndices.end())
317 return I->second;
318
319 // Build the fully qualified name of the scope.
David Majnemer6bdc24e2016-07-01 23:12:45 +0000320 std::string ScopeName = getFullyQualifiedName(Scope);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000321 StringIdRecord SID(TypeIndex(), ScopeName);
Zachary Turner6900de12017-11-28 18:33:17 +0000322 auto TI = TypeTable.writeLeafType(SID);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000323 return recordTypeIndexForDINode(Scope, TI);
324}
325
David Majnemer75c3ebf2016-06-02 17:13:53 +0000326TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
David Majnemer67f684e2016-07-28 05:03:22 +0000327 assert(SP);
Reid Kleckner2280f932016-05-23 20:23:46 +0000328
David Majnemer75c3ebf2016-06-02 17:13:53 +0000329 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000330 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000331 if (I != TypeIndices.end())
332 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000333
Reid Klecknerac945e22016-06-17 16:11:20 +0000334 // The display name includes function template arguments. Drop them to match
335 // MSVC.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000336 StringRef DisplayName = SP->getName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000337
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000338 const DIScope *Scope = SP->getScope().resolve();
339 TypeIndex TI;
340 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
341 // If the scope is a DICompositeType, then this must be a method. Member
342 // function types take some special handling, and require access to the
343 // subprogram.
344 TypeIndex ClassType = getTypeIndex(Class);
345 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
346 DisplayName);
Zachary Turner6900de12017-11-28 18:33:17 +0000347 TI = TypeTable.writeLeafType(MFuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000348 } else {
349 // Otherwise, this must be a free function.
350 TypeIndex ParentScope = getScopeIndex(Scope);
351 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Zachary Turner6900de12017-11-28 18:33:17 +0000352 TI = TypeTable.writeLeafType(FuncId);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000353 }
354
355 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000356}
357
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000358TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
359 const DICompositeType *Class) {
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000360 // Always use the method declaration as the key for the function type. The
361 // method declaration contains the this adjustment.
362 if (SP->getDeclaration())
363 SP = SP->getDeclaration();
364 assert(!SP->getDeclaration() && "should use declaration as key");
365
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000366 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
367 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000368 auto I = TypeIndices.find({SP, Class});
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000369 if (I != TypeIndices.end())
370 return I->second;
371
Reid Klecknerb5af11d2016-07-01 02:41:21 +0000372 // Make sure complete type info for the class is emitted *after* the member
373 // function type, as the complete class type is likely to reference this
374 // member function type.
375 TypeLoweringScope S(*this);
Adrian McCarthyd91bf392017-09-13 20:53:55 +0000376 const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
377 TypeIndex TI = lowerTypeMemberFunction(
378 SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod);
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000379 return recordTypeIndexForDINode(SP, TI, Class);
380}
381
Amjad Aboudacee5682016-07-12 12:06:34 +0000382TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
383 TypeIndex TI,
384 const DIType *ClassTy) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000385 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000386 (void)InsertResult;
387 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000388 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000389}
390
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000391unsigned CodeViewDebug::getPointerSizeInBytes() {
392 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
393}
394
Reid Kleckner876330d2016-02-12 21:48:30 +0000395void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
Reid Kleckner5a791ee2018-03-15 21:24:04 +0000396 const LexicalScope *LS) {
397 if (const DILocation *InlinedAt = LS->getInlinedAt()) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000398 // This variable was inlined. Associate it with the InlineSite.
399 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
400 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
401 Site.InlinedLocals.emplace_back(Var);
402 } else {
Reid Kleckner5a791ee2018-03-15 21:24:04 +0000403 // This variable goes into the corresponding lexical scope.
404 ScopeVariables[LS].emplace_back(Var);
Reid Kleckner876330d2016-02-12 21:48:30 +0000405 }
406}
407
Reid Kleckner829365a2016-02-11 19:41:47 +0000408static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
409 const DILocation *Loc) {
410 auto B = Locs.begin(), E = Locs.end();
411 if (std::find(B, E, Loc) == E)
412 Locs.push_back(Loc);
413}
414
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000415void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000416 const MachineFunction *MF) {
417 // Skip this instruction if it has the same location as the previous one.
Reid Kleckner45a74622017-06-30 21:33:44 +0000418 if (!DL || DL == PrevInstLoc)
Reid Kleckner9533af42016-01-16 00:09:09 +0000419 return;
420
421 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000422 if (!Scope)
423 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000424
David Majnemerc3340db2016-01-13 01:05:23 +0000425 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000426 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
427 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
428 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000429 return;
430
Reid Kleckner2214ed82016-01-29 00:49:42 +0000431 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
432 if (CI.getStartColumn() != DL.getCol())
433 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000434
Reid Kleckner2214ed82016-01-29 00:49:42 +0000435 if (!CurFn->HaveLineInfo)
436 CurFn->HaveLineInfo = true;
437 unsigned FileId = 0;
Reid Kleckner45a74622017-06-30 21:33:44 +0000438 if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
Reid Kleckner2214ed82016-01-29 00:49:42 +0000439 FileId = CurFn->LastFileId;
440 else
441 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
Reid Kleckner45a74622017-06-30 21:33:44 +0000442 PrevInstLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000443
444 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000445 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000446 const DILocation *Loc = DL.get();
447
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000448 // If this location was actually inlined from somewhere else, give it the ID
449 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000450 FuncId =
451 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000452
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000453 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000454 bool FirstLoc = true;
455 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000456 InlineSite &Site =
457 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000458 if (!FirstLoc)
459 addLocIfNotPresent(Site.ChildSites, Loc);
460 FirstLoc = false;
461 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000462 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000463 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000464 }
465
Reid Klecknerdac21b42016-02-03 21:15:48 +0000466 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000467 /*PrologueEnd=*/false, /*IsStmt=*/false,
468 DL->getFilename(), SMLoc());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000469}
470
Reid Kleckner5d122f82016-05-25 23:16:12 +0000471void CodeViewDebug::emitCodeViewMagicVersion() {
472 OS.EmitValueToAlignment(4);
473 OS.AddComment("Debug section magic");
474 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
475}
476
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000477void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000478 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000479 return;
480
481 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000482
483 // The COFF .debug$S section consists of several subsections, each starting
484 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
485 // of the payload followed by the payload itself. The subsections are 4-byte
486 // aligned.
487
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000488 // Use the generic .debug$S section, and make a subsection for all the inlined
489 // subprograms.
490 switchToDebugSectionForSymbol(nullptr);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000491
Zachary Turner8c099fe2017-05-30 16:36:15 +0000492 MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian McCarthy4333daa2016-11-02 21:30:35 +0000493 emitCompilerInformation();
494 endCVSubsection(CompilerInfo);
495
Reid Kleckner5d122f82016-05-25 23:16:12 +0000496 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000497
Reid Kleckner2214ed82016-01-29 00:49:42 +0000498 // Emit per-function debug information.
499 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000500 if (!P.first->isDeclarationForLinker())
Reid Kleckner55baeef2018-03-15 21:12:21 +0000501 emitDebugInfoForFunction(P.first, *P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000502
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000503 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000504 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000505 emitDebugInfoForGlobals();
506
Hans Wennborgb510b452016-06-23 16:33:53 +0000507 // Emit retained types.
508 emitDebugInfoForRetainedTypes();
509
Reid Kleckner5d122f82016-05-25 23:16:12 +0000510 // Switch back to the generic .debug$S section after potentially processing
511 // comdat symbol sections.
512 switchToDebugSectionForSymbol(nullptr);
513
David Majnemer3128b102016-06-15 18:00:01 +0000514 // Emit UDT records for any types used by global variables.
515 if (!GlobalUDTs.empty()) {
Zachary Turner8c099fe2017-05-30 16:36:15 +0000516 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
David Majnemer3128b102016-06-15 18:00:01 +0000517 emitDebugInfoForUDTs(GlobalUDTs);
518 endCVSubsection(SymbolsEnd);
519 }
520
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000521 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000522 OS.AddComment("File index to string table offset subsection");
523 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000524
525 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000526 OS.AddComment("String table");
527 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000528
Zachary Turner048f8f92017-12-13 22:33:58 +0000529 // Emit type information and hashes last, so that any types we translate while
530 // emitting function info are included.
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000531 emitTypeInformation();
532
Zachary Turner048f8f92017-12-13 22:33:58 +0000533 if (EmitDebugGlobalHashes)
534 emitTypeGlobalHashes();
535
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000536 clear();
537}
538
Brock Wyma19e17b32018-02-11 21:26:46 +0000539static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S,
540 unsigned MaxFixedRecordLength = 0xF00) {
Reid Klecknerbb96df62016-10-05 22:36:07 +0000541 // The maximum CV record length is 0xFF00. Most of the strings we emit appear
542 // after a fixed length portion of the record. The fixed length portion should
543 // always be less than 0xF00 (3840) bytes, so truncate the string so that the
544 // overall record size is less than the maximum allowed.
Reid Klecknerbb96df62016-10-05 22:36:07 +0000545 SmallString<32> NullTerminatedString(
546 S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
David Majnemerb9456a52016-03-14 05:15:09 +0000547 NullTerminatedString.push_back('\0');
548 OS.EmitBytes(NullTerminatedString);
549}
550
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000551void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000552 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000553 return;
554
Alexandre Ganead9e96742018-04-09 20:17:56 +0000555 // Start the .debug$T or .debug$P section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000556 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000557 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000558
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000559 SmallString<8> CommentPrefix;
560 if (OS.isVerboseAsm()) {
561 CommentPrefix += '\t';
562 CommentPrefix += Asm->MAI->getCommentString();
563 CommentPrefix += ' ';
564 }
565
Zachary Turner526f4f22017-05-19 19:26:58 +0000566 TypeTableCollection Table(TypeTable.records());
567 Optional<TypeIndex> B = Table.getFirst();
568 while (B) {
569 // This will fail if the record data is invalid.
570 CVType Record = Table.getType(*B);
571
Zachary Turner4efa0a42016-11-08 22:24:53 +0000572 if (OS.isVerboseAsm()) {
573 // Emit a block comment describing the type record for readability.
574 SmallString<512> CommentBlock;
575 raw_svector_ostream CommentOS(CommentBlock);
576 ScopedPrinter SP(CommentOS);
577 SP.setPrefix(CommentPrefix);
Zachary Turner526f4f22017-05-19 19:26:58 +0000578 TypeDumpVisitor TDV(Table, &SP, false);
579
580 Error E = codeview::visitTypeRecord(Record, *B, TDV);
Zachary Turner4efa0a42016-11-08 22:24:53 +0000581 if (E) {
582 logAllUnhandledErrors(std::move(E), errs(), "error: ");
583 llvm_unreachable("produced malformed type record");
584 }
585 // emitRawComment will insert its own tab and comment string before
586 // the first line, so strip off our first one. It also prints its own
587 // newline.
588 OS.emitRawComment(
589 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
Zachary Turner4efa0a42016-11-08 22:24:53 +0000590 }
Zachary Turner526f4f22017-05-19 19:26:58 +0000591 OS.EmitBinaryData(Record.str_data());
592 B = Table.getNext(*B);
593 }
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000594}
595
Zachary Turner048f8f92017-12-13 22:33:58 +0000596void CodeViewDebug::emitTypeGlobalHashes() {
597 if (TypeTable.empty())
598 return;
599
600 // Start the .debug$H section with the version and hash algorithm, currently
601 // hardcoded to version 0, SHA1.
602 OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
603
604 OS.EmitValueToAlignment(4);
605 OS.AddComment("Magic");
606 OS.EmitIntValue(COFF::DEBUG_HASHES_SECTION_MAGIC, 4);
607 OS.AddComment("Section Version");
608 OS.EmitIntValue(0, 2);
609 OS.AddComment("Hash Algorithm");
Zachary Turnerc7626662018-05-17 22:55:15 +0000610 OS.EmitIntValue(uint16_t(GlobalTypeHashAlg::SHA1_8), 2);
Zachary Turner048f8f92017-12-13 22:33:58 +0000611
612 TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
613 for (const auto &GHR : TypeTable.hashes()) {
614 if (OS.isVerboseAsm()) {
615 // Emit an EOL-comment describing which TypeIndex this hash corresponds
616 // to, as well as the stringified SHA1 hash.
617 SmallString<32> Comment;
618 raw_svector_ostream CommentOS(Comment);
619 CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
620 OS.AddComment(Comment);
621 ++TI;
622 }
Zachary Turnerc7626662018-05-17 22:55:15 +0000623 assert(GHR.Hash.size() == 8);
Zachary Turner048f8f92017-12-13 22:33:58 +0000624 StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
625 GHR.Hash.size());
626 OS.EmitBinaryData(S);
627 }
628}
629
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000630static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
631 switch (DWLang) {
632 case dwarf::DW_LANG_C:
633 case dwarf::DW_LANG_C89:
634 case dwarf::DW_LANG_C99:
635 case dwarf::DW_LANG_C11:
636 case dwarf::DW_LANG_ObjC:
637 return SourceLanguage::C;
638 case dwarf::DW_LANG_C_plus_plus:
639 case dwarf::DW_LANG_C_plus_plus_03:
640 case dwarf::DW_LANG_C_plus_plus_11:
641 case dwarf::DW_LANG_C_plus_plus_14:
642 return SourceLanguage::Cpp;
643 case dwarf::DW_LANG_Fortran77:
644 case dwarf::DW_LANG_Fortran90:
645 case dwarf::DW_LANG_Fortran03:
646 case dwarf::DW_LANG_Fortran08:
647 return SourceLanguage::Fortran;
648 case dwarf::DW_LANG_Pascal83:
649 return SourceLanguage::Pascal;
650 case dwarf::DW_LANG_Cobol74:
651 case dwarf::DW_LANG_Cobol85:
652 return SourceLanguage::Cobol;
653 case dwarf::DW_LANG_Java:
654 return SourceLanguage::Java;
Reid Kleckner898ddf62017-07-24 16:16:42 +0000655 case dwarf::DW_LANG_D:
656 return SourceLanguage::D;
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000657 default:
658 // There's no CodeView representation for this language, and CV doesn't
659 // have an "unknown" option for the language field, so we'll use MASM,
660 // as it's very low level.
661 return SourceLanguage::Masm;
662 }
663}
664
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000665namespace {
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000666struct Version {
667 int Part[4];
668};
Reid Kleckner7f6b2532017-07-24 16:16:17 +0000669} // end anonymous namespace
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000670
671// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
672// the version number.
673static Version parseVersion(StringRef Name) {
Adrian McCarthyad8ac542016-09-20 17:42:13 +0000674 Version V = {{0}};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000675 int N = 0;
676 for (const char C : Name) {
677 if (isdigit(C)) {
678 V.Part[N] *= 10;
679 V.Part[N] += C - '0';
680 } else if (C == '.') {
681 ++N;
682 if (N >= 4)
683 return V;
684 } else if (N > 0)
685 return V;
686 }
687 return V;
688}
689
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000690void CodeViewDebug::emitCompilerInformation() {
691 MCContext &Context = MMI->getContext();
692 MCSymbol *CompilerBegin = Context.createTempSymbol(),
693 *CompilerEnd = Context.createTempSymbol();
694 OS.AddComment("Record length");
695 OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
696 OS.EmitLabel(CompilerBegin);
697 OS.AddComment("Record kind: S_COMPILE3");
698 OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
699 uint32_t Flags = 0;
700
701 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
702 const MDNode *Node = *CUs->operands().begin();
703 const auto *CU = cast<DICompileUnit>(Node);
704
705 // The low byte of the flags indicates the source language.
706 Flags = MapDWLangToCVLang(CU->getSourceLanguage());
707 // TODO: Figure out which other flags need to be set.
708
709 OS.AddComment("Flags and language");
710 OS.EmitIntValue(Flags, 4);
711
712 OS.AddComment("CPUType");
Reid Kleckner9ea2c012018-10-01 21:59:45 +0000713 OS.EmitIntValue(static_cast<uint64_t>(TheCPU), 2);
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000714
715 StringRef CompilerVersion = CU->getProducer();
716 Version FrontVer = parseVersion(CompilerVersion);
717 OS.AddComment("Frontend version");
718 for (int N = 0; N < 4; ++N)
719 OS.EmitIntValue(FrontVer.Part[N], 2);
720
721 // Some Microsoft tools, like Binscope, expect a backend version number of at
722 // least 8.something, so we'll coerce the LLVM version into a form that
723 // guarantees it'll be big enough without really lying about the version.
Adrian McCarthyd1185fc2016-09-29 20:28:25 +0000724 int Major = 1000 * LLVM_VERSION_MAJOR +
725 10 * LLVM_VERSION_MINOR +
726 LLVM_VERSION_PATCH;
727 // Clamp it for builds that use unusually large version numbers.
728 Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
729 Version BackVer = {{ Major, 0, 0, 0 }};
Adrian McCarthyc64acfd2016-09-20 17:20:51 +0000730 OS.AddComment("Backend version");
731 for (int N = 0; N < 4; ++N)
732 OS.EmitIntValue(BackVer.Part[N], 2);
733
734 OS.AddComment("Null-terminated compiler version string");
735 emitNullTerminatedSymbolName(OS, CompilerVersion);
736
737 OS.EmitLabel(CompilerEnd);
738}
739
Reid Kleckner5d122f82016-05-25 23:16:12 +0000740void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000741 if (InlinedSubprograms.empty())
742 return;
743
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000744 OS.AddComment("Inlinee lines subsection");
Zachary Turner8c099fe2017-05-30 16:36:15 +0000745 MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000746
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000747 // We emit the checksum info for files. This is used by debuggers to
748 // determine if a pdb matches the source before loading it. Visual Studio,
749 // for instance, will display a warning that the breakpoints are not valid if
750 // the pdb does not match the source.
David Majnemer30579ec2016-02-02 23:18:23 +0000751 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000752 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
753
754 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000755 assert(TypeIndices.count({SP, nullptr}));
756 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000757
David Majnemer30579ec2016-02-02 23:18:23 +0000758 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000759 unsigned FileId = maybeRecordFile(SP->getFile());
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000760 OS.AddComment("Inlined function " + SP->getName() + " starts at " +
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000761 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000762 OS.AddBlankLine();
David Majnemer30579ec2016-02-02 23:18:23 +0000763 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000764 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000765 OS.AddComment("Offset into filechecksum table");
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000766 OS.EmitCVFileChecksumOffsetDirective(FileId);
David Majnemer30579ec2016-02-02 23:18:23 +0000767 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000768 OS.EmitIntValue(SP->getLine(), 4);
769 }
770
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000771 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000772}
773
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000774void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
775 const DILocation *InlinedAt,
776 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000777 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
778 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000779
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000780 assert(TypeIndices.count({Site.Inlinee, nullptr}));
781 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000782
783 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000784 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000785 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000786 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000787 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000788 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000789
Reid Klecknerdac21b42016-02-03 21:15:48 +0000790 OS.AddComment("PtrParent");
791 OS.EmitIntValue(0, 4);
792 OS.AddComment("PtrEnd");
793 OS.EmitIntValue(0, 4);
794 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000795 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000796
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000797 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
798 unsigned StartLineNum = Site.Inlinee->getLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000799
800 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000801 FI.Begin, FI.End);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000802
803 OS.EmitLabel(InlineEnd);
804
Reid Kleckner9ea2c012018-10-01 21:59:45 +0000805 emitLocalVariableList(FI, Site.InlinedLocals);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000806
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000807 // Recurse on child inlined call sites before closing the scope.
808 for (const DILocation *ChildSite : Site.ChildSites) {
809 auto I = FI.InlineSites.find(ChildSite);
810 assert(I != FI.InlineSites.end() &&
811 "child site not in function inline site map");
812 emitInlinedCallSite(FI, ChildSite, I->second);
813 }
814
815 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000816 OS.AddComment("Record length");
817 OS.EmitIntValue(2, 2); // RecordLength
818 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000819 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000820}
821
Reid Kleckner5d122f82016-05-25 23:16:12 +0000822void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
823 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
824 // comdat key. A section may be comdat because of -ffunction-sections or
825 // because it is comdat in the IR.
826 MCSectionCOFF *GVSec =
827 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
828 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
829
830 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
831 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
832 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
833
834 OS.SwitchSection(DebugSec);
835
836 // Emit the magic version number if this is the first time we've switched to
837 // this section.
838 if (ComdatDebugSections.insert(DebugSec).second)
839 emitCodeViewMagicVersion();
840}
841
Brock Wyma94ece8f2018-04-16 16:53:57 +0000842// Emit an S_THUNK32/S_END symbol pair for a thunk routine.
843// The only supported thunk ordinal is currently the standard type.
844void CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
845 FunctionInfo &FI,
846 const MCSymbol *Fn) {
847 std::string FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
848 const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
849
850 OS.AddComment("Symbol subsection for " + Twine(FuncName));
851 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
852
853 // Emit S_THUNK32
854 MCSymbol *ThunkRecordBegin = MMI->getContext().createTempSymbol(),
855 *ThunkRecordEnd = MMI->getContext().createTempSymbol();
856 OS.AddComment("Record length");
857 OS.emitAbsoluteSymbolDiff(ThunkRecordEnd, ThunkRecordBegin, 2);
858 OS.EmitLabel(ThunkRecordBegin);
859 OS.AddComment("Record kind: S_THUNK32");
860 OS.EmitIntValue(unsigned(SymbolKind::S_THUNK32), 2);
861 OS.AddComment("PtrParent");
862 OS.EmitIntValue(0, 4);
863 OS.AddComment("PtrEnd");
864 OS.EmitIntValue(0, 4);
865 OS.AddComment("PtrNext");
866 OS.EmitIntValue(0, 4);
867 OS.AddComment("Thunk section relative address");
868 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
869 OS.AddComment("Thunk section index");
870 OS.EmitCOFFSectionIndex(Fn);
871 OS.AddComment("Code size");
872 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
873 OS.AddComment("Ordinal");
874 OS.EmitIntValue(unsigned(ordinal), 1);
875 OS.AddComment("Function name");
876 emitNullTerminatedSymbolName(OS, FuncName);
877 // Additional fields specific to the thunk ordinal would go here.
878 OS.EmitLabel(ThunkRecordEnd);
879
880 // Local variables/inlined routines are purposely omitted here. The point of
881 // marking this as a thunk is so Visual Studio will NOT stop in this routine.
882
883 // Emit S_PROC_ID_END
884 const unsigned RecordLengthForSymbolEnd = 2;
885 OS.AddComment("Record length");
886 OS.EmitIntValue(RecordLengthForSymbolEnd, 2);
887 OS.AddComment("Record kind: S_PROC_ID_END");
888 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
889
890 endCVSubsection(SymbolsEnd);
891}
892
Reid Kleckner2214ed82016-01-29 00:49:42 +0000893void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
894 FunctionInfo &FI) {
Brock Wyma31cc1eb2018-01-30 13:16:50 +0000895 // For each function there is a separate subsection which holds the PC to
896 // file:line table.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000897 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000898 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000899
Reid Kleckner5d122f82016-05-25 23:16:12 +0000900 // Switch to the to a comdat section, if appropriate.
901 switchToDebugSectionForSymbol(Fn);
902
Reid Klecknerac945e22016-06-17 16:11:20 +0000903 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000904 auto *SP = GV->getSubprogram();
David Majnemer67f684e2016-07-28 05:03:22 +0000905 assert(SP);
David Majnemer3128b102016-06-15 18:00:01 +0000906 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000907
Brock Wyma94ece8f2018-04-16 16:53:57 +0000908 if (SP->isThunk()) {
909 emitDebugInfoForThunk(GV, FI, Fn);
910 return;
911 }
912
Reid Klecknerac945e22016-06-17 16:11:20 +0000913 // If we have a display name, build the fully qualified name by walking the
914 // chain of scopes.
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000915 if (!SP->getName().empty())
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000916 FuncName =
Adrian Prantl9d2f0192017-04-26 23:59:52 +0000917 getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000918
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000919 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000920 if (FuncName.empty())
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +0000921 FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000922
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000923 // Emit FPO data, but only on 32-bit x86. No other platforms use it.
924 if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
925 OS.EmitCVFPOData(Fn);
926
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000927 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000928 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Zachary Turner8c099fe2017-05-30 16:36:15 +0000929 MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000930 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000931 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
932 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000933 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000934 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000935 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000936
Reid Kleckner4ad127f2016-09-14 21:49:21 +0000937 if (GV->hasLocalLinkage()) {
938 OS.AddComment("Record kind: S_LPROC32_ID");
939 OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
940 } else {
941 OS.AddComment("Record kind: S_GPROC32_ID");
942 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
943 }
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000944
David Majnemer30579ec2016-02-02 23:18:23 +0000945 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000946 OS.AddComment("PtrParent");
947 OS.EmitIntValue(0, 4);
948 OS.AddComment("PtrEnd");
949 OS.EmitIntValue(0, 4);
950 OS.AddComment("PtrNext");
951 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000952 // This is the important bit that tells the debugger where the function
953 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000954 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000955 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000956 OS.AddComment("Offset after prologue");
957 OS.EmitIntValue(0, 4);
958 OS.AddComment("Offset before epilogue");
959 OS.EmitIntValue(0, 4);
960 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000961 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000962 OS.AddComment("Function section relative address");
Keno Fischerf7d84ee2017-01-02 03:00:19 +0000963 OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000964 OS.AddComment("Function section index");
965 OS.EmitCOFFSectionIndex(Fn);
966 OS.AddComment("Flags");
967 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000968 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000969 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000970 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000971 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000972 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000973
Reid Kleckner9ea2c012018-10-01 21:59:45 +0000974 MCSymbol *FrameProcBegin = MMI->getContext().createTempSymbol(),
975 *FrameProcEnd = MMI->getContext().createTempSymbol();
976 OS.AddComment("Record length");
977 OS.emitAbsoluteSymbolDiff(FrameProcEnd, FrameProcBegin, 2);
978 OS.EmitLabel(FrameProcBegin);
979 OS.AddComment("Record kind: S_FRAMEPROC");
980 OS.EmitIntValue(unsigned(SymbolKind::S_FRAMEPROC), 2);
981 // Subtract out the CSR size since MSVC excludes that and we include it.
982 OS.AddComment("FrameSize");
983 OS.EmitIntValue(FI.FrameSize - FI.CSRSize, 4);
984 OS.AddComment("Padding");
985 OS.EmitIntValue(0, 4);
986 OS.AddComment("Offset of padding");
987 OS.EmitIntValue(0, 4);
988 OS.AddComment("Bytes of callee saved registers");
989 OS.EmitIntValue(FI.CSRSize, 4);
990 OS.AddComment("Exception handler offset");
991 OS.EmitIntValue(0, 4);
992 OS.AddComment("Exception handler section");
993 OS.EmitIntValue(0, 2);
994 OS.AddComment("Flags (defines frame register)");
995 OS.EmitIntValue(uint32_t(FI.FrameProcOpts), 4);
996 OS.EmitLabel(FrameProcEnd);
997
998 emitLocalVariableList(FI, FI.Locals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +0000999 emitLexicalBlockList(FI.ChildBlocks, FI);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001000
Reid Klecknerf3b9ba42016-01-29 18:16:43 +00001001 // Emit inlined call site information. Only emit functions inlined directly
1002 // into the parent function. We'll emit the other sites recursively as part
1003 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001004 for (const DILocation *InlinedAt : FI.ChildSites) {
1005 auto I = FI.InlineSites.find(InlinedAt);
1006 assert(I != FI.InlineSites.end() &&
1007 "child site not in function inline site map");
1008 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +00001009 }
1010
Reid Klecknere33c94f2017-09-05 20:14:58 +00001011 for (auto Annot : FI.Annotations) {
1012 MCSymbol *Label = Annot.first;
1013 MDTuple *Strs = cast<MDTuple>(Annot.second);
1014 MCSymbol *AnnotBegin = MMI->getContext().createTempSymbol(),
1015 *AnnotEnd = MMI->getContext().createTempSymbol();
1016 OS.AddComment("Record length");
1017 OS.emitAbsoluteSymbolDiff(AnnotEnd, AnnotBegin, 2);
1018 OS.EmitLabel(AnnotBegin);
1019 OS.AddComment("Record kind: S_ANNOTATION");
1020 OS.EmitIntValue(SymbolKind::S_ANNOTATION, 2);
1021 OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
1022 // FIXME: Make sure we don't overflow the max record size.
1023 OS.EmitCOFFSectionIndex(Label);
1024 OS.EmitIntValue(Strs->getNumOperands(), 2);
1025 for (Metadata *MD : Strs->operands()) {
1026 // MDStrings are null terminated, so we can do EmitBytes and get the
1027 // nice .asciz directive.
1028 StringRef Str = cast<MDString>(MD)->getString();
1029 assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
1030 OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
1031 }
1032 OS.EmitLabel(AnnotEnd);
1033 }
1034
David Majnemer3128b102016-06-15 18:00:01 +00001035 if (SP != nullptr)
1036 emitDebugInfoForUDTs(LocalUDTs);
1037
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001038 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +00001039 OS.AddComment("Record length");
1040 OS.EmitIntValue(0x0002, 2);
1041 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +00001042 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001043 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001044 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +00001045
Reid Kleckner2214ed82016-01-29 00:49:42 +00001046 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +00001047 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001048}
1049
Reid Kleckner876330d2016-02-12 21:48:30 +00001050CodeViewDebug::LocalVarDefRange
1051CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
1052 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +00001053 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +00001054 DR.DataOffset = Offset;
1055 assert(DR.DataOffset == Offset && "truncation");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00001056 DR.IsSubfield = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +00001057 DR.StructOffset = 0;
1058 DR.CVRegister = CVRegister;
1059 return DR;
1060}
1061
Matthias Braunef331ef2016-11-30 23:48:50 +00001062void CodeViewDebug::collectVariableInfoFromMFTable(
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001063 DenseSet<InlinedEntity> &Processed) {
Matthias Braunef331ef2016-11-30 23:48:50 +00001064 const MachineFunction &MF = *Asm->MF;
1065 const TargetSubtargetInfo &TSI = MF.getSubtarget();
Reid Kleckner876330d2016-02-12 21:48:30 +00001066 const TargetFrameLowering *TFI = TSI.getFrameLowering();
1067 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1068
Matthias Braunef331ef2016-11-30 23:48:50 +00001069 for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001070 if (!VI.Var)
1071 continue;
1072 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1073 "Expected inlined-at fields to agree");
1074
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001075 Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001076 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1077
1078 // If variable scope is not found then skip this variable.
1079 if (!Scope)
1080 continue;
1081
Reid Klecknerb5fced72017-05-09 19:59:29 +00001082 // If the variable has an attached offset expression, extract it.
1083 // FIXME: Try to handle DW_OP_deref as well.
1084 int64_t ExprOffset = 0;
1085 if (VI.Expr)
1086 if (!VI.Expr->extractIfOffset(ExprOffset))
1087 continue;
1088
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001089 // Get the frame register used and the offset.
1090 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +00001091 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
1092 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001093
1094 // Calculate the label ranges.
Reid Klecknerb5fced72017-05-09 19:59:29 +00001095 LocalVarDefRange DefRange =
1096 createDefRangeMem(CVReg, FrameOffset + ExprOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001097 for (const InsnRange &Range : Scope->getRanges()) {
1098 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1099 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +00001100 End = End ? End : Asm->getFunctionEnd();
1101 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001102 }
1103
Reid Kleckner876330d2016-02-12 21:48:30 +00001104 LocalVariable Var;
1105 Var.DIVar = VI.Var;
1106 Var.DefRanges.emplace_back(std::move(DefRange));
Reid Kleckner5a791ee2018-03-15 21:24:04 +00001107 recordLocalVariable(std::move(Var), Scope);
Reid Kleckner876330d2016-02-12 21:48:30 +00001108 }
1109}
1110
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001111static bool canUseReferenceType(const DbgVariableLocation &Loc) {
1112 return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
1113}
1114
1115static bool needsReferenceType(const DbgVariableLocation &Loc) {
1116 return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
1117}
1118
Bob Haarman223303c2017-08-29 20:59:25 +00001119void CodeViewDebug::calculateRanges(
1120 LocalVariable &Var, const DbgValueHistoryMap::InstrRanges &Ranges) {
1121 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1122
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001123 // Calculate the definition ranges.
Bob Haarman223303c2017-08-29 20:59:25 +00001124 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1125 const InsnRange &Range = *I;
1126 const MachineInstr *DVInst = Range.first;
1127 assert(DVInst->isDebugValue() && "Invalid History entry");
1128 // FIXME: Find a way to represent constant variables, since they are
1129 // relatively common.
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001130 Optional<DbgVariableLocation> Location =
1131 DbgVariableLocation::extractFromMachineInstruction(*DVInst);
1132 if (!Location)
Bob Haarmana88bce12017-08-29 21:01:55 +00001133 continue;
Bob Haarman223303c2017-08-29 20:59:25 +00001134
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001135 // CodeView can only express variables in register and variables in memory
1136 // at a constant offset from a register. However, for variables passed
1137 // indirectly by pointer, it is common for that pointer to be spilled to a
1138 // stack location. For the special case of one offseted load followed by a
1139 // zero offset load (a pointer spilled to the stack), we change the type of
1140 // the local variable from a value type to a reference type. This tricks the
1141 // debugger into doing the load for us.
1142 if (Var.UseReferenceType) {
1143 // We're using a reference type. Drop the last zero offset load.
1144 if (canUseReferenceType(*Location))
1145 Location->LoadChain.pop_back();
1146 else
1147 continue;
1148 } else if (needsReferenceType(*Location)) {
1149 // This location can't be expressed without switching to a reference type.
1150 // Start over using that.
1151 Var.UseReferenceType = true;
Bob Haarman223303c2017-08-29 20:59:25 +00001152 Var.DefRanges.clear();
1153 calculateRanges(Var, Ranges);
1154 return;
1155 }
1156
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001157 // We can only handle a register or an offseted load of a register.
1158 if (Location->Register == 0 || Location->LoadChain.size() > 1)
Bob Haarman223303c2017-08-29 20:59:25 +00001159 continue;
Bob Haarman223303c2017-08-29 20:59:25 +00001160 {
1161 LocalVarDefRange DR;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001162 DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
Reid Kleckner08f5fd52017-08-31 15:56:49 +00001163 DR.InMemory = !Location->LoadChain.empty();
1164 DR.DataOffset =
1165 !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001166 if (Location->FragmentInfo) {
Bob Haarman223303c2017-08-29 20:59:25 +00001167 DR.IsSubfield = true;
Bob Haarman1a4cbbe2017-08-30 17:50:21 +00001168 DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
Bob Haarman223303c2017-08-29 20:59:25 +00001169 } else {
1170 DR.IsSubfield = false;
1171 DR.StructOffset = 0;
1172 }
1173
1174 if (Var.DefRanges.empty() ||
1175 Var.DefRanges.back().isDifferentLocation(DR)) {
1176 Var.DefRanges.emplace_back(std::move(DR));
1177 }
1178 }
1179
1180 // Compute the label range.
1181 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1182 const MCSymbol *End = getLabelAfterInsn(Range.second);
1183 if (!End) {
1184 // This range is valid until the next overlapping bitpiece. In the
1185 // common case, ranges will not be bitpieces, so they will overlap.
1186 auto J = std::next(I);
1187 const DIExpression *DIExpr = DVInst->getDebugExpression();
1188 while (J != E &&
Bjorn Petterssona223f8152018-03-12 18:02:39 +00001189 !DIExpr->fragmentsOverlap(J->first->getDebugExpression()))
Bob Haarman223303c2017-08-29 20:59:25 +00001190 ++J;
1191 if (J != E)
1192 End = getLabelBeforeInsn(J->first);
1193 else
1194 End = Asm->getFunctionEnd();
1195 }
1196
1197 // If the last range end is our begin, just extend the last range.
1198 // Otherwise make a new range.
1199 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1200 Var.DefRanges.back().Ranges;
1201 if (!R.empty() && R.back().second == Begin)
1202 R.back().second = End;
1203 else
1204 R.emplace_back(Begin, End);
1205
1206 // FIXME: Do more range combining.
1207 }
1208}
1209
Reid Kleckner876330d2016-02-12 21:48:30 +00001210void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001211 DenseSet<InlinedEntity> Processed;
Reid Kleckner876330d2016-02-12 21:48:30 +00001212 // Grab the variable info that was squirreled away in the MMI side-table.
Matthias Braunef331ef2016-11-30 23:48:50 +00001213 collectVariableInfoFromMFTable(Processed);
Reid Kleckner876330d2016-02-12 21:48:30 +00001214
Reid Kleckner876330d2016-02-12 21:48:30 +00001215 for (const auto &I : DbgValues) {
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001216 InlinedEntity IV = I.first;
Reid Kleckner876330d2016-02-12 21:48:30 +00001217 if (Processed.count(IV))
1218 continue;
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001219 const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
Reid Kleckner876330d2016-02-12 21:48:30 +00001220 const DILocation *InlinedAt = IV.second;
1221
1222 // Instruction ranges, specifying where IV is accessible.
1223 const auto &Ranges = I.second;
1224
1225 LexicalScope *Scope = nullptr;
1226 if (InlinedAt)
1227 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1228 else
1229 Scope = LScopes.findLexicalScope(DIVar->getScope());
1230 // If variable scope is not found then skip this variable.
1231 if (!Scope)
1232 continue;
1233
1234 LocalVariable Var;
1235 Var.DIVar = DIVar;
1236
Bob Haarman223303c2017-08-29 20:59:25 +00001237 calculateRanges(Var, Ranges);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00001238 recordLocalVariable(std::move(Var), Scope);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001239 }
1240}
1241
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001242void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001243 const TargetSubtargetInfo &TSI = MF->getSubtarget();
1244 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1245 const MachineFrameInfo &MFI = MF->getFrameInfo();
Matthias Braunf1caa282017-12-15 22:22:58 +00001246 const Function &GV = MF->getFunction();
Reid Kleckner55baeef2018-03-15 21:12:21 +00001247 auto Insertion = FnDebugInfo.insert({&GV, llvm::make_unique<FunctionInfo>()});
Reid Klecknere9dc30d2018-03-15 21:18:42 +00001248 assert(Insertion.second && "function already has info");
Reid Kleckner55baeef2018-03-15 21:12:21 +00001249 CurFn = Insertion.first->second.get();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001250 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +00001251 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001252
Reid Kleckner9ea2c012018-10-01 21:59:45 +00001253 // The S_FRAMEPROC record reports the stack size, and how many bytes of
1254 // callee-saved registers were used. For targets that don't use a PUSH
1255 // instruction (AArch64), this will be zero.
1256 CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
1257 CurFn->FrameSize = MFI.getStackSize();
1258
1259 // For this function S_FRAMEPROC record, figure out which codeview register
1260 // will be the frame pointer.
1261 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
1262 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
1263 if (CurFn->FrameSize > 0) {
1264 if (!TSI.getFrameLowering()->hasFP(*MF)) {
1265 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1266 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
1267 } else {
1268 // If there is an FP, parameters are always relative to it.
1269 CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
1270 if (TRI->needsStackRealignment(*MF)) {
1271 // If the stack needs realignment, locals are relative to SP or VFRAME.
1272 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1273 } else {
1274 // Otherwise, locals are relative to EBP, and we probably have VLAs or
1275 // other stack adjustments.
1276 CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
1277 }
1278 }
1279 }
1280
1281 // Compute other frame procedure options.
1282 FrameProcedureOptions FPO = FrameProcedureOptions::None;
1283 if (MFI.hasVarSizedObjects())
1284 FPO |= FrameProcedureOptions::HasAlloca;
1285 if (MF->exposesReturnsTwice())
1286 FPO |= FrameProcedureOptions::HasSetJmp;
1287 // FIXME: Set HasLongJmp if we ever track that info.
1288 if (MF->hasInlineAsm())
1289 FPO |= FrameProcedureOptions::HasInlineAssembly;
1290 if (GV.hasPersonalityFn()) {
1291 if (isAsynchronousEHPersonality(
1292 classifyEHPersonality(GV.getPersonalityFn())))
1293 FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
1294 else
1295 FPO |= FrameProcedureOptions::HasExceptionHandling;
1296 }
1297 if (GV.hasFnAttribute(Attribute::InlineHint))
1298 FPO |= FrameProcedureOptions::MarkedInline;
1299 if (GV.hasFnAttribute(Attribute::Naked))
1300 FPO |= FrameProcedureOptions::Naked;
1301 if (MFI.hasStackProtectorIndex())
1302 FPO |= FrameProcedureOptions::SecurityChecks;
1303 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
1304 FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
1305 if (Asm->TM.getOptLevel() != CodeGenOpt::None && !GV.optForSize() &&
1306 !GV.hasFnAttribute(Attribute::OptimizeNone))
1307 FPO |= FrameProcedureOptions::OptimizedForSpeed;
1308 // FIXME: Set GuardCfg when it is implemented.
1309 CurFn->FrameProcOpts = FPO;
1310
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001311 OS.EmitCVFuncIdDirective(CurFn->FuncId);
1312
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001313 // Find the end of the function prolog. First known non-DBG_VALUE and
1314 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001315 // FIXME: is there a simpler a way to do this? Can we just search
1316 // for the first instruction of the function, not the last of the prolog?
1317 DebugLoc PrologEndLoc;
1318 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001319 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001320 for (const auto &MI : MBB) {
Adrian Prantlfb31da12017-05-22 20:47:09 +00001321 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001322 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001323 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001324 break;
Adrian Prantlfb31da12017-05-22 20:47:09 +00001325 } else if (!MI.isMetaInstruction()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001326 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001327 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001328 }
1329 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001330
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001331 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001332 if (PrologEndLoc && !EmptyPrologue) {
1333 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001334 maybeRecordLocation(FnStartDL, MF);
1335 }
1336}
1337
Zachary Turnera7b04172017-08-28 18:49:04 +00001338static bool shouldEmitUdt(const DIType *T) {
Zachary Turner37c74742017-09-05 22:06:39 +00001339 if (!T)
1340 return false;
1341
1342 // MSVC does not emit UDTs for typedefs that are scoped to classes.
1343 if (T->getTag() == dwarf::DW_TAG_typedef) {
1344 if (DIScope *Scope = T->getScope().resolve()) {
1345 switch (Scope->getTag()) {
1346 case dwarf::DW_TAG_structure_type:
1347 case dwarf::DW_TAG_class_type:
1348 case dwarf::DW_TAG_union_type:
1349 return false;
1350 }
1351 }
1352 }
1353
Zachary Turnera7b04172017-08-28 18:49:04 +00001354 while (true) {
1355 if (!T || T->isForwardDecl())
1356 return false;
1357
1358 const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
1359 if (!DT)
1360 return true;
1361 T = DT->getBaseType().resolve();
1362 }
1363 return true;
1364}
1365
1366void CodeViewDebug::addToUDTs(const DIType *Ty) {
Reid Klecknerad56ea32016-07-01 22:24:51 +00001367 // Don't record empty UDTs.
1368 if (Ty->getName().empty())
1369 return;
Zachary Turnera7b04172017-08-28 18:49:04 +00001370 if (!shouldEmitUdt(Ty))
1371 return;
Reid Klecknerad56ea32016-07-01 22:24:51 +00001372
Hans Wennborg4b63a982016-06-23 22:57:25 +00001373 SmallVector<StringRef, 5> QualifiedNameComponents;
1374 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1375 Ty->getScope().resolve(), QualifiedNameComponents);
1376
1377 std::string FullyQualifiedName =
David Majnemer6bdc24e2016-07-01 23:12:45 +00001378 getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
Hans Wennborg4b63a982016-06-23 22:57:25 +00001379
Zachary Turnera7b04172017-08-28 18:49:04 +00001380 if (ClosestSubprogram == nullptr) {
1381 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1382 } else if (ClosestSubprogram == CurrentSubprogram) {
1383 LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1384 }
Hans Wennborg4b63a982016-06-23 22:57:25 +00001385
1386 // TODO: What if the ClosestSubprogram is neither null or the current
1387 // subprogram? Currently, the UDT just gets dropped on the floor.
1388 //
1389 // The current behavior is not desirable. To get maximal fidelity, we would
1390 // need to perform all type translation before beginning emission of .debug$S
1391 // and then make LocalUDTs a member of FunctionInfo
1392}
1393
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001394TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001395 // Generic dispatch for lowering an unknown type.
1396 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001397 case dwarf::DW_TAG_array_type:
1398 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +00001399 case dwarf::DW_TAG_typedef:
1400 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001401 case dwarf::DW_TAG_base_type:
1402 return lowerTypeBasic(cast<DIBasicType>(Ty));
1403 case dwarf::DW_TAG_pointer_type:
Reid Kleckner9dac4732016-08-31 15:59:30 +00001404 if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1405 return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1406 LLVM_FALLTHROUGH;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001407 case dwarf::DW_TAG_reference_type:
1408 case dwarf::DW_TAG_rvalue_reference_type:
1409 return lowerTypePointer(cast<DIDerivedType>(Ty));
1410 case dwarf::DW_TAG_ptr_to_member_type:
1411 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
Reid Kleckner3acdc672018-02-27 22:08:15 +00001412 case dwarf::DW_TAG_restrict_type:
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001413 case dwarf::DW_TAG_const_type:
1414 case dwarf::DW_TAG_volatile_type:
Victor Leschuke1156c22016-10-31 19:09:38 +00001415 // TODO: add support for DW_TAG_atomic_type here
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001416 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +00001417 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001418 if (ClassTy) {
1419 // The member function type of a member function pointer has no
1420 // ThisAdjustment.
1421 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001422 /*ThisAdjustment=*/0,
1423 /*IsStaticMethod=*/false);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001424 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001425 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +00001426 case dwarf::DW_TAG_enumeration_type:
1427 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +00001428 case dwarf::DW_TAG_class_type:
1429 case dwarf::DW_TAG_structure_type:
1430 return lowerTypeClass(cast<DICompositeType>(Ty));
1431 case dwarf::DW_TAG_union_type:
1432 return lowerTypeUnion(cast<DICompositeType>(Ty));
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001433 case dwarf::DW_TAG_unspecified_type:
1434 return TypeIndex::None();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001435 default:
1436 // Use the null type index.
1437 return TypeIndex();
1438 }
1439}
1440
David Majnemerd065e232016-06-02 06:21:37 +00001441TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +00001442 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1443 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +00001444 StringRef TypeName = Ty->getName();
1445
Zachary Turnera7b04172017-08-28 18:49:04 +00001446 addToUDTs(Ty);
David Majnemer3128b102016-06-15 18:00:01 +00001447
David Majnemerd065e232016-06-02 06:21:37 +00001448 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +00001449 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +00001450 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +00001451 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +00001452 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +00001453 return TypeIndex(SimpleTypeKind::WideCharacter);
Hans Wennborg4b63a982016-06-23 22:57:25 +00001454
David Majnemerd065e232016-06-02 06:21:37 +00001455 return UnderlyingTypeIndex;
1456}
1457
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001458TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1459 DITypeRef ElementTypeRef = Ty->getBaseType();
1460 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1461 // IndexType is size_t, which depends on the bitness of the target.
Matt Arsenault41e5ac42018-03-14 00:36:23 +00001462 TypeIndex IndexType = getPointerSizeInBytes() == 8
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001463 ? TypeIndex(SimpleTypeKind::UInt64Quad)
1464 : TypeIndex(SimpleTypeKind::UInt32Long);
Amjad Aboudacee5682016-07-12 12:06:34 +00001465
1466 uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1467
Amjad Aboudacee5682016-07-12 12:06:34 +00001468 // Add subranges to array type.
1469 DINodeArray Elements = Ty->getElements();
1470 for (int i = Elements.size() - 1; i >= 0; --i) {
1471 const DINode *Element = Elements[i];
1472 assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1473
1474 const DISubrange *Subrange = cast<DISubrange>(Element);
1475 assert(Subrange->getLowerBound() == 0 &&
1476 "codeview doesn't support subranges with lower bounds");
Sander de Smalenfdf40912018-01-24 09:56:07 +00001477 int64_t Count = -1;
1478 if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>())
1479 Count = CI->getSExtValue();
Amjad Aboudacee5682016-07-12 12:06:34 +00001480
Reid Klecknercd7bba02017-09-13 23:30:01 +00001481 // Forward declarations of arrays without a size and VLAs use a count of -1.
1482 // Emit a count of zero in these cases to match what MSVC does for arrays
1483 // without a size. MSVC doesn't support VLAs, so it's not clear what we
1484 // should do for them even if we could distinguish them.
Reid Kleckner6b78e162017-03-24 23:28:42 +00001485 if (Count == -1)
Reid Kleckner89af1122017-09-13 21:54:20 +00001486 Count = 0;
Amjad Aboudacee5682016-07-12 12:06:34 +00001487
Amjad Aboudacee5682016-07-12 12:06:34 +00001488 // Update the element size and element type index for subsequent subranges.
1489 ElementSize *= Count;
Reid Kleckner10762882016-09-09 17:29:36 +00001490
1491 // If this is the outermost array, use the size from the array. It will be
Reid Kleckner6b78e162017-03-24 23:28:42 +00001492 // more accurate if we had a VLA or an incomplete element type size.
Reid Kleckner10762882016-09-09 17:29:36 +00001493 uint64_t ArraySize =
1494 (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1495
1496 StringRef Name = (i == 0) ? Ty->getName() : "";
Zachary Turner4efa0a42016-11-08 22:24:53 +00001497 ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
Zachary Turner6900de12017-11-28 18:33:17 +00001498 ElementTypeIndex = TypeTable.writeLeafType(AR);
Amjad Aboudacee5682016-07-12 12:06:34 +00001499 }
1500
Amjad Aboudacee5682016-07-12 12:06:34 +00001501 return ElementTypeIndex;
Adrian McCarthyf3c3c132016-06-08 18:22:59 +00001502}
1503
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001504TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1505 TypeIndex Index;
1506 dwarf::TypeKind Kind;
1507 uint32_t ByteSize;
1508
1509 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +00001510 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001511
1512 SimpleTypeKind STK = SimpleTypeKind::None;
1513 switch (Kind) {
1514 case dwarf::DW_ATE_address:
1515 // FIXME: Translate
1516 break;
1517 case dwarf::DW_ATE_boolean:
1518 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001519 case 1: STK = SimpleTypeKind::Boolean8; break;
1520 case 2: STK = SimpleTypeKind::Boolean16; break;
1521 case 4: STK = SimpleTypeKind::Boolean32; break;
1522 case 8: STK = SimpleTypeKind::Boolean64; break;
1523 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001524 }
1525 break;
1526 case dwarf::DW_ATE_complex_float:
1527 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001528 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001529 case 4: STK = SimpleTypeKind::Complex32; break;
1530 case 8: STK = SimpleTypeKind::Complex64; break;
1531 case 10: STK = SimpleTypeKind::Complex80; break;
1532 case 16: STK = SimpleTypeKind::Complex128; break;
1533 }
1534 break;
1535 case dwarf::DW_ATE_float:
1536 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +00001537 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001538 case 4: STK = SimpleTypeKind::Float32; break;
1539 case 6: STK = SimpleTypeKind::Float48; break;
1540 case 8: STK = SimpleTypeKind::Float64; break;
1541 case 10: STK = SimpleTypeKind::Float80; break;
1542 case 16: STK = SimpleTypeKind::Float128; break;
1543 }
1544 break;
1545 case dwarf::DW_ATE_signed:
1546 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001547 case 1: STK = SimpleTypeKind::SignedCharacter; break;
1548 case 2: STK = SimpleTypeKind::Int16Short; break;
1549 case 4: STK = SimpleTypeKind::Int32; break;
1550 case 8: STK = SimpleTypeKind::Int64Quad; break;
1551 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001552 }
1553 break;
1554 case dwarf::DW_ATE_unsigned:
1555 switch (ByteSize) {
Reid Klecknere45b2c72016-09-29 17:55:01 +00001556 case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
1557 case 2: STK = SimpleTypeKind::UInt16Short; break;
1558 case 4: STK = SimpleTypeKind::UInt32; break;
1559 case 8: STK = SimpleTypeKind::UInt64Quad; break;
1560 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001561 }
1562 break;
1563 case dwarf::DW_ATE_UTF:
1564 switch (ByteSize) {
1565 case 2: STK = SimpleTypeKind::Character16; break;
1566 case 4: STK = SimpleTypeKind::Character32; break;
1567 }
1568 break;
1569 case dwarf::DW_ATE_signed_char:
1570 if (ByteSize == 1)
1571 STK = SimpleTypeKind::SignedCharacter;
1572 break;
1573 case dwarf::DW_ATE_unsigned_char:
1574 if (ByteSize == 1)
1575 STK = SimpleTypeKind::UnsignedCharacter;
1576 break;
1577 default:
1578 break;
1579 }
1580
1581 // Apply some fixups based on the source-level type name.
1582 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1583 STK = SimpleTypeKind::Int32Long;
1584 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1585 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +00001586 if (STK == SimpleTypeKind::UInt16Short &&
1587 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001588 STK = SimpleTypeKind::WideCharacter;
1589 if ((STK == SimpleTypeKind::SignedCharacter ||
1590 STK == SimpleTypeKind::UnsignedCharacter) &&
1591 Ty->getName() == "char")
1592 STK = SimpleTypeKind::NarrowCharacter;
1593
1594 return TypeIndex(STK);
1595}
1596
Reid Kleckner3acdc672018-02-27 22:08:15 +00001597TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
1598 PointerOptions PO) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001599 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1600
Reid Kleckner3acdc672018-02-27 22:08:15 +00001601 // Pointers to simple types without any options can use SimpleTypeMode, rather
1602 // than having a dedicated pointer type record.
1603 if (PointeeTI.isSimple() && PO == PointerOptions::None &&
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001604 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1605 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1606 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1607 ? SimpleTypeMode::NearPointer64
1608 : SimpleTypeMode::NearPointer32;
1609 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1610 }
1611
1612 PointerKind PK =
1613 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1614 PointerMode PM = PointerMode::Pointer;
1615 switch (Ty->getTag()) {
1616 default: llvm_unreachable("not a pointer tag type");
1617 case dwarf::DW_TAG_pointer_type:
1618 PM = PointerMode::Pointer;
1619 break;
1620 case dwarf::DW_TAG_reference_type:
1621 PM = PointerMode::LValueReference;
1622 break;
1623 case dwarf::DW_TAG_rvalue_reference_type:
1624 PM = PointerMode::RValueReference;
1625 break;
1626 }
Reid Kleckner3acdc672018-02-27 22:08:15 +00001627
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001628 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00001629 return TypeTable.writeLeafType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001630}
1631
Reid Kleckner6fa15462016-06-17 22:14:39 +00001632static PointerToMemberRepresentation
1633translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1634 // SizeInBytes being zero generally implies that the member pointer type was
1635 // incomplete, which can happen if it is part of a function prototype. In this
1636 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001637 if (IsPMF) {
1638 switch (Flags & DINode::FlagPtrToMemberRep) {
1639 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001640 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1641 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001642 case DINode::FlagSingleInheritance:
1643 return PointerToMemberRepresentation::SingleInheritanceFunction;
1644 case DINode::FlagMultipleInheritance:
1645 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1646 case DINode::FlagVirtualInheritance:
1647 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1648 }
1649 } else {
1650 switch (Flags & DINode::FlagPtrToMemberRep) {
1651 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001652 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1653 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001654 case DINode::FlagSingleInheritance:
1655 return PointerToMemberRepresentation::SingleInheritanceData;
1656 case DINode::FlagMultipleInheritance:
1657 return PointerToMemberRepresentation::MultipleInheritanceData;
1658 case DINode::FlagVirtualInheritance:
1659 return PointerToMemberRepresentation::VirtualInheritanceData;
1660 }
1661 }
1662 llvm_unreachable("invalid ptr to member representation");
1663}
1664
Reid Kleckner3acdc672018-02-27 22:08:15 +00001665TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
1666 PointerOptions PO) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001667 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1668 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001669 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Matt Arsenault41e5ac42018-03-14 00:36:23 +00001670 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1671 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001672 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1673 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1674 : PointerMode::PointerToDataMember;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001675
Reid Kleckner6fa15462016-06-17 22:14:39 +00001676 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1677 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1678 MemberPointerInfo MPI(
1679 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001680 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Zachary Turner6900de12017-11-28 18:33:17 +00001681 return TypeTable.writeLeafType(PR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001682}
1683
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001684/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1685/// have a translation, use the NearC convention.
1686static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1687 switch (DwarfCC) {
1688 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1689 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1690 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1691 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1692 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1693 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1694 }
1695 return CallingConvention::NearC;
1696}
1697
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001698TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1699 ModifierOptions Mods = ModifierOptions::None;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001700 PointerOptions PO = PointerOptions::None;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001701 bool IsModifier = true;
1702 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001703 while (IsModifier && BaseTy) {
Victor Leschuke1156c22016-10-31 19:09:38 +00001704 // FIXME: Need to add DWARF tags for __unaligned and _Atomic
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001705 switch (BaseTy->getTag()) {
1706 case dwarf::DW_TAG_const_type:
1707 Mods |= ModifierOptions::Const;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001708 PO |= PointerOptions::Const;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001709 break;
1710 case dwarf::DW_TAG_volatile_type:
1711 Mods |= ModifierOptions::Volatile;
Reid Kleckner3acdc672018-02-27 22:08:15 +00001712 PO |= PointerOptions::Volatile;
1713 break;
1714 case dwarf::DW_TAG_restrict_type:
1715 // Only pointer types be marked with __restrict. There is no known flag
1716 // for __restrict in LF_MODIFIER records.
1717 PO |= PointerOptions::Restrict;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001718 break;
1719 default:
1720 IsModifier = false;
1721 break;
1722 }
1723 if (IsModifier)
1724 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1725 }
Reid Kleckner3acdc672018-02-27 22:08:15 +00001726
1727 // Check if the inner type will use an LF_POINTER record. If so, the
1728 // qualifiers will go in the LF_POINTER record. This comes up for types like
1729 // 'int *const' and 'int *__restrict', not the more common cases like 'const
1730 // char *'.
1731 if (BaseTy) {
1732 switch (BaseTy->getTag()) {
1733 case dwarf::DW_TAG_pointer_type:
1734 case dwarf::DW_TAG_reference_type:
1735 case dwarf::DW_TAG_rvalue_reference_type:
1736 return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
1737 case dwarf::DW_TAG_ptr_to_member_type:
1738 return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
1739 default:
1740 break;
1741 }
1742 }
1743
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001744 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Reid Kleckner3acdc672018-02-27 22:08:15 +00001745
1746 // Return the base type index if there aren't any modifiers. For example, the
1747 // metadata could contain restrict wrappers around non-pointer types.
1748 if (Mods == ModifierOptions::None)
1749 return ModifiedTI;
1750
Zachary Turner4efa0a42016-11-08 22:24:53 +00001751 ModifierRecord MR(ModifiedTI, Mods);
Zachary Turner6900de12017-11-28 18:33:17 +00001752 return TypeTable.writeLeafType(MR);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001753}
1754
David Majnemer75c3ebf2016-06-02 17:13:53 +00001755TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1756 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1757 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1758 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1759
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001760 // MSVC uses type none for variadic argument.
1761 if (ReturnAndArgTypeIndices.size() > 1 &&
1762 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1763 ReturnAndArgTypeIndices.back() = TypeIndex::None();
1764 }
David Majnemer75c3ebf2016-06-02 17:13:53 +00001765 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1766 ArrayRef<TypeIndex> ArgTypeIndices = None;
1767 if (!ReturnAndArgTypeIndices.empty()) {
1768 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1769 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1770 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1771 }
1772
1773 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner6900de12017-11-28 18:33:17 +00001774 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001775
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001776 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1777
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001778 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1779 ArgTypeIndices.size(), ArgListIndex);
Zachary Turner6900de12017-11-28 18:33:17 +00001780 return TypeTable.writeLeafType(Procedure);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001781}
1782
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001783TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001784 const DIType *ClassTy,
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001785 int ThisAdjustment,
1786 bool IsStaticMethod) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001787 // Lower the containing class type.
1788 TypeIndex ClassType = getTypeIndex(ClassTy);
1789
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001790 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1791 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1792 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1793
Aaron Smitha73fa2a2018-01-11 06:42:11 +00001794 // MSVC uses type none for variadic argument.
1795 if (ReturnAndArgTypeIndices.size() > 1 &&
1796 ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1797 ReturnAndArgTypeIndices.back() = TypeIndex::None();
1798 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001799 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1800 ArrayRef<TypeIndex> ArgTypeIndices = None;
1801 if (!ReturnAndArgTypeIndices.empty()) {
1802 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1803 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1804 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1805 }
Reid Kleckner87288b92017-09-15 00:59:07 +00001806 TypeIndex ThisTypeIndex;
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001807 if (!IsStaticMethod && !ArgTypeIndices.empty()) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001808 ThisTypeIndex = ArgTypeIndices.front();
1809 ArgTypeIndices = ArgTypeIndices.drop_front();
1810 }
1811
1812 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
Zachary Turner6900de12017-11-28 18:33:17 +00001813 TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001814
1815 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1816
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001817 // TODO: Need to use the correct values for FunctionOptions.
Zachary Turner4efa0a42016-11-08 22:24:53 +00001818 MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC,
1819 FunctionOptions::None, ArgTypeIndices.size(),
1820 ArgListIndex, ThisAdjustment);
Zachary Turner6900de12017-11-28 18:33:17 +00001821 return TypeTable.writeLeafType(MFR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001822}
1823
Reid Kleckner9dac4732016-08-31 15:59:30 +00001824TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001825 unsigned VSlotCount =
1826 Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
Reid Kleckner9dac4732016-08-31 15:59:30 +00001827 SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
Zachary Turner4efa0a42016-11-08 22:24:53 +00001828
1829 VFTableShapeRecord VFTSR(Slots);
Zachary Turner6900de12017-11-28 18:33:17 +00001830 return TypeTable.writeLeafType(VFTSR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00001831}
1832
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001833static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1834 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001835 case DINode::FlagPrivate: return MemberAccess::Private;
1836 case DINode::FlagPublic: return MemberAccess::Public;
1837 case DINode::FlagProtected: return MemberAccess::Protected;
1838 case 0:
1839 // If there was no explicit access control, provide the default for the tag.
1840 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1841 : MemberAccess::Public;
1842 }
1843 llvm_unreachable("access flags are exclusive");
1844}
1845
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001846static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1847 if (SP->isArtificial())
1848 return MethodOptions::CompilerGenerated;
1849
1850 // FIXME: Handle other MethodOptions.
1851
1852 return MethodOptions::None;
1853}
1854
1855static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1856 bool Introduced) {
Adrian McCarthyd91bf392017-09-13 20:53:55 +00001857 if (SP->getFlags() & DINode::FlagStaticMember)
1858 return MethodKind::Static;
1859
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001860 switch (SP->getVirtuality()) {
1861 case dwarf::DW_VIRTUALITY_none:
1862 break;
1863 case dwarf::DW_VIRTUALITY_virtual:
1864 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1865 case dwarf::DW_VIRTUALITY_pure_virtual:
1866 return Introduced ? MethodKind::PureIntroducingVirtual
1867 : MethodKind::PureVirtual;
1868 default:
1869 llvm_unreachable("unhandled virtuality case");
1870 }
1871
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001872 return MethodKind::Vanilla;
1873}
1874
Reid Klecknera8d57402016-06-03 15:58:20 +00001875static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1876 switch (Ty->getTag()) {
1877 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1878 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1879 }
1880 llvm_unreachable("unexpected tag");
1881}
1882
Reid Klecknere092dad2016-07-02 00:11:07 +00001883/// Return ClassOptions that should be present on both the forward declaration
1884/// and the defintion of a tag type.
1885static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1886 ClassOptions CO = ClassOptions::None;
1887
1888 // MSVC always sets this flag, even for local types. Clang doesn't always
Reid Klecknera8d57402016-06-03 15:58:20 +00001889 // appear to give every type a linkage name, which may be problematic for us.
1890 // FIXME: Investigate the consequences of not following them here.
Reid Klecknere092dad2016-07-02 00:11:07 +00001891 if (!Ty->getIdentifier().empty())
1892 CO |= ClassOptions::HasUniqueName;
1893
1894 // Put the Nested flag on a type if it appears immediately inside a tag type.
1895 // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1896 // here. That flag is only set on definitions, and not forward declarations.
1897 const DIScope *ImmediateScope = Ty->getScope().resolve();
1898 if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1899 CO |= ClassOptions::Nested;
1900
1901 // Put the Scoped flag on function-local types.
1902 for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1903 Scope = Scope->getScope().resolve()) {
1904 if (isa<DISubprogram>(Scope)) {
1905 CO |= ClassOptions::Scoped;
1906 break;
1907 }
1908 }
1909
1910 return CO;
Reid Klecknera8d57402016-06-03 15:58:20 +00001911}
1912
Aaron Smith122d9e72018-03-06 18:20:22 +00001913void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
1914 switch (Ty->getTag()) {
1915 case dwarf::DW_TAG_class_type:
1916 case dwarf::DW_TAG_structure_type:
1917 case dwarf::DW_TAG_union_type:
1918 case dwarf::DW_TAG_enumeration_type:
1919 break;
1920 default:
1921 return;
1922 }
1923
1924 if (const auto *File = Ty->getFile()) {
1925 StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
1926 TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
1927
1928 UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
1929 TypeTable.writeLeafType(USLR);
1930 }
1931}
1932
David Majnemer979cb882016-06-16 21:32:16 +00001933TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
Reid Klecknere092dad2016-07-02 00:11:07 +00001934 ClassOptions CO = getCommonClassOptions(Ty);
David Majnemer979cb882016-06-16 21:32:16 +00001935 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001936 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001937
David Majnemerda9548f2016-06-17 16:13:21 +00001938 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001939 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001940 } else {
Zachary Turner6900de12017-11-28 18:33:17 +00001941 ContinuationRecordBuilder ContinuationBuilder;
1942 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
David Majnemerda9548f2016-06-17 16:13:21 +00001943 for (const DINode *Element : Ty->getElements()) {
1944 // We assume that the frontend provides all members in source declaration
1945 // order, which is what MSVC does.
1946 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00001947 EnumeratorRecord ER(MemberAccess::Public,
1948 APSInt::getUnsigned(Enumerator->getValue()),
1949 Enumerator->getName());
Zachary Turner6900de12017-11-28 18:33:17 +00001950 ContinuationBuilder.writeMemberType(ER);
David Majnemerda9548f2016-06-17 16:13:21 +00001951 EnumeratorCount++;
1952 }
1953 }
Zachary Turner6900de12017-11-28 18:33:17 +00001954 FTI = TypeTable.insertRecord(ContinuationBuilder);
David Majnemerda9548f2016-06-17 16:13:21 +00001955 }
David Majnemer979cb882016-06-16 21:32:16 +00001956
David Majnemer6bdc24e2016-07-01 23:12:45 +00001957 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001958
Zachary Turner4efa0a42016-11-08 22:24:53 +00001959 EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
1960 getTypeIndex(Ty->getBaseType()));
Aaron Smith122d9e72018-03-06 18:20:22 +00001961 TypeIndex EnumTI = TypeTable.writeLeafType(ER);
1962
1963 addUDTSrcLine(Ty, EnumTI);
1964
1965 return EnumTI;
David Majnemer979cb882016-06-16 21:32:16 +00001966}
1967
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001968//===----------------------------------------------------------------------===//
1969// ClassInfo
1970//===----------------------------------------------------------------------===//
1971
1972struct llvm::ClassInfo {
1973 struct MemberInfo {
1974 const DIDerivedType *MemberTypeNode;
David Majnemer08bd7442016-07-01 23:12:48 +00001975 uint64_t BaseOffset;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001976 };
1977 // [MemberInfo]
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001978 using MemberList = std::vector<MemberInfo>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001979
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001980 using MethodsList = TinyPtrVector<const DISubprogram *>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001981 // MethodName -> MethodsList
Eugene Zelenkofb69e662017-06-06 22:22:41 +00001982 using MethodsMap = MapVector<MDString *, MethodsList>;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001983
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00001984 /// Base classes.
1985 std::vector<const DIDerivedType *> Inheritance;
1986
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001987 /// Direct members.
1988 MemberList Members;
1989 // Direct overloaded methods gathered by name.
1990 MethodsMap Methods;
Adrian McCarthy820ca542016-07-06 19:49:51 +00001991
Reid Kleckner9dac4732016-08-31 15:59:30 +00001992 TypeIndex VShapeTI;
1993
Reid Klecknere2e82062017-08-08 20:30:14 +00001994 std::vector<const DIType *> NestedTypes;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001995};
1996
1997void CodeViewDebug::clear() {
1998 assert(CurFn == nullptr);
1999 FileIdMap.clear();
2000 FnDebugInfo.clear();
2001 FileToFilepathMap.clear();
2002 LocalUDTs.clear();
2003 GlobalUDTs.clear();
2004 TypeIndices.clear();
2005 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002006}
2007
2008void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
2009 const DIDerivedType *DDTy) {
2010 if (!DDTy->getName().empty()) {
2011 Info.Members.push_back({DDTy, 0});
2012 return;
2013 }
Shoaib Meenai03303a32018-02-27 21:48:41 +00002014
2015 // An unnamed member may represent a nested struct or union. Attempt to
2016 // interpret the unnamed member as a DICompositeType possibly wrapped in
2017 // qualifier types. Add all the indirect fields to the current record if that
2018 // succeeds, and drop the member if that fails.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002019 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
David Majnemer08bd7442016-07-01 23:12:48 +00002020 uint64_t Offset = DDTy->getOffsetInBits();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002021 const DIType *Ty = DDTy->getBaseType().resolve();
Shoaib Meenai03303a32018-02-27 21:48:41 +00002022 bool FullyResolved = false;
2023 while (!FullyResolved) {
2024 switch (Ty->getTag()) {
2025 case dwarf::DW_TAG_const_type:
2026 case dwarf::DW_TAG_volatile_type:
2027 // FIXME: we should apply the qualifier types to the indirect fields
2028 // rather than dropping them.
2029 Ty = cast<DIDerivedType>(Ty)->getBaseType().resolve();
2030 break;
2031 default:
2032 FullyResolved = true;
2033 break;
2034 }
2035 }
2036
2037 const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
2038 if (!DCTy)
2039 return;
2040
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002041 ClassInfo NestedInfo = collectClassInfo(DCTy);
2042 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002043 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002044 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002045}
2046
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002047ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
2048 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002049 // Add elements to structure type.
2050 DINodeArray Elements = Ty->getElements();
2051 for (auto *Element : Elements) {
2052 // We assume that the frontend provides all members in source declaration
2053 // order, which is what MSVC does.
2054 if (!Element)
2055 continue;
2056 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Reid Kleckner156a7232016-06-22 18:31:14 +00002057 Info.Methods[SP->getRawName()].push_back(SP);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002058 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002059 if (DDTy->getTag() == dwarf::DW_TAG_member) {
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002060 collectMemberInfo(Info, DDTy);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002061 } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
2062 Info.Inheritance.push_back(DDTy);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002063 } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
2064 DDTy->getName() == "__vtbl_ptr_type") {
2065 Info.VShapeTI = getTypeIndex(DDTy);
Reid Klecknere2e82062017-08-08 20:30:14 +00002066 } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
2067 Info.NestedTypes.push_back(DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002068 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
2069 // Ignore friend members. It appears that MSVC emitted info about
2070 // friends in the past, but modern versions do not.
2071 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00002072 } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
Reid Klecknere2e82062017-08-08 20:30:14 +00002073 Info.NestedTypes.push_back(Composite);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002074 }
2075 // Skip other unrecognized kinds of elements.
2076 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002077 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002078}
2079
Brock Wymab60532f2018-06-11 01:39:34 +00002080static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) {
2081 // This routine is used by lowerTypeClass and lowerTypeUnion to determine
2082 // if a complete type should be emitted instead of a forward reference.
2083 return Ty->getName().empty() && Ty->getIdentifier().empty() &&
2084 !Ty->isForwardDecl();
2085}
2086
Reid Klecknera8d57402016-06-03 15:58:20 +00002087TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
Brock Wymab60532f2018-06-11 01:39:34 +00002088 // Emit the complete type for unnamed structs. C++ classes with methods
2089 // which have a circular reference back to the class type are expected to
2090 // be named by the front-end and should not be "unnamed". C unnamed
2091 // structs should not have circular references.
2092 if (shouldAlwaysEmitCompleteClassType(Ty)) {
2093 // If this unnamed complete type is already in the process of being defined
2094 // then the description of the type is malformed and cannot be emitted
2095 // into CodeView correctly so report a fatal error.
2096 auto I = CompleteTypeIndices.find(Ty);
2097 if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
2098 report_fatal_error("cannot debug circular reference to unnamed type");
2099 return getCompleteTypeIndex(Ty);
2100 }
2101
Reid Klecknera8d57402016-06-03 15:58:20 +00002102 // First, construct the forward decl. Don't look into Ty to compute the
2103 // forward decl options, since it might not be available in all TUs.
2104 TypeRecordKind Kind = getRecordKind(Ty);
2105 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00002106 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00002107 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00002108 ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
2109 FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002110 TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
Reid Kleckner643dd832016-06-22 17:15:28 +00002111 if (!Ty->isForwardDecl())
2112 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00002113 return FwdDeclTI;
2114}
2115
2116TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
2117 // Construct the field list and complete type record.
2118 TypeRecordKind Kind = getRecordKind(Ty);
Reid Klecknere092dad2016-07-02 00:11:07 +00002119 ClassOptions CO = getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002120 TypeIndex FieldTI;
2121 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002122 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00002123 bool ContainsNestedClass;
2124 std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
2125 lowerRecordFieldList(Ty);
2126
2127 if (ContainsNestedClass)
2128 CO |= ClassOptions::ContainsNestedClass;
Reid Klecknera8d57402016-06-03 15:58:20 +00002129
David Majnemer6bdc24e2016-07-01 23:12:45 +00002130 std::string FullName = getFullyQualifiedName(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00002131
Reid Klecknera8d57402016-06-03 15:58:20 +00002132 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Hans Wennborg9a519a02016-06-22 21:22:13 +00002133
Zachary Turner4efa0a42016-11-08 22:24:53 +00002134 ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
2135 SizeInBytes, FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002136 TypeIndex ClassTI = TypeTable.writeLeafType(CR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002137
Aaron Smith122d9e72018-03-06 18:20:22 +00002138 addUDTSrcLine(Ty, ClassTI);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002139
Zachary Turnera7b04172017-08-28 18:49:04 +00002140 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00002141
Hans Wennborg9a519a02016-06-22 21:22:13 +00002142 return ClassTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002143}
2144
2145TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
Brock Wymab60532f2018-06-11 01:39:34 +00002146 // Emit the complete type for unnamed unions.
2147 if (shouldAlwaysEmitCompleteClassType(Ty))
2148 return getCompleteTypeIndex(Ty);
2149
Reid Klecknera8d57402016-06-03 15:58:20 +00002150 ClassOptions CO =
Reid Klecknere092dad2016-07-02 00:11:07 +00002151 ClassOptions::ForwardReference | getCommonClassOptions(Ty);
David Majnemer6bdc24e2016-07-01 23:12:45 +00002152 std::string FullName = getFullyQualifiedName(Ty);
Zachary Turner4efa0a42016-11-08 22:24:53 +00002153 UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002154 TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
Reid Kleckner643dd832016-06-22 17:15:28 +00002155 if (!Ty->isForwardDecl())
2156 DeferredCompleteTypes.push_back(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00002157 return FwdDeclTI;
2158}
2159
2160TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
David Majnemere1e73722016-07-06 21:07:42 +00002161 ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002162 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002163 unsigned FieldCount;
Adrian McCarthy820ca542016-07-06 19:49:51 +00002164 bool ContainsNestedClass;
2165 std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
2166 lowerRecordFieldList(Ty);
2167
2168 if (ContainsNestedClass)
2169 CO |= ClassOptions::ContainsNestedClass;
2170
Reid Klecknera8d57402016-06-03 15:58:20 +00002171 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
David Majnemer6bdc24e2016-07-01 23:12:45 +00002172 std::string FullName = getFullyQualifiedName(Ty);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002173
Zachary Turner4efa0a42016-11-08 22:24:53 +00002174 UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
2175 Ty->getIdentifier());
Zachary Turner6900de12017-11-28 18:33:17 +00002176 TypeIndex UnionTI = TypeTable.writeLeafType(UR);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002177
Aaron Smith122d9e72018-03-06 18:20:22 +00002178 addUDTSrcLine(Ty, UnionTI);
Hans Wennborg9a519a02016-06-22 21:22:13 +00002179
Zachary Turnera7b04172017-08-28 18:49:04 +00002180 addToUDTs(Ty);
Hans Wennborg4b63a982016-06-23 22:57:25 +00002181
Hans Wennborg9a519a02016-06-22 21:22:13 +00002182 return UnionTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00002183}
2184
Adrian McCarthy820ca542016-07-06 19:49:51 +00002185std::tuple<TypeIndex, TypeIndex, unsigned, bool>
Reid Klecknera8d57402016-06-03 15:58:20 +00002186CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
2187 // Manually count members. MSVC appears to count everything that generates a
2188 // field list record. Each individual overload in a method overload group
2189 // contributes to this count, even though the overload group is a single field
2190 // list record.
2191 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00002192 ClassInfo Info = collectClassInfo(Ty);
Zachary Turner6900de12017-11-28 18:33:17 +00002193 ContinuationRecordBuilder ContinuationBuilder;
2194 ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002195
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002196 // Create base classes.
2197 for (const DIDerivedType *I : Info.Inheritance) {
2198 if (I->getFlags() & DINode::FlagVirtual) {
2199 // Virtual base.
Brock Wyma3db2b102018-05-14 21:21:22 +00002200 unsigned VBPtrOffset = I->getVBPtrOffset();
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002201 // FIXME: Despite the accessor name, the offset is really in bytes.
2202 unsigned VBTableIndex = I->getOffsetInBits() / 4;
Bob Haarman26a87bd2016-10-25 22:11:52 +00002203 auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
2204 ? TypeRecordKind::IndirectVirtualBaseClass
2205 : TypeRecordKind::VirtualBaseClass;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002206 VirtualBaseClassRecord VBCR(
Bob Haarman26a87bd2016-10-25 22:11:52 +00002207 RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002208 getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
Zachary Turner4efa0a42016-11-08 22:24:53 +00002209 VBTableIndex);
2210
Zachary Turner6900de12017-11-28 18:33:17 +00002211 ContinuationBuilder.writeMemberType(VBCR);
Brock Wyma4536c1f2018-02-01 20:37:38 +00002212 MemberCount++;
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002213 } else {
2214 assert(I->getOffsetInBits() % 8 == 0 &&
2215 "bases must be on byte boundaries");
Zachary Turner4efa0a42016-11-08 22:24:53 +00002216 BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
2217 getTypeIndex(I->getBaseType()),
2218 I->getOffsetInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00002219 ContinuationBuilder.writeMemberType(BCR);
Brock Wyma4536c1f2018-02-01 20:37:38 +00002220 MemberCount++;
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002221 }
2222 }
2223
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002224 // Create members.
2225 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
2226 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
2227 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
David Majnemer9319cbc2016-06-30 03:00:20 +00002228 StringRef MemberName = Member->getName();
2229 MemberAccess Access =
2230 translateAccessFlags(Ty->getTag(), Member->getFlags());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002231
2232 if (Member->isStaticMember()) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00002233 StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
Zachary Turner6900de12017-11-28 18:33:17 +00002234 ContinuationBuilder.writeMemberType(SDMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002235 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00002236 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00002237 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002238
Reid Kleckner9dac4732016-08-31 15:59:30 +00002239 // Virtual function pointer member.
2240 if ((Member->getFlags() & DINode::FlagArtificial) &&
2241 Member->getName().startswith("_vptr$")) {
Zachary Turner4efa0a42016-11-08 22:24:53 +00002242 VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
Zachary Turner6900de12017-11-28 18:33:17 +00002243 ContinuationBuilder.writeMemberType(VFPR);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002244 MemberCount++;
2245 continue;
2246 }
2247
David Majnemer9319cbc2016-06-30 03:00:20 +00002248 // Data member.
David Majnemer08bd7442016-07-01 23:12:48 +00002249 uint64_t MemberOffsetInBits =
2250 Member->getOffsetInBits() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00002251 if (Member->isBitField()) {
2252 uint64_t StartBitOffset = MemberOffsetInBits;
2253 if (const auto *CI =
2254 dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
David Majnemer08bd7442016-07-01 23:12:48 +00002255 MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
David Majnemer9319cbc2016-06-30 03:00:20 +00002256 }
2257 StartBitOffset -= MemberOffsetInBits;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002258 BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2259 StartBitOffset);
Zachary Turner6900de12017-11-28 18:33:17 +00002260 MemberBaseType = TypeTable.writeLeafType(BFR);
David Majnemer9319cbc2016-06-30 03:00:20 +00002261 }
2262 uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
Zachary Turner4efa0a42016-11-08 22:24:53 +00002263 DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2264 MemberName);
Zachary Turner6900de12017-11-28 18:33:17 +00002265 ContinuationBuilder.writeMemberType(DMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002266 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00002267 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002268
2269 // Create methods
2270 for (auto &MethodItr : Info.Methods) {
2271 StringRef Name = MethodItr.first->getString();
2272
2273 std::vector<OneMethodRecord> Methods;
Reid Kleckner156a7232016-06-22 18:31:14 +00002274 for (const DISubprogram *SP : MethodItr.second) {
2275 TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2276 bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002277
2278 unsigned VFTableOffset = -1;
2279 if (Introduced)
2280 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2281
Zachary Turner7251ede2016-11-02 17:05:19 +00002282 Methods.push_back(OneMethodRecord(
2283 MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
2284 translateMethodKindFlags(SP, Introduced),
2285 translateMethodOptionFlags(SP), VFTableOffset, Name));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002286 MemberCount++;
2287 }
Eugene Zelenkofb69e662017-06-06 22:22:41 +00002288 assert(!Methods.empty() && "Empty methods map entry");
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002289 if (Methods.size() == 1)
Zachary Turner6900de12017-11-28 18:33:17 +00002290 ContinuationBuilder.writeMemberType(Methods[0]);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002291 else {
Zachary Turner6900de12017-11-28 18:33:17 +00002292 // FIXME: Make this use its own ContinuationBuilder so that
2293 // MethodOverloadList can be split correctly.
Zachary Turner4efa0a42016-11-08 22:24:53 +00002294 MethodOverloadListRecord MOLR(Methods);
Zachary Turner6900de12017-11-28 18:33:17 +00002295 TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
2296
Zachary Turner4efa0a42016-11-08 22:24:53 +00002297 OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
Zachary Turner6900de12017-11-28 18:33:17 +00002298 ContinuationBuilder.writeMemberType(OMR);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002299 }
2300 }
Adrian McCarthy820ca542016-07-06 19:49:51 +00002301
2302 // Create nested classes.
Reid Klecknere2e82062017-08-08 20:30:14 +00002303 for (const DIType *Nested : Info.NestedTypes) {
Adrian McCarthy820ca542016-07-06 19:49:51 +00002304 NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
Zachary Turner6900de12017-11-28 18:33:17 +00002305 ContinuationBuilder.writeMemberType(R);
Adrian McCarthy820ca542016-07-06 19:49:51 +00002306 MemberCount++;
2307 }
2308
Zachary Turner6900de12017-11-28 18:33:17 +00002309 TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
Reid Kleckner9dac4732016-08-31 15:59:30 +00002310 return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
Reid Klecknere2e82062017-08-08 20:30:14 +00002311 !Info.NestedTypes.empty());
Reid Klecknera8d57402016-06-03 15:58:20 +00002312}
2313
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002314TypeIndex CodeViewDebug::getVBPTypeIndex() {
2315 if (!VBPType.getIndex()) {
2316 // Make a 'const int *' type.
2317 ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
Zachary Turner6900de12017-11-28 18:33:17 +00002318 TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002319
2320 PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2321 : PointerKind::Near32;
2322 PointerMode PM = PointerMode::Pointer;
2323 PointerOptions PO = PointerOptions::None;
2324 PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
Zachary Turner6900de12017-11-28 18:33:17 +00002325 VBPType = TypeTable.writeLeafType(PR);
Reid Kleckner9f7f3e12016-06-24 16:24:24 +00002326 }
2327
2328 return VBPType;
2329}
2330
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002331TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002332 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002333 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002334
2335 // The null DIType is the void type. Don't try to hash it.
2336 if (!Ty)
2337 return TypeIndex::Void();
2338
Reid Klecknera8d57402016-06-03 15:58:20 +00002339 // Check if we've already translated this type. Don't try to do a
2340 // get-or-create style insertion that caches the hash lookup across the
2341 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00002342 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002343 if (I != TypeIndices.end())
2344 return I->second;
2345
Reid Klecknerb5af11d2016-07-01 02:41:21 +00002346 TypeLoweringScope S(*this);
2347 TypeIndex TI = lowerType(Ty, ClassTy);
2348 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00002349}
2350
Bob Haarman223303c2017-08-29 20:59:25 +00002351TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(DITypeRef TypeRef) {
2352 DIType *Ty = TypeRef.resolve();
2353 PointerRecord PR(getTypeIndex(Ty),
2354 getPointerSizeInBytes() == 8 ? PointerKind::Near64
2355 : PointerKind::Near32,
2356 PointerMode::LValueReference, PointerOptions::None,
2357 Ty->getSizeInBits() / 8);
Zachary Turner6900de12017-11-28 18:33:17 +00002358 return TypeTable.writeLeafType(PR);
Bob Haarman223303c2017-08-29 20:59:25 +00002359}
2360
Reid Klecknera8d57402016-06-03 15:58:20 +00002361TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
2362 const DIType *Ty = TypeRef.resolve();
2363
2364 // The null DIType is the void type. Don't try to hash it.
2365 if (!Ty)
2366 return TypeIndex::Void();
2367
2368 // If this is a non-record type, the complete type index is the same as the
2369 // normal type index. Just call getTypeIndex.
2370 switch (Ty->getTag()) {
2371 case dwarf::DW_TAG_class_type:
2372 case dwarf::DW_TAG_structure_type:
2373 case dwarf::DW_TAG_union_type:
2374 break;
2375 default:
2376 return getTypeIndex(Ty);
2377 }
2378
Brock Wymab60532f2018-06-11 01:39:34 +00002379 // Check if we've already translated the complete record type.
Reid Klecknera8d57402016-06-03 15:58:20 +00002380 const auto *CTy = cast<DICompositeType>(Ty);
2381 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
2382 if (!InsertResult.second)
2383 return InsertResult.first->second;
2384
Reid Kleckner643dd832016-06-22 17:15:28 +00002385 TypeLoweringScope S(*this);
2386
Reid Klecknera8d57402016-06-03 15:58:20 +00002387 // Make sure the forward declaration is emitted first. It's unclear if this
2388 // is necessary, but MSVC does it, and we should follow suit until we can show
2389 // otherwise.
Brock Wymab60532f2018-06-11 01:39:34 +00002390 // We only emit a forward declaration for named types.
2391 if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
2392 TypeIndex FwdDeclTI = getTypeIndex(CTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00002393
Brock Wymab60532f2018-06-11 01:39:34 +00002394 // Just use the forward decl if we don't have complete type info. This
2395 // might happen if the frontend is using modules and expects the complete
2396 // definition to be emitted elsewhere.
2397 if (CTy->isForwardDecl())
2398 return FwdDeclTI;
2399 }
Reid Klecknera8d57402016-06-03 15:58:20 +00002400
2401 TypeIndex TI;
2402 switch (CTy->getTag()) {
2403 case dwarf::DW_TAG_class_type:
2404 case dwarf::DW_TAG_structure_type:
2405 TI = lowerCompleteTypeClass(CTy);
2406 break;
2407 case dwarf::DW_TAG_union_type:
2408 TI = lowerCompleteTypeUnion(CTy);
2409 break;
2410 default:
2411 llvm_unreachable("not a record");
2412 }
2413
Brock Wymab60532f2018-06-11 01:39:34 +00002414 // Update the type index associated with this CompositeType. This cannot
2415 // use the 'InsertResult' iterator above because it is potentially
2416 // invalidated by map insertions which can occur while lowering the class
2417 // type above.
2418 CompleteTypeIndices[CTy] = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002419 return TI;
2420}
2421
Reid Kleckner643dd832016-06-22 17:15:28 +00002422/// Emit all the deferred complete record types. Try to do this in FIFO order,
Amjad Aboudacee5682016-07-12 12:06:34 +00002423/// and do this until fixpoint, as each complete record type typically
2424/// references
Reid Kleckner643dd832016-06-22 17:15:28 +00002425/// many other record types.
2426void CodeViewDebug::emitDeferredCompleteTypes() {
2427 SmallVector<const DICompositeType *, 4> TypesToEmit;
2428 while (!DeferredCompleteTypes.empty()) {
2429 std::swap(DeferredCompleteTypes, TypesToEmit);
2430 for (const DICompositeType *RecordTy : TypesToEmit)
2431 getCompleteTypeIndex(RecordTy);
2432 TypesToEmit.clear();
2433 }
2434}
2435
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002436void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
2437 ArrayRef<LocalVariable> Locals) {
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002438 // Get the sorted list of parameters and emit them first.
2439 SmallVector<const LocalVariable *, 6> Params;
2440 for (const LocalVariable &L : Locals)
2441 if (L.DIVar->isParameter())
2442 Params.push_back(&L);
Fangrui Song0cac7262018-09-27 02:13:45 +00002443 llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
2444 return L->DIVar->getArg() < R->DIVar->getArg();
2445 });
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002446 for (const LocalVariable *L : Params)
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002447 emitLocalVariable(FI, *L);
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002448
2449 // Next emit all non-parameters in the order that we found them.
2450 for (const LocalVariable &L : Locals)
2451 if (!L.DIVar->isParameter())
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002452 emitLocalVariable(FI, L);
Reid Kleckner10dd55c2016-06-24 17:55:40 +00002453}
2454
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002455void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
2456 const LocalVariable &Var) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002457 // LocalSym record, see SymbolRecord.h for more info.
2458 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
2459 *LocalEnd = MMI->getContext().createTempSymbol();
2460 OS.AddComment("Record length");
2461 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
2462 OS.EmitLabel(LocalBegin);
2463
2464 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00002465 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002466
Zachary Turner63a28462016-05-17 23:50:21 +00002467 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002468 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00002469 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00002470 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00002471 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002472
2473 OS.AddComment("TypeIndex");
Reid Kleckner08f5fd52017-08-31 15:56:49 +00002474 TypeIndex TI = Var.UseReferenceType
2475 ? getTypeIndexForReferenceTo(Var.DIVar->getType())
2476 : getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00002477 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002478 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00002479 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00002480 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00002481 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002482 OS.EmitLabel(LocalEnd);
2483
Reid Kleckner876330d2016-02-12 21:48:30 +00002484 // Calculate the on disk prefix of the appropriate def range record. The
2485 // records and on disk formats are described in SymbolRecords.h. BytePrefix
2486 // should be big enough to hold all forms without memory allocation.
2487 SmallString<20> BytePrefix;
2488 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2489 BytePrefix.clear();
Reid Kleckner876330d2016-02-12 21:48:30 +00002490 if (DefRange.InMemory) {
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002491 int Offset = DefRange.DataOffset;
2492 unsigned Reg = DefRange.CVRegister;
2493
2494 // x86 call sequences often use PUSH instructions, which disrupt
2495 // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
2496 // instead. In simple cases, $T0 will be the CFA. If the frame required
2497 // re-alignment, it will be the CFA aligned downwards.
2498 if (RegisterId(Reg) == RegisterId::ESP) {
2499 Reg = unsigned(RegisterId::VFRAME);
2500 Offset -= FI.FrameSize;
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002501 }
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002502
2503 // If we can use the chosen frame pointer for the frame and this isn't a
2504 // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
2505 // Otherwise, use S_DEFRANGE_REGISTER_REL.
2506 EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU);
2507 if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
2508 (bool(Flags & LocalSymFlags::IsParameter)
2509 ? (EncFP == FI.EncodedParamFramePtrReg)
2510 : (EncFP == FI.EncodedLocalFramePtrReg))) {
2511 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_FRAMEPOINTER_REL);
2512 little32_t FPOffset = little32_t(Offset);
2513 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2514 sizeof(SymKind));
2515 BytePrefix += StringRef(reinterpret_cast<const char *>(&FPOffset),
2516 sizeof(FPOffset));
2517 } else {
2518 uint16_t RegRelFlags = 0;
2519 if (DefRange.IsSubfield) {
2520 RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2521 (DefRange.StructOffset
2522 << DefRangeRegisterRelSym::OffsetInParentShift);
2523 }
2524 DefRangeRegisterRelSym::Header DRHdr;
2525 DRHdr.Register = Reg;
2526 DRHdr.Flags = RegRelFlags;
2527 DRHdr.BasePointerOffset = Offset;
2528 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
2529 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2530 sizeof(SymKind));
2531 BytePrefix += StringRef(reinterpret_cast<const char *>(&DRHdr),
2532 sizeof(DRHdr));
2533 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002534 } else {
2535 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002536 if (DefRange.IsSubfield) {
2537 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002538 DefRangeSubfieldRegisterSym Sym(S_DEFRANGE_SUBFIELD_REGISTER);
2539 Sym.Hdr.Register = DefRange.CVRegister;
2540 Sym.Hdr.MayHaveNoName = 0;
2541 Sym.Hdr.OffsetInParent = DefRange.StructOffset;
2542
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002543 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_SUBFIELD_REGISTER);
2544 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2545 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002546 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2547 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002548 } else {
2549 // Unclear what matters here.
Zachary Turner46225b12016-12-16 22:48:14 +00002550 DefRangeRegisterSym Sym(S_DEFRANGE_REGISTER);
2551 Sym.Hdr.Register = DefRange.CVRegister;
2552 Sym.Hdr.MayHaveNoName = 0;
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002553 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
2554 BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2555 sizeof(SymKind));
Zachary Turner46225b12016-12-16 22:48:14 +00002556 BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2557 sizeof(Sym.Hdr));
Reid Kleckner2b3e6422016-10-05 21:21:33 +00002558 }
Reid Kleckner876330d2016-02-12 21:48:30 +00002559 }
2560 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2561 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002562}
2563
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002564void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
2565 const FunctionInfo& FI) {
2566 for (LexicalBlock *Block : Blocks)
2567 emitLexicalBlock(*Block, FI);
2568}
2569
2570/// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
2571/// lexical block scope.
2572void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
2573 const FunctionInfo& FI) {
2574 MCSymbol *RecordBegin = MMI->getContext().createTempSymbol(),
2575 *RecordEnd = MMI->getContext().createTempSymbol();
2576
2577 // Lexical block symbol record.
2578 OS.AddComment("Record length");
2579 OS.emitAbsoluteSymbolDiff(RecordEnd, RecordBegin, 2); // Record Length
2580 OS.EmitLabel(RecordBegin);
2581 OS.AddComment("Record kind: S_BLOCK32");
2582 OS.EmitIntValue(SymbolKind::S_BLOCK32, 2); // Record Kind
2583 OS.AddComment("PtrParent");
2584 OS.EmitIntValue(0, 4); // PtrParent
2585 OS.AddComment("PtrEnd");
2586 OS.EmitIntValue(0, 4); // PtrEnd
2587 OS.AddComment("Code size");
2588 OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4); // Code Size
2589 OS.AddComment("Function section relative address");
2590 OS.EmitCOFFSecRel32(Block.Begin, /*Offset=*/0); // Func Offset
2591 OS.AddComment("Function section index");
2592 OS.EmitCOFFSectionIndex(FI.Begin); // Func Symbol
2593 OS.AddComment("Lexical block name");
2594 emitNullTerminatedSymbolName(OS, Block.Name); // Name
2595 OS.EmitLabel(RecordEnd);
2596
2597 // Emit variables local to this lexical block.
Reid Kleckner9ea2c012018-10-01 21:59:45 +00002598 emitLocalVariableList(FI, Block.Locals);
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002599
2600 // Emit lexical blocks contained within this block.
2601 emitLexicalBlockList(Block.Children, FI);
2602
2603 // Close the lexical block scope.
2604 OS.AddComment("Record length");
2605 OS.EmitIntValue(2, 2); // Record Length
2606 OS.AddComment("Record kind: S_END");
2607 OS.EmitIntValue(SymbolKind::S_END, 2); // Record Kind
2608}
2609
2610/// Convenience routine for collecting lexical block information for a list
2611/// of lexical scopes.
2612void CodeViewDebug::collectLexicalBlockInfo(
2613 SmallVectorImpl<LexicalScope *> &Scopes,
2614 SmallVectorImpl<LexicalBlock *> &Blocks,
2615 SmallVectorImpl<LocalVariable> &Locals) {
2616 for (LexicalScope *Scope : Scopes)
2617 collectLexicalBlockInfo(*Scope, Blocks, Locals);
2618}
2619
2620/// Populate the lexical blocks and local variable lists of the parent with
2621/// information about the specified lexical scope.
2622void CodeViewDebug::collectLexicalBlockInfo(
2623 LexicalScope &Scope,
2624 SmallVectorImpl<LexicalBlock *> &ParentBlocks,
2625 SmallVectorImpl<LocalVariable> &ParentLocals) {
2626 if (Scope.isAbstractScope())
2627 return;
2628
2629 auto LocalsIter = ScopeVariables.find(&Scope);
2630 if (LocalsIter == ScopeVariables.end()) {
2631 // This scope does not contain variables and can be eliminated.
2632 collectLexicalBlockInfo(Scope.getChildren(), ParentBlocks, ParentLocals);
2633 return;
2634 }
2635 SmallVectorImpl<LocalVariable> &Locals = LocalsIter->second;
2636
2637 const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
2638 if (!DILB) {
2639 // This scope is not a lexical block and can be eliminated, but keep any
2640 // local variables it contains.
2641 ParentLocals.append(Locals.begin(), Locals.end());
2642 collectLexicalBlockInfo(Scope.getChildren(), ParentBlocks, ParentLocals);
2643 return;
2644 }
2645
2646 const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
2647 if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second)) {
2648 // This lexical block scope has too many address ranges to represent in the
2649 // current CodeView format or does not have a valid address range.
2650 // Eliminate this lexical scope and promote any locals it contains to the
2651 // parent scope.
2652 //
2653 // For lexical scopes with multiple address ranges you may be tempted to
2654 // construct a single range covering every instruction where the block is
2655 // live and everything in between. Unfortunately, Visual Studio only
2656 // displays variables from the first matching lexical block scope. If the
2657 // first lexical block contains exception handling code or cold code which
2658 // is moved to the bottom of the routine creating a single range covering
2659 // nearly the entire routine, then it will hide all other lexical blocks
2660 // and the variables they contain.
2661 //
2662 ParentLocals.append(Locals.begin(), Locals.end());
2663 collectLexicalBlockInfo(Scope.getChildren(), ParentBlocks, ParentLocals);
2664 return;
2665 }
2666
2667 // Create a new CodeView lexical block for this lexical scope. If we've
2668 // seen this DILexicalBlock before then the scope tree is malformed and
2669 // we can handle this gracefully by not processing it a second time.
2670 auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
2671 if (!BlockInsertion.second)
2672 return;
2673
2674 // Create a lexical block containing the local variables and collect the
2675 // the lexical block information for the children.
2676 const InsnRange &Range = Ranges.front();
2677 assert(Range.first && Range.second);
2678 LexicalBlock &Block = BlockInsertion.first->second;
2679 Block.Begin = getLabelBeforeInsn(Range.first);
2680 Block.End = getLabelAfterInsn(Range.second);
2681 assert(Block.Begin && "missing label for scope begin");
2682 assert(Block.End && "missing label for scope end");
2683 Block.Name = DILB->getName();
2684 Block.Locals = std::move(Locals);
2685 ParentBlocks.push_back(&Block);
2686 collectLexicalBlockInfo(Scope.getChildren(), Block.Children, Block.Locals);
2687}
2688
David Blaikieb2fbb4b2017-02-16 18:48:33 +00002689void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002690 const Function &GV = MF->getFunction();
2691 assert(FnDebugInfo.count(&GV));
Reid Kleckner55baeef2018-03-15 21:12:21 +00002692 assert(CurFn == FnDebugInfo[&GV].get());
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00002693
Matthias Braunf1caa282017-12-15 22:22:58 +00002694 collectVariableInfo(GV.getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00002695
Reid Kleckner5a791ee2018-03-15 21:24:04 +00002696 // Build the lexical block structure to emit for this routine.
2697 if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
2698 collectLexicalBlockInfo(*CFS, CurFn->ChildBlocks, CurFn->Locals);
2699
2700 // Clear the scope and variable information from the map which will not be
2701 // valid after we have finished processing this routine. This also prepares
2702 // the map for the subsequent routine.
2703 ScopeVariables.clear();
2704
Reid Kleckner2214ed82016-01-29 00:49:42 +00002705 // Don't emit anything if we don't have any line tables.
Brock Wyma94ece8f2018-04-16 16:53:57 +00002706 // Thunks are compiler-generated and probably won't have source correlation.
2707 if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
Matthias Braunf1caa282017-12-15 22:22:58 +00002708 FnDebugInfo.erase(&GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002709 CurFn = nullptr;
2710 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00002711 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002712
Reid Klecknere33c94f2017-09-05 20:14:58 +00002713 CurFn->Annotations = MF->getCodeViewAnnotations();
2714
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002715 CurFn->End = Asm->getFunctionEnd();
2716
Craig Topper353eda42014-04-24 06:44:33 +00002717 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002718}
2719
Reid Kleckner70f5bc92016-01-14 19:25:04 +00002720void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00002721 DebugHandlerBase::beginInstruction(MI);
2722
Shiva Chen801bf7e2018-05-09 02:42:00 +00002723 // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
2724 if (!Asm || !CurFn || MI->isDebugInstr() ||
David Majnemer67f684e2016-07-28 05:03:22 +00002725 MI->getFlag(MachineInstr::FrameSetup))
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002726 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002727
2728 // If the first instruction of a new MBB has no location, find the first
2729 // instruction with a location and use that.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002730 DebugLoc DL = MI->getDebugLoc();
Reid Kleckner45a74622017-06-30 21:33:44 +00002731 if (!DL && MI->getParent() != PrevInstBB) {
2732 for (const auto &NextMI : *MI->getParent()) {
Shiva Chen801bf7e2018-05-09 02:42:00 +00002733 if (NextMI.isDebugInstr())
Reid Kleckner2de471d2017-07-31 21:03:08 +00002734 continue;
Reid Kleckner45a74622017-06-30 21:33:44 +00002735 DL = NextMI.getDebugLoc();
2736 if (DL)
2737 break;
2738 }
2739 }
2740 PrevInstBB = MI->getParent();
2741
2742 // If we still don't have a debug location, don't record a location.
2743 if (!DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002744 return;
Reid Kleckner45a74622017-06-30 21:33:44 +00002745
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00002746 maybeRecordLocation(DL, Asm->MF);
2747}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002748
Zachary Turner8c099fe2017-05-30 16:36:15 +00002749MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002750 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2751 *EndLabel = MMI->getContext().createTempSymbol();
2752 OS.EmitIntValue(unsigned(Kind), 4);
2753 OS.AddComment("Subsection size");
2754 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2755 OS.EmitLabel(BeginLabel);
2756 return EndLabel;
2757}
2758
2759void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2760 OS.EmitLabel(EndLabel);
2761 // Every subsection must be aligned to a 4-byte boundary.
2762 OS.EmitValueToAlignment(4);
2763}
2764
David Majnemer3128b102016-06-15 18:00:01 +00002765void CodeViewDebug::emitDebugInfoForUDTs(
Zachary Turnera7b04172017-08-28 18:49:04 +00002766 ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
2767 for (const auto &UDT : UDTs) {
2768 const DIType *T = UDT.second;
2769 assert(shouldEmitUdt(T));
2770
David Majnemer3128b102016-06-15 18:00:01 +00002771 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
2772 *UDTRecordEnd = MMI->getContext().createTempSymbol();
2773 OS.AddComment("Record length");
2774 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
2775 OS.EmitLabel(UDTRecordBegin);
2776
2777 OS.AddComment("Record kind: S_UDT");
2778 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
2779
2780 OS.AddComment("Type");
Zachary Turnera7b04172017-08-28 18:49:04 +00002781 OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
David Majnemer3128b102016-06-15 18:00:01 +00002782
2783 emitNullTerminatedSymbolName(OS, UDT.first);
2784 OS.EmitLabel(UDTRecordEnd);
2785 }
2786}
2787
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002788void CodeViewDebug::emitDebugInfoForGlobals() {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002789 DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2790 GlobalMap;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002791 for (const GlobalVariable &GV : MMI->getModule()->globals()) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002792 SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2793 GV.getDebugInfo(GVEs);
2794 for (const auto *GVE : GVEs)
2795 GlobalMap[GVE] = &GV;
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002796 }
2797
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002798 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2799 for (const MDNode *Node : CUs->operands()) {
2800 const auto *CU = cast<DICompileUnit>(Node);
2801
2802 // First, emit all globals that are not in a comdat in a single symbol
2803 // substream. MSVC doesn't like it if the substream is empty, so only open
2804 // it if we have at least one global to emit.
2805 switchToDebugSectionForSymbol(nullptr);
2806 MCSymbol *EndLabel = nullptr;
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002807 for (const auto *GVE : CU->getGlobalVariables()) {
2808 if (const auto *GV = GlobalMap.lookup(GVE))
David Majnemer577be0f2016-06-15 00:19:52 +00002809 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002810 if (!EndLabel) {
2811 OS.AddComment("Symbol subsection for globals");
Zachary Turner8c099fe2017-05-30 16:36:15 +00002812 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002813 }
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002814 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2815 emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002816 }
2817 }
2818 if (EndLabel)
2819 endCVSubsection(EndLabel);
2820
2821 // Second, emit each global that is in a comdat into its own .debug$S
2822 // section along with its own symbol substream.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002823 for (const auto *GVE : CU->getGlobalVariables()) {
2824 if (const auto *GV = GlobalMap.lookup(GVE)) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002825 if (GV->hasComdat()) {
2826 MCSymbol *GVSym = Asm->getSymbol(GV);
2827 OS.AddComment("Symbol subsection for " +
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00002828 Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002829 switchToDebugSectionForSymbol(GVSym);
Zachary Turner8c099fe2017-05-30 16:36:15 +00002830 EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002831 // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2832 emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002833 endCVSubsection(EndLabel);
2834 }
2835 }
2836 }
2837 }
2838}
2839
Hans Wennborgb510b452016-06-23 16:33:53 +00002840void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2841 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2842 for (const MDNode *Node : CUs->operands()) {
2843 for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2844 if (DIType *RT = dyn_cast<DIType>(Ty)) {
2845 getTypeIndex(RT);
2846 // FIXME: Add to global/local DTU list.
2847 }
2848 }
2849 }
2850}
2851
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002852void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
Peter Collingbourned4135bb2016-09-13 01:12:59 +00002853 const GlobalVariable *GV,
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002854 MCSymbol *GVSym) {
2855 // DataSym record, see SymbolRecord.h for more info.
2856 // FIXME: Thread local data, etc
2857 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2858 *DataEnd = MMI->getContext().createTempSymbol();
Brock Wyma19e17b32018-02-11 21:26:46 +00002859 const unsigned FixedLengthOfThisRecord = 12;
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002860 OS.AddComment("Record length");
2861 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2862 OS.EmitLabel(DataBegin);
David Majnemer7abd2692016-07-06 21:07:47 +00002863 if (DIGV->isLocalToUnit()) {
David Majnemera54fe1a2016-07-07 05:14:21 +00002864 if (GV->isThreadLocal()) {
2865 OS.AddComment("Record kind: S_LTHREAD32");
2866 OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2867 } else {
2868 OS.AddComment("Record kind: S_LDATA32");
2869 OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2870 }
David Majnemer7abd2692016-07-06 21:07:47 +00002871 } else {
David Majnemera54fe1a2016-07-07 05:14:21 +00002872 if (GV->isThreadLocal()) {
2873 OS.AddComment("Record kind: S_GTHREAD32");
2874 OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2875 } else {
2876 OS.AddComment("Record kind: S_GDATA32");
2877 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2878 }
David Majnemer7abd2692016-07-06 21:07:47 +00002879 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002880 OS.AddComment("Type");
2881 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2882 OS.AddComment("DataOffset");
Keno Fischerf7d84ee2017-01-02 03:00:19 +00002883 OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002884 OS.AddComment("Segment");
2885 OS.EmitCOFFSectionIndex(GVSym);
2886 OS.AddComment("Name");
Brock Wyma19e17b32018-02-11 21:26:46 +00002887 emitNullTerminatedSymbolName(OS, DIGV->getName(), FixedLengthOfThisRecord);
Reid Kleckner6f3406d2016-06-07 00:02:03 +00002888 OS.EmitLabel(DataEnd);
2889}