xref: /llvm-project/llvm/lib/MC/MCCodeView.cpp (revision 6c42d0d7df55f28084e41b482dd7c25d4e7bcd10)
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(Filename);
48   Filename = FilenameOffset.first;
49   unsigned Idx = FileNumber - 1;
50   if (Idx >= Files.size())
51     Files.resize(Idx + 1);
52 
53   if (Filename.empty())
54     Filename = "<stdin>";
55 
56   if (Files[Idx].Assigned)
57     return false;
58 
59   FilenameOffset = addToStringTable(Filename);
60   Filename = FilenameOffset.first;
61   unsigned Offset = FilenameOffset.second;
62 
63   auto ChecksumOffsetSymbol =
64       OS.getContext().createTempSymbol("checksum_offset", 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(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(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(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(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(std::make_pair(S, unsigned(StrTab.size())));
137   // Return the string from the table, since it is stable.
138   std::pair<StringRef, unsigned> Ret =
139       std::make_pair(Insertion.first->first(), Insertion.first->second);
140   if (Insertion.second) {
141     // The string map key is always null terminated.
142     StrTab.append(Ret.first.begin(), 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(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("strtab_begin", false),
159            *StringEnd = Ctx.createTempSymbol("strtab_end", false);
160 
161   OS.emitInt32(uint32_t(DebugSubsectionKind::StringTable));
162   OS.emitAbsoluteSymbolDiff(StringEnd, StringBegin, 4);
163   OS.emitLabel(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(StrTabFragment);
171   }
172 
173   OS.emitValueToAlignment(Align(4), 0);
174 
175   OS.emitLabel(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("filechecksums_begin", false),
186            *FileEnd = Ctx.createTempSymbol("filechecksums_end", false);
187 
188   OS.emitInt32(uint32_t(DebugSubsectionKind::FileChecksums));
189   OS.emitAbsoluteSymbolDiff(FileEnd, FileBegin, 4);
190   OS.emitLabel(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(File.ChecksumTableOffset,
199                       MCConstantExpr::create(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(CurrentOffset, 4);
208     }
209 
210     OS.emitInt32(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(0);
216       continue;
217     }
218     OS.emitInt8(static_cast<uint8_t>(File.Checksum.size()));
219     OS.emitInt8(File.ChecksumKind);
220     OS.emitBytes(toStringRef(File.Checksum));
221     OS.emitValueToAlignment(Align(4));
222   }
223 
224   OS.emitLabel(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(Idx + 1);
239 
240   if (ChecksumOffsetsAssigned) {
241     OS.emitSymbolValue(Files[Idx].ChecksumTableOffset, 4);
242     return;
243   }
244 
245   const MCSymbolRefExpr *SRE =
246       MCSymbolRefExpr::create(Files[Idx].ChecksumTableOffset, OS.getContext());
247 
248   OS.emitValueImpl(SRE, 4);
249 }
250 
251 void CodeViewContext::addLineEntry(const MCCVLoc &LineEntry) {
252   size_t Offset = MCCVLines.size();
253   auto I = MCCVLineStartStop.insert(
254       {LineEntry.getFunctionId(), {Offset, Offset + 1}});
255   if (!I.second)
256     I.first->second.second = Offset + 1;
257   MCCVLines.push_back(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(LocBegin, 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(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(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(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(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(LocBegin, 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(ChildId);
319       LocBegin = std::min(LocBegin, Extent.first);
320       LocEnd = std::max(LocEnd, 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("linetable_begin", false),
341            *LineEnd = Ctx.createTempSymbol("linetable_end", false);
342 
343   OS.emitInt32(uint32_t(DebugSubsectionKind::Lines));
344   OS.emitAbsoluteSymbolDiff(LineEnd, LineBegin, 4);
345   OS.emitLabel(LineBegin);
346   OS.emitCOFFSecRel32(FuncBegin, /*Offset=*/0);
347   OS.emitCOFFSectionIndex(FuncBegin);
348 
349   // Actual line info.
350   std::vector<MCCVLoc> Locs = getFunctionLineEntries(FuncId);
351   bool HaveColumns = any_of(Locs, [](const MCCVLoc &LineEntry) {
352     return LineEntry.getColumn() != 0;
353   });
354   OS.emitInt16(HaveColumns ? int(LF_HaveColumns) : 0);
355   OS.emitAbsoluteSymbolDiff(FuncEnd, FuncBegin, 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(I, E, [CurFileNum](const MCCVLoc &Loc) {
362           return Loc.getFileNum() != CurFileNum;
363         });
364     unsigned EntryCount = FileSegEnd - I;
365     OS.AddComment("Segment for file '" +
366                   Twine(StrTab[Files[CurFileNum - 1].StringTableOffset]) +
367                   "' begins");
368     OS.emitCVFileChecksumOffsetDirective(CurFileNum);
369     OS.emitInt32(EntryCount);
370     uint32_t SegmentSize = 12;
371     SegmentSize += 8 * EntryCount;
372     if (HaveColumns)
373       SegmentSize += 4 * EntryCount;
374     OS.emitInt32(SegmentSize);
375 
376     for (auto J = I; J != FileSegEnd; ++J) {
377       OS.emitAbsoluteSymbolDiff(J->getLabel(), FuncBegin, 4);
378       unsigned LineData = J->getLine();
379       if (J->isStmt())
380         LineData |= LineInfo::StatementFlag;
381       OS.emitInt32(LineData);
382     }
383     if (HaveColumns) {
384       for (auto J = I; J != FileSegEnd; ++J) {
385         OS.emitInt16(J->getColumn());
386         OS.emitInt16(0);
387       }
388     }
389     I = FileSegEnd;
390   }
391   OS.emitLabel(LineEnd);
392 }
393 
394 static bool compressAnnotation(uint32_t Data, SmallVectorImpl<char> &Buffer) {
395   if (isUInt<7>(Data)) {
396     Buffer.push_back(Data);
397     return true;
398   }
399 
400   if (isUInt<14>(Data)) {
401     Buffer.push_back((Data >> 8) | 0x80);
402     Buffer.push_back(Data & 0xff);
403     return true;
404   }
405 
406   if (isUInt<29>(Data)) {
407     Buffer.push_back((Data >> 24) | 0xC0);
408     Buffer.push_back((Data >> 16) & 0xff);
409     Buffer.push_back((Data >> 8) & 0xff);
410     Buffer.push_back(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(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       PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, 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   // Create and insert a fragment into the current section that will be encoded
446   // later.
447   auto *F =
448       MCCtx->allocFragment<MCCVDefRangeFragment>(Ranges, FixedSizePortion);
449   OS.insert(F);
450   return F;
451 }
452 
453 static unsigned computeLabelDiff(const MCAssembler &Asm, const MCSymbol *Begin,
454                                  const MCSymbol *End) {
455   MCContext &Ctx = Asm.getContext();
456   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
457   const MCExpr *BeginRef = MCSymbolRefExpr::create(Begin, Variant, Ctx),
458                *EndRef = MCSymbolRefExpr::create(End, Variant, Ctx);
459   const MCExpr *AddrDelta =
460       MCBinaryExpr::create(MCBinaryExpr::Sub, EndRef, BeginRef, Ctx);
461   int64_t Result;
462   bool Success = AddrDelta->evaluateKnownAbsolute(Result, Asm);
463   assert(Success && "failed to evaluate label difference as absolute");
464   (void)Success;
465   assert(Result >= 0 && "negative label difference requested");
466   assert(Result < UINT_MAX && "label difference greater than 2GB");
467   return unsigned(Result);
468 }
469 
470 void CodeViewContext::encodeInlineLineTable(const MCAssembler &Asm,
471                                             MCCVInlineLineTableFragment &Frag) {
472   size_t LocBegin;
473   size_t LocEnd;
474   std::tie(LocBegin, LocEnd) = getLineExtentIncludingInlinees(Frag.SiteFuncId);
475 
476   if (LocBegin >= LocEnd)
477     return;
478   ArrayRef<MCCVLoc> Locs = getLinesForExtent(LocBegin, LocEnd);
479   if (Locs.empty())
480     return;
481 
482   // Check that the locations are all in the same section.
483 #ifndef NDEBUG
484   const MCSection *FirstSec = &Locs.front().getLabel()->getSection();
485   for (const MCCVLoc &Loc : Locs) {
486     if (&Loc.getLabel()->getSection() != FirstSec) {
487       errs() << ".cv_loc " << Loc.getFunctionId() << ' ' << Loc.getFileNum()
488              << ' ' << Loc.getLine() << ' ' << Loc.getColumn()
489              << " is in the wrong section\n";
490       llvm_unreachable(".cv_loc crosses sections");
491     }
492   }
493 #endif
494 
495   // Make an artificial start location using the function start and the inlinee
496   // lines start location information. All deltas start relative to this
497   // location.
498   MCCVLoc StartLoc = Locs.front();
499   StartLoc.setLabel(Frag.getFnStartSym());
500   StartLoc.setFileNum(Frag.StartFileId);
501   StartLoc.setLine(Frag.StartLineNum);
502   bool HaveOpenRange = false;
503 
504   const MCSymbol *LastLabel = Frag.getFnStartSym();
505   MCCVFunctionInfo::LineInfo LastSourceLoc, CurSourceLoc;
506   LastSourceLoc.File = Frag.StartFileId;
507   LastSourceLoc.Line = Frag.StartLineNum;
508 
509   MCCVFunctionInfo *SiteInfo = getCVFunctionInfo(Frag.SiteFuncId);
510 
511   SmallVectorImpl<char> &Buffer = Frag.getContents();
512   Buffer.clear(); // Clear old contents if we went through relaxation.
513   for (const MCCVLoc &Loc : Locs) {
514     // Exit early if our line table would produce an oversized InlineSiteSym
515     // record. Account for the ChangeCodeLength annotation emitted after the
516     // loop ends.
517     constexpr uint32_t InlineSiteSize = 12;
518     constexpr uint32_t AnnotationSize = 8;
519     size_t MaxBufferSize = MaxRecordLength - InlineSiteSize - AnnotationSize;
520     if (Buffer.size() >= MaxBufferSize)
521       break;
522 
523     if (Loc.getFunctionId() == Frag.SiteFuncId) {
524       CurSourceLoc.File = Loc.getFileNum();
525       CurSourceLoc.Line = Loc.getLine();
526     } else {
527       auto I = SiteInfo->InlinedAtMap.find(Loc.getFunctionId());
528       if (I != SiteInfo->InlinedAtMap.end()) {
529         // This .cv_loc is from a child inline call site. Use the source
530         // location of the inlined call site instead of the .cv_loc directive
531         // source location.
532         CurSourceLoc = I->second;
533       } else {
534         // We've hit a cv_loc not attributed to this inline call site. Use this
535         // label to end the PC range.
536         if (HaveOpenRange) {
537           unsigned Length = computeLabelDiff(Asm, LastLabel, Loc.getLabel());
538           compressAnnotation(BinaryAnnotationsOpCode::ChangeCodeLength, Buffer);
539           compressAnnotation(Length, Buffer);
540           LastLabel = Loc.getLabel();
541         }
542         HaveOpenRange = false;
543         continue;
544       }
545     }
546 
547     // Skip this .cv_loc if we have an open range and this isn't a meaningful
548     // source location update. The current table format does not support column
549     // info, so we can skip updates for those.
550     if (HaveOpenRange && CurSourceLoc.File == LastSourceLoc.File &&
551         CurSourceLoc.Line == LastSourceLoc.Line)
552       continue;
553 
554     HaveOpenRange = true;
555 
556     if (CurSourceLoc.File != LastSourceLoc.File) {
557       unsigned FileOffset = static_cast<const MCConstantExpr *>(
558                                 Files[CurSourceLoc.File - 1]
559                                     .ChecksumTableOffset->getVariableValue())
560                                 ->getValue();
561       compressAnnotation(BinaryAnnotationsOpCode::ChangeFile, Buffer);
562       compressAnnotation(FileOffset, Buffer);
563     }
564 
565     int LineDelta = CurSourceLoc.Line - LastSourceLoc.Line;
566     unsigned EncodedLineDelta = encodeSignedNumber(LineDelta);
567     unsigned CodeDelta = computeLabelDiff(Asm, LastLabel, Loc.getLabel());
568     if (EncodedLineDelta < 0x8 && CodeDelta <= 0xf) {
569       // The ChangeCodeOffsetAndLineOffset combination opcode is used when the
570       // encoded line delta uses 3 or fewer set bits and the code offset fits
571       // in one nibble.
572       unsigned Operand = (EncodedLineDelta << 4) | CodeDelta;
573       compressAnnotation(BinaryAnnotationsOpCode::ChangeCodeOffsetAndLineOffset,
574                          Buffer);
575       compressAnnotation(Operand, Buffer);
576     } else {
577       // Otherwise use the separate line and code deltas.
578       if (LineDelta != 0) {
579         compressAnnotation(BinaryAnnotationsOpCode::ChangeLineOffset, Buffer);
580         compressAnnotation(EncodedLineDelta, Buffer);
581       }
582       compressAnnotation(BinaryAnnotationsOpCode::ChangeCodeOffset, Buffer);
583       compressAnnotation(CodeDelta, Buffer);
584     }
585 
586     LastLabel = Loc.getLabel();
587     LastSourceLoc = CurSourceLoc;
588   }
589 
590   assert(HaveOpenRange);
591 
592   unsigned EndSymLength =
593       computeLabelDiff(Asm, LastLabel, Frag.getFnEndSym());
594   unsigned LocAfterLength = ~0U;
595   ArrayRef<MCCVLoc> LocAfter = getLinesForExtent(LocEnd, LocEnd + 1);
596   if (!LocAfter.empty()) {
597     // Only try to compute this difference if we're in the same section.
598     const MCCVLoc &Loc = LocAfter[0];
599     if (&Loc.getLabel()->getSection() == &LastLabel->getSection())
600       LocAfterLength = computeLabelDiff(Asm, LastLabel, Loc.getLabel());
601   }
602 
603   compressAnnotation(BinaryAnnotationsOpCode::ChangeCodeLength, Buffer);
604   compressAnnotation(std::min(EndSymLength, LocAfterLength), Buffer);
605 }
606 
607 void CodeViewContext::encodeDefRange(const MCAssembler &Asm,
608                                      MCCVDefRangeFragment &Frag) {
609   MCContext &Ctx = Asm.getContext();
610   SmallVectorImpl<char> &Contents = Frag.getContents();
611   Contents.clear();
612   SmallVectorImpl<MCFixup> &Fixups = Frag.getFixups();
613   Fixups.clear();
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, LastLabel, Range.first) : 0;
622     unsigned RangeSize = computeLabelDiff(Asm, Range.first, Range.second);
623     GapAndRangeSizes.push_back({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((uint32_t)MaxDefRange, RangeSize);
649 
650       const MCSymbolRefExpr *SRE = MCSymbolRefExpr::create(RangeBegin, Ctx);
651       const MCBinaryExpr *BE =
652           MCBinaryExpr::createAdd(SRE, MCConstantExpr::create(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>(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(MCFixup::create(Contents.size(), BE, FK_SecRel_4));
668       LEWriter.write<uint32_t>(0); // Fixup for code start.
669       // Make space for a fixup that will record the section index for the code.
670       Fixups.push_back(MCFixup::create(Contents.size(), BE, FK_SecRel_2));
671       LEWriter.write<uint16_t>(0); // Fixup for section index.
672       // Write down the range's extent.
673       LEWriter.write<uint16_t>(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(GapSize, RangeSize) = GapAndRangeSizes[I];
688       LEWriter.write<uint16_t>(GapStartOffset);
689       LEWriter.write<uint16_t>(GapSize);
690       GapStartOffset += GapSize + RangeSize;
691     }
692   }
693 }
694