blob: f50fdab8dfa187e4c410928bda3e752488a0b5a5 [file] [log] [blame]
Reid Kleckner2214ed82016-01-29 00:49:42 +00001//===- MCCodeView.h - Machine Code CodeView support -------------*- C++ -*-===//
2//
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//
10// Holds state from .cv_file and .cv_loc directives for later emission.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/MC/MCCodeView.h"
Reid Kleckner1fcd6102016-02-02 17:41:18 +000015#include "llvm/MC/MCAsmLayout.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000016#include "llvm/ADT/STLExtras.h"
17#include "llvm/DebugInfo/CodeView/CodeView.h"
18#include "llvm/DebugInfo/CodeView/Line.h"
David Majnemer6fcbd7e2016-01-29 19:24:12 +000019#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000020#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCObjectStreamer.h"
22#include "llvm/Support/COFF.h"
23
24using namespace llvm;
25using namespace llvm::codeview;
26
27CodeViewContext::CodeViewContext() {}
28
29CodeViewContext::~CodeViewContext() {
30 // If someone inserted strings into the string table but never actually
31 // emitted them somewhere, clean up the fragment.
32 if (!InsertedStrTabFragment)
33 delete StrTabFragment;
34}
35
36/// This is a valid number for use with .cv_loc if we've already seen a .cv_file
37/// for it.
38bool CodeViewContext::isValidFileNumber(unsigned FileNumber) const {
39 unsigned Idx = FileNumber - 1;
40 if (Idx < Filenames.size())
41 return !Filenames[Idx].empty();
42 return false;
43}
44
45bool CodeViewContext::addFile(unsigned FileNumber, StringRef Filename) {
46 assert(FileNumber > 0);
47 Filename = addToStringTable(Filename);
48 unsigned Idx = FileNumber - 1;
49 if (Idx >= Filenames.size())
50 Filenames.resize(Idx + 1);
51
52 if (Filename.empty())
53 Filename = "<stdin>";
54
55 if (!Filenames[Idx].empty())
56 return false;
57
58 // FIXME: We should store the string table offset of the filename, rather than
59 // the filename itself for efficiency.
60 Filename = addToStringTable(Filename);
61
62 Filenames[Idx] = Filename;
63 return true;
64}
65
66MCDataFragment *CodeViewContext::getStringTableFragment() {
67 if (!StrTabFragment) {
68 StrTabFragment = new MCDataFragment();
69 // Start a new string table out with a null byte.
70 StrTabFragment->getContents().push_back('\0');
71 }
72 return StrTabFragment;
73}
74
75StringRef CodeViewContext::addToStringTable(StringRef S) {
76 SmallVectorImpl<char> &Contents = getStringTableFragment()->getContents();
77 auto Insertion =
78 StringTable.insert(std::make_pair(S, unsigned(Contents.size())));
79 // Return the string from the table, since it is stable.
80 S = Insertion.first->first();
81 if (Insertion.second) {
82 // The string map key is always null terminated.
83 Contents.append(S.begin(), S.end() + 1);
84 }
85 return S;
86}
87
88unsigned CodeViewContext::getStringTableOffset(StringRef S) {
89 // A string table offset of zero is always the empty string.
90 if (S.empty())
91 return 0;
92 auto I = StringTable.find(S);
93 assert(I != StringTable.end());
94 return I->second;
95}
96
97void CodeViewContext::emitStringTable(MCObjectStreamer &OS) {
98 MCContext &Ctx = OS.getContext();
David Blaikiea0b44ef2016-01-29 02:23:13 +000099 MCSymbol *StringBegin = Ctx.createTempSymbol("strtab_begin", false),
100 *StringEnd = Ctx.createTempSymbol("strtab_end", false);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000101
102 OS.EmitIntValue(unsigned(ModuleSubstreamKind::StringTable), 4);
103 OS.emitAbsoluteSymbolDiff(StringEnd, StringBegin, 4);
104 OS.EmitLabel(StringBegin);
105
106 // Put the string table data fragment here, if we haven't already put it
107 // somewhere else. If somebody wants two string tables in their .s file, one
108 // will just be empty.
109 if (!InsertedStrTabFragment) {
110 OS.insert(getStringTableFragment());
111 InsertedStrTabFragment = true;
112 }
113
114 OS.EmitValueToAlignment(4, 0);
115
116 OS.EmitLabel(StringEnd);
117}
118
119void CodeViewContext::emitFileChecksums(MCObjectStreamer &OS) {
120 MCContext &Ctx = OS.getContext();
David Blaikiea0b44ef2016-01-29 02:23:13 +0000121 MCSymbol *FileBegin = Ctx.createTempSymbol("filechecksums_begin", false),
122 *FileEnd = Ctx.createTempSymbol("filechecksums_end", false);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000123
124 OS.EmitIntValue(unsigned(ModuleSubstreamKind::FileChecksums), 4);
125 OS.emitAbsoluteSymbolDiff(FileEnd, FileBegin, 4);
126 OS.EmitLabel(FileBegin);
127
128 // Emit an array of FileChecksum entries. We index into this table using the
129 // user-provided file number. Each entry is currently 8 bytes, as we don't
130 // emit checksums.
131 for (StringRef Filename : Filenames) {
132 OS.EmitIntValue(getStringTableOffset(Filename), 4);
133 // Zero the next two fields and align back to 4 bytes. This indicates that
134 // no checksum is present.
135 OS.EmitIntValue(0, 4);
136 }
137
138 OS.EmitLabel(FileEnd);
139}
140
141void CodeViewContext::emitLineTableForFunction(MCObjectStreamer &OS,
142 unsigned FuncId,
143 const MCSymbol *FuncBegin,
144 const MCSymbol *FuncEnd) {
145 MCContext &Ctx = OS.getContext();
David Blaikiea0b44ef2016-01-29 02:23:13 +0000146 MCSymbol *LineBegin = Ctx.createTempSymbol("linetable_begin", false),
147 *LineEnd = Ctx.createTempSymbol("linetable_end", false);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000148
149 OS.EmitIntValue(unsigned(ModuleSubstreamKind::Lines), 4);
150 OS.emitAbsoluteSymbolDiff(LineEnd, LineBegin, 4);
151 OS.EmitLabel(LineBegin);
152 OS.EmitCOFFSecRel32(FuncBegin);
153 OS.EmitCOFFSectionIndex(FuncBegin);
154
155 // Actual line info.
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000156 std::vector<MCCVLineEntry> Locs = getFunctionLineEntries(FuncId);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000157 bool HaveColumns = any_of(Locs, [](const MCCVLineEntry &LineEntry) {
158 return LineEntry.getColumn() != 0;
159 });
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000160 OS.EmitIntValue(HaveColumns ? int(LineFlags::HaveColumns) : 0, 2);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000161 OS.emitAbsoluteSymbolDiff(FuncEnd, FuncBegin, 4);
162
163 for (auto I = Locs.begin(), E = Locs.end(); I != E;) {
164 // Emit a file segment for the run of locations that share a file id.
165 unsigned CurFileNum = I->getFileNum();
166 auto FileSegEnd =
167 std::find_if(I, E, [CurFileNum](const MCCVLineEntry &Loc) {
168 return Loc.getFileNum() != CurFileNum;
169 });
170 unsigned EntryCount = FileSegEnd - I;
171 OS.AddComment("Segment for file '" + Twine(Filenames[CurFileNum - 1]) +
172 "' begins");
173 OS.EmitIntValue(8 * (CurFileNum - 1), 4);
174 OS.EmitIntValue(EntryCount, 4);
175 uint32_t SegmentSize = 12;
176 SegmentSize += 8 * EntryCount;
177 if (HaveColumns)
178 SegmentSize += 4 * EntryCount;
179 OS.EmitIntValue(SegmentSize, 4);
180
181 for (auto J = I; J != FileSegEnd; ++J) {
182 OS.emitAbsoluteSymbolDiff(J->getLabel(), FuncBegin, 4);
183 unsigned LineData = J->getLine();
184 if (J->isStmt())
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000185 LineData |= LineInfo::StatementFlag;
Reid Kleckner2214ed82016-01-29 00:49:42 +0000186 OS.EmitIntValue(LineData, 4);
187 }
188 if (HaveColumns) {
189 for (auto J = I; J != FileSegEnd; ++J) {
190 OS.EmitIntValue(J->getColumn(), 2);
191 OS.EmitIntValue(0, 2);
192 }
193 }
194 I = FileSegEnd;
195 }
196 OS.EmitLabel(LineEnd);
197}
198
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000199static bool compressAnnotation(uint32_t Data, SmallVectorImpl<char> &Buffer) {
200 if (isUInt<7>(Data)) {
201 Buffer.push_back(Data);
202 return true;
203 }
204
205 if (isUInt<14>(Data)) {
206 Buffer.push_back((Data >> 8) | 0x80);
207 Buffer.push_back(Data & 0xff);
208 return true;
209 }
210
211 if (isUInt<29>(Data)) {
212 Buffer.push_back((Data >> 24) | 0xC0);
213 Buffer.push_back((Data >> 16) & 0xff);
214 Buffer.push_back((Data >> 8) & 0xff);
215 Buffer.push_back(Data & 0xff);
216 return true;
217 }
218
219 return false;
220}
221
222static uint32_t encodeSignedNumber(uint32_t Data) {
223 if (Data >> 31)
224 return ((-Data) << 1) | 1;
225 return Data << 1;
226}
227
228void CodeViewContext::emitInlineLineTableForFunction(
229 MCObjectStreamer &OS, unsigned PrimaryFunctionId, unsigned SourceFileId,
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000230 unsigned SourceLineNum, const MCSymbol *FnStartSym,
David Majnemerc9911f22016-02-02 19:22:34 +0000231 const MCSymbol *FnEndSym, ArrayRef<unsigned> SecondaryFunctionIds) {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000232 // Create and insert a fragment into the current section that will be encoded
233 // later.
234 new MCCVInlineLineTableFragment(
David Majnemerc9911f22016-02-02 19:22:34 +0000235 PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym,
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000236 SecondaryFunctionIds, OS.getCurrentSectionOnly());
237}
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000238
Reid Klecknercb91e7d2016-02-04 00:21:42 +0000239static unsigned computeLabelDiff(MCAsmLayout &Layout, const MCSymbol *Begin,
240 const MCSymbol *End) {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000241 MCContext &Ctx = Layout.getAssembler().getContext();
242 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
243 const MCExpr *BeginRef = MCSymbolRefExpr::create(Begin, Variant, Ctx),
244 *EndRef = MCSymbolRefExpr::create(End, Variant, Ctx);
245 const MCExpr *AddrDelta =
246 MCBinaryExpr::create(MCBinaryExpr::Sub, EndRef, BeginRef, Ctx);
247 int64_t Result;
248 bool Success = AddrDelta->evaluateKnownAbsolute(Result, Layout);
249 assert(Success && "failed to evaluate label difference as absolute");
250 (void)Success;
251 assert(Result >= 0 && "negative label difference requested");
252 assert(Result < UINT_MAX && "label difference greater than 2GB");
253 return unsigned(Result);
254}
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000255
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000256void CodeViewContext::encodeInlineLineTable(MCAsmLayout &Layout,
257 MCCVInlineLineTableFragment &Frag) {
258 size_t LocBegin;
259 size_t LocEnd;
260 std::tie(LocBegin, LocEnd) = getLineExtent(Frag.SiteFuncId);
261 for (unsigned SecondaryId : Frag.SecondaryFuncs) {
262 auto Extent = getLineExtent(SecondaryId);
263 LocBegin = std::min(LocBegin, Extent.first);
264 LocEnd = std::max(LocEnd, Extent.second);
265 }
266 if (LocBegin >= LocEnd)
267 return;
David Majnemerc9911f22016-02-02 19:22:34 +0000268 ArrayRef<MCCVLineEntry> Locs = getLinesForExtent(LocBegin, LocEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000269 if (Locs.empty())
270 return;
271
272 SmallSet<unsigned, 8> InlinedFuncIds;
273 InlinedFuncIds.insert(Frag.SiteFuncId);
274 InlinedFuncIds.insert(Frag.SecondaryFuncs.begin(), Frag.SecondaryFuncs.end());
275
276 // Make an artificial start location using the function start and the inlinee
277 // lines start location information. All deltas start relative to this
278 // location.
279 MCCVLineEntry StartLoc(Frag.getFnStartSym(), MCCVLoc(Locs.front()));
280 StartLoc.setFileNum(Frag.StartFileId);
281 StartLoc.setLine(Frag.StartLineNum);
282 const MCCVLineEntry *LastLoc = &StartLoc;
283 bool WithinFunction = true;
284
285 SmallVectorImpl<char> &Buffer = Frag.getContents();
286 Buffer.clear(); // Clear old contents if we went through relaxation.
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000287 for (const MCCVLineEntry &Loc : Locs) {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000288 if (!InlinedFuncIds.count(Loc.getFunctionId())) {
289 // We've hit a cv_loc not attributed to this inline call site. Use this
290 // label to end the PC range.
291 if (WithinFunction) {
292 unsigned Length =
293 computeLabelDiff(Layout, LastLoc->getLabel(), Loc.getLabel());
294 compressAnnotation(ChangeCodeLength, Buffer);
295 compressAnnotation(Length, Buffer);
296 }
297 WithinFunction = false;
298 continue;
299 }
300 WithinFunction = true;
301
302 if (Loc.getFileNum() != LastLoc->getFileNum()) {
303 compressAnnotation(ChangeFile, Buffer);
304 compressAnnotation(Loc.getFileNum(), Buffer);
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000305 }
306
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000307 int LineDelta = Loc.getLine() - LastLoc->getLine();
308 if (LineDelta == 0)
309 continue;
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000310
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000311 unsigned EncodedLineDelta = encodeSignedNumber(LineDelta);
312 unsigned CodeDelta =
313 computeLabelDiff(Layout, LastLoc->getLabel(), Loc.getLabel());
314 if (CodeDelta == 0) {
315 compressAnnotation(ChangeLineOffset, Buffer);
316 compressAnnotation(EncodedLineDelta, Buffer);
317 } else if (EncodedLineDelta < 0x8 && CodeDelta <= 0xf) {
318 // The ChangeCodeOffsetAndLineOffset combination opcode is used when the
319 // encoded line delta uses 3 or fewer set bits and the code offset fits
320 // in one nibble.
321 unsigned Operand = (EncodedLineDelta << 4) | CodeDelta;
322 compressAnnotation(ChangeCodeOffsetAndLineOffset, Buffer);
323 compressAnnotation(Operand, Buffer);
324 } else {
325 // Otherwise use the separate line and code deltas.
326 compressAnnotation(ChangeLineOffset, Buffer);
327 compressAnnotation(EncodedLineDelta, Buffer);
328 compressAnnotation(ChangeCodeOffset, Buffer);
329 compressAnnotation(CodeDelta, Buffer);
330 }
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000331
332 LastLoc = &Loc;
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000333 }
David Majnemerc9911f22016-02-02 19:22:34 +0000334
335 assert(WithinFunction);
336
337 unsigned EndSymLength =
338 computeLabelDiff(Layout, LastLoc->getLabel(), Frag.getFnEndSym());
339 unsigned LocAfterLength = ~0U;
340 ArrayRef<MCCVLineEntry> LocAfter = getLinesForExtent(LocEnd, LocEnd + 1);
Reid Klecknercb91e7d2016-02-04 00:21:42 +0000341 if (!LocAfter.empty()) {
342 // Only try to compute this difference if we're in the same section.
343 const MCCVLineEntry &Loc = LocAfter[0];
344 if (&Loc.getLabel()->getSection(false) ==
345 &LastLoc->getLabel()->getSection(false)) {
346 LocAfterLength =
347 computeLabelDiff(Layout, LastLoc->getLabel(), Loc.getLabel());
348 }
349 }
David Majnemerc9911f22016-02-02 19:22:34 +0000350
351 compressAnnotation(ChangeCodeLength, Buffer);
352 compressAnnotation(std::min(EndSymLength, LocAfterLength), Buffer);
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000353}
354
Reid Kleckner2214ed82016-01-29 00:49:42 +0000355//
356// This is called when an instruction is assembled into the specified section
357// and if there is information from the last .cv_loc directive that has yet to have
358// a line entry made for it is made.
359//
360void MCCVLineEntry::Make(MCObjectStreamer *MCOS) {
361 if (!MCOS->getContext().getCVLocSeen())
362 return;
363
364 // Create a symbol at in the current section for use in the line entry.
365 MCSymbol *LineSym = MCOS->getContext().createTempSymbol();
366 // Set the value of the symbol to use for the MCCVLineEntry.
367 MCOS->EmitLabel(LineSym);
368
369 // Get the current .loc info saved in the context.
370 const MCCVLoc &CVLoc = MCOS->getContext().getCurrentCVLoc();
371
372 // Create a (local) line entry with the symbol and the current .loc info.
373 MCCVLineEntry LineEntry(LineSym, CVLoc);
374
375 // clear CVLocSeen saying the current .loc info is now used.
376 MCOS->getContext().clearCVLocSeen();
377
378 // Add the line entry to this section's entries.
379 MCOS->getContext().getCVContext().addLineEntry(LineEntry);
380}