blob: 31f0872a30102495b3e2bc48e1b23b53c63681c9 [file] [log] [blame]
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001//===-- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp --*- C++ -*--===//
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"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000015#include "llvm/DebugInfo/CodeView/CodeView.h"
Reid Klecknera8d57402016-06-03 15:58:20 +000016#include "llvm/DebugInfo/CodeView/FieldListRecordBuilder.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000017#include "llvm/DebugInfo/CodeView/Line.h"
Reid Kleckner6b3faef2016-01-13 23:44:57 +000018#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000019#include "llvm/DebugInfo/CodeView/TypeDumper.h"
Reid Klecknerf3b9ba42016-01-29 18:16:43 +000020#include "llvm/DebugInfo/CodeView/TypeIndex.h"
21#include "llvm/DebugInfo/CodeView/TypeRecord.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000022#include "llvm/MC/MCExpr.h"
Reid Kleckner5d122f82016-05-25 23:16:12 +000023#include "llvm/MC/MCSectionCOFF.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000024#include "llvm/MC/MCSymbol.h"
25#include "llvm/Support/COFF.h"
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +000026#include "llvm/Support/ScopedPrinter.h"
Reid Klecknerf9c275f2016-02-10 20:55:49 +000027#include "llvm/Target/TargetFrameLowering.h"
Amjad Aboud76c9eb92016-06-18 10:25:07 +000028#include "llvm/Target/TargetRegisterInfo.h"
29#include "llvm/Target/TargetSubtargetInfo.h"
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000030
Reid Klecknerf9c275f2016-02-10 20:55:49 +000031using namespace llvm;
Reid Kleckner6b3faef2016-01-13 23:44:57 +000032using namespace llvm::codeview;
33
Reid Klecknerf9c275f2016-02-10 20:55:49 +000034CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
35 : DebugHandlerBase(AP), OS(*Asm->OutStreamer), CurFn(nullptr) {
36 // If module doesn't have named metadata anchors or COFF debug section
37 // is not available, skip any debug info related stuff.
38 if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
39 !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
40 Asm = nullptr;
41 return;
42 }
43
44 // Tell MMI that we have debug info.
45 MMI->setDebugInfoAvailability(true);
46}
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000047
Reid Kleckner9533af42016-01-16 00:09:09 +000048StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
49 std::string &Filepath = FileToFilepathMap[File];
Reid Kleckner1f11b4e2015-12-02 22:34:30 +000050 if (!Filepath.empty())
51 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000052
Reid Kleckner9533af42016-01-16 00:09:09 +000053 StringRef Dir = File->getDirectory(), Filename = File->getFilename();
54
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000055 // Clang emits directory and relative filename info into the IR, but CodeView
56 // operates on full paths. We could change Clang to emit full paths too, but
57 // that would increase the IR size and probably not needed for other users.
58 // For now, just concatenate and canonicalize the path here.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000059 if (Filename.find(':') == 1)
60 Filepath = Filename;
61 else
Yaron Keren75e0c4b2015-03-27 17:51:30 +000062 Filepath = (Dir + "\\" + Filename).str();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000063
64 // Canonicalize the path. We have to do it textually because we may no longer
65 // have access the file in the filesystem.
66 // First, replace all slashes with backslashes.
67 std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
68
69 // Remove all "\.\" with "\".
70 size_t Cursor = 0;
71 while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
72 Filepath.erase(Cursor, 2);
73
74 // Replace all "\XXX\..\" with "\". Don't try too hard though as the original
75 // path should be well-formatted, e.g. start with a drive letter, etc.
76 Cursor = 0;
77 while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
78 // Something's wrong if the path starts with "\..\", abort.
79 if (Cursor == 0)
80 break;
81
82 size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
83 if (PrevSlash == std::string::npos)
84 // Something's wrong, abort.
85 break;
86
87 Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
88 // The next ".." might be following the one we've just erased.
89 Cursor = PrevSlash;
90 }
91
92 // Remove all duplicate backslashes.
93 Cursor = 0;
94 while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
95 Filepath.erase(Cursor, 1);
96
Reid Kleckner1f11b4e2015-12-02 22:34:30 +000097 return Filepath;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +000098}
99
Reid Kleckner2214ed82016-01-29 00:49:42 +0000100unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
101 unsigned NextId = FileIdMap.size() + 1;
102 auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
103 if (Insertion.second) {
104 // We have to compute the full filepath and emit a .cv_file directive.
105 StringRef FullPath = getFullFilepath(F);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000106 NextId = OS.EmitCVFileDirective(NextId, FullPath);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000107 assert(NextId == FileIdMap.size() && ".cv_file directive failed");
108 }
109 return Insertion.first->second;
110}
111
Reid Kleckner876330d2016-02-12 21:48:30 +0000112CodeViewDebug::InlineSite &
113CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
114 const DISubprogram *Inlinee) {
Reid Klecknerfbd77872016-03-18 18:54:32 +0000115 auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
116 InlineSite *Site = &SiteInsertion.first->second;
117 if (SiteInsertion.second) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000118 Site->SiteFuncId = NextFuncId++;
Reid Kleckner876330d2016-02-12 21:48:30 +0000119 Site->Inlinee = Inlinee;
Reid Kleckner2280f932016-05-23 20:23:46 +0000120 InlinedSubprograms.insert(Inlinee);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000121 getFuncIdForSubprogram(Inlinee);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000122 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000123 return *Site;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000124}
125
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000126static const DISubprogram *getQualifiedNameComponents(
127 const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
128 const DISubprogram *ClosestSubprogram = nullptr;
129 while (Scope != nullptr) {
130 if (ClosestSubprogram == nullptr)
131 ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
132 StringRef ScopeName = Scope->getName();
133 if (!ScopeName.empty())
134 QualifiedNameComponents.push_back(ScopeName);
135 Scope = Scope->getScope().resolve();
136 }
137 return ClosestSubprogram;
138}
139
140static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
141 StringRef TypeName) {
142 std::string FullyQualifiedName;
143 for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) {
144 FullyQualifiedName.append(QualifiedNameComponent);
145 FullyQualifiedName.append("::");
146 }
147 FullyQualifiedName.append(TypeName);
148 return FullyQualifiedName;
149}
150
151static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
152 SmallVector<StringRef, 5> QualifiedNameComponents;
153 getQualifiedNameComponents(Scope, QualifiedNameComponents);
154 return getQualifiedName(QualifiedNameComponents, Name);
155}
156
157TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
158 // No scope means global scope and that uses the zero index.
159 if (!Scope || isa<DIFile>(Scope))
160 return TypeIndex();
161
162 assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
163
164 // Check if we've already translated this scope.
165 auto I = TypeIndices.find({Scope, nullptr});
166 if (I != TypeIndices.end())
167 return I->second;
168
169 // Build the fully qualified name of the scope.
170 std::string ScopeName =
171 getFullyQualifiedName(Scope->getScope().resolve(), Scope->getName());
172 TypeIndex TI =
173 TypeTable.writeStringId(StringIdRecord(TypeIndex(), ScopeName));
174 return recordTypeIndexForDINode(Scope, TI);
175}
176
David Majnemer75c3ebf2016-06-02 17:13:53 +0000177TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
178 // It's possible to ask for the FuncId of a function which doesn't have a
179 // subprogram: inlining a function with debug info into a function with none.
180 if (!SP)
David Majnemerb68f32f02016-06-02 18:51:24 +0000181 return TypeIndex::None();
Reid Kleckner2280f932016-05-23 20:23:46 +0000182
David Majnemer75c3ebf2016-06-02 17:13:53 +0000183 // Check if we've already translated this subprogram.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000184 auto I = TypeIndices.find({SP, nullptr});
David Majnemer75c3ebf2016-06-02 17:13:53 +0000185 if (I != TypeIndices.end())
186 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000187
Reid Klecknerac945e22016-06-17 16:11:20 +0000188 // The display name includes function template arguments. Drop them to match
189 // MSVC.
190 StringRef DisplayName = SP->getDisplayName().split('<').first;
David Majnemer75c3ebf2016-06-02 17:13:53 +0000191
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000192 const DIScope *Scope = SP->getScope().resolve();
193 TypeIndex TI;
194 if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
195 // If the scope is a DICompositeType, then this must be a method. Member
196 // function types take some special handling, and require access to the
197 // subprogram.
198 TypeIndex ClassType = getTypeIndex(Class);
199 MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
200 DisplayName);
201 TI = TypeTable.writeMemberFuncId(MFuncId);
202 } else {
203 // Otherwise, this must be a free function.
204 TypeIndex ParentScope = getScopeIndex(Scope);
205 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
206 TI = TypeTable.writeFuncId(FuncId);
207 }
208
209 return recordTypeIndexForDINode(SP, TI);
Reid Kleckner2280f932016-05-23 20:23:46 +0000210}
211
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000212TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
213 const DICompositeType *Class) {
214 // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
215 // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
216 auto I = TypeIndices.find({SP, nullptr});
217 if (I != TypeIndices.end())
218 return I->second;
219
220 // FIXME: Get the ThisAdjustment off of SP when it is available.
221 TypeIndex TI =
222 lowerTypeMemberFunction(SP->getType(), Class, /*ThisAdjustment=*/0);
223
224 return recordTypeIndexForDINode(SP, TI, Class);
225}
226
227TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node, TypeIndex TI,
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000228 const DIType *ClassTy) {
229 auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
Reid Klecknera8d57402016-06-03 15:58:20 +0000230 (void)InsertResult;
231 assert(InsertResult.second && "DINode was already assigned a type index");
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000232 return TI;
Reid Klecknera8d57402016-06-03 15:58:20 +0000233}
234
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000235unsigned CodeViewDebug::getPointerSizeInBytes() {
236 return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
237}
238
Reid Kleckner876330d2016-02-12 21:48:30 +0000239void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
240 const DILocation *InlinedAt) {
241 if (InlinedAt) {
242 // This variable was inlined. Associate it with the InlineSite.
243 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
244 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
245 Site.InlinedLocals.emplace_back(Var);
246 } else {
247 // This variable goes in the main ProcSym.
248 CurFn->Locals.emplace_back(Var);
249 }
250}
251
Reid Kleckner829365a2016-02-11 19:41:47 +0000252static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
253 const DILocation *Loc) {
254 auto B = Locs.begin(), E = Locs.end();
255 if (std::find(B, E, Loc) == E)
256 Locs.push_back(Loc);
257}
258
Benjamin Kramerbdc49562016-06-12 15:39:02 +0000259void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000260 const MachineFunction *MF) {
261 // Skip this instruction if it has the same location as the previous one.
262 if (DL == CurFn->LastLoc)
263 return;
264
265 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000266 if (!Scope)
267 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000268
David Majnemerc3340db2016-01-13 01:05:23 +0000269 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000270 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
271 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
272 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000273 return;
274
Reid Kleckner2214ed82016-01-29 00:49:42 +0000275 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
276 if (CI.getStartColumn() != DL.getCol())
277 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000278
Reid Kleckner2214ed82016-01-29 00:49:42 +0000279 if (!CurFn->HaveLineInfo)
280 CurFn->HaveLineInfo = true;
281 unsigned FileId = 0;
282 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
283 FileId = CurFn->LastFileId;
284 else
285 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
286 CurFn->LastLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000287
288 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000289 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000290 const DILocation *Loc = DL.get();
291
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000292 // If this location was actually inlined from somewhere else, give it the ID
293 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000294 FuncId =
295 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000296
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000297 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000298 bool FirstLoc = true;
299 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000300 InlineSite &Site =
301 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000302 if (!FirstLoc)
303 addLocIfNotPresent(Site.ChildSites, Loc);
304 FirstLoc = false;
305 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000306 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000307 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000308 }
309
Reid Klecknerdac21b42016-02-03 21:15:48 +0000310 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
311 /*PrologueEnd=*/false,
312 /*IsStmt=*/false, DL->getFilename());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000313}
314
Reid Kleckner5d122f82016-05-25 23:16:12 +0000315void CodeViewDebug::emitCodeViewMagicVersion() {
316 OS.EmitValueToAlignment(4);
317 OS.AddComment("Debug section magic");
318 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
319}
320
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000321void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000322 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000323 return;
324
325 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000326
327 // The COFF .debug$S section consists of several subsections, each starting
328 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
329 // of the payload followed by the payload itself. The subsections are 4-byte
330 // aligned.
331
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000332 // Use the generic .debug$S section, and make a subsection for all the inlined
333 // subprograms.
334 switchToDebugSectionForSymbol(nullptr);
Reid Kleckner5d122f82016-05-25 23:16:12 +0000335 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000336
Reid Kleckner2214ed82016-01-29 00:49:42 +0000337 // Emit per-function debug information.
338 for (auto &P : FnDebugInfo)
David Majnemer577be0f2016-06-15 00:19:52 +0000339 if (!P.first->isDeclarationForLinker())
340 emitDebugInfoForFunction(P.first, P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000341
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000342 // Emit global variable debug information.
David Majnemer3128b102016-06-15 18:00:01 +0000343 setCurrentSubprogram(nullptr);
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000344 emitDebugInfoForGlobals();
345
Reid Kleckner5d122f82016-05-25 23:16:12 +0000346 // Switch back to the generic .debug$S section after potentially processing
347 // comdat symbol sections.
348 switchToDebugSectionForSymbol(nullptr);
349
David Majnemer3128b102016-06-15 18:00:01 +0000350 // Emit UDT records for any types used by global variables.
351 if (!GlobalUDTs.empty()) {
352 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
353 emitDebugInfoForUDTs(GlobalUDTs);
354 endCVSubsection(SymbolsEnd);
355 }
356
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000357 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000358 OS.AddComment("File index to string table offset subsection");
359 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000360
361 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000362 OS.AddComment("String table");
363 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000364
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000365 // Emit type information last, so that any types we translate while emitting
366 // function info are included.
367 emitTypeInformation();
368
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000369 clear();
370}
371
David Majnemerb9456a52016-03-14 05:15:09 +0000372static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
373 // Microsoft's linker seems to have trouble with symbol names longer than
374 // 0xffd8 bytes.
375 S = S.substr(0, 0xffd8);
376 SmallString<32> NullTerminatedString(S);
377 NullTerminatedString.push_back('\0');
378 OS.EmitBytes(NullTerminatedString);
379}
380
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000381void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000382 // Do nothing if we have no debug info or if no non-trivial types were emitted
383 // to TypeTable during codegen.
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000384 NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
Reid Klecknerfbd77872016-03-18 18:54:32 +0000385 if (!CU_Nodes)
386 return;
Reid Kleckner2280f932016-05-23 20:23:46 +0000387 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000388 return;
389
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000390 // Start the .debug$T section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000391 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000392 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000393
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000394 SmallString<8> CommentPrefix;
395 if (OS.isVerboseAsm()) {
396 CommentPrefix += '\t';
397 CommentPrefix += Asm->MAI->getCommentString();
398 CommentPrefix += ' ';
399 }
400
401 CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false);
Reid Kleckner2280f932016-05-23 20:23:46 +0000402 TypeTable.ForEachRecord(
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000403 [&](TypeIndex Index, StringRef Record) {
404 if (OS.isVerboseAsm()) {
405 // Emit a block comment describing the type record for readability.
406 SmallString<512> CommentBlock;
407 raw_svector_ostream CommentOS(CommentBlock);
408 ScopedPrinter SP(CommentOS);
409 SP.setPrefix(CommentPrefix);
410 CVTD.setPrinter(&SP);
Zachary Turner01ee3dae2016-06-16 18:22:27 +0000411 Error EC = CVTD.dump({Record.bytes_begin(), Record.bytes_end()});
412 assert(!EC && "produced malformed type record");
413 consumeError(std::move(EC));
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000414 // emitRawComment will insert its own tab and comment string before
415 // the first line, so strip off our first one. It also prints its own
416 // newline.
417 OS.emitRawComment(
418 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
419 }
420 OS.EmitBinaryData(Record);
Reid Kleckner2280f932016-05-23 20:23:46 +0000421 });
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000422}
423
Reid Kleckner5d122f82016-05-25 23:16:12 +0000424void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000425 if (InlinedSubprograms.empty())
426 return;
427
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000428 OS.AddComment("Inlinee lines subsection");
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000429 MCSymbol *InlineEnd = beginCVSubsection(ModuleSubstreamKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000430
431 // We don't provide any extra file info.
432 // FIXME: Find out if debuggers use this info.
David Majnemer30579ec2016-02-02 23:18:23 +0000433 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000434 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
435
436 for (const DISubprogram *SP : InlinedSubprograms) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000437 assert(TypeIndices.count({SP, nullptr}));
438 TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
Reid Kleckner2280f932016-05-23 20:23:46 +0000439
David Majnemer30579ec2016-02-02 23:18:23 +0000440 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000441 unsigned FileId = maybeRecordFile(SP->getFile());
442 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
443 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000444 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000445 // The filechecksum table uses 8 byte entries for now, and file ids start at
446 // 1.
447 unsigned FileOffset = (FileId - 1) * 8;
David Majnemer30579ec2016-02-02 23:18:23 +0000448 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000449 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000450 OS.AddComment("Offset into filechecksum table");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000451 OS.EmitIntValue(FileOffset, 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000452 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000453 OS.EmitIntValue(SP->getLine(), 4);
454 }
455
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000456 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000457}
458
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000459void CodeViewDebug::collectInlineSiteChildren(
460 SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI,
461 const InlineSite &Site) {
462 for (const DILocation *ChildSiteLoc : Site.ChildSites) {
463 auto I = FI.InlineSites.find(ChildSiteLoc);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000464 const InlineSite &ChildSite = I->second;
465 Children.push_back(ChildSite.SiteFuncId);
466 collectInlineSiteChildren(Children, FI, ChildSite);
467 }
468}
469
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000470void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
471 const DILocation *InlinedAt,
472 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000473 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
474 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000475
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000476 assert(TypeIndices.count({Site.Inlinee, nullptr}));
477 TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000478
479 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000480 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000481 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000482 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000483 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000484 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000485
Reid Klecknerdac21b42016-02-03 21:15:48 +0000486 OS.AddComment("PtrParent");
487 OS.EmitIntValue(0, 4);
488 OS.AddComment("PtrEnd");
489 OS.EmitIntValue(0, 4);
490 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000491 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000492
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000493 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
494 unsigned StartLineNum = Site.Inlinee->getLine();
495 SmallVector<unsigned, 3> SecondaryFuncIds;
496 collectInlineSiteChildren(SecondaryFuncIds, FI, Site);
497
498 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
David Majnemerc9911f22016-02-02 19:22:34 +0000499 FI.Begin, FI.End, SecondaryFuncIds);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000500
501 OS.EmitLabel(InlineEnd);
502
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000503 for (const LocalVariable &Var : Site.InlinedLocals)
504 emitLocalVariable(Var);
505
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000506 // Recurse on child inlined call sites before closing the scope.
507 for (const DILocation *ChildSite : Site.ChildSites) {
508 auto I = FI.InlineSites.find(ChildSite);
509 assert(I != FI.InlineSites.end() &&
510 "child site not in function inline site map");
511 emitInlinedCallSite(FI, ChildSite, I->second);
512 }
513
514 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000515 OS.AddComment("Record length");
516 OS.EmitIntValue(2, 2); // RecordLength
517 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000518 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000519}
520
Reid Kleckner5d122f82016-05-25 23:16:12 +0000521void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
522 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
523 // comdat key. A section may be comdat because of -ffunction-sections or
524 // because it is comdat in the IR.
525 MCSectionCOFF *GVSec =
526 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
527 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
528
529 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
530 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
531 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
532
533 OS.SwitchSection(DebugSec);
534
535 // Emit the magic version number if this is the first time we've switched to
536 // this section.
537 if (ComdatDebugSections.insert(DebugSec).second)
538 emitCodeViewMagicVersion();
539}
540
Reid Kleckner2214ed82016-01-29 00:49:42 +0000541void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
542 FunctionInfo &FI) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000543 // For each function there is a separate subsection
544 // which holds the PC to file:line table.
545 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000546 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000547
Reid Kleckner5d122f82016-05-25 23:16:12 +0000548 // Switch to the to a comdat section, if appropriate.
549 switchToDebugSectionForSymbol(Fn);
550
Reid Klecknerac945e22016-06-17 16:11:20 +0000551 std::string FuncName;
David Majnemer3128b102016-06-15 18:00:01 +0000552 auto *SP = GV->getSubprogram();
553 setCurrentSubprogram(SP);
Reid Klecknerac945e22016-06-17 16:11:20 +0000554
555 // If we have a display name, build the fully qualified name by walking the
556 // chain of scopes.
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000557 if (SP != nullptr && !SP->getDisplayName().empty())
558 FuncName =
559 getFullyQualifiedName(SP->getScope().resolve(), SP->getDisplayName());
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000560
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000561 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000562 if (FuncName.empty())
563 FuncName = GlobalValue::getRealLinkageName(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000564
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000565 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000566 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000567 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000568 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000569 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
570 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000571 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000572 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000573 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000574
Reid Klecknerdac21b42016-02-03 21:15:48 +0000575 OS.AddComment("Record kind: S_GPROC32_ID");
Zachary Turner63a28462016-05-17 23:50:21 +0000576 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000577
David Majnemer30579ec2016-02-02 23:18:23 +0000578 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000579 OS.AddComment("PtrParent");
580 OS.EmitIntValue(0, 4);
581 OS.AddComment("PtrEnd");
582 OS.EmitIntValue(0, 4);
583 OS.AddComment("PtrNext");
584 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000585 // This is the important bit that tells the debugger where the function
586 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000587 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000588 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000589 OS.AddComment("Offset after prologue");
590 OS.EmitIntValue(0, 4);
591 OS.AddComment("Offset before epilogue");
592 OS.EmitIntValue(0, 4);
593 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000594 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000595 OS.AddComment("Function section relative address");
596 OS.EmitCOFFSecRel32(Fn);
597 OS.AddComment("Function section index");
598 OS.EmitCOFFSectionIndex(Fn);
599 OS.AddComment("Flags");
600 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000601 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000602 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000603 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000604 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000605 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000606
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000607 for (const LocalVariable &Var : FI.Locals)
608 emitLocalVariable(Var);
609
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000610 // Emit inlined call site information. Only emit functions inlined directly
611 // into the parent function. We'll emit the other sites recursively as part
612 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000613 for (const DILocation *InlinedAt : FI.ChildSites) {
614 auto I = FI.InlineSites.find(InlinedAt);
615 assert(I != FI.InlineSites.end() &&
616 "child site not in function inline site map");
617 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000618 }
619
David Majnemer3128b102016-06-15 18:00:01 +0000620 if (SP != nullptr)
621 emitDebugInfoForUDTs(LocalUDTs);
622
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000623 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000624 OS.AddComment("Record length");
625 OS.EmitIntValue(0x0002, 2);
626 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000627 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000628 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000629 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000630
Reid Kleckner2214ed82016-01-29 00:49:42 +0000631 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000632 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000633}
634
Reid Kleckner876330d2016-02-12 21:48:30 +0000635CodeViewDebug::LocalVarDefRange
636CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
637 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +0000638 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +0000639 DR.DataOffset = Offset;
640 assert(DR.DataOffset == Offset && "truncation");
641 DR.StructOffset = 0;
642 DR.CVRegister = CVRegister;
643 return DR;
644}
645
646CodeViewDebug::LocalVarDefRange
647CodeViewDebug::createDefRangeReg(uint16_t CVRegister) {
648 LocalVarDefRange DR;
649 DR.InMemory = 0;
650 DR.DataOffset = 0;
651 DR.StructOffset = 0;
652 DR.CVRegister = CVRegister;
653 return DR;
654}
655
656void CodeViewDebug::collectVariableInfoFromMMITable(
657 DenseSet<InlinedVariable> &Processed) {
658 const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
659 const TargetFrameLowering *TFI = TSI.getFrameLowering();
660 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
661
662 for (const MachineModuleInfo::VariableDbgInfo &VI :
663 MMI->getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000664 if (!VI.Var)
665 continue;
666 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
667 "Expected inlined-at fields to agree");
668
Reid Kleckner876330d2016-02-12 21:48:30 +0000669 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000670 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
671
672 // If variable scope is not found then skip this variable.
673 if (!Scope)
674 continue;
675
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000676 // Get the frame register used and the offset.
677 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000678 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
679 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000680
681 // Calculate the label ranges.
Reid Kleckner876330d2016-02-12 21:48:30 +0000682 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000683 for (const InsnRange &Range : Scope->getRanges()) {
684 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
685 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +0000686 End = End ? End : Asm->getFunctionEnd();
687 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000688 }
689
Reid Kleckner876330d2016-02-12 21:48:30 +0000690 LocalVariable Var;
691 Var.DIVar = VI.Var;
692 Var.DefRanges.emplace_back(std::move(DefRange));
693 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
694 }
695}
696
697void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
698 DenseSet<InlinedVariable> Processed;
699 // Grab the variable info that was squirreled away in the MMI side-table.
700 collectVariableInfoFromMMITable(Processed);
701
702 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
703
704 for (const auto &I : DbgValues) {
705 InlinedVariable IV = I.first;
706 if (Processed.count(IV))
707 continue;
708 const DILocalVariable *DIVar = IV.first;
709 const DILocation *InlinedAt = IV.second;
710
711 // Instruction ranges, specifying where IV is accessible.
712 const auto &Ranges = I.second;
713
714 LexicalScope *Scope = nullptr;
715 if (InlinedAt)
716 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
717 else
718 Scope = LScopes.findLexicalScope(DIVar->getScope());
719 // If variable scope is not found then skip this variable.
720 if (!Scope)
721 continue;
722
723 LocalVariable Var;
724 Var.DIVar = DIVar;
725
726 // Calculate the definition ranges.
727 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
728 const InsnRange &Range = *I;
729 const MachineInstr *DVInst = Range.first;
730 assert(DVInst->isDebugValue() && "Invalid History entry");
731 const DIExpression *DIExpr = DVInst->getDebugExpression();
732
733 // Bail if there is a complex DWARF expression for now.
734 if (DIExpr && DIExpr->getNumElements() > 0)
735 continue;
736
Reid Kleckner9a593ee2016-02-16 21:49:26 +0000737 // Bail if operand 0 is not a valid register. This means the variable is a
738 // simple constant, or is described by a complex expression.
739 // FIXME: Find a way to represent constant variables, since they are
740 // relatively common.
741 unsigned Reg =
742 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
743 if (Reg == 0)
Reid Kleckner6e0d5f52016-02-16 21:14:51 +0000744 continue;
745
Reid Kleckner876330d2016-02-12 21:48:30 +0000746 // Handle the two cases we can handle: indirect in memory and in register.
747 bool IsIndirect = DVInst->getOperand(1).isImm();
748 unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg());
749 {
750 LocalVarDefRange DefRange;
751 if (IsIndirect) {
752 int64_t Offset = DVInst->getOperand(1).getImm();
753 DefRange = createDefRangeMem(CVReg, Offset);
754 } else {
755 DefRange = createDefRangeReg(CVReg);
756 }
757 if (Var.DefRanges.empty() ||
758 Var.DefRanges.back().isDifferentLocation(DefRange)) {
759 Var.DefRanges.emplace_back(std::move(DefRange));
760 }
761 }
762
763 // Compute the label range.
764 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
765 const MCSymbol *End = getLabelAfterInsn(Range.second);
766 if (!End) {
767 if (std::next(I) != E)
768 End = getLabelBeforeInsn(std::next(I)->first);
769 else
770 End = Asm->getFunctionEnd();
771 }
772
773 // If the last range end is our begin, just extend the last range.
774 // Otherwise make a new range.
775 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
776 Var.DefRanges.back().Ranges;
777 if (!Ranges.empty() && Ranges.back().second == Begin)
778 Ranges.back().second = End;
779 else
780 Ranges.emplace_back(Begin, End);
781
782 // FIXME: Do more range combining.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000783 }
Reid Kleckner876330d2016-02-12 21:48:30 +0000784
785 recordLocalVariable(std::move(Var), InlinedAt);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000786 }
787}
788
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000789void CodeViewDebug::beginFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000790 assert(!CurFn && "Can't process two functions at once!");
791
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000792 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000793 return;
794
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000795 DebugHandlerBase::beginFunction(MF);
796
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000797 const Function *GV = MF->getFunction();
798 assert(FnDebugInfo.count(GV) == false);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000799 CurFn = &FnDebugInfo[GV];
Reid Kleckner2214ed82016-01-29 00:49:42 +0000800 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000801 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000802
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000803 // Find the end of the function prolog. First known non-DBG_VALUE and
804 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000805 // FIXME: is there a simpler a way to do this? Can we just search
806 // for the first instruction of the function, not the last of the prolog?
807 DebugLoc PrologEndLoc;
808 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000809 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000810 for (const auto &MI : MBB) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000811 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
812 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000813 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000814 break;
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000815 } else if (!MI.isDebugValue()) {
816 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000817 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000818 }
819 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000820
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000821 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000822 if (PrologEndLoc && !EmptyPrologue) {
823 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000824 maybeRecordLocation(FnStartDL, MF);
825 }
826}
827
Amjad Aboud76c9eb92016-06-18 10:25:07 +0000828TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000829 // Generic dispatch for lowering an unknown type.
830 switch (Ty->getTag()) {
Adrian McCarthyf3c3c132016-06-08 18:22:59 +0000831 case dwarf::DW_TAG_array_type:
832 return lowerTypeArray(cast<DICompositeType>(Ty));
David Majnemerd065e232016-06-02 06:21:37 +0000833 case dwarf::DW_TAG_typedef:
834 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000835 case dwarf::DW_TAG_base_type:
836 return lowerTypeBasic(cast<DIBasicType>(Ty));
837 case dwarf::DW_TAG_pointer_type:
838 case dwarf::DW_TAG_reference_type:
839 case dwarf::DW_TAG_rvalue_reference_type:
840 return lowerTypePointer(cast<DIDerivedType>(Ty));
841 case dwarf::DW_TAG_ptr_to_member_type:
842 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
843 case dwarf::DW_TAG_const_type:
844 case dwarf::DW_TAG_volatile_type:
845 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +0000846 case dwarf::DW_TAG_subroutine_type:
Reid Kleckner0c5d8742016-06-22 01:32:56 +0000847 if (ClassTy) {
848 // The member function type of a member function pointer has no
849 // ThisAdjustment.
850 return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
851 /*ThisAdjustment=*/0);
852 }
David Majnemer75c3ebf2016-06-02 17:13:53 +0000853 return lowerTypeFunction(cast<DISubroutineType>(Ty));
David Majnemer979cb882016-06-16 21:32:16 +0000854 case dwarf::DW_TAG_enumeration_type:
855 return lowerTypeEnum(cast<DICompositeType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +0000856 case dwarf::DW_TAG_class_type:
857 case dwarf::DW_TAG_structure_type:
858 return lowerTypeClass(cast<DICompositeType>(Ty));
859 case dwarf::DW_TAG_union_type:
860 return lowerTypeUnion(cast<DICompositeType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000861 default:
862 // Use the null type index.
863 return TypeIndex();
864 }
865}
866
David Majnemerd065e232016-06-02 06:21:37 +0000867TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
David Majnemerd065e232016-06-02 06:21:37 +0000868 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
869 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
David Majnemer3128b102016-06-15 18:00:01 +0000870 StringRef TypeName = Ty->getName();
871
872 SmallVector<StringRef, 5> QualifiedNameComponents;
873 const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
874 Ty->getScope().resolve(), QualifiedNameComponents);
875
876 if (ClosestSubprogram == nullptr) {
877 std::string FullyQualifiedName =
878 getQualifiedName(QualifiedNameComponents, TypeName);
879 GlobalUDTs.emplace_back(std::move(FullyQualifiedName), UnderlyingTypeIndex);
880 } else if (ClosestSubprogram == CurrentSubprogram) {
881 std::string FullyQualifiedName =
882 getQualifiedName(QualifiedNameComponents, TypeName);
883 LocalUDTs.emplace_back(std::move(FullyQualifiedName), UnderlyingTypeIndex);
884 }
885 // TODO: What if the ClosestSubprogram is neither null or the current
886 // subprogram? Currently, the UDT just gets dropped on the floor.
887 //
888 // The current behavior is not desirable. To get maximal fidelity, we would
889 // need to perform all type translation before beginning emission of .debug$S
890 // and then make LocalUDTs a member of FunctionInfo
891
David Majnemerd065e232016-06-02 06:21:37 +0000892 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
David Majnemer3128b102016-06-15 18:00:01 +0000893 TypeName == "HRESULT")
David Majnemerd065e232016-06-02 06:21:37 +0000894 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +0000895 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
David Majnemer3128b102016-06-15 18:00:01 +0000896 TypeName == "wchar_t")
David Majnemer8c46a4c2016-06-04 15:40:33 +0000897 return TypeIndex(SimpleTypeKind::WideCharacter);
David Majnemerd065e232016-06-02 06:21:37 +0000898 return UnderlyingTypeIndex;
899}
900
Adrian McCarthyf3c3c132016-06-08 18:22:59 +0000901TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
902 DITypeRef ElementTypeRef = Ty->getBaseType();
903 TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
904 // IndexType is size_t, which depends on the bitness of the target.
905 TypeIndex IndexType = Asm->MAI->getPointerSize() == 8
906 ? TypeIndex(SimpleTypeKind::UInt64Quad)
907 : TypeIndex(SimpleTypeKind::UInt32Long);
908 uint64_t Size = Ty->getSizeInBits() / 8;
909 ArrayRecord Record(ElementTypeIndex, IndexType, Size, Ty->getName());
910 return TypeTable.writeArray(Record);
911}
912
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000913TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
914 TypeIndex Index;
915 dwarf::TypeKind Kind;
916 uint32_t ByteSize;
917
918 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +0000919 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000920
921 SimpleTypeKind STK = SimpleTypeKind::None;
922 switch (Kind) {
923 case dwarf::DW_ATE_address:
924 // FIXME: Translate
925 break;
926 case dwarf::DW_ATE_boolean:
927 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000928 case 1: STK = SimpleTypeKind::Boolean8; break;
929 case 2: STK = SimpleTypeKind::Boolean16; break;
930 case 4: STK = SimpleTypeKind::Boolean32; break;
931 case 8: STK = SimpleTypeKind::Boolean64; break;
932 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000933 }
934 break;
935 case dwarf::DW_ATE_complex_float:
936 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000937 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000938 case 4: STK = SimpleTypeKind::Complex32; break;
939 case 8: STK = SimpleTypeKind::Complex64; break;
940 case 10: STK = SimpleTypeKind::Complex80; break;
941 case 16: STK = SimpleTypeKind::Complex128; break;
942 }
943 break;
944 case dwarf::DW_ATE_float:
945 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000946 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000947 case 4: STK = SimpleTypeKind::Float32; break;
948 case 6: STK = SimpleTypeKind::Float48; break;
949 case 8: STK = SimpleTypeKind::Float64; break;
950 case 10: STK = SimpleTypeKind::Float80; break;
951 case 16: STK = SimpleTypeKind::Float128; break;
952 }
953 break;
954 case dwarf::DW_ATE_signed:
955 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000956 case 1: STK = SimpleTypeKind::SByte; break;
957 case 2: STK = SimpleTypeKind::Int16Short; break;
958 case 4: STK = SimpleTypeKind::Int32; break;
959 case 8: STK = SimpleTypeKind::Int64Quad; break;
960 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000961 }
962 break;
963 case dwarf::DW_ATE_unsigned:
964 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000965 case 1: STK = SimpleTypeKind::Byte; break;
966 case 2: STK = SimpleTypeKind::UInt16Short; break;
967 case 4: STK = SimpleTypeKind::UInt32; break;
968 case 8: STK = SimpleTypeKind::UInt64Quad; break;
969 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000970 }
971 break;
972 case dwarf::DW_ATE_UTF:
973 switch (ByteSize) {
974 case 2: STK = SimpleTypeKind::Character16; break;
975 case 4: STK = SimpleTypeKind::Character32; break;
976 }
977 break;
978 case dwarf::DW_ATE_signed_char:
979 if (ByteSize == 1)
980 STK = SimpleTypeKind::SignedCharacter;
981 break;
982 case dwarf::DW_ATE_unsigned_char:
983 if (ByteSize == 1)
984 STK = SimpleTypeKind::UnsignedCharacter;
985 break;
986 default:
987 break;
988 }
989
990 // Apply some fixups based on the source-level type name.
991 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
992 STK = SimpleTypeKind::Int32Long;
993 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
994 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +0000995 if (STK == SimpleTypeKind::UInt16Short &&
996 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000997 STK = SimpleTypeKind::WideCharacter;
998 if ((STK == SimpleTypeKind::SignedCharacter ||
999 STK == SimpleTypeKind::UnsignedCharacter) &&
1000 Ty->getName() == "char")
1001 STK = SimpleTypeKind::NarrowCharacter;
1002
1003 return TypeIndex(STK);
1004}
1005
1006TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1007 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1008
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001009 // While processing the type being pointed to it is possible we already
1010 // created this pointer type. If so, we check here and return the existing
1011 // pointer type.
1012 auto I = TypeIndices.find({Ty, nullptr});
1013 if (I != TypeIndices.end())
1014 return I->second;
1015
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001016 // Pointers to simple types can use SimpleTypeMode, rather than having a
1017 // dedicated pointer type record.
1018 if (PointeeTI.isSimple() &&
1019 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1020 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1021 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1022 ? SimpleTypeMode::NearPointer64
1023 : SimpleTypeMode::NearPointer32;
1024 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1025 }
1026
1027 PointerKind PK =
1028 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1029 PointerMode PM = PointerMode::Pointer;
1030 switch (Ty->getTag()) {
1031 default: llvm_unreachable("not a pointer tag type");
1032 case dwarf::DW_TAG_pointer_type:
1033 PM = PointerMode::Pointer;
1034 break;
1035 case dwarf::DW_TAG_reference_type:
1036 PM = PointerMode::LValueReference;
1037 break;
1038 case dwarf::DW_TAG_rvalue_reference_type:
1039 PM = PointerMode::RValueReference;
1040 break;
1041 }
1042 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1043 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1044 // do.
1045 PointerOptions PO = PointerOptions::None;
1046 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1047 return TypeTable.writePointer(PR);
1048}
1049
Reid Kleckner6fa15462016-06-17 22:14:39 +00001050static PointerToMemberRepresentation
1051translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1052 // SizeInBytes being zero generally implies that the member pointer type was
1053 // incomplete, which can happen if it is part of a function prototype. In this
1054 // case, use the unknown model instead of the general model.
Reid Kleckner604105b2016-06-17 21:31:33 +00001055 if (IsPMF) {
1056 switch (Flags & DINode::FlagPtrToMemberRep) {
1057 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001058 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1059 : PointerToMemberRepresentation::GeneralFunction;
Reid Kleckner604105b2016-06-17 21:31:33 +00001060 case DINode::FlagSingleInheritance:
1061 return PointerToMemberRepresentation::SingleInheritanceFunction;
1062 case DINode::FlagMultipleInheritance:
1063 return PointerToMemberRepresentation::MultipleInheritanceFunction;
1064 case DINode::FlagVirtualInheritance:
1065 return PointerToMemberRepresentation::VirtualInheritanceFunction;
1066 }
1067 } else {
1068 switch (Flags & DINode::FlagPtrToMemberRep) {
1069 case 0:
Reid Kleckner6fa15462016-06-17 22:14:39 +00001070 return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1071 : PointerToMemberRepresentation::GeneralData;
Reid Kleckner604105b2016-06-17 21:31:33 +00001072 case DINode::FlagSingleInheritance:
1073 return PointerToMemberRepresentation::SingleInheritanceData;
1074 case DINode::FlagMultipleInheritance:
1075 return PointerToMemberRepresentation::MultipleInheritanceData;
1076 case DINode::FlagVirtualInheritance:
1077 return PointerToMemberRepresentation::VirtualInheritanceData;
1078 }
1079 }
1080 llvm_unreachable("invalid ptr to member representation");
1081}
1082
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001083TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1084 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1085 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001086 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001087 PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64
1088 : PointerKind::Near32;
Reid Kleckner604105b2016-06-17 21:31:33 +00001089 bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1090 PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1091 : PointerMode::PointerToDataMember;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001092 PointerOptions PO = PointerOptions::None; // FIXME
Reid Kleckner6fa15462016-06-17 22:14:39 +00001093 assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1094 uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1095 MemberPointerInfo MPI(
1096 ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
Reid Kleckner604105b2016-06-17 21:31:33 +00001097 PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001098 return TypeTable.writePointer(PR);
1099}
1100
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001101/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1102/// have a translation, use the NearC convention.
1103static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1104 switch (DwarfCC) {
1105 case dwarf::DW_CC_normal: return CallingConvention::NearC;
1106 case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1107 case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
1108 case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
1109 case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
1110 case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
1111 }
1112 return CallingConvention::NearC;
1113}
1114
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001115TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1116 ModifierOptions Mods = ModifierOptions::None;
1117 bool IsModifier = true;
1118 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +00001119 while (IsModifier && BaseTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001120 // FIXME: Need to add DWARF tag for __unaligned.
1121 switch (BaseTy->getTag()) {
1122 case dwarf::DW_TAG_const_type:
1123 Mods |= ModifierOptions::Const;
1124 break;
1125 case dwarf::DW_TAG_volatile_type:
1126 Mods |= ModifierOptions::Volatile;
1127 break;
1128 default:
1129 IsModifier = false;
1130 break;
1131 }
1132 if (IsModifier)
1133 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1134 }
1135 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001136
1137 // While processing the type being pointed to, it is possible we already
1138 // created this modifier type. If so, we check here and return the existing
1139 // modifier type.
1140 auto I = TypeIndices.find({Ty, nullptr});
1141 if (I != TypeIndices.end())
1142 return I->second;
1143
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001144 ModifierRecord MR(ModifiedTI, Mods);
1145 return TypeTable.writeModifier(MR);
1146}
1147
David Majnemer75c3ebf2016-06-02 17:13:53 +00001148TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1149 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1150 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1151 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1152
1153 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1154 ArrayRef<TypeIndex> ArgTypeIndices = None;
1155 if (!ReturnAndArgTypeIndices.empty()) {
1156 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1157 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1158 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1159 }
1160
1161 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1162 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec);
1163
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001164 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1165
Reid Klecknerde3d8b52016-06-08 20:34:29 +00001166 ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1167 ArgTypeIndices.size(), ArgListIndex);
David Majnemer75c3ebf2016-06-02 17:13:53 +00001168 return TypeTable.writeProcedure(Procedure);
1169}
1170
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001171TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001172 const DIType *ClassTy,
1173 int ThisAdjustment) {
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001174 // Lower the containing class type.
1175 TypeIndex ClassType = getTypeIndex(ClassTy);
1176
1177 // While processing the class type it is possible we already created this
1178 // member function. If so, we check here and return the existing one.
1179 auto I = TypeIndices.find({Ty, ClassTy});
1180 if (I != TypeIndices.end())
1181 return I->second;
1182
1183 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1184 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1185 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1186
1187 TypeIndex ReturnTypeIndex = TypeIndex::Void();
1188 ArrayRef<TypeIndex> ArgTypeIndices = None;
1189 if (!ReturnAndArgTypeIndices.empty()) {
1190 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1191 ReturnTypeIndex = ReturnAndArgTypesRef.front();
1192 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1193 }
1194 TypeIndex ThisTypeIndex = TypeIndex::Void();
1195 if (!ArgTypeIndices.empty()) {
1196 ThisTypeIndex = ArgTypeIndices.front();
1197 ArgTypeIndices = ArgTypeIndices.drop_front();
1198 }
1199
1200 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1201 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec);
1202
1203 CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1204
1205 // TODO: Need to use the correct values for:
1206 // FunctionOptions
1207 // ThisPointerAdjustment.
1208 TypeIndex TI = TypeTable.writeMemberFunction(MemberFunctionRecord(
1209 ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FunctionOptions::None,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001210 ArgTypeIndices.size(), ArgListIndex, ThisAdjustment));
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001211
1212 return TI;
1213}
1214
1215static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1216 switch (Flags & DINode::FlagAccessibility) {
Reid Klecknera8d57402016-06-03 15:58:20 +00001217 case DINode::FlagPrivate: return MemberAccess::Private;
1218 case DINode::FlagPublic: return MemberAccess::Public;
1219 case DINode::FlagProtected: return MemberAccess::Protected;
1220 case 0:
1221 // If there was no explicit access control, provide the default for the tag.
1222 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1223 : MemberAccess::Public;
1224 }
1225 llvm_unreachable("access flags are exclusive");
1226}
1227
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001228static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1229 if (SP->isArtificial())
1230 return MethodOptions::CompilerGenerated;
1231
1232 // FIXME: Handle other MethodOptions.
1233
1234 return MethodOptions::None;
1235}
1236
1237static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1238 bool Introduced) {
1239 switch (SP->getVirtuality()) {
1240 case dwarf::DW_VIRTUALITY_none:
1241 break;
1242 case dwarf::DW_VIRTUALITY_virtual:
1243 return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1244 case dwarf::DW_VIRTUALITY_pure_virtual:
1245 return Introduced ? MethodKind::PureIntroducingVirtual
1246 : MethodKind::PureVirtual;
1247 default:
1248 llvm_unreachable("unhandled virtuality case");
1249 }
1250
1251 // FIXME: Get Clang to mark DISubprogram as static and do something with it.
1252
1253 return MethodKind::Vanilla;
1254}
1255
Reid Klecknera8d57402016-06-03 15:58:20 +00001256static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1257 switch (Ty->getTag()) {
1258 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
1259 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1260 }
1261 llvm_unreachable("unexpected tag");
1262}
1263
1264/// Return the HasUniqueName option if it should be present in ClassOptions, or
1265/// None otherwise.
1266static ClassOptions getRecordUniqueNameOption(const DICompositeType *Ty) {
1267 // MSVC always sets this flag now, even for local types. Clang doesn't always
1268 // appear to give every type a linkage name, which may be problematic for us.
1269 // FIXME: Investigate the consequences of not following them here.
1270 return !Ty->getIdentifier().empty() ? ClassOptions::HasUniqueName
1271 : ClassOptions::None;
1272}
1273
David Majnemer979cb882016-06-16 21:32:16 +00001274TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
1275 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
1276 TypeIndex FTI;
David Majnemerda9548f2016-06-17 16:13:21 +00001277 unsigned EnumeratorCount = 0;
David Majnemer979cb882016-06-16 21:32:16 +00001278
David Majnemerda9548f2016-06-17 16:13:21 +00001279 if (Ty->isForwardDecl()) {
David Majnemer979cb882016-06-16 21:32:16 +00001280 CO |= ClassOptions::ForwardReference;
David Majnemerda9548f2016-06-17 16:13:21 +00001281 } else {
1282 FieldListRecordBuilder Fields;
1283 for (const DINode *Element : Ty->getElements()) {
1284 // We assume that the frontend provides all members in source declaration
1285 // order, which is what MSVC does.
1286 if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
1287 Fields.writeEnumerator(EnumeratorRecord(
1288 MemberAccess::Public, APSInt::getUnsigned(Enumerator->getValue()),
1289 Enumerator->getName()));
1290 EnumeratorCount++;
1291 }
1292 }
1293 FTI = TypeTable.writeFieldList(Fields);
1294 }
David Majnemer979cb882016-06-16 21:32:16 +00001295
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001296 std::string FullName =
1297 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
1298
1299 return TypeTable.writeEnum(EnumRecord(EnumeratorCount, CO, FTI, FullName,
David Majnemer979cb882016-06-16 21:32:16 +00001300 Ty->getIdentifier(),
1301 getTypeIndex(Ty->getBaseType())));
1302}
1303
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001304//===----------------------------------------------------------------------===//
1305// ClassInfo
1306//===----------------------------------------------------------------------===//
1307
1308struct llvm::ClassInfo {
1309 struct MemberInfo {
1310 const DIDerivedType *MemberTypeNode;
1311 unsigned BaseOffset;
1312 };
1313 // [MemberInfo]
1314 typedef std::vector<MemberInfo> MemberList;
1315
1316 struct MethodInfo {
1317 const DISubprogram *Method;
1318 bool Introduced;
1319 };
1320 // [MethodInfo]
1321 typedef std::vector<MethodInfo> MethodsList;
1322 // MethodName -> MethodsList
1323 typedef MapVector<MDString *, MethodsList> MethodsMap;
1324
1325 /// Direct members.
1326 MemberList Members;
1327 // Direct overloaded methods gathered by name.
1328 MethodsMap Methods;
1329};
1330
1331void CodeViewDebug::clear() {
1332 assert(CurFn == nullptr);
1333 FileIdMap.clear();
1334 FnDebugInfo.clear();
1335 FileToFilepathMap.clear();
1336 LocalUDTs.clear();
1337 GlobalUDTs.clear();
1338 TypeIndices.clear();
1339 CompleteTypeIndices.clear();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001340}
1341
1342void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1343 const DIDerivedType *DDTy) {
1344 if (!DDTy->getName().empty()) {
1345 Info.Members.push_back({DDTy, 0});
1346 return;
1347 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001348 // An unnamed member must represent a nested struct or union. Add all the
1349 // indirect fields to the current record.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001350 assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001351 unsigned Offset = DDTy->getOffsetInBits() / 8;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001352 const DIType *Ty = DDTy->getBaseType().resolve();
Reid Kleckner9ff936c2016-06-21 14:56:24 +00001353 const DICompositeType *DCTy = cast<DICompositeType>(Ty);
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001354 ClassInfo NestedInfo = collectClassInfo(DCTy);
1355 for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001356 Info.Members.push_back(
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001357 {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001358}
1359
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001360ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1361 ClassInfo Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001362 // Add elements to structure type.
1363 DINodeArray Elements = Ty->getElements();
1364 for (auto *Element : Elements) {
1365 // We assume that the frontend provides all members in source declaration
1366 // order, which is what MSVC does.
1367 if (!Element)
1368 continue;
1369 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
1370 // Non-virtual methods does not need the introduced marker.
1371 // Set it to false.
1372 bool Introduced = false;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001373 Info.Methods[SP->getRawName()].push_back({SP, Introduced});
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001374 } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
1375 if (DDTy->getTag() == dwarf::DW_TAG_member)
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001376 collectMemberInfo(Info, DDTy);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001377 else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1378 // FIXME: collect class info from inheritance.
1379 } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1380 // Ignore friend members. It appears that MSVC emitted info about
1381 // friends in the past, but modern versions do not.
1382 }
1383 // FIXME: Get Clang to emit function virtual table here and handle it.
1384 // FIXME: Get clang to emit nested types here and do something with
1385 // them.
1386 }
1387 // Skip other unrecognized kinds of elements.
1388 }
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001389 return Info;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001390}
1391
Reid Klecknera8d57402016-06-03 15:58:20 +00001392TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1393 // First, construct the forward decl. Don't look into Ty to compute the
1394 // forward decl options, since it might not be available in all TUs.
1395 TypeRecordKind Kind = getRecordKind(Ty);
1396 ClassOptions CO =
1397 ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001398 std::string FullName =
1399 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
Reid Klecknera8d57402016-06-03 15:58:20 +00001400 TypeIndex FwdDeclTI = TypeTable.writeClass(ClassRecord(
1401 Kind, 0, CO, HfaKind::None, WindowsRTClassKind::None, TypeIndex(),
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001402 TypeIndex(), TypeIndex(), 0, FullName, Ty->getIdentifier()));
Reid Klecknera8d57402016-06-03 15:58:20 +00001403 return FwdDeclTI;
1404}
1405
1406TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1407 // Construct the field list and complete type record.
1408 TypeRecordKind Kind = getRecordKind(Ty);
1409 // FIXME: Other ClassOptions, like ContainsNestedClass and NestedClass.
1410 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001411 TypeIndex FieldTI;
1412 TypeIndex VShapeTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001413 unsigned FieldCount;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001414 std::tie(FieldTI, VShapeTI, FieldCount) = lowerRecordFieldList(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001415
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001416 std::string FullName =
1417 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
1418
Reid Klecknera8d57402016-06-03 15:58:20 +00001419 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001420 return TypeTable.writeClass(ClassRecord(
1421 Kind, FieldCount, CO, HfaKind::None, WindowsRTClassKind::None, FieldTI,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001422 TypeIndex(), VShapeTI, SizeInBytes, FullName, Ty->getIdentifier()));
Reid Klecknera8d57402016-06-03 15:58:20 +00001423 // FIXME: Make an LF_UDT_SRC_LINE record.
1424}
1425
1426TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1427 ClassOptions CO =
1428 ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty);
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001429 std::string FullName =
1430 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
Reid Klecknera8d57402016-06-03 15:58:20 +00001431 TypeIndex FwdDeclTI =
1432 TypeTable.writeUnion(UnionRecord(0, CO, HfaKind::None, TypeIndex(), 0,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001433 FullName, Ty->getIdentifier()));
Reid Klecknera8d57402016-06-03 15:58:20 +00001434 return FwdDeclTI;
1435}
1436
1437TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
1438 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001439 TypeIndex FieldTI;
Reid Klecknera8d57402016-06-03 15:58:20 +00001440 unsigned FieldCount;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001441 std::tie(FieldTI, std::ignore, FieldCount) = lowerRecordFieldList(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001442 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001443 std::string FullName =
1444 getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001445 return TypeTable.writeUnion(UnionRecord(FieldCount, CO, HfaKind::None,
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001446 FieldTI, SizeInBytes, FullName,
Reid Klecknera8d57402016-06-03 15:58:20 +00001447 Ty->getIdentifier()));
1448 // FIXME: Make an LF_UDT_SRC_LINE record.
1449}
1450
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001451std::tuple<TypeIndex, TypeIndex, unsigned>
Reid Klecknera8d57402016-06-03 15:58:20 +00001452CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1453 // Manually count members. MSVC appears to count everything that generates a
1454 // field list record. Each individual overload in a method overload group
1455 // contributes to this count, even though the overload group is a single field
1456 // list record.
1457 unsigned MemberCount = 0;
Reid Kleckner1ab7eac2016-06-22 16:06:42 +00001458 ClassInfo Info = collectClassInfo(Ty);
Reid Klecknera8d57402016-06-03 15:58:20 +00001459 FieldListRecordBuilder Fields;
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001460
1461 // Create members.
1462 for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1463 const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1464 TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
1465
1466 if (Member->isStaticMember()) {
1467 Fields.writeStaticDataMember(StaticDataMemberRecord(
1468 translateAccessFlags(Ty->getTag(), Member->getFlags()),
1469 MemberBaseType, Member->getName()));
1470 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001471 continue;
Reid Klecknera8d57402016-06-03 15:58:20 +00001472 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001473
1474 uint64_t OffsetInBytes = MemberInfo.BaseOffset;
1475
1476 // FIXME: Handle bitfield type memeber.
1477 OffsetInBytes += Member->getOffsetInBits() / 8;
1478
1479 Fields.writeDataMember(
1480 DataMemberRecord(translateAccessFlags(Ty->getTag(), Member->getFlags()),
1481 MemberBaseType, OffsetInBytes, Member->getName()));
1482 MemberCount++;
Reid Klecknera8d57402016-06-03 15:58:20 +00001483 }
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001484
1485 // Create methods
1486 for (auto &MethodItr : Info.Methods) {
1487 StringRef Name = MethodItr.first->getString();
1488
1489 std::vector<OneMethodRecord> Methods;
1490 for (ClassInfo::MethodInfo &MethodInfo : MethodItr.second) {
1491 const DISubprogram *SP = MethodInfo.Method;
1492 bool Introduced = MethodInfo.Introduced;
1493
1494 TypeIndex MethodType = getTypeIndex(SP->getType(), Ty);
1495
1496 unsigned VFTableOffset = -1;
1497 if (Introduced)
1498 VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
1499
1500 Methods.push_back(
1501 OneMethodRecord(MethodType, translateMethodKindFlags(SP, Introduced),
1502 translateMethodOptionFlags(SP),
1503 translateAccessFlags(Ty->getTag(), SP->getFlags()),
1504 VFTableOffset, Name));
1505 MemberCount++;
1506 }
1507 assert(Methods.size() > 0 && "Empty methods map entry");
1508 if (Methods.size() == 1)
1509 Fields.writeOneMethod(Methods[0]);
1510 else {
1511 TypeIndex MethodList =
1512 TypeTable.writeMethodOverloadList(MethodOverloadListRecord(Methods));
1513 Fields.writeOverloadedMethod(
1514 OverloadedMethodRecord(Methods.size(), MethodList, Name));
1515 }
1516 }
1517 TypeIndex FieldTI = TypeTable.writeFieldList(Fields);
1518 return std::make_tuple(FieldTI, TypeIndex(), MemberCount);
Reid Klecknera8d57402016-06-03 15:58:20 +00001519}
1520
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001521TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001522 const DIType *Ty = TypeRef.resolve();
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001523 const DIType *ClassTy = ClassTyRef.resolve();
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001524
1525 // The null DIType is the void type. Don't try to hash it.
1526 if (!Ty)
1527 return TypeIndex::Void();
1528
Reid Klecknera8d57402016-06-03 15:58:20 +00001529 // Check if we've already translated this type. Don't try to do a
1530 // get-or-create style insertion that caches the hash lookup across the
1531 // lowerType call. It will update the TypeIndices map.
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001532 auto I = TypeIndices.find({Ty, ClassTy});
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001533 if (I != TypeIndices.end())
1534 return I->second;
1535
Amjad Aboud76c9eb92016-06-18 10:25:07 +00001536 TypeIndex TI = lowerType(Ty, ClassTy);
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001537
Reid Kleckner0c5d8742016-06-22 01:32:56 +00001538 return recordTypeIndexForDINode(Ty, TI, ClassTy);
Reid Klecknera8d57402016-06-03 15:58:20 +00001539}
1540
1541TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1542 const DIType *Ty = TypeRef.resolve();
1543
1544 // The null DIType is the void type. Don't try to hash it.
1545 if (!Ty)
1546 return TypeIndex::Void();
1547
1548 // If this is a non-record type, the complete type index is the same as the
1549 // normal type index. Just call getTypeIndex.
1550 switch (Ty->getTag()) {
1551 case dwarf::DW_TAG_class_type:
1552 case dwarf::DW_TAG_structure_type:
1553 case dwarf::DW_TAG_union_type:
1554 break;
1555 default:
1556 return getTypeIndex(Ty);
1557 }
1558
1559 // Check if we've already translated the complete record type. Lowering a
1560 // complete type should never trigger lowering another complete type, so we
1561 // can reuse the hash table lookup result.
1562 const auto *CTy = cast<DICompositeType>(Ty);
1563 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1564 if (!InsertResult.second)
1565 return InsertResult.first->second;
1566
1567 // Make sure the forward declaration is emitted first. It's unclear if this
1568 // is necessary, but MSVC does it, and we should follow suit until we can show
1569 // otherwise.
1570 TypeIndex FwdDeclTI = getTypeIndex(CTy);
1571
1572 // Just use the forward decl if we don't have complete type info. This might
1573 // happen if the frontend is using modules and expects the complete definition
1574 // to be emitted elsewhere.
1575 if (CTy->isForwardDecl())
1576 return FwdDeclTI;
1577
1578 TypeIndex TI;
1579 switch (CTy->getTag()) {
1580 case dwarf::DW_TAG_class_type:
1581 case dwarf::DW_TAG_structure_type:
1582 TI = lowerCompleteTypeClass(CTy);
1583 break;
1584 case dwarf::DW_TAG_union_type:
1585 TI = lowerCompleteTypeUnion(CTy);
1586 break;
1587 default:
1588 llvm_unreachable("not a record");
1589 }
1590
1591 InsertResult.first->second = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001592 return TI;
1593}
1594
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001595void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
1596 // LocalSym record, see SymbolRecord.h for more info.
1597 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
1598 *LocalEnd = MMI->getContext().createTempSymbol();
1599 OS.AddComment("Record length");
1600 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
1601 OS.EmitLabel(LocalBegin);
1602
1603 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00001604 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001605
Zachary Turner63a28462016-05-17 23:50:21 +00001606 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001607 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00001608 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00001609 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00001610 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001611
1612 OS.AddComment("TypeIndex");
Reid Klecknera8d57402016-06-03 15:58:20 +00001613 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001614 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001615 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00001616 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00001617 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00001618 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001619 OS.EmitLabel(LocalEnd);
1620
Reid Kleckner876330d2016-02-12 21:48:30 +00001621 // Calculate the on disk prefix of the appropriate def range record. The
1622 // records and on disk formats are described in SymbolRecords.h. BytePrefix
1623 // should be big enough to hold all forms without memory allocation.
1624 SmallString<20> BytePrefix;
1625 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
1626 BytePrefix.clear();
1627 // FIXME: Handle bitpieces.
1628 if (DefRange.StructOffset != 0)
1629 continue;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001630
Reid Kleckner876330d2016-02-12 21:48:30 +00001631 if (DefRange.InMemory) {
Zachary Turnera78ecd12016-05-23 18:49:06 +00001632 DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0,
1633 0, 0, ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00001634 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00001635 BytePrefix +=
1636 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00001637 BytePrefix +=
1638 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1639 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00001640 } else {
1641 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Zachary Turnera78ecd12016-05-23 18:49:06 +00001642 // Unclear what matters here.
1643 DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0,
1644 ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00001645 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
Reid Kleckner876330d2016-02-12 21:48:30 +00001646 BytePrefix +=
1647 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00001648 BytePrefix +=
1649 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1650 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00001651 }
1652 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
1653 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001654}
1655
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001656void CodeViewDebug::endFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001657 if (!Asm || !CurFn) // We haven't created any debug info for this function.
1658 return;
1659
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001660 const Function *GV = MF->getFunction();
Yaron Keren6d3194f2014-06-20 10:26:56 +00001661 assert(FnDebugInfo.count(GV));
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001662 assert(CurFn == &FnDebugInfo[GV]);
1663
Pete Cooperadebb932016-03-11 02:14:16 +00001664 collectVariableInfo(GV->getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00001665
1666 DebugHandlerBase::endFunction(MF);
1667
Reid Kleckner2214ed82016-01-29 00:49:42 +00001668 // Don't emit anything if we don't have any line tables.
1669 if (!CurFn->HaveLineInfo) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001670 FnDebugInfo.erase(GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001671 CurFn = nullptr;
1672 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00001673 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001674
1675 CurFn->End = Asm->getFunctionEnd();
1676
Craig Topper353eda42014-04-24 06:44:33 +00001677 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001678}
1679
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001680void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001681 DebugHandlerBase::beginInstruction(MI);
1682
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001683 // Ignore DBG_VALUE locations and function prologue.
1684 if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup))
1685 return;
1686 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001687 if (DL == PrevInstLoc || !DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001688 return;
1689 maybeRecordLocation(DL, Asm->MF);
1690}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001691
1692MCSymbol *CodeViewDebug::beginCVSubsection(ModuleSubstreamKind Kind) {
1693 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
1694 *EndLabel = MMI->getContext().createTempSymbol();
1695 OS.EmitIntValue(unsigned(Kind), 4);
1696 OS.AddComment("Subsection size");
1697 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
1698 OS.EmitLabel(BeginLabel);
1699 return EndLabel;
1700}
1701
1702void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
1703 OS.EmitLabel(EndLabel);
1704 // Every subsection must be aligned to a 4-byte boundary.
1705 OS.EmitValueToAlignment(4);
1706}
1707
David Majnemer3128b102016-06-15 18:00:01 +00001708void CodeViewDebug::emitDebugInfoForUDTs(
1709 ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
1710 for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
1711 MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
1712 *UDTRecordEnd = MMI->getContext().createTempSymbol();
1713 OS.AddComment("Record length");
1714 OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
1715 OS.EmitLabel(UDTRecordBegin);
1716
1717 OS.AddComment("Record kind: S_UDT");
1718 OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
1719
1720 OS.AddComment("Type");
1721 OS.EmitIntValue(UDT.second.getIndex(), 4);
1722
1723 emitNullTerminatedSymbolName(OS, UDT.first);
1724 OS.EmitLabel(UDTRecordEnd);
1725 }
1726}
1727
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001728void CodeViewDebug::emitDebugInfoForGlobals() {
1729 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
1730 for (const MDNode *Node : CUs->operands()) {
1731 const auto *CU = cast<DICompileUnit>(Node);
1732
1733 // First, emit all globals that are not in a comdat in a single symbol
1734 // substream. MSVC doesn't like it if the substream is empty, so only open
1735 // it if we have at least one global to emit.
1736 switchToDebugSectionForSymbol(nullptr);
1737 MCSymbol *EndLabel = nullptr;
1738 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
Reid Kleckner6d1d2752016-06-09 00:29:00 +00001739 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
David Majnemer577be0f2016-06-15 00:19:52 +00001740 if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001741 if (!EndLabel) {
1742 OS.AddComment("Symbol subsection for globals");
1743 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
1744 }
1745 emitDebugInfoForGlobal(G, Asm->getSymbol(GV));
1746 }
Reid Kleckner6d1d2752016-06-09 00:29:00 +00001747 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001748 }
1749 if (EndLabel)
1750 endCVSubsection(EndLabel);
1751
1752 // Second, emit each global that is in a comdat into its own .debug$S
1753 // section along with its own symbol substream.
1754 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
Reid Kleckner6d1d2752016-06-09 00:29:00 +00001755 if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001756 if (GV->hasComdat()) {
1757 MCSymbol *GVSym = Asm->getSymbol(GV);
1758 OS.AddComment("Symbol subsection for " +
1759 Twine(GlobalValue::getRealLinkageName(GV->getName())));
1760 switchToDebugSectionForSymbol(GVSym);
1761 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
1762 emitDebugInfoForGlobal(G, GVSym);
1763 endCVSubsection(EndLabel);
1764 }
1765 }
1766 }
1767 }
1768}
1769
1770void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
1771 MCSymbol *GVSym) {
1772 // DataSym record, see SymbolRecord.h for more info.
1773 // FIXME: Thread local data, etc
1774 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
1775 *DataEnd = MMI->getContext().createTempSymbol();
1776 OS.AddComment("Record length");
1777 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
1778 OS.EmitLabel(DataBegin);
1779 OS.AddComment("Record kind: S_GDATA32");
1780 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
1781 OS.AddComment("Type");
1782 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
1783 OS.AddComment("DataOffset");
1784 OS.EmitCOFFSecRel32(GVSym);
1785 OS.AddComment("Segment");
1786 OS.EmitCOFFSectionIndex(GVSym);
1787 OS.AddComment("Name");
1788 emitNullTerminatedSymbolName(OS, DIGV->getName());
1789 OS.EmitLabel(DataEnd);
1790}