blob: d14537c8f3b4d60ac3a68faf9271417870e78ac1 [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"
15#include "llvm/ADT/STLExtras.h"
Reid Kleckner26fa1bf2017-09-19 18:14:45 +000016#include "llvm/ADT/StringExtras.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000017#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"
Zachary Turnerd4273832017-05-30 21:53:05 +000020#include "llvm/MC/MCAsmLayout.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000021#include "llvm/MC/MCContext.h"
22#include "llvm/MC/MCObjectStreamer.h"
David Majnemer408b5e62016-02-05 01:55:49 +000023#include "llvm/MC/MCValue.h"
Reid Kleckner858239d2016-06-22 23:23:08 +000024#include "llvm/Support/EndianStream.h"
Reid Kleckner2214ed82016-01-29 00:49:42 +000025
26using namespace llvm;
27using namespace llvm::codeview;
28
29CodeViewContext::CodeViewContext() {}
30
31CodeViewContext::~CodeViewContext() {
32 // If someone inserted strings into the string table but never actually
33 // emitted them somewhere, clean up the fragment.
34 if (!InsertedStrTabFragment)
35 delete StrTabFragment;
36}
37
38/// This is a valid number for use with .cv_loc if we've already seen a .cv_file
39/// for it.
40bool CodeViewContext::isValidFileNumber(unsigned FileNumber) const {
41 unsigned Idx = FileNumber - 1;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +000042 if (Idx < Files.size())
43 return Files[Idx].Assigned;
Reid Kleckner2214ed82016-01-29 00:49:42 +000044 return false;
45}
46
Reid Kleckner26fa1bf2017-09-19 18:14:45 +000047bool CodeViewContext::addFile(MCStreamer &OS, unsigned FileNumber,
48 StringRef Filename,
49 ArrayRef<uint8_t> ChecksumBytes,
50 uint8_t ChecksumKind) {
Reid Kleckner2214ed82016-01-29 00:49:42 +000051 assert(FileNumber > 0);
Reid Kleckner26fa1bf2017-09-19 18:14:45 +000052 auto FilenameOffset = addToStringTable(Filename);
53 Filename = FilenameOffset.first;
Reid Kleckner2214ed82016-01-29 00:49:42 +000054 unsigned Idx = FileNumber - 1;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +000055 if (Idx >= Files.size())
56 Files.resize(Idx + 1);
Reid Kleckner2214ed82016-01-29 00:49:42 +000057
58 if (Filename.empty())
59 Filename = "<stdin>";
60
Reid Kleckner26fa1bf2017-09-19 18:14:45 +000061 if (Files[Idx].Assigned)
Reid Kleckner2214ed82016-01-29 00:49:42 +000062 return false;
63
Reid Kleckner26fa1bf2017-09-19 18:14:45 +000064 FilenameOffset = addToStringTable(Filename);
65 Filename = FilenameOffset.first;
66 unsigned Offset = FilenameOffset.second;
Reid Kleckner2214ed82016-01-29 00:49:42 +000067
Reid Kleckner26fa1bf2017-09-19 18:14:45 +000068 auto ChecksumOffsetSymbol =
69 OS.getContext().createTempSymbol("checksum_offset", false);
70 Files[Idx].StringTableOffset = Offset;
71 Files[Idx].ChecksumTableOffset = ChecksumOffsetSymbol;
72 Files[Idx].Assigned = true;
73 Files[Idx].Checksum = ChecksumBytes;
74 Files[Idx].ChecksumKind = ChecksumKind;
75
Reid Kleckner2214ed82016-01-29 00:49:42 +000076 return true;
77}
78
Reid Klecknera9f4cc92016-09-07 16:15:31 +000079bool CodeViewContext::recordFunctionId(unsigned FuncId) {
80 if (FuncId >= Functions.size())
81 Functions.resize(FuncId + 1);
82
83 // Return false if this function info was already allocated.
84 if (!Functions[FuncId].isUnallocatedFunctionInfo())
85 return false;
86
87 // Mark this as an allocated normal function, and leave the rest alone.
88 Functions[FuncId].ParentFuncIdPlusOne = MCCVFunctionInfo::FunctionSentinel;
89 return true;
90}
91
92bool CodeViewContext::recordInlinedCallSiteId(unsigned FuncId, unsigned IAFunc,
93 unsigned IAFile, unsigned IALine,
94 unsigned IACol) {
95 if (FuncId >= Functions.size())
96 Functions.resize(FuncId + 1);
97
98 // Return false if this function info was already allocated.
99 if (!Functions[FuncId].isUnallocatedFunctionInfo())
100 return false;
101
102 MCCVFunctionInfo::LineInfo InlinedAt;
103 InlinedAt.File = IAFile;
104 InlinedAt.Line = IALine;
105 InlinedAt.Col = IACol;
106
107 // Mark this as an inlined call site and record call site line info.
108 MCCVFunctionInfo *Info = &Functions[FuncId];
109 Info->ParentFuncIdPlusOne = IAFunc + 1;
110 Info->InlinedAt = InlinedAt;
111
112 // Walk up the call chain adding this function id to the InlinedAtMap of all
113 // transitive callers until we hit a real function.
114 while (Info->isInlinedCallSite()) {
115 InlinedAt = Info->InlinedAt;
116 Info = getCVFunctionInfo(Info->getParentFuncId());
117 Info->InlinedAtMap[FuncId] = InlinedAt;
118 }
119
120 return true;
121}
122
Reid Kleckner2214ed82016-01-29 00:49:42 +0000123MCDataFragment *CodeViewContext::getStringTableFragment() {
124 if (!StrTabFragment) {
125 StrTabFragment = new MCDataFragment();
126 // Start a new string table out with a null byte.
127 StrTabFragment->getContents().push_back('\0');
128 }
129 return StrTabFragment;
130}
131
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000132std::pair<StringRef, unsigned> CodeViewContext::addToStringTable(StringRef S) {
Reid Kleckner2214ed82016-01-29 00:49:42 +0000133 SmallVectorImpl<char> &Contents = getStringTableFragment()->getContents();
134 auto Insertion =
135 StringTable.insert(std::make_pair(S, unsigned(Contents.size())));
136 // Return the string from the table, since it is stable.
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000137 std::pair<StringRef, unsigned> Ret =
138 std::make_pair(Insertion.first->first(), Insertion.first->second);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000139 if (Insertion.second) {
140 // The string map key is always null terminated.
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000141 Contents.append(Ret.first.begin(), Ret.first.end() + 1);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000142 }
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000143 return Ret;
Reid Kleckner2214ed82016-01-29 00:49:42 +0000144}
145
146unsigned CodeViewContext::getStringTableOffset(StringRef S) {
147 // A string table offset of zero is always the empty string.
148 if (S.empty())
149 return 0;
150 auto I = StringTable.find(S);
151 assert(I != StringTable.end());
152 return I->second;
153}
154
155void CodeViewContext::emitStringTable(MCObjectStreamer &OS) {
156 MCContext &Ctx = OS.getContext();
David Blaikiea0b44ef2016-01-29 02:23:13 +0000157 MCSymbol *StringBegin = Ctx.createTempSymbol("strtab_begin", false),
158 *StringEnd = Ctx.createTempSymbol("strtab_end", false);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000159
Zachary Turner8c099fe2017-05-30 16:36:15 +0000160 OS.EmitIntValue(unsigned(DebugSubsectionKind::StringTable), 4);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000161 OS.emitAbsoluteSymbolDiff(StringEnd, StringBegin, 4);
162 OS.EmitLabel(StringBegin);
163
164 // Put the string table data fragment here, if we haven't already put it
165 // somewhere else. If somebody wants two string tables in their .s file, one
166 // will just be empty.
167 if (!InsertedStrTabFragment) {
168 OS.insert(getStringTableFragment());
169 InsertedStrTabFragment = true;
170 }
171
172 OS.EmitValueToAlignment(4, 0);
173
174 OS.EmitLabel(StringEnd);
175}
176
177void CodeViewContext::emitFileChecksums(MCObjectStreamer &OS) {
Reid Kleckneree641c22016-06-08 17:50:29 +0000178 // Do nothing if there are no file checksums. Microsoft's linker rejects empty
179 // CodeView substreams.
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000180 if (Files.empty())
Reid Kleckneree641c22016-06-08 17:50:29 +0000181 return;
182
Reid Kleckner2214ed82016-01-29 00:49:42 +0000183 MCContext &Ctx = OS.getContext();
David Blaikiea0b44ef2016-01-29 02:23:13 +0000184 MCSymbol *FileBegin = Ctx.createTempSymbol("filechecksums_begin", false),
185 *FileEnd = Ctx.createTempSymbol("filechecksums_end", false);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000186
Zachary Turner8c099fe2017-05-30 16:36:15 +0000187 OS.EmitIntValue(unsigned(DebugSubsectionKind::FileChecksums), 4);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000188 OS.emitAbsoluteSymbolDiff(FileEnd, FileBegin, 4);
189 OS.EmitLabel(FileBegin);
190
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000191 unsigned CurrentOffset = 0;
192
Reid Kleckner2214ed82016-01-29 00:49:42 +0000193 // Emit an array of FileChecksum entries. We index into this table using the
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000194 // user-provided file number. Each entry may be a variable number of bytes
195 // determined by the checksum kind and size.
196 for (auto File : Files) {
197 OS.EmitAssignment(File.ChecksumTableOffset,
198 MCConstantExpr::create(CurrentOffset, Ctx));
199 CurrentOffset += 4; // String table offset.
200 if (!File.ChecksumKind) {
201 CurrentOffset +=
202 4; // One byte each for checksum size and kind, then align to 4 bytes.
203 } else {
204 CurrentOffset += 2; // One byte each for checksum size and kind.
205 CurrentOffset += File.Checksum.size();
206 CurrentOffset = alignTo(CurrentOffset, 4);
207 }
208
209 OS.EmitIntValue(File.StringTableOffset, 4);
210
211 if (!File.ChecksumKind) {
212 // There is no checksum. Therefore zero the next two fields and align
213 // back to 4 bytes.
214 OS.EmitIntValue(0, 4);
215 continue;
216 }
217 OS.EmitIntValue(static_cast<uint8_t>(File.Checksum.size()), 1);
218 OS.EmitIntValue(File.ChecksumKind, 1);
219 OS.EmitBytes(toStringRef(File.Checksum));
220 OS.EmitValueToAlignment(4);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000221 }
222
223 OS.EmitLabel(FileEnd);
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000224
225 ChecksumOffsetsAssigned = true;
226}
227
228// Output checksum table offset of the given file number. It is possible that
229// not all files have been registered yet, and so the offset cannot be
230// calculated. In this case a symbol representing the offset is emitted, and
231// the value of this symbol will be fixed up at a later time.
232void CodeViewContext::emitFileChecksumOffset(MCObjectStreamer &OS,
233 unsigned FileNo) {
234 unsigned Idx = FileNo - 1;
235
236 if (Idx >= Files.size())
237 Files.resize(Idx + 1);
238
239 if (ChecksumOffsetsAssigned) {
240 OS.EmitSymbolValue(Files[Idx].ChecksumTableOffset, 4);
241 return;
242 }
243
244 const MCSymbolRefExpr *SRE =
245 MCSymbolRefExpr::create(Files[Idx].ChecksumTableOffset, OS.getContext());
246
247 OS.EmitValueImpl(SRE, 4);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000248}
249
250void CodeViewContext::emitLineTableForFunction(MCObjectStreamer &OS,
251 unsigned FuncId,
252 const MCSymbol *FuncBegin,
253 const MCSymbol *FuncEnd) {
254 MCContext &Ctx = OS.getContext();
David Blaikiea0b44ef2016-01-29 02:23:13 +0000255 MCSymbol *LineBegin = Ctx.createTempSymbol("linetable_begin", false),
256 *LineEnd = Ctx.createTempSymbol("linetable_end", false);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000257
Zachary Turner8c099fe2017-05-30 16:36:15 +0000258 OS.EmitIntValue(unsigned(DebugSubsectionKind::Lines), 4);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000259 OS.emitAbsoluteSymbolDiff(LineEnd, LineBegin, 4);
260 OS.EmitLabel(LineBegin);
Keno Fischerf7d84ee2017-01-02 03:00:19 +0000261 OS.EmitCOFFSecRel32(FuncBegin, /*Offset=*/0);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000262 OS.EmitCOFFSectionIndex(FuncBegin);
263
264 // Actual line info.
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000265 std::vector<MCCVLineEntry> Locs = getFunctionLineEntries(FuncId);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000266 bool HaveColumns = any_of(Locs, [](const MCCVLineEntry &LineEntry) {
267 return LineEntry.getColumn() != 0;
268 });
Zachary Turner5b6e4e02017-04-29 01:13:21 +0000269 OS.EmitIntValue(HaveColumns ? int(LF_HaveColumns) : 0, 2);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000270 OS.emitAbsoluteSymbolDiff(FuncEnd, FuncBegin, 4);
271
272 for (auto I = Locs.begin(), E = Locs.end(); I != E;) {
273 // Emit a file segment for the run of locations that share a file id.
274 unsigned CurFileNum = I->getFileNum();
275 auto FileSegEnd =
276 std::find_if(I, E, [CurFileNum](const MCCVLineEntry &Loc) {
277 return Loc.getFileNum() != CurFileNum;
278 });
279 unsigned EntryCount = FileSegEnd - I;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000280 OS.AddComment(
281 "Segment for file '" +
282 Twine(getStringTableFragment()
283 ->getContents()[Files[CurFileNum - 1].StringTableOffset]) +
284 "' begins");
285 OS.EmitCVFileChecksumOffsetDirective(CurFileNum);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000286 OS.EmitIntValue(EntryCount, 4);
287 uint32_t SegmentSize = 12;
288 SegmentSize += 8 * EntryCount;
289 if (HaveColumns)
290 SegmentSize += 4 * EntryCount;
291 OS.EmitIntValue(SegmentSize, 4);
292
293 for (auto J = I; J != FileSegEnd; ++J) {
294 OS.emitAbsoluteSymbolDiff(J->getLabel(), FuncBegin, 4);
295 unsigned LineData = J->getLine();
296 if (J->isStmt())
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000297 LineData |= LineInfo::StatementFlag;
Reid Kleckner2214ed82016-01-29 00:49:42 +0000298 OS.EmitIntValue(LineData, 4);
299 }
300 if (HaveColumns) {
301 for (auto J = I; J != FileSegEnd; ++J) {
302 OS.EmitIntValue(J->getColumn(), 2);
303 OS.EmitIntValue(0, 2);
304 }
305 }
306 I = FileSegEnd;
307 }
308 OS.EmitLabel(LineEnd);
309}
310
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000311static bool compressAnnotation(uint32_t Data, SmallVectorImpl<char> &Buffer) {
312 if (isUInt<7>(Data)) {
313 Buffer.push_back(Data);
314 return true;
315 }
316
317 if (isUInt<14>(Data)) {
318 Buffer.push_back((Data >> 8) | 0x80);
319 Buffer.push_back(Data & 0xff);
320 return true;
321 }
322
323 if (isUInt<29>(Data)) {
324 Buffer.push_back((Data >> 24) | 0xC0);
325 Buffer.push_back((Data >> 16) & 0xff);
326 Buffer.push_back((Data >> 8) & 0xff);
327 Buffer.push_back(Data & 0xff);
328 return true;
329 }
330
331 return false;
332}
333
Zachary Turner63a28462016-05-17 23:50:21 +0000334static bool compressAnnotation(BinaryAnnotationsOpCode Annotation,
335 SmallVectorImpl<char> &Buffer) {
336 return compressAnnotation(static_cast<uint32_t>(Annotation), Buffer);
337}
338
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000339static uint32_t encodeSignedNumber(uint32_t Data) {
340 if (Data >> 31)
341 return ((-Data) << 1) | 1;
342 return Data << 1;
343}
344
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000345void CodeViewContext::emitInlineLineTableForFunction(MCObjectStreamer &OS,
346 unsigned PrimaryFunctionId,
347 unsigned SourceFileId,
348 unsigned SourceLineNum,
349 const MCSymbol *FnStartSym,
350 const MCSymbol *FnEndSym) {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000351 // Create and insert a fragment into the current section that will be encoded
352 // later.
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000353 new MCCVInlineLineTableFragment(PrimaryFunctionId, SourceFileId,
354 SourceLineNum, FnStartSym, FnEndSym,
355 OS.getCurrentSectionOnly());
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000356}
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000357
David Majnemer408b5e62016-02-05 01:55:49 +0000358void CodeViewContext::emitDefRange(
359 MCObjectStreamer &OS,
360 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
361 StringRef FixedSizePortion) {
362 // Create and insert a fragment into the current section that will be encoded
363 // later.
364 new MCCVDefRangeFragment(Ranges, FixedSizePortion,
365 OS.getCurrentSectionOnly());
366}
367
Reid Klecknercb91e7d2016-02-04 00:21:42 +0000368static unsigned computeLabelDiff(MCAsmLayout &Layout, const MCSymbol *Begin,
369 const MCSymbol *End) {
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000370 MCContext &Ctx = Layout.getAssembler().getContext();
371 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
372 const MCExpr *BeginRef = MCSymbolRefExpr::create(Begin, Variant, Ctx),
373 *EndRef = MCSymbolRefExpr::create(End, Variant, Ctx);
374 const MCExpr *AddrDelta =
375 MCBinaryExpr::create(MCBinaryExpr::Sub, EndRef, BeginRef, Ctx);
376 int64_t Result;
377 bool Success = AddrDelta->evaluateKnownAbsolute(Result, Layout);
378 assert(Success && "failed to evaluate label difference as absolute");
379 (void)Success;
380 assert(Result >= 0 && "negative label difference requested");
381 assert(Result < UINT_MAX && "label difference greater than 2GB");
382 return unsigned(Result);
383}
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000384
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000385void CodeViewContext::encodeInlineLineTable(MCAsmLayout &Layout,
386 MCCVInlineLineTableFragment &Frag) {
387 size_t LocBegin;
388 size_t LocEnd;
389 std::tie(LocBegin, LocEnd) = getLineExtent(Frag.SiteFuncId);
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000390
391 // Include all child inline call sites in our .cv_loc extent.
392 MCCVFunctionInfo *SiteInfo = getCVFunctionInfo(Frag.SiteFuncId);
393 for (auto &KV : SiteInfo->InlinedAtMap) {
394 unsigned ChildId = KV.first;
395 auto Extent = getLineExtent(ChildId);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000396 LocBegin = std::min(LocBegin, Extent.first);
397 LocEnd = std::max(LocEnd, Extent.second);
398 }
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000399
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000400 if (LocBegin >= LocEnd)
401 return;
David Majnemerc9911f22016-02-02 19:22:34 +0000402 ArrayRef<MCCVLineEntry> Locs = getLinesForExtent(LocBegin, LocEnd);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000403 if (Locs.empty())
404 return;
405
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000406 // Make an artificial start location using the function start and the inlinee
407 // lines start location information. All deltas start relative to this
408 // location.
409 MCCVLineEntry StartLoc(Frag.getFnStartSym(), MCCVLoc(Locs.front()));
410 StartLoc.setFileNum(Frag.StartFileId);
411 StartLoc.setLine(Frag.StartLineNum);
Reid Klecknerc29b4f02016-07-14 23:47:15 +0000412 bool HaveOpenRange = false;
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000413
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000414 const MCSymbol *LastLabel = Frag.getFnStartSym();
415 MCCVFunctionInfo::LineInfo LastSourceLoc, CurSourceLoc;
416 LastSourceLoc.File = Frag.StartFileId;
417 LastSourceLoc.Line = Frag.StartLineNum;
418
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000419 SmallVectorImpl<char> &Buffer = Frag.getContents();
420 Buffer.clear(); // Clear old contents if we went through relaxation.
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000421 for (const MCCVLineEntry &Loc : Locs) {
Reid Klecknerbb96df62016-10-05 22:36:07 +0000422 // Exit early if our line table would produce an oversized InlineSiteSym
423 // record. Account for the ChangeCodeLength annotation emitted after the
424 // loop ends.
Zachary Turner46225b12016-12-16 22:48:14 +0000425 constexpr uint32_t InlineSiteSize = 12;
426 constexpr uint32_t AnnotationSize = 8;
427 size_t MaxBufferSize = MaxRecordLength - InlineSiteSize - AnnotationSize;
Reid Klecknerbb96df62016-10-05 22:36:07 +0000428 if (Buffer.size() >= MaxBufferSize)
429 break;
430
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000431 if (Loc.getFunctionId() == Frag.SiteFuncId) {
432 CurSourceLoc.File = Loc.getFileNum();
433 CurSourceLoc.Line = Loc.getLine();
434 } else {
435 auto I = SiteInfo->InlinedAtMap.find(Loc.getFunctionId());
436 if (I != SiteInfo->InlinedAtMap.end()) {
437 // This .cv_loc is from a child inline call site. Use the source
438 // location of the inlined call site instead of the .cv_loc directive
439 // source location.
440 CurSourceLoc = I->second;
441 } else {
442 // We've hit a cv_loc not attributed to this inline call site. Use this
443 // label to end the PC range.
444 if (HaveOpenRange) {
445 unsigned Length = computeLabelDiff(Layout, LastLabel, Loc.getLabel());
446 compressAnnotation(BinaryAnnotationsOpCode::ChangeCodeLength, Buffer);
447 compressAnnotation(Length, Buffer);
448 LastLabel = Loc.getLabel();
449 }
450 HaveOpenRange = false;
451 continue;
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000452 }
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000453 }
Reid Klecknerc29b4f02016-07-14 23:47:15 +0000454
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000455 // Skip this .cv_loc if we have an open range and this isn't a meaningful
456 // source location update. The current table format does not support column
457 // info, so we can skip updates for those.
458 if (HaveOpenRange && CurSourceLoc.File == LastSourceLoc.File &&
459 CurSourceLoc.Line == LastSourceLoc.Line)
Reid Klecknerc29b4f02016-07-14 23:47:15 +0000460 continue;
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000461
Reid Klecknerc29b4f02016-07-14 23:47:15 +0000462 HaveOpenRange = true;
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000463
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000464 if (CurSourceLoc.File != LastSourceLoc.File) {
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000465 unsigned FileOffset = static_cast<const MCConstantExpr *>(
466 Files[CurSourceLoc.File - 1]
467 .ChecksumTableOffset->getVariableValue())
468 ->getValue();
Zachary Turner63a28462016-05-17 23:50:21 +0000469 compressAnnotation(BinaryAnnotationsOpCode::ChangeFile, Buffer);
Reid Kleckner344078f2016-02-19 23:55:38 +0000470 compressAnnotation(FileOffset, Buffer);
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000471 }
472
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000473 int LineDelta = CurSourceLoc.Line - LastSourceLoc.Line;
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000474 unsigned EncodedLineDelta = encodeSignedNumber(LineDelta);
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000475 unsigned CodeDelta = computeLabelDiff(Layout, LastLabel, Loc.getLabel());
476 if (CodeDelta == 0 && LineDelta != 0) {
Zachary Turner63a28462016-05-17 23:50:21 +0000477 compressAnnotation(BinaryAnnotationsOpCode::ChangeLineOffset, Buffer);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000478 compressAnnotation(EncodedLineDelta, Buffer);
479 } else if (EncodedLineDelta < 0x8 && CodeDelta <= 0xf) {
480 // The ChangeCodeOffsetAndLineOffset combination opcode is used when the
481 // encoded line delta uses 3 or fewer set bits and the code offset fits
482 // in one nibble.
483 unsigned Operand = (EncodedLineDelta << 4) | CodeDelta;
Zachary Turner63a28462016-05-17 23:50:21 +0000484 compressAnnotation(BinaryAnnotationsOpCode::ChangeCodeOffsetAndLineOffset,
485 Buffer);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000486 compressAnnotation(Operand, Buffer);
487 } else {
488 // Otherwise use the separate line and code deltas.
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000489 if (LineDelta != 0) {
490 compressAnnotation(BinaryAnnotationsOpCode::ChangeLineOffset, Buffer);
491 compressAnnotation(EncodedLineDelta, Buffer);
492 }
Zachary Turner63a28462016-05-17 23:50:21 +0000493 compressAnnotation(BinaryAnnotationsOpCode::ChangeCodeOffset, Buffer);
Reid Kleckner1fcd6102016-02-02 17:41:18 +0000494 compressAnnotation(CodeDelta, Buffer);
495 }
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000496
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000497 LastLabel = Loc.getLabel();
498 LastSourceLoc = CurSourceLoc;
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000499 }
David Majnemerc9911f22016-02-02 19:22:34 +0000500
Reid Klecknerc29b4f02016-07-14 23:47:15 +0000501 assert(HaveOpenRange);
David Majnemerc9911f22016-02-02 19:22:34 +0000502
503 unsigned EndSymLength =
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000504 computeLabelDiff(Layout, LastLabel, Frag.getFnEndSym());
David Majnemerc9911f22016-02-02 19:22:34 +0000505 unsigned LocAfterLength = ~0U;
506 ArrayRef<MCCVLineEntry> LocAfter = getLinesForExtent(LocEnd, LocEnd + 1);
Reid Klecknercb91e7d2016-02-04 00:21:42 +0000507 if (!LocAfter.empty()) {
508 // Only try to compute this difference if we're in the same section.
509 const MCCVLineEntry &Loc = LocAfter[0];
Sam Clegg5e102ee2018-01-12 18:05:40 +0000510 if (&Loc.getLabel()->getSection() == &LastLabel->getSection())
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000511 LocAfterLength = computeLabelDiff(Layout, LastLabel, Loc.getLabel());
Reid Klecknercb91e7d2016-02-04 00:21:42 +0000512 }
David Majnemerc9911f22016-02-02 19:22:34 +0000513
Zachary Turner63a28462016-05-17 23:50:21 +0000514 compressAnnotation(BinaryAnnotationsOpCode::ChangeCodeLength, Buffer);
David Majnemerc9911f22016-02-02 19:22:34 +0000515 compressAnnotation(std::min(EndSymLength, LocAfterLength), Buffer);
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000516}
517
David Majnemer408b5e62016-02-05 01:55:49 +0000518void CodeViewContext::encodeDefRange(MCAsmLayout &Layout,
519 MCCVDefRangeFragment &Frag) {
520 MCContext &Ctx = Layout.getAssembler().getContext();
521 SmallVectorImpl<char> &Contents = Frag.getContents();
522 Contents.clear();
523 SmallVectorImpl<MCFixup> &Fixups = Frag.getFixups();
524 Fixups.clear();
525 raw_svector_ostream OS(Contents);
526
Reid Klecknerbe82d3e2016-09-15 22:05:08 +0000527 // Compute all the sizes up front.
528 SmallVector<std::pair<unsigned, unsigned>, 4> GapAndRangeSizes;
529 const MCSymbol *LastLabel = nullptr;
David Majnemer408b5e62016-02-05 01:55:49 +0000530 for (std::pair<const MCSymbol *, const MCSymbol *> Range : Frag.getRanges()) {
Reid Klecknerbe82d3e2016-09-15 22:05:08 +0000531 unsigned GapSize =
532 LastLabel ? computeLabelDiff(Layout, LastLabel, Range.first) : 0;
David Majnemer408b5e62016-02-05 01:55:49 +0000533 unsigned RangeSize = computeLabelDiff(Layout, Range.first, Range.second);
Reid Klecknerbe82d3e2016-09-15 22:05:08 +0000534 GapAndRangeSizes.push_back({GapSize, RangeSize});
535 LastLabel = Range.second;
536 }
537
538 // Write down each range where the variable is defined.
539 for (size_t I = 0, E = Frag.getRanges().size(); I != E;) {
540 // If the range size of multiple consecutive ranges is under the max,
541 // combine the ranges and emit some gaps.
542 const MCSymbol *RangeBegin = Frag.getRanges()[I].first;
543 unsigned RangeSize = GapAndRangeSizes[I].second;
544 size_t J = I + 1;
545 for (; J != E; ++J) {
546 unsigned GapAndRangeSize = GapAndRangeSizes[J].first + GapAndRangeSizes[J].second;
547 if (RangeSize + GapAndRangeSize > MaxDefRange)
548 break;
549 RangeSize += GapAndRangeSize;
550 }
551 unsigned NumGaps = J - I - 1;
552
553 support::endian::Writer<support::little> LEWriter(OS);
554
David Majnemer408b5e62016-02-05 01:55:49 +0000555 unsigned Bias = 0;
556 // We must split the range into chunks of MaxDefRange, this is a fundamental
557 // limitation of the file format.
558 do {
559 uint16_t Chunk = std::min((uint32_t)MaxDefRange, RangeSize);
560
Reid Klecknerbe82d3e2016-09-15 22:05:08 +0000561 const MCSymbolRefExpr *SRE = MCSymbolRefExpr::create(RangeBegin, Ctx);
David Majnemer408b5e62016-02-05 01:55:49 +0000562 const MCBinaryExpr *BE =
563 MCBinaryExpr::createAdd(SRE, MCConstantExpr::create(Bias, Ctx), Ctx);
564 MCValue Res;
565 BE->evaluateAsRelocatable(Res, &Layout, /*Fixup=*/nullptr);
566
567 // Each record begins with a 2-byte number indicating how large the record
568 // is.
569 StringRef FixedSizePortion = Frag.getFixedSizePortion();
570 // Our record is a fixed sized prefix and a LocalVariableAddrRange that we
571 // are artificially constructing.
Reid Klecknerbe82d3e2016-09-15 22:05:08 +0000572 size_t RecordSize = FixedSizePortion.size() +
573 sizeof(LocalVariableAddrRange) + 4 * NumGaps;
Reid Kleckner11cf0532017-01-24 16:57:55 +0000574 // Write out the record size.
575 LEWriter.write<uint16_t>(RecordSize);
David Majnemer408b5e62016-02-05 01:55:49 +0000576 // Write out the fixed size prefix.
577 OS << FixedSizePortion;
578 // Make space for a fixup that will eventually have a section relative
579 // relocation pointing at the offset where the variable becomes live.
580 Fixups.push_back(MCFixup::create(Contents.size(), BE, FK_SecRel_4));
Reid Kleckner11cf0532017-01-24 16:57:55 +0000581 LEWriter.write<uint32_t>(0); // Fixup for code start.
David Majnemer408b5e62016-02-05 01:55:49 +0000582 // Make space for a fixup that will record the section index for the code.
583 Fixups.push_back(MCFixup::create(Contents.size(), BE, FK_SecRel_2));
Reid Kleckner11cf0532017-01-24 16:57:55 +0000584 LEWriter.write<uint16_t>(0); // Fixup for section index.
David Majnemer408b5e62016-02-05 01:55:49 +0000585 // Write down the range's extent.
Reid Klecknerbe82d3e2016-09-15 22:05:08 +0000586 LEWriter.write<uint16_t>(Chunk);
David Majnemer408b5e62016-02-05 01:55:49 +0000587
588 // Move on to the next range.
589 Bias += Chunk;
590 RangeSize -= Chunk;
591 } while (RangeSize > 0);
Reid Klecknerbe82d3e2016-09-15 22:05:08 +0000592
593 // Emit the gaps afterwards.
Reid Kleckner11cf0532017-01-24 16:57:55 +0000594 assert((NumGaps == 0 || Bias <= MaxDefRange) &&
Reid Klecknerbe82d3e2016-09-15 22:05:08 +0000595 "large ranges should not have gaps");
596 unsigned GapStartOffset = GapAndRangeSizes[I].second;
597 for (++I; I != J; ++I) {
598 unsigned GapSize, RangeSize;
599 assert(I < GapAndRangeSizes.size());
600 std::tie(GapSize, RangeSize) = GapAndRangeSizes[I];
601 LEWriter.write<uint16_t>(GapStartOffset);
Reid Kleckner11cf0532017-01-24 16:57:55 +0000602 LEWriter.write<uint16_t>(GapSize);
Reid Klecknerbe82d3e2016-09-15 22:05:08 +0000603 GapStartOffset += GapSize + RangeSize;
604 }
David Majnemer408b5e62016-02-05 01:55:49 +0000605 }
606}
607
Reid Kleckner2214ed82016-01-29 00:49:42 +0000608//
609// This is called when an instruction is assembled into the specified section
610// and if there is information from the last .cv_loc directive that has yet to have
611// a line entry made for it is made.
612//
613void MCCVLineEntry::Make(MCObjectStreamer *MCOS) {
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000614 CodeViewContext &CVC = MCOS->getContext().getCVContext();
615 if (!CVC.getCVLocSeen())
Reid Kleckner2214ed82016-01-29 00:49:42 +0000616 return;
617
618 // Create a symbol at in the current section for use in the line entry.
619 MCSymbol *LineSym = MCOS->getContext().createTempSymbol();
620 // Set the value of the symbol to use for the MCCVLineEntry.
621 MCOS->EmitLabel(LineSym);
622
623 // Get the current .loc info saved in the context.
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000624 const MCCVLoc &CVLoc = CVC.getCurrentCVLoc();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000625
626 // Create a (local) line entry with the symbol and the current .loc info.
627 MCCVLineEntry LineEntry(LineSym, CVLoc);
628
629 // clear CVLocSeen saying the current .loc info is now used.
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000630 CVC.clearCVLocSeen();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000631
632 // Add the line entry to this section's entries.
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000633 CVC.addLineEntry(LineEntry);
Reid Kleckner2214ed82016-01-29 00:49:42 +0000634}