1 | //===- MCCodeView.h - Machine Code CodeView support -------------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // Holds state from .cv_file and .cv_loc directives for later emission. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #include "llvm/MC/MCCodeView.h" |
14 | #include "llvm/ADT/STLExtras.h" |
15 | #include "llvm/ADT/StringExtras.h" |
16 | #include "llvm/DebugInfo/CodeView/CodeView.h" |
17 | #include "llvm/DebugInfo/CodeView/Line.h" |
18 | #include "llvm/DebugInfo/CodeView/SymbolRecord.h" |
19 | #include "llvm/MC/MCAssembler.h" |
20 | #include "llvm/MC/MCContext.h" |
21 | #include "llvm/MC/MCObjectStreamer.h" |
22 | #include "llvm/MC/MCValue.h" |
23 | #include "llvm/Support/EndianStream.h" |
24 | |
25 | using namespace llvm; |
26 | using namespace llvm::codeview; |
27 | |
28 | void CodeViewContext::finish() { |
29 | if (StrTabFragment) |
30 | StrTabFragment->setContents(StrTab); |
31 | } |
32 | |
33 | /// This is a valid number for use with .cv_loc if we've already seen a .cv_file |
34 | /// for it. |
35 | bool CodeViewContext::isValidFileNumber(unsigned FileNumber) const { |
36 | unsigned Idx = FileNumber - 1; |
37 | if (Idx < Files.size()) |
38 | return Files[Idx].Assigned; |
39 | return false; |
40 | } |
41 | |
42 | bool CodeViewContext::addFile(MCStreamer &OS, unsigned FileNumber, |
43 | StringRef Filename, |
44 | ArrayRef<uint8_t> ChecksumBytes, |
45 | uint8_t ChecksumKind) { |
46 | assert(FileNumber > 0); |
47 | auto FilenameOffset = addToStringTable(S: Filename); |
48 | Filename = FilenameOffset.first; |
49 | unsigned Idx = FileNumber - 1; |
50 | if (Idx >= Files.size()) |
51 | Files.resize(N: Idx + 1); |
52 | |
53 | if (Filename.empty()) |
54 | Filename = "<stdin>" ; |
55 | |
56 | if (Files[Idx].Assigned) |
57 | return false; |
58 | |
59 | FilenameOffset = addToStringTable(S: Filename); |
60 | Filename = FilenameOffset.first; |
61 | unsigned Offset = FilenameOffset.second; |
62 | |
63 | auto ChecksumOffsetSymbol = |
64 | OS.getContext().createTempSymbol(Name: "checksum_offset" , AlwaysAddSuffix: false); |
65 | Files[Idx].StringTableOffset = Offset; |
66 | Files[Idx].ChecksumTableOffset = ChecksumOffsetSymbol; |
67 | Files[Idx].Assigned = true; |
68 | Files[Idx].Checksum = ChecksumBytes; |
69 | Files[Idx].ChecksumKind = ChecksumKind; |
70 | |
71 | return true; |
72 | } |
73 | |
74 | MCCVFunctionInfo *CodeViewContext::getCVFunctionInfo(unsigned FuncId) { |
75 | if (FuncId >= Functions.size()) |
76 | return nullptr; |
77 | if (Functions[FuncId].isUnallocatedFunctionInfo()) |
78 | return nullptr; |
79 | return &Functions[FuncId]; |
80 | } |
81 | |
82 | bool CodeViewContext::recordFunctionId(unsigned FuncId) { |
83 | if (FuncId >= Functions.size()) |
84 | Functions.resize(new_size: FuncId + 1); |
85 | |
86 | // Return false if this function info was already allocated. |
87 | if (!Functions[FuncId].isUnallocatedFunctionInfo()) |
88 | return false; |
89 | |
90 | // Mark this as an allocated normal function, and leave the rest alone. |
91 | Functions[FuncId].ParentFuncIdPlusOne = MCCVFunctionInfo::FunctionSentinel; |
92 | return true; |
93 | } |
94 | |
95 | bool CodeViewContext::recordInlinedCallSiteId(unsigned FuncId, unsigned IAFunc, |
96 | unsigned IAFile, unsigned IALine, |
97 | unsigned IACol) { |
98 | if (FuncId >= Functions.size()) |
99 | Functions.resize(new_size: FuncId + 1); |
100 | |
101 | // Return false if this function info was already allocated. |
102 | if (!Functions[FuncId].isUnallocatedFunctionInfo()) |
103 | return false; |
104 | |
105 | MCCVFunctionInfo::LineInfo InlinedAt; |
106 | InlinedAt.File = IAFile; |
107 | InlinedAt.Line = IALine; |
108 | InlinedAt.Col = IACol; |
109 | |
110 | // Mark this as an inlined call site and record call site line info. |
111 | MCCVFunctionInfo *Info = &Functions[FuncId]; |
112 | Info->ParentFuncIdPlusOne = IAFunc + 1; |
113 | Info->InlinedAt = InlinedAt; |
114 | |
115 | // Walk up the call chain adding this function id to the InlinedAtMap of all |
116 | // transitive callers until we hit a real function. |
117 | while (Info->isInlinedCallSite()) { |
118 | InlinedAt = Info->InlinedAt; |
119 | Info = getCVFunctionInfo(FuncId: Info->getParentFuncId()); |
120 | Info->InlinedAtMap[FuncId] = InlinedAt; |
121 | } |
122 | |
123 | return true; |
124 | } |
125 | |
126 | void CodeViewContext::recordCVLoc(MCContext &Ctx, const MCSymbol *Label, |
127 | unsigned FunctionId, unsigned FileNo, |
128 | unsigned Line, unsigned Column, |
129 | bool PrologueEnd, bool IsStmt) { |
130 | addLineEntry(LineEntry: MCCVLoc{ |
131 | Label, FunctionId, FileNo, Line, Column, PrologueEnd, IsStmt}); |
132 | } |
133 | |
134 | std::pair<StringRef, unsigned> CodeViewContext::addToStringTable(StringRef S) { |
135 | auto Insertion = |
136 | StringTable.insert(KV: std::make_pair(x&: S, y: unsigned(StrTab.size()))); |
137 | // Return the string from the table, since it is stable. |
138 | std::pair<StringRef, unsigned> Ret = |
139 | std::make_pair(x: Insertion.first->first(), y&: Insertion.first->second); |
140 | if (Insertion.second) { |
141 | // The string map key is always null terminated. |
142 | StrTab.append(in_start: Ret.first.begin(), in_end: Ret.first.end() + 1); |
143 | } |
144 | return Ret; |
145 | } |
146 | |
147 | unsigned CodeViewContext::getStringTableOffset(StringRef S) { |
148 | // A string table offset of zero is always the empty string. |
149 | if (S.empty()) |
150 | return 0; |
151 | auto I = StringTable.find(Key: S); |
152 | assert(I != StringTable.end()); |
153 | return I->second; |
154 | } |
155 | |
156 | void CodeViewContext::emitStringTable(MCObjectStreamer &OS) { |
157 | MCContext &Ctx = OS.getContext(); |
158 | MCSymbol *StringBegin = Ctx.createTempSymbol(Name: "strtab_begin" , AlwaysAddSuffix: false), |
159 | *StringEnd = Ctx.createTempSymbol(Name: "strtab_end" , AlwaysAddSuffix: false); |
160 | |
161 | OS.emitInt32(Value: uint32_t(DebugSubsectionKind::StringTable)); |
162 | OS.emitAbsoluteSymbolDiff(Hi: StringEnd, Lo: StringBegin, Size: 4); |
163 | OS.emitLabel(Symbol: StringBegin); |
164 | |
165 | // Put the string table data fragment here, if we haven't already put it |
166 | // somewhere else. If somebody wants two string tables in their .s file, one |
167 | // will just be empty. |
168 | if (!StrTabFragment) { |
169 | StrTabFragment = Ctx.allocFragment<MCDataFragment>(); |
170 | OS.insert(F: StrTabFragment); |
171 | } |
172 | |
173 | OS.emitValueToAlignment(Alignment: Align(4), Value: 0); |
174 | |
175 | OS.emitLabel(Symbol: StringEnd); |
176 | } |
177 | |
178 | void CodeViewContext::emitFileChecksums(MCObjectStreamer &OS) { |
179 | // Do nothing if there are no file checksums. Microsoft's linker rejects empty |
180 | // CodeView substreams. |
181 | if (Files.empty()) |
182 | return; |
183 | |
184 | MCContext &Ctx = OS.getContext(); |
185 | MCSymbol *FileBegin = Ctx.createTempSymbol(Name: "filechecksums_begin" , AlwaysAddSuffix: false), |
186 | *FileEnd = Ctx.createTempSymbol(Name: "filechecksums_end" , AlwaysAddSuffix: false); |
187 | |
188 | OS.emitInt32(Value: uint32_t(DebugSubsectionKind::FileChecksums)); |
189 | OS.emitAbsoluteSymbolDiff(Hi: FileEnd, Lo: FileBegin, Size: 4); |
190 | OS.emitLabel(Symbol: FileBegin); |
191 | |
192 | unsigned CurrentOffset = 0; |
193 | |
194 | // Emit an array of FileChecksum entries. We index into this table using the |
195 | // user-provided file number. Each entry may be a variable number of bytes |
196 | // determined by the checksum kind and size. |
197 | for (auto File : Files) { |
198 | OS.emitAssignment(Symbol: File.ChecksumTableOffset, |
199 | Value: MCConstantExpr::create(Value: CurrentOffset, Ctx)); |
200 | CurrentOffset += 4; // String table offset. |
201 | if (!File.ChecksumKind) { |
202 | CurrentOffset += |
203 | 4; // One byte each for checksum size and kind, then align to 4 bytes. |
204 | } else { |
205 | CurrentOffset += 2; // One byte each for checksum size and kind. |
206 | CurrentOffset += File.Checksum.size(); |
207 | CurrentOffset = alignTo(Value: CurrentOffset, Align: 4); |
208 | } |
209 | |
210 | OS.emitInt32(Value: File.StringTableOffset); |
211 | |
212 | if (!File.ChecksumKind) { |
213 | // There is no checksum. Therefore zero the next two fields and align |
214 | // back to 4 bytes. |
215 | OS.emitInt32(Value: 0); |
216 | continue; |
217 | } |
218 | OS.emitInt8(Value: static_cast<uint8_t>(File.Checksum.size())); |
219 | OS.emitInt8(Value: File.ChecksumKind); |
220 | OS.emitBytes(Data: toStringRef(Input: File.Checksum)); |
221 | OS.emitValueToAlignment(Alignment: Align(4)); |
222 | } |
223 | |
224 | OS.emitLabel(Symbol: FileEnd); |
225 | |
226 | ChecksumOffsetsAssigned = true; |
227 | } |
228 | |
229 | // Output checksum table offset of the given file number. It is possible that |
230 | // not all files have been registered yet, and so the offset cannot be |
231 | // calculated. In this case a symbol representing the offset is emitted, and |
232 | // the value of this symbol will be fixed up at a later time. |
233 | void CodeViewContext::emitFileChecksumOffset(MCObjectStreamer &OS, |
234 | unsigned FileNo) { |
235 | unsigned Idx = FileNo - 1; |
236 | |
237 | if (Idx >= Files.size()) |
238 | Files.resize(N: Idx + 1); |
239 | |
240 | if (ChecksumOffsetsAssigned) { |
241 | OS.emitSymbolValue(Sym: Files[Idx].ChecksumTableOffset, Size: 4); |
242 | return; |
243 | } |
244 | |
245 | const MCSymbolRefExpr *SRE = |
246 | MCSymbolRefExpr::create(Symbol: Files[Idx].ChecksumTableOffset, Ctx&: OS.getContext()); |
247 | |
248 | OS.emitValueImpl(Value: SRE, Size: 4); |
249 | } |
250 | |
251 | void CodeViewContext::addLineEntry(const MCCVLoc &LineEntry) { |
252 | size_t Offset = MCCVLines.size(); |
253 | auto I = MCCVLineStartStop.insert( |
254 | x: {LineEntry.getFunctionId(), {Offset, Offset + 1}}); |
255 | if (!I.second) |
256 | I.first->second.second = Offset + 1; |
257 | MCCVLines.push_back(x: LineEntry); |
258 | } |
259 | |
260 | std::vector<MCCVLoc> |
261 | CodeViewContext::getFunctionLineEntries(unsigned FuncId) { |
262 | std::vector<MCCVLoc> FilteredLines; |
263 | size_t LocBegin; |
264 | size_t LocEnd; |
265 | std::tie(args&: LocBegin, args&: LocEnd) = getLineExtentIncludingInlinees(FuncId); |
266 | if (LocBegin >= LocEnd) { |
267 | return FilteredLines; |
268 | } |
269 | |
270 | MCCVFunctionInfo *SiteInfo = getCVFunctionInfo(FuncId); |
271 | for (size_t Idx = LocBegin; Idx != LocEnd; ++Idx) { |
272 | unsigned LocationFuncId = MCCVLines[Idx].getFunctionId(); |
273 | if (LocationFuncId == FuncId) { |
274 | // This was a .cv_loc directly for FuncId, so record it. |
275 | FilteredLines.push_back(x: MCCVLines[Idx]); |
276 | } else { |
277 | // Check if the current location is inlined in this function. If it is, |
278 | // synthesize a statement .cv_loc at the original inlined call site. |
279 | auto I = SiteInfo->InlinedAtMap.find(Val: LocationFuncId); |
280 | if (I != SiteInfo->InlinedAtMap.end()) { |
281 | MCCVFunctionInfo::LineInfo &IA = I->second; |
282 | // Only add the location if it differs from the previous location. |
283 | // Large inlined calls will have many .cv_loc entries and we only need |
284 | // one line table entry in the parent function. |
285 | if (FilteredLines.empty() || |
286 | FilteredLines.back().getFileNum() != IA.File || |
287 | FilteredLines.back().getLine() != IA.Line || |
288 | FilteredLines.back().getColumn() != IA.Col) { |
289 | FilteredLines.push_back(x: MCCVLoc(MCCVLines[Idx].getLabel(), FuncId, |
290 | IA.File, IA.Line, IA.Col, false, |
291 | false)); |
292 | } |
293 | } |
294 | } |
295 | } |
296 | return FilteredLines; |
297 | } |
298 | |
299 | std::pair<size_t, size_t> CodeViewContext::getLineExtent(unsigned FuncId) { |
300 | auto I = MCCVLineStartStop.find(x: FuncId); |
301 | // Return an empty extent if there are no cv_locs for this function id. |
302 | if (I == MCCVLineStartStop.end()) |
303 | return {~0ULL, 0}; |
304 | return I->second; |
305 | } |
306 | |
307 | std::pair<size_t, size_t> |
308 | CodeViewContext::getLineExtentIncludingInlinees(unsigned FuncId) { |
309 | size_t LocBegin; |
310 | size_t LocEnd; |
311 | std::tie(args&: LocBegin, args&: LocEnd) = getLineExtent(FuncId); |
312 | |
313 | // Include all child inline call sites in our extent. |
314 | MCCVFunctionInfo *SiteInfo = getCVFunctionInfo(FuncId); |
315 | if (SiteInfo) { |
316 | for (auto &KV : SiteInfo->InlinedAtMap) { |
317 | unsigned ChildId = KV.first; |
318 | auto Extent = getLineExtent(FuncId: ChildId); |
319 | LocBegin = std::min(a: LocBegin, b: Extent.first); |
320 | LocEnd = std::max(a: LocEnd, b: Extent.second); |
321 | } |
322 | } |
323 | |
324 | return {LocBegin, LocEnd}; |
325 | } |
326 | |
327 | ArrayRef<MCCVLoc> CodeViewContext::getLinesForExtent(size_t L, size_t R) { |
328 | if (R <= L) |
329 | return {}; |
330 | if (L >= MCCVLines.size()) |
331 | return {}; |
332 | return ArrayRef(&MCCVLines[L], R - L); |
333 | } |
334 | |
335 | void CodeViewContext::emitLineTableForFunction(MCObjectStreamer &OS, |
336 | unsigned FuncId, |
337 | const MCSymbol *FuncBegin, |
338 | const MCSymbol *FuncEnd) { |
339 | MCContext &Ctx = OS.getContext(); |
340 | MCSymbol *LineBegin = Ctx.createTempSymbol(Name: "linetable_begin" , AlwaysAddSuffix: false), |
341 | *LineEnd = Ctx.createTempSymbol(Name: "linetable_end" , AlwaysAddSuffix: false); |
342 | |
343 | OS.emitInt32(Value: uint32_t(DebugSubsectionKind::Lines)); |
344 | OS.emitAbsoluteSymbolDiff(Hi: LineEnd, Lo: LineBegin, Size: 4); |
345 | OS.emitLabel(Symbol: LineBegin); |
346 | OS.emitCOFFSecRel32(Symbol: FuncBegin, /*Offset=*/0); |
347 | OS.emitCOFFSectionIndex(Symbol: FuncBegin); |
348 | |
349 | // Actual line info. |
350 | std::vector<MCCVLoc> Locs = getFunctionLineEntries(FuncId); |
351 | bool HaveColumns = any_of(Range&: Locs, P: [](const MCCVLoc &LineEntry) { |
352 | return LineEntry.getColumn() != 0; |
353 | }); |
354 | OS.emitInt16(Value: HaveColumns ? int(LF_HaveColumns) : 0); |
355 | OS.emitAbsoluteSymbolDiff(Hi: FuncEnd, Lo: FuncBegin, Size: 4); |
356 | |
357 | for (auto I = Locs.begin(), E = Locs.end(); I != E;) { |
358 | // Emit a file segment for the run of locations that share a file id. |
359 | unsigned CurFileNum = I->getFileNum(); |
360 | auto FileSegEnd = |
361 | std::find_if(first: I, last: E, pred: [CurFileNum](const MCCVLoc &Loc) { |
362 | return Loc.getFileNum() != CurFileNum; |
363 | }); |
364 | unsigned EntryCount = FileSegEnd - I; |
365 | OS.AddComment(T: "Segment for file '" + |
366 | Twine(StrTab[Files[CurFileNum - 1].StringTableOffset]) + |
367 | "' begins" ); |
368 | OS.emitCVFileChecksumOffsetDirective(FileNo: CurFileNum); |
369 | OS.emitInt32(Value: EntryCount); |
370 | uint32_t SegmentSize = 12; |
371 | SegmentSize += 8 * EntryCount; |
372 | if (HaveColumns) |
373 | SegmentSize += 4 * EntryCount; |
374 | OS.emitInt32(Value: SegmentSize); |
375 | |
376 | for (auto J = I; J != FileSegEnd; ++J) { |
377 | OS.emitAbsoluteSymbolDiff(Hi: J->getLabel(), Lo: FuncBegin, Size: 4); |
378 | unsigned LineData = J->getLine(); |
379 | if (J->isStmt()) |
380 | LineData |= LineInfo::StatementFlag; |
381 | OS.emitInt32(Value: LineData); |
382 | } |
383 | if (HaveColumns) { |
384 | for (auto J = I; J != FileSegEnd; ++J) { |
385 | OS.emitInt16(Value: J->getColumn()); |
386 | OS.emitInt16(Value: 0); |
387 | } |
388 | } |
389 | I = FileSegEnd; |
390 | } |
391 | OS.emitLabel(Symbol: LineEnd); |
392 | } |
393 | |
394 | static bool compressAnnotation(uint32_t Data, SmallVectorImpl<char> &Buffer) { |
395 | if (isUInt<7>(x: Data)) { |
396 | Buffer.push_back(Elt: Data); |
397 | return true; |
398 | } |
399 | |
400 | if (isUInt<14>(x: Data)) { |
401 | Buffer.push_back(Elt: (Data >> 8) | 0x80); |
402 | Buffer.push_back(Elt: Data & 0xff); |
403 | return true; |
404 | } |
405 | |
406 | if (isUInt<29>(x: Data)) { |
407 | Buffer.push_back(Elt: (Data >> 24) | 0xC0); |
408 | Buffer.push_back(Elt: (Data >> 16) & 0xff); |
409 | Buffer.push_back(Elt: (Data >> 8) & 0xff); |
410 | Buffer.push_back(Elt: Data & 0xff); |
411 | return true; |
412 | } |
413 | |
414 | return false; |
415 | } |
416 | |
417 | static bool compressAnnotation(BinaryAnnotationsOpCode Annotation, |
418 | SmallVectorImpl<char> &Buffer) { |
419 | return compressAnnotation(Data: static_cast<uint32_t>(Annotation), Buffer); |
420 | } |
421 | |
422 | static uint32_t encodeSignedNumber(uint32_t Data) { |
423 | if (Data >> 31) |
424 | return ((-Data) << 1) | 1; |
425 | return Data << 1; |
426 | } |
427 | |
428 | void CodeViewContext::emitInlineLineTableForFunction(MCObjectStreamer &OS, |
429 | unsigned PrimaryFunctionId, |
430 | unsigned SourceFileId, |
431 | unsigned SourceLineNum, |
432 | const MCSymbol *FnStartSym, |
433 | const MCSymbol *FnEndSym) { |
434 | // Create and insert a fragment into the current section that will be encoded |
435 | // later. |
436 | auto *F = MCCtx->allocFragment<MCCVInlineLineTableFragment>( |
437 | args&: PrimaryFunctionId, args&: SourceFileId, args&: SourceLineNum, args&: FnStartSym, args&: FnEndSym); |
438 | OS.insert(F); |
439 | } |
440 | |
441 | MCFragment *CodeViewContext::emitDefRange( |
442 | MCObjectStreamer &OS, |
443 | ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges, |
444 | StringRef FixedSizePortion) { |
445 | // Store `Ranges` and `FixedSizePortion` in the context, returning references, |
446 | // as MCCVDefRangeFragment does not own these objects. |
447 | FixedSizePortion = MCCtx->allocateString(s: FixedSizePortion); |
448 | auto &Saved = DefRangeStorage.emplace_back(args: Ranges.begin(), args: Ranges.end()); |
449 | // Create and insert a fragment into the current section that will be encoded |
450 | // later. |
451 | auto *F = MCCtx->allocFragment<MCCVDefRangeFragment>(args&: Saved, args&: FixedSizePortion); |
452 | OS.insert(F); |
453 | return F; |
454 | } |
455 | |
456 | static unsigned computeLabelDiff(const MCAssembler &Asm, const MCSymbol *Begin, |
457 | const MCSymbol *End) { |
458 | MCContext &Ctx = Asm.getContext(); |
459 | const MCExpr *BeginRef = MCSymbolRefExpr::create(Symbol: Begin, Ctx), |
460 | *EndRef = MCSymbolRefExpr::create(Symbol: End, Ctx); |
461 | const MCExpr *AddrDelta = |
462 | MCBinaryExpr::create(Op: MCBinaryExpr::Sub, LHS: EndRef, RHS: BeginRef, Ctx); |
463 | int64_t Result; |
464 | bool Success = AddrDelta->evaluateKnownAbsolute(Res&: Result, Asm); |
465 | assert(Success && "failed to evaluate label difference as absolute" ); |
466 | (void)Success; |
467 | assert(Result >= 0 && "negative label difference requested" ); |
468 | assert(Result < UINT_MAX && "label difference greater than 2GB" ); |
469 | return unsigned(Result); |
470 | } |
471 | |
472 | void CodeViewContext::encodeInlineLineTable(const MCAssembler &Asm, |
473 | MCCVInlineLineTableFragment &Frag) { |
474 | size_t LocBegin; |
475 | size_t LocEnd; |
476 | std::tie(args&: LocBegin, args&: LocEnd) = getLineExtentIncludingInlinees(FuncId: Frag.SiteFuncId); |
477 | |
478 | if (LocBegin >= LocEnd) |
479 | return; |
480 | ArrayRef<MCCVLoc> Locs = getLinesForExtent(L: LocBegin, R: LocEnd); |
481 | if (Locs.empty()) |
482 | return; |
483 | |
484 | // Check that the locations are all in the same section. |
485 | #ifndef NDEBUG |
486 | const MCSection *FirstSec = &Locs.front().getLabel()->getSection(); |
487 | for (const MCCVLoc &Loc : Locs) { |
488 | if (&Loc.getLabel()->getSection() != FirstSec) { |
489 | errs() << ".cv_loc " << Loc.getFunctionId() << ' ' << Loc.getFileNum() |
490 | << ' ' << Loc.getLine() << ' ' << Loc.getColumn() |
491 | << " is in the wrong section\n" ; |
492 | llvm_unreachable(".cv_loc crosses sections" ); |
493 | } |
494 | } |
495 | #endif |
496 | |
497 | // Make an artificial start location using the function start and the inlinee |
498 | // lines start location information. All deltas start relative to this |
499 | // location. |
500 | MCCVLoc StartLoc = Locs.front(); |
501 | StartLoc.setLabel(Frag.getFnStartSym()); |
502 | StartLoc.setFileNum(Frag.StartFileId); |
503 | StartLoc.setLine(Frag.StartLineNum); |
504 | bool HaveOpenRange = false; |
505 | |
506 | const MCSymbol *LastLabel = Frag.getFnStartSym(); |
507 | MCCVFunctionInfo::LineInfo LastSourceLoc, CurSourceLoc; |
508 | LastSourceLoc.File = Frag.StartFileId; |
509 | LastSourceLoc.Line = Frag.StartLineNum; |
510 | |
511 | MCCVFunctionInfo *SiteInfo = getCVFunctionInfo(FuncId: Frag.SiteFuncId); |
512 | |
513 | SmallVector<char, 0> Buffer; |
514 | for (const MCCVLoc &Loc : Locs) { |
515 | // Exit early if our line table would produce an oversized InlineSiteSym |
516 | // record. Account for the ChangeCodeLength annotation emitted after the |
517 | // loop ends. |
518 | constexpr uint32_t InlineSiteSize = 12; |
519 | constexpr uint32_t AnnotationSize = 8; |
520 | size_t MaxBufferSize = MaxRecordLength - InlineSiteSize - AnnotationSize; |
521 | if (Buffer.size() >= MaxBufferSize) |
522 | break; |
523 | |
524 | if (Loc.getFunctionId() == Frag.SiteFuncId) { |
525 | CurSourceLoc.File = Loc.getFileNum(); |
526 | CurSourceLoc.Line = Loc.getLine(); |
527 | } else { |
528 | auto I = SiteInfo->InlinedAtMap.find(Val: Loc.getFunctionId()); |
529 | if (I != SiteInfo->InlinedAtMap.end()) { |
530 | // This .cv_loc is from a child inline call site. Use the source |
531 | // location of the inlined call site instead of the .cv_loc directive |
532 | // source location. |
533 | CurSourceLoc = I->second; |
534 | } else { |
535 | // We've hit a cv_loc not attributed to this inline call site. Use this |
536 | // label to end the PC range. |
537 | if (HaveOpenRange) { |
538 | unsigned Length = computeLabelDiff(Asm, Begin: LastLabel, End: Loc.getLabel()); |
539 | compressAnnotation(Annotation: BinaryAnnotationsOpCode::ChangeCodeLength, Buffer); |
540 | compressAnnotation(Data: Length, Buffer); |
541 | LastLabel = Loc.getLabel(); |
542 | } |
543 | HaveOpenRange = false; |
544 | continue; |
545 | } |
546 | } |
547 | |
548 | // Skip this .cv_loc if we have an open range and this isn't a meaningful |
549 | // source location update. The current table format does not support column |
550 | // info, so we can skip updates for those. |
551 | if (HaveOpenRange && CurSourceLoc.File == LastSourceLoc.File && |
552 | CurSourceLoc.Line == LastSourceLoc.Line) |
553 | continue; |
554 | |
555 | HaveOpenRange = true; |
556 | |
557 | if (CurSourceLoc.File != LastSourceLoc.File) { |
558 | unsigned FileOffset = static_cast<const MCConstantExpr *>( |
559 | Files[CurSourceLoc.File - 1] |
560 | .ChecksumTableOffset->getVariableValue()) |
561 | ->getValue(); |
562 | compressAnnotation(Annotation: BinaryAnnotationsOpCode::ChangeFile, Buffer); |
563 | compressAnnotation(Data: FileOffset, Buffer); |
564 | } |
565 | |
566 | int LineDelta = CurSourceLoc.Line - LastSourceLoc.Line; |
567 | unsigned EncodedLineDelta = encodeSignedNumber(Data: LineDelta); |
568 | unsigned CodeDelta = computeLabelDiff(Asm, Begin: LastLabel, End: Loc.getLabel()); |
569 | if (EncodedLineDelta < 0x8 && CodeDelta <= 0xf) { |
570 | // The ChangeCodeOffsetAndLineOffset combination opcode is used when the |
571 | // encoded line delta uses 3 or fewer set bits and the code offset fits |
572 | // in one nibble. |
573 | unsigned Operand = (EncodedLineDelta << 4) | CodeDelta; |
574 | compressAnnotation(Annotation: BinaryAnnotationsOpCode::ChangeCodeOffsetAndLineOffset, |
575 | Buffer); |
576 | compressAnnotation(Data: Operand, Buffer); |
577 | } else { |
578 | // Otherwise use the separate line and code deltas. |
579 | if (LineDelta != 0) { |
580 | compressAnnotation(Annotation: BinaryAnnotationsOpCode::ChangeLineOffset, Buffer); |
581 | compressAnnotation(Data: EncodedLineDelta, Buffer); |
582 | } |
583 | compressAnnotation(Annotation: BinaryAnnotationsOpCode::ChangeCodeOffset, Buffer); |
584 | compressAnnotation(Data: CodeDelta, Buffer); |
585 | } |
586 | |
587 | LastLabel = Loc.getLabel(); |
588 | LastSourceLoc = CurSourceLoc; |
589 | } |
590 | |
591 | assert(HaveOpenRange); |
592 | |
593 | unsigned EndSymLength = |
594 | computeLabelDiff(Asm, Begin: LastLabel, End: Frag.getFnEndSym()); |
595 | unsigned LocAfterLength = ~0U; |
596 | ArrayRef<MCCVLoc> LocAfter = getLinesForExtent(L: LocEnd, R: LocEnd + 1); |
597 | if (!LocAfter.empty()) { |
598 | // Only try to compute this difference if we're in the same section. |
599 | const MCCVLoc &Loc = LocAfter[0]; |
600 | if (&Loc.getLabel()->getSection() == &LastLabel->getSection()) |
601 | LocAfterLength = computeLabelDiff(Asm, Begin: LastLabel, End: Loc.getLabel()); |
602 | } |
603 | |
604 | compressAnnotation(Annotation: BinaryAnnotationsOpCode::ChangeCodeLength, Buffer); |
605 | compressAnnotation(Data: std::min(a: EndSymLength, b: LocAfterLength), Buffer); |
606 | Frag.setContents(Buffer); |
607 | } |
608 | |
609 | void CodeViewContext::encodeDefRange(const MCAssembler &Asm, |
610 | MCCVDefRangeFragment &Frag) { |
611 | MCContext &Ctx = Asm.getContext(); |
612 | SmallVector<char, 0> Contents; |
613 | SmallVector<MCFixup, 0> Fixups; |
614 | raw_svector_ostream OS(Contents); |
615 | |
616 | // Compute all the sizes up front. |
617 | SmallVector<std::pair<unsigned, unsigned>, 4> GapAndRangeSizes; |
618 | const MCSymbol *LastLabel = nullptr; |
619 | for (std::pair<const MCSymbol *, const MCSymbol *> Range : Frag.getRanges()) { |
620 | unsigned GapSize = |
621 | LastLabel ? computeLabelDiff(Asm, Begin: LastLabel, End: Range.first) : 0; |
622 | unsigned RangeSize = computeLabelDiff(Asm, Begin: Range.first, End: Range.second); |
623 | GapAndRangeSizes.push_back(Elt: {GapSize, RangeSize}); |
624 | LastLabel = Range.second; |
625 | } |
626 | |
627 | // Write down each range where the variable is defined. |
628 | for (size_t I = 0, E = Frag.getRanges().size(); I != E;) { |
629 | // If the range size of multiple consecutive ranges is under the max, |
630 | // combine the ranges and emit some gaps. |
631 | const MCSymbol *RangeBegin = Frag.getRanges()[I].first; |
632 | unsigned RangeSize = GapAndRangeSizes[I].second; |
633 | size_t J = I + 1; |
634 | for (; J != E; ++J) { |
635 | unsigned GapAndRangeSize = GapAndRangeSizes[J].first + GapAndRangeSizes[J].second; |
636 | if (RangeSize + GapAndRangeSize > MaxDefRange) |
637 | break; |
638 | RangeSize += GapAndRangeSize; |
639 | } |
640 | unsigned NumGaps = J - I - 1; |
641 | |
642 | support::endian::Writer LEWriter(OS, llvm::endianness::little); |
643 | |
644 | unsigned Bias = 0; |
645 | // We must split the range into chunks of MaxDefRange, this is a fundamental |
646 | // limitation of the file format. |
647 | do { |
648 | uint16_t Chunk = std::min(a: (uint32_t)MaxDefRange, b: RangeSize); |
649 | |
650 | const MCSymbolRefExpr *SRE = MCSymbolRefExpr::create(Symbol: RangeBegin, Ctx); |
651 | const MCBinaryExpr *BE = |
652 | MCBinaryExpr::createAdd(LHS: SRE, RHS: MCConstantExpr::create(Value: Bias, Ctx), Ctx); |
653 | |
654 | // Each record begins with a 2-byte number indicating how large the record |
655 | // is. |
656 | StringRef FixedSizePortion = Frag.getFixedSizePortion(); |
657 | // Our record is a fixed sized prefix and a LocalVariableAddrRange that we |
658 | // are artificially constructing. |
659 | size_t RecordSize = FixedSizePortion.size() + |
660 | sizeof(LocalVariableAddrRange) + 4 * NumGaps; |
661 | // Write out the record size. |
662 | LEWriter.write<uint16_t>(Val: RecordSize); |
663 | // Write out the fixed size prefix. |
664 | OS << FixedSizePortion; |
665 | // Make space for a fixup that will eventually have a section relative |
666 | // relocation pointing at the offset where the variable becomes live. |
667 | Fixups.push_back(Elt: MCFixup::create(Offset: Contents.size(), Value: BE, Kind: FK_SecRel_4)); |
668 | LEWriter.write<uint32_t>(Val: 0); // Fixup for code start. |
669 | // Make space for a fixup that will record the section index for the code. |
670 | Fixups.push_back(Elt: MCFixup::create(Offset: Contents.size(), Value: BE, Kind: FK_SecRel_2)); |
671 | LEWriter.write<uint16_t>(Val: 0); // Fixup for section index. |
672 | // Write down the range's extent. |
673 | LEWriter.write<uint16_t>(Val: Chunk); |
674 | |
675 | // Move on to the next range. |
676 | Bias += Chunk; |
677 | RangeSize -= Chunk; |
678 | } while (RangeSize > 0); |
679 | |
680 | // Emit the gaps afterwards. |
681 | assert((NumGaps == 0 || Bias <= MaxDefRange) && |
682 | "large ranges should not have gaps" ); |
683 | unsigned GapStartOffset = GapAndRangeSizes[I].second; |
684 | for (++I; I != J; ++I) { |
685 | unsigned GapSize, RangeSize; |
686 | assert(I < GapAndRangeSizes.size()); |
687 | std::tie(args&: GapSize, args&: RangeSize) = GapAndRangeSizes[I]; |
688 | LEWriter.write<uint16_t>(Val: GapStartOffset); |
689 | LEWriter.write<uint16_t>(Val: GapSize); |
690 | GapStartOffset += GapSize + RangeSize; |
691 | } |
692 | } |
693 | |
694 | Frag.setContents(Contents); |
695 | Frag.setFixups(Fixups); |
696 | } |
697 | |