blob: 98f69c56cd5f14560e36c8ab511c03b07bb8d099 [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() {
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000235 if (FnDebugInfo.empty())
236 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 Kleckner1fcd6102016-02-02 17:41:18 +0000245 // Make a subsection for all the inlined subprograms.
Reid Kleckner5d122f82016-05-25 23:16:12 +0000246 emitInlineeLinesSubsection();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000247
Reid Kleckner2214ed82016-01-29 00:49:42 +0000248 // Emit per-function debug information.
249 for (auto &P : FnDebugInfo)
250 emitDebugInfoForFunction(P.first, P.second);
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000251
Reid Kleckner5d122f82016-05-25 23:16:12 +0000252 // Switch back to the generic .debug$S section after potentially processing
253 // comdat symbol sections.
254 switchToDebugSectionForSymbol(nullptr);
255
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000256 // This subsection holds a file index to offset in string table table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000257 OS.AddComment("File index to string table offset subsection");
258 OS.EmitCVFileChecksumsDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000259
260 // This subsection holds the string table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000261 OS.AddComment("String table");
262 OS.EmitCVStringTableDirective();
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000263
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000264 // Emit type information last, so that any types we translate while emitting
265 // function info are included.
266 emitTypeInformation();
267
Timur Iskhodzhanov2cf8a1d2014-10-10 16:05:32 +0000268 clear();
269}
270
David Majnemerb9456a52016-03-14 05:15:09 +0000271static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
272 // Microsoft's linker seems to have trouble with symbol names longer than
273 // 0xffd8 bytes.
274 S = S.substr(0, 0xffd8);
275 SmallString<32> NullTerminatedString(S);
276 NullTerminatedString.push_back('\0');
277 OS.EmitBytes(NullTerminatedString);
278}
279
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000280void CodeViewDebug::emitTypeInformation() {
Reid Kleckner2280f932016-05-23 20:23:46 +0000281 // Do nothing if we have no debug info or if no non-trivial types were emitted
282 // to TypeTable during codegen.
Reid Klecknerfbd77872016-03-18 18:54:32 +0000283 NamedMDNode *CU_Nodes =
284 MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
285 if (!CU_Nodes)
286 return;
Reid Kleckner2280f932016-05-23 20:23:46 +0000287 if (TypeTable.empty())
Reid Klecknerfbd77872016-03-18 18:54:32 +0000288 return;
289
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000290 // Start the .debug$T section with 0x4.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000291 OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
Reid Kleckner5d122f82016-05-25 23:16:12 +0000292 emitCodeViewMagicVersion();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000293
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000294 SmallString<8> CommentPrefix;
295 if (OS.isVerboseAsm()) {
296 CommentPrefix += '\t';
297 CommentPrefix += Asm->MAI->getCommentString();
298 CommentPrefix += ' ';
299 }
300
301 CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false);
Reid Kleckner2280f932016-05-23 20:23:46 +0000302 TypeTable.ForEachRecord(
Reid Klecknerfbdbe9e2016-05-31 18:45:36 +0000303 [&](TypeIndex Index, StringRef Record) {
304 if (OS.isVerboseAsm()) {
305 // Emit a block comment describing the type record for readability.
306 SmallString<512> CommentBlock;
307 raw_svector_ostream CommentOS(CommentBlock);
308 ScopedPrinter SP(CommentOS);
309 SP.setPrefix(CommentPrefix);
310 CVTD.setPrinter(&SP);
311 bool DumpSuccess =
312 CVTD.dump({Record.bytes_begin(), Record.bytes_end()});
313 (void)DumpSuccess;
314 assert(DumpSuccess && "produced malformed type record");
315 // emitRawComment will insert its own tab and comment string before
316 // the first line, so strip off our first one. It also prints its own
317 // newline.
318 OS.emitRawComment(
319 CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
320 }
321 OS.EmitBinaryData(Record);
Reid Kleckner2280f932016-05-23 20:23:46 +0000322 });
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000323}
324
Reid Kleckner5d122f82016-05-25 23:16:12 +0000325void CodeViewDebug::emitInlineeLinesSubsection() {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000326 if (InlinedSubprograms.empty())
327 return;
328
Reid Kleckner5d122f82016-05-25 23:16:12 +0000329 // Use the generic .debug$S section.
330 switchToDebugSectionForSymbol(nullptr);
331
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000332 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
333 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000334
335 OS.AddComment("Inlinee lines subsection");
336 OS.EmitIntValue(unsigned(ModuleSubstreamKind::InlineeLines), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000337 OS.AddComment("Subsection size");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000338 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 4);
339 OS.EmitLabel(InlineBegin);
340
341 // We don't provide any extra file info.
342 // FIXME: Find out if debuggers use this info.
David Majnemer30579ec2016-02-02 23:18:23 +0000343 OS.AddComment("Inlinee lines signature");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000344 OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
345
346 for (const DISubprogram *SP : InlinedSubprograms) {
Reid Kleckner2280f932016-05-23 20:23:46 +0000347 assert(TypeIndices.count(SP));
348 TypeIndex InlineeIdx = TypeIndices[SP];
349
David Majnemer30579ec2016-02-02 23:18:23 +0000350 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000351 unsigned FileId = maybeRecordFile(SP->getFile());
352 OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
353 SP->getFilename() + Twine(':') + Twine(SP->getLine()));
David Majnemer30579ec2016-02-02 23:18:23 +0000354 OS.AddBlankLine();
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000355 // The filechecksum table uses 8 byte entries for now, and file ids start at
356 // 1.
357 unsigned FileOffset = (FileId - 1) * 8;
David Majnemer30579ec2016-02-02 23:18:23 +0000358 OS.AddComment("Type index of inlined function");
Reid Kleckner2280f932016-05-23 20:23:46 +0000359 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000360 OS.AddComment("Offset into filechecksum table");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000361 OS.EmitIntValue(FileOffset, 4);
David Majnemer30579ec2016-02-02 23:18:23 +0000362 OS.AddComment("Starting line number");
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000363 OS.EmitIntValue(SP->getLine(), 4);
364 }
365
366 OS.EmitLabel(InlineEnd);
367}
368
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000369void CodeViewDebug::collectInlineSiteChildren(
370 SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI,
371 const InlineSite &Site) {
372 for (const DILocation *ChildSiteLoc : Site.ChildSites) {
373 auto I = FI.InlineSites.find(ChildSiteLoc);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000374 const InlineSite &ChildSite = I->second;
375 Children.push_back(ChildSite.SiteFuncId);
376 collectInlineSiteChildren(Children, FI, ChildSite);
377 }
378}
379
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000380void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
381 const DILocation *InlinedAt,
382 const InlineSite &Site) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000383 MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
384 *InlineEnd = MMI->getContext().createTempSymbol();
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000385
Reid Kleckner2280f932016-05-23 20:23:46 +0000386 assert(TypeIndices.count(Site.Inlinee));
387 TypeIndex InlineeIdx = TypeIndices[Site.Inlinee];
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000388
389 // SymbolRecord
Reid Klecknerdac21b42016-02-03 21:15:48 +0000390 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000391 OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2); // RecordLength
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000392 OS.EmitLabel(InlineBegin);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000393 OS.AddComment("Record kind: S_INLINESITE");
Zachary Turner63a28462016-05-17 23:50:21 +0000394 OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000395
Reid Klecknerdac21b42016-02-03 21:15:48 +0000396 OS.AddComment("PtrParent");
397 OS.EmitIntValue(0, 4);
398 OS.AddComment("PtrEnd");
399 OS.EmitIntValue(0, 4);
400 OS.AddComment("Inlinee type index");
Reid Kleckner2280f932016-05-23 20:23:46 +0000401 OS.EmitIntValue(InlineeIdx.getIndex(), 4);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000402
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000403 unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
404 unsigned StartLineNum = Site.Inlinee->getLine();
405 SmallVector<unsigned, 3> SecondaryFuncIds;
406 collectInlineSiteChildren(SecondaryFuncIds, FI, Site);
407
408 OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
David Majnemerc9911f22016-02-02 19:22:34 +0000409 FI.Begin, FI.End, SecondaryFuncIds);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000410
411 OS.EmitLabel(InlineEnd);
412
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000413 for (const LocalVariable &Var : Site.InlinedLocals)
414 emitLocalVariable(Var);
415
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000416 // Recurse on child inlined call sites before closing the scope.
417 for (const DILocation *ChildSite : Site.ChildSites) {
418 auto I = FI.InlineSites.find(ChildSite);
419 assert(I != FI.InlineSites.end() &&
420 "child site not in function inline site map");
421 emitInlinedCallSite(FI, ChildSite, I->second);
422 }
423
424 // Close the scope.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000425 OS.AddComment("Record length");
426 OS.EmitIntValue(2, 2); // RecordLength
427 OS.AddComment("Record kind: S_INLINESITE_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000428 OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000429}
430
Reid Kleckner5d122f82016-05-25 23:16:12 +0000431void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
432 // If we have a symbol, it may be in a section that is COMDAT. If so, find the
433 // comdat key. A section may be comdat because of -ffunction-sections or
434 // because it is comdat in the IR.
435 MCSectionCOFF *GVSec =
436 GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
437 const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
438
439 MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
440 Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
441 DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
442
443 OS.SwitchSection(DebugSec);
444
445 // Emit the magic version number if this is the first time we've switched to
446 // this section.
447 if (ComdatDebugSections.insert(DebugSec).second)
448 emitCodeViewMagicVersion();
449}
450
Reid Kleckner2214ed82016-01-29 00:49:42 +0000451void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
452 FunctionInfo &FI) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000453 // For each function there is a separate subsection
454 // which holds the PC to file:line table.
455 const MCSymbol *Fn = Asm->getSymbol(GV);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000456 assert(Fn);
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +0000457
Reid Kleckner5d122f82016-05-25 23:16:12 +0000458 // Switch to the to a comdat section, if appropriate.
459 switchToDebugSectionForSymbol(Fn);
460
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000461 StringRef FuncName;
Pete Cooperadebb932016-03-11 02:14:16 +0000462 if (auto *SP = GV->getSubprogram())
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000463 FuncName = SP->getDisplayName();
Duncan P. N. Exon Smith23e56ec2015-03-20 19:50:00 +0000464
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000465 // If our DISubprogram name is empty, use the mangled name.
Reid Kleckner72e2ba72016-01-13 19:32:35 +0000466 if (FuncName.empty())
467 FuncName = GlobalValue::getRealLinkageName(GV->getName());
Reid Kleckner3c0ff982016-01-14 00:12:54 +0000468
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000469 // Emit a symbol subsection, required by VS2012+ to find function boundaries.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000470 MCSymbol *SymbolsBegin = MMI->getContext().createTempSymbol(),
471 *SymbolsEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000472 OS.AddComment("Symbol subsection for " + Twine(FuncName));
473 OS.EmitIntValue(unsigned(ModuleSubstreamKind::Symbols), 4);
474 OS.AddComment("Subsection size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000475 OS.emitAbsoluteSymbolDiff(SymbolsEnd, SymbolsBegin, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000476 OS.EmitLabel(SymbolsBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000477 {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000478 MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
479 *ProcRecordEnd = MMI->getContext().createTempSymbol();
Reid Klecknerdac21b42016-02-03 21:15:48 +0000480 OS.AddComment("Record length");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000481 OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000482 OS.EmitLabel(ProcRecordBegin);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000483
Reid Klecknerdac21b42016-02-03 21:15:48 +0000484 OS.AddComment("Record kind: S_GPROC32_ID");
Zachary Turner63a28462016-05-17 23:50:21 +0000485 OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
Reid Kleckner6b3faef2016-01-13 23:44:57 +0000486
David Majnemer30579ec2016-02-02 23:18:23 +0000487 // These fields are filled in by tools like CVPACK which run after the fact.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000488 OS.AddComment("PtrParent");
489 OS.EmitIntValue(0, 4);
490 OS.AddComment("PtrEnd");
491 OS.EmitIntValue(0, 4);
492 OS.AddComment("PtrNext");
493 OS.EmitIntValue(0, 4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000494 // This is the important bit that tells the debugger where the function
495 // code is located and what's its size:
Reid Klecknerdac21b42016-02-03 21:15:48 +0000496 OS.AddComment("Code size");
Reid Klecknereb3bcdd2016-02-03 21:24:42 +0000497 OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000498 OS.AddComment("Offset after prologue");
499 OS.EmitIntValue(0, 4);
500 OS.AddComment("Offset before epilogue");
501 OS.EmitIntValue(0, 4);
502 OS.AddComment("Function type index");
David Majnemer75c3ebf2016-06-02 17:13:53 +0000503 OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000504 OS.AddComment("Function section relative address");
505 OS.EmitCOFFSecRel32(Fn);
506 OS.AddComment("Function section index");
507 OS.EmitCOFFSectionIndex(Fn);
508 OS.AddComment("Flags");
509 OS.EmitIntValue(0, 1);
Timur Iskhodzhanova11b32b2014-11-12 20:10:09 +0000510 // Emit the function display name as a null-terminated string.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000511 OS.AddComment("Function name");
David Majnemer12561252016-03-13 10:53:30 +0000512 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +0000513 emitNullTerminatedSymbolName(OS, FuncName);
Reid Klecknerdac21b42016-02-03 21:15:48 +0000514 OS.EmitLabel(ProcRecordEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000515
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000516 for (const LocalVariable &Var : FI.Locals)
517 emitLocalVariable(Var);
518
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000519 // Emit inlined call site information. Only emit functions inlined directly
520 // into the parent function. We'll emit the other sites recursively as part
521 // of their parent inline site.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000522 for (const DILocation *InlinedAt : FI.ChildSites) {
523 auto I = FI.InlineSites.find(InlinedAt);
524 assert(I != FI.InlineSites.end() &&
525 "child site not in function inline site map");
526 emitInlinedCallSite(FI, InlinedAt, I->second);
Reid Klecknerf3b9ba42016-01-29 18:16:43 +0000527 }
528
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000529 // We're done with this function.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000530 OS.AddComment("Record length");
531 OS.EmitIntValue(0x0002, 2);
532 OS.AddComment("Record kind: S_PROC_ID_END");
Zachary Turner63a28462016-05-17 23:50:21 +0000533 OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000534 }
Reid Klecknerdac21b42016-02-03 21:15:48 +0000535 OS.EmitLabel(SymbolsEnd);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000536 // Every subsection must be aligned to a 4-byte boundary.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000537 OS.EmitValueToAlignment(4);
Timur Iskhodzhanov2bc90fd2014-10-24 01:27:45 +0000538
Reid Kleckner2214ed82016-01-29 00:49:42 +0000539 // We have an assembler directive that takes care of the whole line table.
Reid Klecknerdac21b42016-02-03 21:15:48 +0000540 OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000541}
542
Reid Kleckner876330d2016-02-12 21:48:30 +0000543CodeViewDebug::LocalVarDefRange
544CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
545 LocalVarDefRange DR;
Aaron Ballmanc6a2f212016-02-16 15:35:51 +0000546 DR.InMemory = -1;
Reid Kleckner876330d2016-02-12 21:48:30 +0000547 DR.DataOffset = Offset;
548 assert(DR.DataOffset == Offset && "truncation");
549 DR.StructOffset = 0;
550 DR.CVRegister = CVRegister;
551 return DR;
552}
553
554CodeViewDebug::LocalVarDefRange
555CodeViewDebug::createDefRangeReg(uint16_t CVRegister) {
556 LocalVarDefRange DR;
557 DR.InMemory = 0;
558 DR.DataOffset = 0;
559 DR.StructOffset = 0;
560 DR.CVRegister = CVRegister;
561 return DR;
562}
563
564void CodeViewDebug::collectVariableInfoFromMMITable(
565 DenseSet<InlinedVariable> &Processed) {
566 const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
567 const TargetFrameLowering *TFI = TSI.getFrameLowering();
568 const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
569
570 for (const MachineModuleInfo::VariableDbgInfo &VI :
571 MMI->getVariableDbgInfo()) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000572 if (!VI.Var)
573 continue;
574 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
575 "Expected inlined-at fields to agree");
576
Reid Kleckner876330d2016-02-12 21:48:30 +0000577 Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000578 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
579
580 // If variable scope is not found then skip this variable.
581 if (!Scope)
582 continue;
583
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000584 // Get the frame register used and the offset.
585 unsigned FrameReg = 0;
Reid Kleckner876330d2016-02-12 21:48:30 +0000586 int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
587 uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000588
589 // Calculate the label ranges.
Reid Kleckner876330d2016-02-12 21:48:30 +0000590 LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000591 for (const InsnRange &Range : Scope->getRanges()) {
592 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
593 const MCSymbol *End = getLabelAfterInsn(Range.second);
Reid Kleckner876330d2016-02-12 21:48:30 +0000594 End = End ? End : Asm->getFunctionEnd();
595 DefRange.Ranges.emplace_back(Begin, End);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000596 }
597
Reid Kleckner876330d2016-02-12 21:48:30 +0000598 LocalVariable Var;
599 Var.DIVar = VI.Var;
600 Var.DefRanges.emplace_back(std::move(DefRange));
601 recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
602 }
603}
604
605void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
606 DenseSet<InlinedVariable> Processed;
607 // Grab the variable info that was squirreled away in the MMI side-table.
608 collectVariableInfoFromMMITable(Processed);
609
610 const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
611
612 for (const auto &I : DbgValues) {
613 InlinedVariable IV = I.first;
614 if (Processed.count(IV))
615 continue;
616 const DILocalVariable *DIVar = IV.first;
617 const DILocation *InlinedAt = IV.second;
618
619 // Instruction ranges, specifying where IV is accessible.
620 const auto &Ranges = I.second;
621
622 LexicalScope *Scope = nullptr;
623 if (InlinedAt)
624 Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
625 else
626 Scope = LScopes.findLexicalScope(DIVar->getScope());
627 // If variable scope is not found then skip this variable.
628 if (!Scope)
629 continue;
630
631 LocalVariable Var;
632 Var.DIVar = DIVar;
633
634 // Calculate the definition ranges.
635 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
636 const InsnRange &Range = *I;
637 const MachineInstr *DVInst = Range.first;
638 assert(DVInst->isDebugValue() && "Invalid History entry");
639 const DIExpression *DIExpr = DVInst->getDebugExpression();
640
641 // Bail if there is a complex DWARF expression for now.
642 if (DIExpr && DIExpr->getNumElements() > 0)
643 continue;
644
Reid Kleckner9a593ee2016-02-16 21:49:26 +0000645 // Bail if operand 0 is not a valid register. This means the variable is a
646 // simple constant, or is described by a complex expression.
647 // FIXME: Find a way to represent constant variables, since they are
648 // relatively common.
649 unsigned Reg =
650 DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
651 if (Reg == 0)
Reid Kleckner6e0d5f52016-02-16 21:14:51 +0000652 continue;
653
Reid Kleckner876330d2016-02-12 21:48:30 +0000654 // Handle the two cases we can handle: indirect in memory and in register.
655 bool IsIndirect = DVInst->getOperand(1).isImm();
656 unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg());
657 {
658 LocalVarDefRange DefRange;
659 if (IsIndirect) {
660 int64_t Offset = DVInst->getOperand(1).getImm();
661 DefRange = createDefRangeMem(CVReg, Offset);
662 } else {
663 DefRange = createDefRangeReg(CVReg);
664 }
665 if (Var.DefRanges.empty() ||
666 Var.DefRanges.back().isDifferentLocation(DefRange)) {
667 Var.DefRanges.emplace_back(std::move(DefRange));
668 }
669 }
670
671 // Compute the label range.
672 const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
673 const MCSymbol *End = getLabelAfterInsn(Range.second);
674 if (!End) {
675 if (std::next(I) != E)
676 End = getLabelBeforeInsn(std::next(I)->first);
677 else
678 End = Asm->getFunctionEnd();
679 }
680
681 // If the last range end is our begin, just extend the last range.
682 // Otherwise make a new range.
683 SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
684 Var.DefRanges.back().Ranges;
685 if (!Ranges.empty() && Ranges.back().second == Begin)
686 Ranges.back().second = End;
687 else
688 Ranges.emplace_back(Begin, End);
689
690 // FIXME: Do more range combining.
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000691 }
Reid Kleckner876330d2016-02-12 21:48:30 +0000692
693 recordLocalVariable(std::move(Var), InlinedAt);
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000694 }
695}
696
Reid Kleckner70f5bc92016-01-14 19:25:04 +0000697void CodeViewDebug::beginFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000698 assert(!CurFn && "Can't process two functions at once!");
699
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000700 if (!Asm || !MMI->hasDebugInfo())
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000701 return;
702
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000703 DebugHandlerBase::beginFunction(MF);
704
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000705 const Function *GV = MF->getFunction();
706 assert(FnDebugInfo.count(GV) == false);
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000707 CurFn = &FnDebugInfo[GV];
Reid Kleckner2214ed82016-01-29 00:49:42 +0000708 CurFn->FuncId = NextFuncId++;
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000709 CurFn->Begin = Asm->getFunctionBegin();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000710
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000711 // Find the end of the function prolog. First known non-DBG_VALUE and
712 // non-frame setup location marks the beginning of the function body.
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000713 // FIXME: is there a simpler a way to do this? Can we just search
714 // for the first instruction of the function, not the last of the prolog?
715 DebugLoc PrologEndLoc;
716 bool EmptyPrologue = true;
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000717 for (const auto &MBB : *MF) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000718 for (const auto &MI : MBB) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000719 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
720 MI.getDebugLoc()) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000721 PrologEndLoc = MI.getDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000722 break;
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000723 } else if (!MI.isDebugValue()) {
724 EmptyPrologue = false;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000725 }
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000726 }
727 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000728
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000729 // Record beginning of function if we have a non-empty prologue.
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000730 if (PrologEndLoc && !EmptyPrologue) {
731 DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +0000732 maybeRecordLocation(FnStartDL, MF);
733 }
734}
735
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000736TypeIndex CodeViewDebug::lowerType(const DIType *Ty) {
737 // Generic dispatch for lowering an unknown type.
738 switch (Ty->getTag()) {
David Majnemerd065e232016-06-02 06:21:37 +0000739 case dwarf::DW_TAG_typedef:
740 return lowerTypeAlias(cast<DIDerivedType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000741 case dwarf::DW_TAG_base_type:
742 return lowerTypeBasic(cast<DIBasicType>(Ty));
743 case dwarf::DW_TAG_pointer_type:
744 case dwarf::DW_TAG_reference_type:
745 case dwarf::DW_TAG_rvalue_reference_type:
746 return lowerTypePointer(cast<DIDerivedType>(Ty));
747 case dwarf::DW_TAG_ptr_to_member_type:
748 return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
749 case dwarf::DW_TAG_const_type:
750 case dwarf::DW_TAG_volatile_type:
751 return lowerTypeModifier(cast<DIDerivedType>(Ty));
David Majnemer75c3ebf2016-06-02 17:13:53 +0000752 case dwarf::DW_TAG_subroutine_type:
753 return lowerTypeFunction(cast<DISubroutineType>(Ty));
Reid Klecknera8d57402016-06-03 15:58:20 +0000754 case dwarf::DW_TAG_class_type:
755 case dwarf::DW_TAG_structure_type:
756 return lowerTypeClass(cast<DICompositeType>(Ty));
757 case dwarf::DW_TAG_union_type:
758 return lowerTypeUnion(cast<DICompositeType>(Ty));
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000759 default:
760 // Use the null type index.
761 return TypeIndex();
762 }
763}
764
David Majnemerd065e232016-06-02 06:21:37 +0000765TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
766 // TODO: MSVC emits a S_UDT record.
767 DITypeRef UnderlyingTypeRef = Ty->getBaseType();
768 TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
769 if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
770 Ty->getName() == "HRESULT")
771 return TypeIndex(SimpleTypeKind::HResult);
772 return UnderlyingTypeIndex;
773}
774
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000775TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
776 TypeIndex Index;
777 dwarf::TypeKind Kind;
778 uint32_t ByteSize;
779
780 Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
David Majnemerafefa672016-06-02 06:21:42 +0000781 ByteSize = Ty->getSizeInBits() / 8;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000782
783 SimpleTypeKind STK = SimpleTypeKind::None;
784 switch (Kind) {
785 case dwarf::DW_ATE_address:
786 // FIXME: Translate
787 break;
788 case dwarf::DW_ATE_boolean:
789 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000790 case 1: STK = SimpleTypeKind::Boolean8; break;
791 case 2: STK = SimpleTypeKind::Boolean16; break;
792 case 4: STK = SimpleTypeKind::Boolean32; break;
793 case 8: STK = SimpleTypeKind::Boolean64; break;
794 case 16: STK = SimpleTypeKind::Boolean128; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000795 }
796 break;
797 case dwarf::DW_ATE_complex_float:
798 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000799 case 2: STK = SimpleTypeKind::Complex16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000800 case 4: STK = SimpleTypeKind::Complex32; break;
801 case 8: STK = SimpleTypeKind::Complex64; break;
802 case 10: STK = SimpleTypeKind::Complex80; break;
803 case 16: STK = SimpleTypeKind::Complex128; break;
804 }
805 break;
806 case dwarf::DW_ATE_float:
807 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000808 case 2: STK = SimpleTypeKind::Float16; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000809 case 4: STK = SimpleTypeKind::Float32; break;
810 case 6: STK = SimpleTypeKind::Float48; break;
811 case 8: STK = SimpleTypeKind::Float64; break;
812 case 10: STK = SimpleTypeKind::Float80; break;
813 case 16: STK = SimpleTypeKind::Float128; break;
814 }
815 break;
816 case dwarf::DW_ATE_signed:
817 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000818 case 1: STK = SimpleTypeKind::SByte; break;
819 case 2: STK = SimpleTypeKind::Int16Short; break;
820 case 4: STK = SimpleTypeKind::Int32; break;
821 case 8: STK = SimpleTypeKind::Int64Quad; break;
822 case 16: STK = SimpleTypeKind::Int128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000823 }
824 break;
825 case dwarf::DW_ATE_unsigned:
826 switch (ByteSize) {
David Majnemer1c2cb1d2016-06-02 07:02:32 +0000827 case 1: STK = SimpleTypeKind::Byte; break;
828 case 2: STK = SimpleTypeKind::UInt16Short; break;
829 case 4: STK = SimpleTypeKind::UInt32; break;
830 case 8: STK = SimpleTypeKind::UInt64Quad; break;
831 case 16: STK = SimpleTypeKind::UInt128Oct; break;
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000832 }
833 break;
834 case dwarf::DW_ATE_UTF:
835 switch (ByteSize) {
836 case 2: STK = SimpleTypeKind::Character16; break;
837 case 4: STK = SimpleTypeKind::Character32; break;
838 }
839 break;
840 case dwarf::DW_ATE_signed_char:
841 if (ByteSize == 1)
842 STK = SimpleTypeKind::SignedCharacter;
843 break;
844 case dwarf::DW_ATE_unsigned_char:
845 if (ByteSize == 1)
846 STK = SimpleTypeKind::UnsignedCharacter;
847 break;
848 default:
849 break;
850 }
851
852 // Apply some fixups based on the source-level type name.
853 if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
854 STK = SimpleTypeKind::Int32Long;
855 if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
856 STK = SimpleTypeKind::UInt32Long;
857 if ((STK == SimpleTypeKind::Int16Short ||
858 STK == SimpleTypeKind::UInt16Short) &&
859 Ty->getName() == "wchar_t")
860 STK = SimpleTypeKind::WideCharacter;
861 if ((STK == SimpleTypeKind::SignedCharacter ||
862 STK == SimpleTypeKind::UnsignedCharacter) &&
863 Ty->getName() == "char")
864 STK = SimpleTypeKind::NarrowCharacter;
865
866 return TypeIndex(STK);
867}
868
869TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
870 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
871
872 // Pointers to simple types can use SimpleTypeMode, rather than having a
873 // dedicated pointer type record.
874 if (PointeeTI.isSimple() &&
875 PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
876 Ty->getTag() == dwarf::DW_TAG_pointer_type) {
877 SimpleTypeMode Mode = Ty->getSizeInBits() == 64
878 ? SimpleTypeMode::NearPointer64
879 : SimpleTypeMode::NearPointer32;
880 return TypeIndex(PointeeTI.getSimpleKind(), Mode);
881 }
882
883 PointerKind PK =
884 Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
885 PointerMode PM = PointerMode::Pointer;
886 switch (Ty->getTag()) {
887 default: llvm_unreachable("not a pointer tag type");
888 case dwarf::DW_TAG_pointer_type:
889 PM = PointerMode::Pointer;
890 break;
891 case dwarf::DW_TAG_reference_type:
892 PM = PointerMode::LValueReference;
893 break;
894 case dwarf::DW_TAG_rvalue_reference_type:
895 PM = PointerMode::RValueReference;
896 break;
897 }
898 // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
899 // 'this' pointer, but not normal contexts. Figure out what we're supposed to
900 // do.
901 PointerOptions PO = PointerOptions::None;
902 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
903 return TypeTable.writePointer(PR);
904}
905
906TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
907 assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
908 TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
909 TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
910 PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64
911 : PointerKind::Near32;
912 PointerMode PM = isa<DISubroutineType>(Ty->getBaseType())
913 ? PointerMode::PointerToMemberFunction
914 : PointerMode::PointerToDataMember;
915 PointerOptions PO = PointerOptions::None; // FIXME
916 // FIXME: Thread this ABI info through metadata.
917 PointerToMemberRepresentation PMR = PointerToMemberRepresentation::Unknown;
918 MemberPointerInfo MPI(ClassTI, PMR);
919 PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8, MPI);
920 return TypeTable.writePointer(PR);
921}
922
923TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
924 ModifierOptions Mods = ModifierOptions::None;
925 bool IsModifier = true;
926 const DIType *BaseTy = Ty;
Reid Klecknerb9c80fd2016-06-02 17:40:51 +0000927 while (IsModifier && BaseTy) {
Reid Kleckner5acacbb2016-06-01 17:05:51 +0000928 // FIXME: Need to add DWARF tag for __unaligned.
929 switch (BaseTy->getTag()) {
930 case dwarf::DW_TAG_const_type:
931 Mods |= ModifierOptions::Const;
932 break;
933 case dwarf::DW_TAG_volatile_type:
934 Mods |= ModifierOptions::Volatile;
935 break;
936 default:
937 IsModifier = false;
938 break;
939 }
940 if (IsModifier)
941 BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
942 }
943 TypeIndex ModifiedTI = getTypeIndex(BaseTy);
944 ModifierRecord MR(ModifiedTI, Mods);
945 return TypeTable.writeModifier(MR);
946}
947
David Majnemer75c3ebf2016-06-02 17:13:53 +0000948TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
949 SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
950 for (DITypeRef ArgTypeRef : Ty->getTypeArray())
951 ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
952
953 TypeIndex ReturnTypeIndex = TypeIndex::Void();
954 ArrayRef<TypeIndex> ArgTypeIndices = None;
955 if (!ReturnAndArgTypeIndices.empty()) {
956 auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
957 ReturnTypeIndex = ReturnAndArgTypesRef.front();
958 ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
959 }
960
961 ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
962 TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec);
963
964 // TODO: We should use DW_AT_calling_convention to determine what CC this
965 // procedure record should have.
966 // TODO: Some functions are member functions, we should use a more appropriate
967 // record for those.
968 ProcedureRecord Procedure(ReturnTypeIndex, CallingConvention::NearC,
969 FunctionOptions::None, ArgTypeIndices.size(),
970 ArgListIndex);
971 return TypeTable.writeProcedure(Procedure);
972}
973
Reid Klecknera8d57402016-06-03 15:58:20 +0000974static MemberAccess translateAccessFlags(unsigned RecordTag,
975 const DIType *Member) {
976 switch (Member->getFlags() & DINode::FlagAccessibility) {
977 case DINode::FlagPrivate: return MemberAccess::Private;
978 case DINode::FlagPublic: return MemberAccess::Public;
979 case DINode::FlagProtected: return MemberAccess::Protected;
980 case 0:
981 // If there was no explicit access control, provide the default for the tag.
982 return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
983 : MemberAccess::Public;
984 }
985 llvm_unreachable("access flags are exclusive");
986}
987
988static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
989 switch (Ty->getTag()) {
990 case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
991 case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
992 }
993 llvm_unreachable("unexpected tag");
994}
995
996/// Return the HasUniqueName option if it should be present in ClassOptions, or
997/// None otherwise.
998static ClassOptions getRecordUniqueNameOption(const DICompositeType *Ty) {
999 // MSVC always sets this flag now, even for local types. Clang doesn't always
1000 // appear to give every type a linkage name, which may be problematic for us.
1001 // FIXME: Investigate the consequences of not following them here.
1002 return !Ty->getIdentifier().empty() ? ClassOptions::HasUniqueName
1003 : ClassOptions::None;
1004}
1005
1006TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1007 // First, construct the forward decl. Don't look into Ty to compute the
1008 // forward decl options, since it might not be available in all TUs.
1009 TypeRecordKind Kind = getRecordKind(Ty);
1010 ClassOptions CO =
1011 ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty);
1012 TypeIndex FwdDeclTI = TypeTable.writeClass(ClassRecord(
1013 Kind, 0, CO, HfaKind::None, WindowsRTClassKind::None, TypeIndex(),
1014 TypeIndex(), TypeIndex(), 0, Ty->getName(), Ty->getIdentifier()));
1015 return FwdDeclTI;
1016}
1017
1018TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1019 // Construct the field list and complete type record.
1020 TypeRecordKind Kind = getRecordKind(Ty);
1021 // FIXME: Other ClassOptions, like ContainsNestedClass and NestedClass.
1022 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
1023 TypeIndex FTI;
1024 unsigned FieldCount;
1025 std::tie(FTI, FieldCount) = lowerRecordFieldList(Ty);
1026
1027 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1028 return TypeTable.writeClass(ClassRecord(Kind, FieldCount, CO, HfaKind::None,
1029 WindowsRTClassKind::None, FTI,
1030 TypeIndex(), TypeIndex(), SizeInBytes,
1031 Ty->getName(), Ty->getIdentifier()));
1032 // FIXME: Make an LF_UDT_SRC_LINE record.
1033}
1034
1035TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1036 ClassOptions CO =
1037 ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty);
1038 TypeIndex FwdDeclTI =
1039 TypeTable.writeUnion(UnionRecord(0, CO, HfaKind::None, TypeIndex(), 0,
1040 Ty->getName(), Ty->getIdentifier()));
1041 return FwdDeclTI;
1042}
1043
1044TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
1045 ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
1046 TypeIndex FTI;
1047 unsigned FieldCount;
1048 std::tie(FTI, FieldCount) = lowerRecordFieldList(Ty);
1049 uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1050 return TypeTable.writeUnion(UnionRecord(FieldCount, CO, HfaKind::None, FTI,
1051 SizeInBytes, Ty->getName(),
1052 Ty->getIdentifier()));
1053 // FIXME: Make an LF_UDT_SRC_LINE record.
1054}
1055
1056std::pair<TypeIndex, unsigned>
1057CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1058 // Manually count members. MSVC appears to count everything that generates a
1059 // field list record. Each individual overload in a method overload group
1060 // contributes to this count, even though the overload group is a single field
1061 // list record.
1062 unsigned MemberCount = 0;
1063 FieldListRecordBuilder Fields;
1064 for (const DINode *Element : Ty->getElements()) {
1065 // We assume that the frontend provides all members in source declaration
1066 // order, which is what MSVC does.
1067 if (!Element)
1068 continue;
1069 if (auto *SP = dyn_cast<DISubprogram>(Element)) {
1070 // C++ method.
1071 // FIXME: Overloaded methods are grouped together, so we'll need two
1072 // passes to group them.
1073 (void)SP;
1074 } else if (auto *Member = dyn_cast<DIDerivedType>(Element)) {
1075 if (Member->getTag() == dwarf::DW_TAG_member) {
1076 if (Member->isStaticMember()) {
1077 // Static data member.
1078 Fields.writeStaticDataMember(StaticDataMemberRecord(
1079 translateAccessFlags(Ty->getTag(), Member),
1080 getTypeIndex(Member->getBaseType()), Member->getName()));
1081 MemberCount++;
1082 } else {
1083 // Data member.
1084 // FIXME: Make a BitFieldRecord for bitfields.
1085 Fields.writeDataMember(DataMemberRecord(
1086 translateAccessFlags(Ty->getTag(), Member),
1087 getTypeIndex(Member->getBaseType()),
1088 Member->getOffsetInBits() / 8, Member->getName()));
1089 MemberCount++;
1090 }
1091 } else if (Member->getTag() == dwarf::DW_TAG_friend) {
1092 // Ignore friend members. It appears that MSVC emitted info about
1093 // friends in the past, but modern versions do not.
1094 }
1095 // FIXME: Get clang to emit nested types here and do something with
1096 // them.
1097 }
1098 // Skip other unrecognized kinds of elements.
1099 }
1100 return {TypeTable.writeFieldList(Fields), MemberCount};
1101}
1102
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001103TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef) {
1104 const DIType *Ty = TypeRef.resolve();
1105
1106 // The null DIType is the void type. Don't try to hash it.
1107 if (!Ty)
1108 return TypeIndex::Void();
1109
Reid Klecknera8d57402016-06-03 15:58:20 +00001110 // Check if we've already translated this type. Don't try to do a
1111 // get-or-create style insertion that caches the hash lookup across the
1112 // lowerType call. It will update the TypeIndices map.
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001113 auto I = TypeIndices.find(Ty);
1114 if (I != TypeIndices.end())
1115 return I->second;
1116
1117 TypeIndex TI = lowerType(Ty);
1118
Reid Klecknera8d57402016-06-03 15:58:20 +00001119 recordTypeIndexForDINode(Ty, TI);
1120 return TI;
1121}
1122
1123TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1124 const DIType *Ty = TypeRef.resolve();
1125
1126 // The null DIType is the void type. Don't try to hash it.
1127 if (!Ty)
1128 return TypeIndex::Void();
1129
1130 // If this is a non-record type, the complete type index is the same as the
1131 // normal type index. Just call getTypeIndex.
1132 switch (Ty->getTag()) {
1133 case dwarf::DW_TAG_class_type:
1134 case dwarf::DW_TAG_structure_type:
1135 case dwarf::DW_TAG_union_type:
1136 break;
1137 default:
1138 return getTypeIndex(Ty);
1139 }
1140
1141 // Check if we've already translated the complete record type. Lowering a
1142 // complete type should never trigger lowering another complete type, so we
1143 // can reuse the hash table lookup result.
1144 const auto *CTy = cast<DICompositeType>(Ty);
1145 auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1146 if (!InsertResult.second)
1147 return InsertResult.first->second;
1148
1149 // Make sure the forward declaration is emitted first. It's unclear if this
1150 // is necessary, but MSVC does it, and we should follow suit until we can show
1151 // otherwise.
1152 TypeIndex FwdDeclTI = getTypeIndex(CTy);
1153
1154 // Just use the forward decl if we don't have complete type info. This might
1155 // happen if the frontend is using modules and expects the complete definition
1156 // to be emitted elsewhere.
1157 if (CTy->isForwardDecl())
1158 return FwdDeclTI;
1159
1160 TypeIndex TI;
1161 switch (CTy->getTag()) {
1162 case dwarf::DW_TAG_class_type:
1163 case dwarf::DW_TAG_structure_type:
1164 TI = lowerCompleteTypeClass(CTy);
1165 break;
1166 case dwarf::DW_TAG_union_type:
1167 TI = lowerCompleteTypeUnion(CTy);
1168 break;
1169 default:
1170 llvm_unreachable("not a record");
1171 }
1172
1173 InsertResult.first->second = TI;
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001174 return TI;
1175}
1176
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001177void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
1178 // LocalSym record, see SymbolRecord.h for more info.
1179 MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
1180 *LocalEnd = MMI->getContext().createTempSymbol();
1181 OS.AddComment("Record length");
1182 OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
1183 OS.EmitLabel(LocalBegin);
1184
1185 OS.AddComment("Record kind: S_LOCAL");
Zachary Turner63a28462016-05-17 23:50:21 +00001186 OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001187
Zachary Turner63a28462016-05-17 23:50:21 +00001188 LocalSymFlags Flags = LocalSymFlags::None;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001189 if (Var.DIVar->isParameter())
Zachary Turner63a28462016-05-17 23:50:21 +00001190 Flags |= LocalSymFlags::IsParameter;
Reid Kleckner876330d2016-02-12 21:48:30 +00001191 if (Var.DefRanges.empty())
Zachary Turner63a28462016-05-17 23:50:21 +00001192 Flags |= LocalSymFlags::IsOptimizedOut;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001193
1194 OS.AddComment("TypeIndex");
Reid Klecknera8d57402016-06-03 15:58:20 +00001195 TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
Reid Kleckner5acacbb2016-06-01 17:05:51 +00001196 OS.EmitIntValue(TI.getIndex(), 4);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001197 OS.AddComment("Flags");
Zachary Turner63a28462016-05-17 23:50:21 +00001198 OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
David Majnemer12561252016-03-13 10:53:30 +00001199 // Truncate the name so we won't overflow the record length field.
David Majnemerb9456a52016-03-14 05:15:09 +00001200 emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001201 OS.EmitLabel(LocalEnd);
1202
Reid Kleckner876330d2016-02-12 21:48:30 +00001203 // Calculate the on disk prefix of the appropriate def range record. The
1204 // records and on disk formats are described in SymbolRecords.h. BytePrefix
1205 // should be big enough to hold all forms without memory allocation.
1206 SmallString<20> BytePrefix;
1207 for (const LocalVarDefRange &DefRange : Var.DefRanges) {
1208 BytePrefix.clear();
1209 // FIXME: Handle bitpieces.
1210 if (DefRange.StructOffset != 0)
1211 continue;
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001212
Reid Kleckner876330d2016-02-12 21:48:30 +00001213 if (DefRange.InMemory) {
Zachary Turnera78ecd12016-05-23 18:49:06 +00001214 DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0,
1215 0, 0, ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00001216 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
Reid Kleckner876330d2016-02-12 21:48:30 +00001217 BytePrefix +=
1218 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00001219 BytePrefix +=
1220 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1221 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00001222 } else {
1223 assert(DefRange.DataOffset == 0 && "unexpected offset into register");
Zachary Turnera78ecd12016-05-23 18:49:06 +00001224 // Unclear what matters here.
1225 DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0,
1226 ArrayRef<LocalVariableAddrGap>());
Reid Kleckner876330d2016-02-12 21:48:30 +00001227 ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
Reid Kleckner876330d2016-02-12 21:48:30 +00001228 BytePrefix +=
1229 StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
Zachary Turnera78ecd12016-05-23 18:49:06 +00001230 BytePrefix +=
1231 StringRef(reinterpret_cast<const char *>(&Sym.Header),
1232 sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
Reid Kleckner876330d2016-02-12 21:48:30 +00001233 }
1234 OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
1235 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001236}
1237
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001238void CodeViewDebug::endFunction(const MachineFunction *MF) {
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001239 if (!Asm || !CurFn) // We haven't created any debug info for this function.
1240 return;
1241
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001242 const Function *GV = MF->getFunction();
Yaron Keren6d3194f2014-06-20 10:26:56 +00001243 assert(FnDebugInfo.count(GV));
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001244 assert(CurFn == &FnDebugInfo[GV]);
1245
Pete Cooperadebb932016-03-11 02:14:16 +00001246 collectVariableInfo(GV->getSubprogram());
Reid Kleckner876330d2016-02-12 21:48:30 +00001247
1248 DebugHandlerBase::endFunction(MF);
1249
Reid Kleckner2214ed82016-01-29 00:49:42 +00001250 // Don't emit anything if we don't have any line tables.
1251 if (!CurFn->HaveLineInfo) {
Timur Iskhodzhanovb5b7a612014-03-26 11:24:36 +00001252 FnDebugInfo.erase(GV);
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001253 CurFn = nullptr;
1254 return;
Timur Iskhodzhanov8499a122014-03-26 09:50:36 +00001255 }
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001256
1257 CurFn->End = Asm->getFunctionEnd();
1258
Craig Topper353eda42014-04-24 06:44:33 +00001259 CurFn = nullptr;
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001260}
1261
Reid Kleckner70f5bc92016-01-14 19:25:04 +00001262void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001263 DebugHandlerBase::beginInstruction(MI);
1264
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001265 // Ignore DBG_VALUE locations and function prologue.
1266 if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup))
1267 return;
1268 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +00001269 if (DL == PrevInstLoc || !DL)
Timur Iskhodzhanovf166f6c2014-01-30 01:39:17 +00001270 return;
1271 maybeRecordLocation(DL, Asm->MF);
1272}