blob: db1dc519ed57613fc5d2beeabea2e92002d53f3e [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/TargetSubtargetInfo.h"
28#include "llvm/Target/TargetRegisterInfo.h"
29#include "llvm/Target/TargetFrameLowering.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
David Majnemer75c3ebf2016-06-02 17:13:53 +0000126TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
127 // It's possible to ask for the FuncId of a function which doesn't have a
128 // subprogram: inlining a function with debug info into a function with none.
129 if (!SP)
David Majnemerb68f32f02016-06-02 18:51:24 +0000130 return TypeIndex::None();
Reid Kleckner2280f932016-05-23 20:23:46 +0000131
David Majnemer75c3ebf2016-06-02 17:13:53 +0000132 // Check if we've already translated this subprogram.
133 auto I = TypeIndices.find(SP);
134 if (I != TypeIndices.end())
135 return I->second;
Reid Kleckner2280f932016-05-23 20:23:46 +0000136
Reid Kleckner2280f932016-05-23 20:23:46 +0000137 TypeIndex ParentScope = TypeIndex(0);
138 StringRef DisplayName = SP->getDisplayName();
David Majnemer75c3ebf2016-06-02 17:13:53 +0000139 FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
Reid Kleckner2280f932016-05-23 20:23:46 +0000140 TypeIndex TI = TypeTable.writeFuncId(FuncId);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000141
Reid Klecknera8d57402016-06-03 15:58:20 +0000142 recordTypeIndexForDINode(SP, TI);
David Majnemer75c3ebf2016-06-02 17:13:53 +0000143 return TI;
Reid Kleckner2280f932016-05-23 20:23:46 +0000144}
145
Reid Klecknera8d57402016-06-03 15:58:20 +0000146void CodeViewDebug::recordTypeIndexForDINode(const DINode *Node, TypeIndex TI) {
147 auto InsertResult = TypeIndices.insert({Node, TI});
148 (void)InsertResult;
149 assert(InsertResult.second && "DINode was already assigned a type index");
150}
151
Reid Kleckner876330d2016-02-12 21:48:30 +0000152void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
153 const DILocation *InlinedAt) {
154 if (InlinedAt) {
155 // This variable was inlined. Associate it with the InlineSite.
156 const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
157 InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
158 Site.InlinedLocals.emplace_back(Var);
159 } else {
160 // This variable goes in the main ProcSym.
161 CurFn->Locals.emplace_back(Var);
162 }
163}
164
Reid Kleckner829365a2016-02-11 19:41:47 +0000165static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
166 const DILocation *Loc) {
167 auto B = Locs.begin(), E = Locs.end();
168 if (std::find(B, E, Loc) == E)
169 Locs.push_back(Loc);
170}
171
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000172void CodeViewDebug::maybeRecordLocation(DebugLoc DL,
Reid Kleckner9533af42016-01-16 00:09:09 +0000173 const MachineFunction *MF) {
174 // Skip this instruction if it has the same location as the previous one.
175 if (DL == CurFn->LastLoc)
176 return;
177
178 const DIScope *Scope = DL.get()->getScope();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000179 if (!Scope)
180 return;
Reid Kleckner9533af42016-01-16 00:09:09 +0000181
David Majnemerc3340db2016-01-13 01:05:23 +0000182 // Skip this line if it is longer than the maximum we can record.
Reid Kleckner2214ed82016-01-29 00:49:42 +0000183 LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
184 if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
185 LI.isNeverStepInto())
David Majnemerc3340db2016-01-13 01:05:23 +0000186 return;
187
Reid Kleckner2214ed82016-01-29 00:49:42 +0000188 ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
189 if (CI.getStartColumn() != DL.getCol())
190 return;
Reid Kleckner00d96392016-01-29 00:13:28 +0000191
Reid Kleckner2214ed82016-01-29 00:49:42 +0000192 if (!CurFn->HaveLineInfo)
193 CurFn->HaveLineInfo = true;
194 unsigned FileId = 0;
195 if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
196 FileId = CurFn->LastFileId;
197 else
198 FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
199 CurFn->LastLoc = DL;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000200
201 unsigned FuncId = CurFn->FuncId;
Reid Kleckner876330d2016-02-12 21:48:30 +0000202 if (const DILocation *SiteLoc = DL->getInlinedAt()) {
Reid Kleckner829365a2016-02-11 19:41:47 +0000203 const DILocation *Loc = DL.get();
204
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000205 // If this location was actually inlined from somewhere else, give it the ID
206 // of the inline call site.
Reid Kleckner876330d2016-02-12 21:48:30 +0000207 FuncId =
208 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
Reid Kleckner829365a2016-02-11 19:41:47 +0000209
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000210 // Ensure we have links in the tree of inline call sites.
Reid Kleckner829365a2016-02-11 19:41:47 +0000211 bool FirstLoc = true;
212 while ((SiteLoc = Loc->getInlinedAt())) {
Reid Kleckner876330d2016-02-12 21:48:30 +0000213 InlineSite &Site =
214 getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
Reid Kleckner829365a2016-02-11 19:41:47 +0000215 if (!FirstLoc)
216 addLocIfNotPresent(Site.ChildSites, Loc);
217 FirstLoc = false;
218 Loc = SiteLoc;
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000219 }
Reid Kleckner829365a2016-02-11 19:41:47 +0000220 addLocIfNotPresent(CurFn->ChildSites, Loc);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000221 }
222
Reid Klecknerdac21b42016-02-03 21:15:48 +0000223 OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
224 /*PrologueEnd=*/false,
225 /*IsStmt=*/false, DL->getFilename());
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000226}
227
Reid Kleckner5d122f82016-05-25 23:16:12 +0000228void CodeViewDebug::emitCodeViewMagicVersion() {
229 OS.EmitValueToAlignment(4);
230 OS.AddComment("Debug section magic");
231 OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
232}
233
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000234void CodeViewDebug::endModule() {
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000235 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000236 return;
237
238 assert(Asm != nullptr);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000239
240 // The COFF .debug$S section consists of several subsections, each starting
241 // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
242 // of the payload followed by the payload itself. The subsections are 4-byte
243 // aligned.
244
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000245 // Use the generic .debug$S section, and make a subsection for all the inlined
246 // subprograms.
247 switchToDebugSectionForSymbol(nullptr);
Reid Kleckner5d122f82016-05-25 23:16:12 +0000248 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000249
Reid Kleckner2214ed82016-01-29 00:49:42 +0000250 // Emit per-function debug information.
251 for (auto &P : FnDebugInfo)
252 emitDebugInfoForFunction(P.first, P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000253
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000254 // Emit global variable debug information.
255 emitDebugInfoForGlobals();
256
Reid Kleckner5d122f82016-05-25 23:16:12 +0000257 // Switch back to the generic .debug$S section after potentially processing
258 // comdat symbol sections.
259 switchToDebugSectionForSymbol(nullptr);
260
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000261 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000262 OS.AddComment("File index to string table offset subsection");
263 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000264
265 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000266 OS.AddComment("String table");
267 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000268
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000269 // Emit type information last, so that any types we translate while emitting
270 // function info are included.
271 emitTypeInformation();
272
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000273 clear();
274}
275
David Majnemerb9456a52016-03-14 05:15:09 +0000276static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
277 // Microsoft's linker seems to have trouble with symbol names longer than
278 // 0xffd8 bytes.
279 S = S.substr(0, 0xffd8);
280 SmallString<32> NullTerminatedString(S);
281 NullTerminatedString.push_back('\0');
282 OS.EmitBytes(NullTerminatedString);
283}
284
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000285void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000286 // Do nothing if we have no debug info or if no non-trivial types were emitted
287 // to TypeTable during codegen.
Reid Klecknerfbd77872016-03-18 18:54:32 +0000288 NamedMDNode *CU_Nodes =
289 MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
290 if (!CU_Nodes)
291 return;
Reid Kleckner2280f932016-05-23 20:23:46 +0000292 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000293 return;
294
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000295 // Start the .debug$T section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000296 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000297 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000298
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000299 SmallString<8> CommentPrefix;
300 if (OS.isVerboseAsm()) {
301 CommentPrefix += '\t';
302 CommentPrefix += Asm->MAI->getCommentString();
303 CommentPrefix += ' ';
304 }
305
306 CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false);
Reid Kleckner2280f932016-05-23 20:23:46 +0000307 TypeTable.ForEachRecord(
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000308 [&](TypeIndex Index, StringRef Record) {
309 if (OS.isVerboseAsm()) {
310 // Emit a block comment describing the type record for readability.
311 SmallString<512> CommentBlock;
312 raw_svector_ostream CommentOS(CommentBlock);
313 ScopedPrinter SP(CommentOS);
314 SP.setPrefix(CommentPrefix);
315 CVTD.setPrinter(&SP);
316 bool DumpSuccess =
317 CVTD.dump({Record.bytes_begin(), Record.bytes_end()});
318 (void)DumpSuccess;
319 assert(DumpSuccess && "produced malformed type record");
320 // emitRawComment will insert its own tab and comment string before
321 // the first line, so strip off our first one. It also prints its own
322 // newline.
323 OS.emitRawComment(
324 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
325 }
326 OS.EmitBinaryData(Record);
Reid Kleckner2280f932016-05-23 20:23:46 +0000327 });
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000328}
329
Reid Kleckner5d122f82016-05-25 23:16:12 +0000330void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000331 if (InlinedSubprograms.empty())
332 return;
333
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000334
335 OS.AddComment("Inlinee lines subsection");
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000336 MCSymbol *InlineEnd = beginCVSubsection(ModuleSubstreamKind::InlineeLines);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000337
338 // We don't provide any extra file info.
339 // FIXME: Find out if debuggers use this info.
David Majnemer30579ec2016-02-02 23:18:23 +0000340 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000341 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
342
343 for (const DISubprogram *SP : InlinedSubprograms) {
Reid Kleckner2280f932016-05-23 20:23:46 +0000344 assert(TypeIndices.count(SP));
345 TypeIndex InlineeIdx = TypeIndices[SP];
346
David Majnemer30579ec2016-02-02 23:18:23 +0000347 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000348 unsigned FileId = maybeRecordFile(SP->getFile());
349 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
350 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000351 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000352 // The filechecksum table uses 8 byte entries for now, and file ids start at
353 // 1.
354 unsigned FileOffset = (FileId - 1) * 8;
David Majnemer30579ec2016-02-02 23:18:23 +0000355 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000356 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000357 OS.AddComment("Offset into filechecksum table");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000358 OS.EmitIntValue(FileOffset, 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000359 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000360 OS.EmitIntValue(SP->getLine(), 4);
361 }
362
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000363 endCVSubsection(InlineEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000364}
365
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000366void CodeViewDebug::collectInlineSiteChildren(
367 SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI,
368 const InlineSite &Site) {
369 for (const DILocation *ChildSiteLoc : Site.ChildSites) {
370 auto I = FI.InlineSites.find(ChildSiteLoc);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000371 const InlineSite &ChildSite = I->second;
372 Children.push_back(ChildSite.SiteFuncId);
373 collectInlineSiteChildren(Children, FI, ChildSite);
374 }
375}
376
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000377void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
378 const DILocation *InlinedAt,
379 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000380 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
381 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000382
Reid Kleckner2280f932016-05-23 20:23:46 +0000383 assert(TypeIndices.count(Site.Inlinee));
384 TypeIndex InlineeIdx = TypeIndices[Site.Inlinee];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000385
386 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000387 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000388 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000389 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000390 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000391 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000392
Reid Klecknerdac21b42016-02-03 21:15:48 +0000393 OS.AddComment("PtrParent");
394 OS.EmitIntValue(0, 4);
395 OS.AddComment("PtrEnd");
396 OS.EmitIntValue(0, 4);
397 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000398 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000399
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000400 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
401 unsigned StartLineNum = Site.Inlinee->getLine();
402 SmallVector<unsigned, 3> SecondaryFuncIds;
403 collectInlineSiteChildren(SecondaryFuncIds, FI, Site);
404
405 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
David Majnemerc9911f22016-02-02 19:22:34 +0000406 FI.Begin, FI.End, SecondaryFuncIds);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000407
408 OS.EmitLabel(InlineEnd);
409
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000410 for (const LocalVariable &Var : Site.InlinedLocals)
411 emitLocalVariable(Var);
412
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000413 // Recurse on child inlined call sites before closing the scope.
414 for (const DILocation *ChildSite : Site.ChildSites) {
415 auto I = FI.InlineSites.find(ChildSite);
416 assert(I != FI.InlineSites.end() &&
417 "child site not in function inline site map");
418 emitInlinedCallSite(FI, ChildSite, I->second);
419 }
420
421 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000422 OS.AddComment("Record length");
423 OS.EmitIntValue(2, 2); // RecordLength
424 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000425 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000426}
427
Reid Kleckner5d122f82016-05-25 23:16:12 +0000428void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
429 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
430 // comdat key. A section may be comdat because of -ffunction-sections or
431 // because it is comdat in the IR.
432 MCSectionCOFF *GVSec =
433 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
434 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
435
436 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
437 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
438 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
439
440 OS.SwitchSection(DebugSec);
441
442 // Emit the magic version number if this is the first time we've switched to
443 // this section.
444 if (ComdatDebugSections.insert(DebugSec).second)
445 emitCodeViewMagicVersion();
446}
447
Reid Kleckner2214ed82016-01-29 00:49:42 +0000448void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
449 FunctionInfo &FI) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000450 // For each function there is a separate subsection
451 // which holds the PC to file:line table.
452 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000453 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000454
Reid Kleckner5d122f82016-05-25 23:16:12 +0000455 // Switch to the to a comdat section, if appropriate.
456 switchToDebugSectionForSymbol(Fn);
457
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000458 StringRef FuncName;
Pete Cooperadebb932016-03-11 02:14:16 +0000459 if (auto *SP = GV->getSubprogram())
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000460 FuncName = SP->getDisplayName();
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000461
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000462 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000463 if (FuncName.empty())
464 FuncName = GlobalValue::getRealLinkageName(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000465
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000466 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000467 OS.AddComment("Symbol subsection for " + Twine(FuncName));
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000468 MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000469 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000470 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
471 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000472 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000473 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000474 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000475
Reid Klecknerdac21b42016-02-03 21:15:48 +0000476 OS.AddComment("Record kind: S_GPROC32_ID");
Zachary Turner63a28462016-05-17 23:50:21 +0000477 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000478
David Majnemer30579ec2016-02-02 23:18:23 +0000479 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000480 OS.AddComment("PtrParent");
481 OS.EmitIntValue(0, 4);
482 OS.AddComment("PtrEnd");
483 OS.EmitIntValue(0, 4);
484 OS.AddComment("PtrNext");
485 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000486 // This is the important bit that tells the debugger where the function
487 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000488 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000489 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000490 OS.AddComment("Offset after prologue");
491 OS.EmitIntValue(0, 4);
492 OS.AddComment("Offset before epilogue");
493 OS.EmitIntValue(0, 4);
494 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000495 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000496 OS.AddComment("Function section relative address");
497 OS.EmitCOFFSecRel32(Fn);
498 OS.AddComment("Function section index");
499 OS.EmitCOFFSectionIndex(Fn);
500 OS.AddComment("Flags");
501 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000502 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000503 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000504 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000505 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000506 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000507
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000508 for (const LocalVariable &Var : FI.Locals)
509 emitLocalVariable(Var);
510
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000511 // Emit inlined call site information. Only emit functions inlined directly
512 // into the parent function. We'll emit the other sites recursively as part
513 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000514 for (const DILocation *InlinedAt : FI.ChildSites) {
515 auto I = FI.InlineSites.find(InlinedAt);
516 assert(I != FI.InlineSites.end() &&
517 "child site not in function inline site map");
518 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000519 }
520
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000521 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000522 OS.AddComment("Record length");
523 OS.EmitIntValue(0x0002, 2);
524 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000525 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000526 }
Reid Kleckner6f3406d2016-06-07 00:02:03 +0000527 endCVSubsection(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000528
Reid Kleckner2214ed82016-01-29 00:49:42 +0000529 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000530 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000531}
532
Reid Kleckner876330d2016-02-12 21:48:30 +0000533CodeViewDebug::LocalVarDefRange
534CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
535 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +0000536 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +0000537 DR.DataOffset = Offset;
538 assert(DR.DataOffset == Offset && "truncation");
539 DR.StructOffset = 0;
540 DR.CVRegister = CVRegister;
541 return DR;
542}
543
544CodeViewDebug::LocalVarDefRange
545CodeViewDebug::createDefRangeReg(uint16_t CVRegister) {
546 LocalVarDefRange DR;
547 DR.InMemory = 0;
548 DR.DataOffset = 0;
549 DR.StructOffset = 0;
550 DR.CVRegister = CVRegister;
551 return DR;
552}
553
554void CodeViewDebug::collectVariableInfoFromMMITable(
555 DenseSet<InlinedVariable> &Processed) {
556 const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
557 const TargetFrameLowering *TFI = TSI.getFrameLowering();
558 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
559
560 for (const MachineModuleInfo::VariableDbgInfo &VI :
561 MMI->getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000562 if (!VI.Var)
563 continue;
564 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
565 "Expected inlined-at fields to agree");
566
Reid Kleckner876330d2016-02-12 21:48:30 +0000567 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000568 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
569
570 // If variable scope is not found then skip this variable.
571 if (!Scope)
572 continue;
573
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000574 // Get the frame register used and the offset.
575 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000576 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
577 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000578
579 // Calculate the label ranges.
Reid Kleckner876330d2016-02-12 21:48:30 +0000580 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000581 for (const InsnRange &Range : Scope->getRanges()) {
582 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
583 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +0000584 End = End ? End : Asm->getFunctionEnd();
585 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000586 }
587
Reid Kleckner876330d2016-02-12 21:48:30 +0000588 LocalVariable Var;
589 Var.DIVar = VI.Var;
590 Var.DefRanges.emplace_back(std::move(DefRange));
591 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
592 }
593}
594
595void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
596 DenseSet<InlinedVariable> Processed;
597 // Grab the variable info that was squirreled away in the MMI side-table.
598 collectVariableInfoFromMMITable(Processed);
599
600 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
601
602 for (const auto &I : DbgValues) {
603 InlinedVariable IV = I.first;
604 if (Processed.count(IV))
605 continue;
606 const DILocalVariable *DIVar = IV.first;
607 const DILocation *InlinedAt = IV.second;
608
609 // Instruction ranges, specifying where IV is accessible.
610 const auto &Ranges = I.second;
611
612 LexicalScope *Scope = nullptr;
613 if (InlinedAt)
614 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
615 else
616 Scope = LScopes.findLexicalScope(DIVar->getScope());
617 // If variable scope is not found then skip this variable.
618 if (!Scope)
619 continue;
620
621 LocalVariable Var;
622 Var.DIVar = DIVar;
623
624 // Calculate the definition ranges.
625 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
626 const InsnRange &Range = *I;
627 const MachineInstr *DVInst = Range.first;
628 assert(DVInst->isDebugValue() && "Invalid History entry");
629 const DIExpression *DIExpr = DVInst->getDebugExpression();
630
631 // Bail if there is a complex DWARF expression for now.
632 if (DIExpr && DIExpr->getNumElements() > 0)
633 continue;
634
Reid Kleckner9a593ee2016-02-16 21:49:26 +0000635 // Bail if operand 0 is not a valid register. This means the variable is a
636 // simple constant, or is described by a complex expression.
637 // FIXME: Find a way to represent constant variables, since they are
638 // relatively common.
639 unsigned Reg =
640 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
641 if (Reg == 0)
Reid Kleckner6e0d5f52016-02-16 21:14:51 +0000642 continue;
643
Reid Kleckner876330d2016-02-12 21:48:30 +0000644 // Handle the two cases we can handle: indirect in memory and in register.
645 bool IsIndirect = DVInst->getOperand(1).isImm();
646 unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg());
647 {
648 LocalVarDefRange DefRange;
649 if (IsIndirect) {
650 int64_t Offset = DVInst->getOperand(1).getImm();
651 DefRange = createDefRangeMem(CVReg, Offset);
652 } else {
653 DefRange = createDefRangeReg(CVReg);
654 }
655 if (Var.DefRanges.empty() ||
656 Var.DefRanges.back().isDifferentLocation(DefRange)) {
657 Var.DefRanges.emplace_back(std::move(DefRange));
658 }
659 }
660
661 // Compute the label range.
662 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
663 const MCSymbol *End = getLabelAfterInsn(Range.second);
664 if (!End) {
665 if (std::next(I) != E)
666 End = getLabelBeforeInsn(std::next(I)->first);
667 else
668 End = Asm->getFunctionEnd();
669 }
670
671 // If the last range end is our begin, just extend the last range.
672 // Otherwise make a new range.
673 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
674 Var.DefRanges.back().Ranges;
675 if (!Ranges.empty() && Ranges.back().second == Begin)
676 Ranges.back().second = End;
677 else
678 Ranges.emplace_back(Begin, End);
679
680 // FIXME: Do more range combining.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000681 }
Reid Kleckner876330d2016-02-12 21:48:30 +0000682
683 recordLocalVariable(std::move(Var), InlinedAt);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000684 }
685}
686
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000687void CodeViewDebug::beginFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000688 assert(!CurFn && "Can't process two functions at once!");
689
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000690 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000691 return;
692
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000693 DebugHandlerBase::beginFunction(MF);
694
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000695 const Function *GV = MF->getFunction();
696 assert(FnDebugInfo.count(GV) == false);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000697 CurFn = &FnDebugInfo[GV];
Reid Kleckner2214ed82016-01-29 00:49:42 +0000698 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000699 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000700
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000701 // Find the end of the function prolog. First known non-DBG_VALUE and
702 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000703 // FIXME: is there a simpler a way to do this? Can we just search
704 // for the first instruction of the function, not the last of the prolog?
705 DebugLoc PrologEndLoc;
706 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000707 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000708 for (const auto &MI : MBB) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000709 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
710 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000711 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000712 break;
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000713 } else if (!MI.isDebugValue()) {
714 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000715 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000716 }
717 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000718
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000719 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000720 if (PrologEndLoc && !EmptyPrologue) {
721 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000722 maybeRecordLocation(FnStartDL, MF);
723 }
724}
725
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000726TypeIndex CodeViewDebug::lowerType(const DIType *Ty) {
727 // Generic dispatch for lowering an unknown type.
728 switch (Ty->getTag()) {
David Majnemerd065e232016-06-02 06:21:37 +0000729 case dwarf::DW_TAG_typedef:
730 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000731 case dwarf::DW_TAG_base_type:
732 return lowerTypeBasic(cast<DIBasicType>(Ty));
733 case dwarf::DW_TAG_pointer_type:
734 case dwarf::DW_TAG_reference_type:
735 case dwarf::DW_TAG_rvalue_reference_type:
736 return lowerTypePointer(cast<DIDerivedType>(Ty));
737 case dwarf::DW_TAG_ptr_to_member_type:
738 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
739 case dwarf::DW_TAG_const_type:
740 case dwarf::DW_TAG_volatile_type:
741 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +0000742 case dwarf::DW_TAG_subroutine_type:
743 return lowerTypeFunction(cast<DISubroutineType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +0000744 case dwarf::DW_TAG_class_type:
745 case dwarf::DW_TAG_structure_type:
746 return lowerTypeClass(cast<DICompositeType>(Ty));
747 case dwarf::DW_TAG_union_type:
748 return lowerTypeUnion(cast<DICompositeType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000749 default:
750 // Use the null type index.
751 return TypeIndex();
752 }
753}
754
David Majnemerd065e232016-06-02 06:21:37 +0000755TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
756 // TODO: MSVC emits a S_UDT record.
757 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
758 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
759 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
760 Ty->getName() == "HRESULT")
761 return TypeIndex(SimpleTypeKind::HResult);
David Majnemer8c46a4c2016-06-04 15:40:33 +0000762 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
763 Ty->getName() == "wchar_t")
764 return TypeIndex(SimpleTypeKind::WideCharacter);
David Majnemerd065e232016-06-02 06:21:37 +0000765 return UnderlyingTypeIndex;
766}
767
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000768TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
769 TypeIndex Index;
770 dwarf::TypeKind Kind;
771 uint32_t ByteSize;
772
773 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +0000774 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000775
776 SimpleTypeKind STK = SimpleTypeKind::None;
777 switch (Kind) {
778 case dwarf::DW_ATE_address:
779 // FIXME: Translate
780 break;
781 case dwarf::DW_ATE_boolean:
782 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000783 case 1: STK = SimpleTypeKind::Boolean8; break;
784 case 2: STK = SimpleTypeKind::Boolean16; break;
785 case 4: STK = SimpleTypeKind::Boolean32; break;
786 case 8: STK = SimpleTypeKind::Boolean64; break;
787 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000788 }
789 break;
790 case dwarf::DW_ATE_complex_float:
791 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000792 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000793 case 4: STK = SimpleTypeKind::Complex32; break;
794 case 8: STK = SimpleTypeKind::Complex64; break;
795 case 10: STK = SimpleTypeKind::Complex80; break;
796 case 16: STK = SimpleTypeKind::Complex128; break;
797 }
798 break;
799 case dwarf::DW_ATE_float:
800 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000801 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000802 case 4: STK = SimpleTypeKind::Float32; break;
803 case 6: STK = SimpleTypeKind::Float48; break;
804 case 8: STK = SimpleTypeKind::Float64; break;
805 case 10: STK = SimpleTypeKind::Float80; break;
806 case 16: STK = SimpleTypeKind::Float128; break;
807 }
808 break;
809 case dwarf::DW_ATE_signed:
810 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000811 case 1: STK = SimpleTypeKind::SByte; break;
812 case 2: STK = SimpleTypeKind::Int16Short; break;
813 case 4: STK = SimpleTypeKind::Int32; break;
814 case 8: STK = SimpleTypeKind::Int64Quad; break;
815 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000816 }
817 break;
818 case dwarf::DW_ATE_unsigned:
819 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000820 case 1: STK = SimpleTypeKind::Byte; break;
821 case 2: STK = SimpleTypeKind::UInt16Short; break;
822 case 4: STK = SimpleTypeKind::UInt32; break;
823 case 8: STK = SimpleTypeKind::UInt64Quad; break;
824 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000825 }
826 break;
827 case dwarf::DW_ATE_UTF:
828 switch (ByteSize) {
829 case 2: STK = SimpleTypeKind::Character16; break;
830 case 4: STK = SimpleTypeKind::Character32; break;
831 }
832 break;
833 case dwarf::DW_ATE_signed_char:
834 if (ByteSize == 1)
835 STK = SimpleTypeKind::SignedCharacter;
836 break;
837 case dwarf::DW_ATE_unsigned_char:
838 if (ByteSize == 1)
839 STK = SimpleTypeKind::UnsignedCharacter;
840 break;
841 default:
842 break;
843 }
844
845 // Apply some fixups based on the source-level type name.
846 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
847 STK = SimpleTypeKind::Int32Long;
848 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
849 STK = SimpleTypeKind::UInt32Long;
David Majnemer8c46a4c2016-06-04 15:40:33 +0000850 if (STK == SimpleTypeKind::UInt16Short &&
851 (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000852 STK = SimpleTypeKind::WideCharacter;
853 if ((STK == SimpleTypeKind::SignedCharacter ||
854 STK == SimpleTypeKind::UnsignedCharacter) &&
855 Ty->getName() == "char")
856 STK = SimpleTypeKind::NarrowCharacter;
857
858 return TypeIndex(STK);
859}
860
861TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
862 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
863
864 // Pointers to simple types can use SimpleTypeMode, rather than having a
865 // dedicated pointer type record.
866 if (PointeeTI.isSimple() &&
867 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
868 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
869 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
870 ? SimpleTypeMode::NearPointer64
871 : SimpleTypeMode::NearPointer32;
872 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
873 }
874
875 PointerKind PK =
876 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
877 PointerMode PM = PointerMode::Pointer;
878 switch (Ty->getTag()) {
879 default: llvm_unreachable("not a pointer tag type");
880 case dwarf::DW_TAG_pointer_type:
881 PM = PointerMode::Pointer;
882 break;
883 case dwarf::DW_TAG_reference_type:
884 PM = PointerMode::LValueReference;
885 break;
886 case dwarf::DW_TAG_rvalue_reference_type:
887 PM = PointerMode::RValueReference;
888 break;
889 }
890 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
891 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
892 // do.
893 PointerOptions PO = PointerOptions::None;
894 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
895 return TypeTable.writePointer(PR);
896}
897
898TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
899 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
900 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
901 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
902 PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64
903 : PointerKind::Near32;
904 PointerMode PM = isa<DISubroutineType>(Ty->getBaseType())
905 ? PointerMode::PointerToMemberFunction
906 : PointerMode::PointerToDataMember;
907 PointerOptions PO = PointerOptions::None; // FIXME
908 // FIXME: Thread this ABI info through metadata.
909 PointerToMemberRepresentation PMR = PointerToMemberRepresentation::Unknown;
910 MemberPointerInfo MPI(ClassTI, PMR);
911 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8, MPI);
912 return TypeTable.writePointer(PR);
913}
914
915TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
916 ModifierOptions Mods = ModifierOptions::None;
917 bool IsModifier = true;
918 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +0000919 while (IsModifier && BaseTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000920 // FIXME: Need to add DWARF tag for __unaligned.
921 switch (BaseTy->getTag()) {
922 case dwarf::DW_TAG_const_type:
923 Mods |= ModifierOptions::Const;
924 break;
925 case dwarf::DW_TAG_volatile_type:
926 Mods |= ModifierOptions::Volatile;
927 break;
928 default:
929 IsModifier = false;
930 break;
931 }
932 if (IsModifier)
933 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
934 }
935 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
936 ModifierRecord MR(ModifiedTI, Mods);
937 return TypeTable.writeModifier(MR);
938}
939
David Majnemer75c3ebf2016-06-02 17:13:53 +0000940TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
941 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
942 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
943 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
944
945 TypeIndex ReturnTypeIndex = TypeIndex::Void();
946 ArrayRef<TypeIndex> ArgTypeIndices = None;
947 if (!ReturnAndArgTypeIndices.empty()) {
948 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
949 ReturnTypeIndex = ReturnAndArgTypesRef.front();
950 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
951 }
952
953 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
954 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec);
955
956 // TODO: We should use DW_AT_calling_convention to determine what CC this
957 // procedure record should have.
958 // TODO: Some functions are member functions, we should use a more appropriate
959 // record for those.
960 ProcedureRecord Procedure(ReturnTypeIndex, CallingConvention::NearC,
961 FunctionOptions::None, ArgTypeIndices.size(),
962 ArgListIndex);
963 return TypeTable.writeProcedure(Procedure);
964}
965
Reid Klecknera8d57402016-06-03 15:58:20 +0000966static MemberAccess translateAccessFlags(unsigned RecordTag,
967 const DIType *Member) {
968 switch (Member->getFlags() & DINode::FlagAccessibility) {
969 case DINode::FlagPrivate: return MemberAccess::Private;
970 case DINode::FlagPublic: return MemberAccess::Public;
971 case DINode::FlagProtected: return MemberAccess::Protected;
972 case 0:
973 // If there was no explicit access control, provide the default for the tag.
974 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
975 : MemberAccess::Public;
976 }
977 llvm_unreachable("access flags are exclusive");
978}
979
980static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
981 switch (Ty->getTag()) {
982 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
983 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
984 }
985 llvm_unreachable("unexpected tag");
986}
987
988/// Return the HasUniqueName option if it should be present in ClassOptions, or
989/// None otherwise.
990static ClassOptions getRecordUniqueNameOption(const DICompositeType *Ty) {
991 // MSVC always sets this flag now, even for local types. Clang doesn't always
992 // appear to give every type a linkage name, which may be problematic for us.
993 // FIXME: Investigate the consequences of not following them here.
994 return !Ty->getIdentifier().empty() ? ClassOptions::HasUniqueName
995 : ClassOptions::None;
996}
997
998TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
999 // First, construct the forward decl. Don't look into Ty to compute the
1000 // forward decl options, since it might not be available in all TUs.
1001 TypeRecordKind Kind = getRecordKind(Ty);
1002 ClassOptions CO =
1003 ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty);
1004 TypeIndex FwdDeclTI = TypeTable.writeClass(ClassRecord(
1005 Kind, 0, CO, HfaKind::None, WindowsRTClassKind::None, TypeIndex(),
1006 TypeIndex(), TypeIndex(), 0, Ty->getName(), Ty->getIdentifier()));
1007 return FwdDeclTI;
1008}
1009
1010TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1011 // Construct the field list and complete type record.
1012 TypeRecordKind Kind = getRecordKind(Ty);
1013 // FIXME: Other ClassOptions, like ContainsNestedClass and NestedClass.
1014 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
1015 TypeIndex FTI;
1016 unsigned FieldCount;
1017 std::tie(FTI, FieldCount) = lowerRecordFieldList(Ty);
1018
1019 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1020 return TypeTable.writeClass(ClassRecord(Kind, FieldCount, CO, HfaKind::None,
1021 WindowsRTClassKind::None, FTI,
1022 TypeIndex(), TypeIndex(), SizeInBytes,
1023 Ty->getName(), Ty->getIdentifier()));
1024 // FIXME: Make an LF_UDT_SRC_LINE record.
1025}
1026
1027TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1028 ClassOptions CO =
1029 ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty);
1030 TypeIndex FwdDeclTI =
1031 TypeTable.writeUnion(UnionRecord(0, CO, HfaKind::None, TypeIndex(), 0,
1032 Ty->getName(), Ty->getIdentifier()));
1033 return FwdDeclTI;
1034}
1035
1036TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
1037 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
1038 TypeIndex FTI;
1039 unsigned FieldCount;
1040 std::tie(FTI, FieldCount) = lowerRecordFieldList(Ty);
1041 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1042 return TypeTable.writeUnion(UnionRecord(FieldCount, CO, HfaKind::None, FTI,
1043 SizeInBytes, Ty->getName(),
1044 Ty->getIdentifier()));
1045 // FIXME: Make an LF_UDT_SRC_LINE record.
1046}
1047
1048std::pair<TypeIndex, unsigned>
1049CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1050 // Manually count members. MSVC appears to count everything that generates a
1051 // field list record. Each individual overload in a method overload group
1052 // contributes to this count, even though the overload group is a single field
1053 // list record.
1054 unsigned MemberCount = 0;
1055 FieldListRecordBuilder Fields;
1056 for (const DINode *Element : Ty->getElements()) {
1057 // We assume that the frontend provides all members in source declaration
1058 // order, which is what MSVC does.
1059 if (!Element)
1060 continue;
1061 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
1062 // C++ method.
1063 // FIXME: Overloaded methods are grouped together, so we'll need two
1064 // passes to group them.
1065 (void)SP;
1066 } else if (auto *Member = dyn_cast<DIDerivedType>(Element)) {
1067 if (Member->getTag() == dwarf::DW_TAG_member) {
1068 if (Member->isStaticMember()) {
1069 // Static data member.
1070 Fields.writeStaticDataMember(StaticDataMemberRecord(
1071 translateAccessFlags(Ty->getTag(), Member),
1072 getTypeIndex(Member->getBaseType()), Member->getName()));
1073 MemberCount++;
1074 } else {
1075 // Data member.
1076 // FIXME: Make a BitFieldRecord for bitfields.
1077 Fields.writeDataMember(DataMemberRecord(
1078 translateAccessFlags(Ty->getTag(), Member),
1079 getTypeIndex(Member->getBaseType()),
1080 Member->getOffsetInBits() / 8, Member->getName()));
1081 MemberCount++;
1082 }
1083 } else if (Member->getTag() == dwarf::DW_TAG_friend) {
1084 // Ignore friend members. It appears that MSVC emitted info about
1085 // friends in the past, but modern versions do not.
1086 }
1087 // FIXME: Get clang to emit nested types here and do something with
1088 // them.
1089 }
1090 // Skip other unrecognized kinds of elements.
1091 }
1092 return {TypeTable.writeFieldList(Fields), MemberCount};
1093}
1094
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001095TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef) {
1096 const DIType *Ty = TypeRef.resolve();
1097
1098 // The null DIType is the void type. Don't try to hash it.
1099 if (!Ty)
1100 return TypeIndex::Void();
1101
Reid Klecknera8d57402016-06-03 15:58:20 +00001102 // Check if we've already translated this type. Don't try to do a
1103 // get-or-create style insertion that caches the hash lookup across the
1104 // lowerType call. It will update the TypeIndices map.
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001105 auto I = TypeIndices.find(Ty);
1106 if (I != TypeIndices.end())
1107 return I->second;
1108
1109 TypeIndex TI = lowerType(Ty);
1110
Reid Klecknera8d57402016-06-03 15:58:20 +00001111 recordTypeIndexForDINode(Ty, TI);
1112 return TI;
1113}
1114
1115TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1116 const DIType *Ty = TypeRef.resolve();
1117
1118 // The null DIType is the void type. Don't try to hash it.
1119 if (!Ty)
1120 return TypeIndex::Void();
1121
1122 // If this is a non-record type, the complete type index is the same as the
1123 // normal type index. Just call getTypeIndex.
1124 switch (Ty->getTag()) {
1125 case dwarf::DW_TAG_class_type:
1126 case dwarf::DW_TAG_structure_type:
1127 case dwarf::DW_TAG_union_type:
1128 break;
1129 default:
1130 return getTypeIndex(Ty);
1131 }
1132
1133 // Check if we've already translated the complete record type. Lowering a
1134 // complete type should never trigger lowering another complete type, so we
1135 // can reuse the hash table lookup result.
1136 const auto *CTy = cast<DICompositeType>(Ty);
1137 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1138 if (!InsertResult.second)
1139 return InsertResult.first->second;
1140
1141 // Make sure the forward declaration is emitted first. It's unclear if this
1142 // is necessary, but MSVC does it, and we should follow suit until we can show
1143 // otherwise.
1144 TypeIndex FwdDeclTI = getTypeIndex(CTy);
1145
1146 // Just use the forward decl if we don't have complete type info. This might
1147 // happen if the frontend is using modules and expects the complete definition
1148 // to be emitted elsewhere.
1149 if (CTy->isForwardDecl())
1150 return FwdDeclTI;
1151
1152 TypeIndex TI;
1153 switch (CTy->getTag()) {
1154 case dwarf::DW_TAG_class_type:
1155 case dwarf::DW_TAG_structure_type:
1156 TI = lowerCompleteTypeClass(CTy);
1157 break;
1158 case dwarf::DW_TAG_union_type:
1159 TI = lowerCompleteTypeUnion(CTy);
1160 break;
1161 default:
1162 llvm_unreachable("not a record");
1163 }
1164
1165 InsertResult.first->second = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001166 return TI;
1167}
1168
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001169void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
1170 // LocalSym record, see SymbolRecord.h for more info.
1171 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
1172 *LocalEnd = MMI->getContext().createTempSymbol();
1173 OS.AddComment("Record length");
1174 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
1175 OS.EmitLabel(LocalBegin);
1176
1177 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00001178 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001179
Zachary Turner63a28462016-05-17 23:50:21 +00001180 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001181 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00001182 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00001183 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00001184 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001185
1186 OS.AddComment("TypeIndex");
Reid Klecknera8d57402016-06-03 15:58:20 +00001187 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001188 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001189 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00001190 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00001191 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00001192 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001193 OS.EmitLabel(LocalEnd);
1194
Reid Kleckner876330d2016-02-12 21:48:30 +00001195 // Calculate the on disk prefix of the appropriate def range record. The
1196 // records and on disk formats are described in SymbolRecords.h. BytePrefix
1197 // should be big enough to hold all forms without memory allocation.
1198 SmallString<20> BytePrefix;
1199 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
1200 BytePrefix.clear();
1201 // FIXME: Handle bitpieces.
1202 if (DefRange.StructOffset != 0)
1203 continue;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001204
Reid Kleckner876330d2016-02-12 21:48:30 +00001205 if (DefRange.InMemory) {
Zachary Turnera78ecd12016-05-23 18:49:06 +00001206 DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0,
1207 0, 0, ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00001208 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00001209 BytePrefix +=
1210 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00001211 BytePrefix +=
1212 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1213 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00001214 } else {
1215 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Zachary Turnera78ecd12016-05-23 18:49:06 +00001216 // Unclear what matters here.
1217 DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0,
1218 ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00001219 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
Reid Kleckner876330d2016-02-12 21:48:30 +00001220 BytePrefix +=
1221 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00001222 BytePrefix +=
1223 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1224 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00001225 }
1226 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
1227 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001228}
1229
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001230void CodeViewDebug::endFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001231 if (!Asm || !CurFn) // We haven't created any debug info for this function.
1232 return;
1233
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001234 const Function *GV = MF->getFunction();
Yaron Keren6d3194f2014-06-20 10:26:56 +00001235 assert(FnDebugInfo.count(GV));
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001236 assert(CurFn == &FnDebugInfo[GV]);
1237
Pete Cooperadebb932016-03-11 02:14:16 +00001238 collectVariableInfo(GV->getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00001239
1240 DebugHandlerBase::endFunction(MF);
1241
Reid Kleckner2214ed82016-01-29 00:49:42 +00001242 // Don't emit anything if we don't have any line tables.
1243 if (!CurFn->HaveLineInfo) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001244 FnDebugInfo.erase(GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001245 CurFn = nullptr;
1246 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00001247 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001248
1249 CurFn->End = Asm->getFunctionEnd();
1250
Craig Topper353eda42014-04-24 06:44:33 +00001251 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001252}
1253
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001254void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001255 DebugHandlerBase::beginInstruction(MI);
1256
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001257 // Ignore DBG_VALUE locations and function prologue.
1258 if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup))
1259 return;
1260 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001261 if (DL == PrevInstLoc || !DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001262 return;
1263 maybeRecordLocation(DL, Asm->MF);
1264}
Reid Kleckner6f3406d2016-06-07 00:02:03 +00001265
1266MCSymbol *CodeViewDebug::beginCVSubsection(ModuleSubstreamKind Kind) {
1267 MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
1268 *EndLabel = MMI->getContext().createTempSymbol();
1269 OS.EmitIntValue(unsigned(Kind), 4);
1270 OS.AddComment("Subsection size");
1271 OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
1272 OS.EmitLabel(BeginLabel);
1273 return EndLabel;
1274}
1275
1276void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
1277 OS.EmitLabel(EndLabel);
1278 // Every subsection must be aligned to a 4-byte boundary.
1279 OS.EmitValueToAlignment(4);
1280}
1281
1282void CodeViewDebug::emitDebugInfoForGlobals() {
1283 NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
1284 for (const MDNode *Node : CUs->operands()) {
1285 const auto *CU = cast<DICompileUnit>(Node);
1286
1287 // First, emit all globals that are not in a comdat in a single symbol
1288 // substream. MSVC doesn't like it if the substream is empty, so only open
1289 // it if we have at least one global to emit.
1290 switchToDebugSectionForSymbol(nullptr);
1291 MCSymbol *EndLabel = nullptr;
1292 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
1293 if (const auto *GV = dyn_cast<GlobalVariable>(G->getVariable()))
1294 if (!GV->hasComdat()) {
1295 if (!EndLabel) {
1296 OS.AddComment("Symbol subsection for globals");
1297 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
1298 }
1299 emitDebugInfoForGlobal(G, Asm->getSymbol(GV));
1300 }
1301 }
1302 if (EndLabel)
1303 endCVSubsection(EndLabel);
1304
1305 // Second, emit each global that is in a comdat into its own .debug$S
1306 // section along with its own symbol substream.
1307 for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
1308 if (const auto *GV = dyn_cast<GlobalVariable>(G->getVariable())) {
1309 if (GV->hasComdat()) {
1310 MCSymbol *GVSym = Asm->getSymbol(GV);
1311 OS.AddComment("Symbol subsection for " +
1312 Twine(GlobalValue::getRealLinkageName(GV->getName())));
1313 switchToDebugSectionForSymbol(GVSym);
1314 EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
1315 emitDebugInfoForGlobal(G, GVSym);
1316 endCVSubsection(EndLabel);
1317 }
1318 }
1319 }
1320 }
1321}
1322
1323void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
1324 MCSymbol *GVSym) {
1325 // DataSym record, see SymbolRecord.h for more info.
1326 // FIXME: Thread local data, etc
1327 MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
1328 *DataEnd = MMI->getContext().createTempSymbol();
1329 OS.AddComment("Record length");
1330 OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
1331 OS.EmitLabel(DataBegin);
1332 OS.AddComment("Record kind: S_GDATA32");
1333 OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
1334 OS.AddComment("Type");
1335 OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
1336 OS.AddComment("DataOffset");
1337 OS.EmitCOFFSecRel32(GVSym);
1338 OS.AddComment("Segment");
1339 OS.EmitCOFFSectionIndex(GVSym);
1340 OS.AddComment("Name");
1341 emitNullTerminatedSymbolName(OS, DIGV->getName());
1342 OS.EmitLabel(DataEnd);
1343}