1 //===- bolt/Core/DebugData.cpp - Debugging information handling -----------===//
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 // This file implements functions and classes for handling debug info.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "bolt/Core/DebugData.h"
14 #include "bolt/Core/BinaryContext.h"
15 #include "bolt/Utils/Utils.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCObjectStreamer.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/EndianStream.h"
20 #include "llvm/Support/LEB128.h"
21 #include <algorithm>
22 #include <cassert>
23 #include <cstdint>
24 #include <limits>
25 #include <unordered_map>
26 
27 #define DEBUG_TYPE "bolt-debug-info"
28 
29 namespace opts {
30 extern llvm::cl::opt<unsigned> Verbosity;
31 } // namespace opts
32 
33 namespace llvm {
34 class MCSymbol;
35 
36 namespace bolt {
37 
38 const DebugLineTableRowRef DebugLineTableRowRef::NULL_ROW{0, 0};
39 
40 namespace {
41 
42 LLVM_ATTRIBUTE_UNUSED
43 static void printLE64(const std::string &S) {
44   for (uint32_t I = 0, Size = S.size(); I < Size; ++I) {
45     errs() << Twine::utohexstr(S[I]);
46     errs() << Twine::utohexstr((int8_t)S[I]);
47   }
48   errs() << "\n";
49 }
50 
51 // Writes address ranges to Writer as pairs of 64-bit (address, size).
52 // If RelativeRange is true, assumes the address range to be written must be of
53 // the form (begin address, range size), otherwise (begin address, end address).
54 // Terminates the list by writing a pair of two zeroes.
55 // Returns the number of written bytes.
56 uint64_t writeAddressRanges(raw_svector_ostream &Stream,
57                             const DebugAddressRangesVector &AddressRanges,
58                             const bool WriteRelativeRanges = false) {
59   for (const DebugAddressRange &Range : AddressRanges) {
60     support::endian::write(Stream, Range.LowPC, support::little);
61     support::endian::write(
62         Stream, WriteRelativeRanges ? Range.HighPC - Range.LowPC : Range.HighPC,
63         support::little);
64   }
65   // Finish with 0 entries.
66   support::endian::write(Stream, 0ULL, support::little);
67   support::endian::write(Stream, 0ULL, support::little);
68   return AddressRanges.size() * 16 + 16;
69 }
70 
71 } // namespace
72 
73 DebugRangesSectionWriter::DebugRangesSectionWriter() {
74   RangesBuffer = std::make_unique<DebugBufferVector>();
75   RangesStream = std::make_unique<raw_svector_ostream>(*RangesBuffer);
76 
77   // Add an empty range as the first entry;
78   SectionOffset +=
79       writeAddressRanges(*RangesStream.get(), DebugAddressRangesVector{});
80 }
81 
82 uint64_t DebugRangesSectionWriter::addRanges(
83     DebugAddressRangesVector &&Ranges,
84     std::map<DebugAddressRangesVector, uint64_t> &CachedRanges) {
85   if (Ranges.empty())
86     return getEmptyRangesOffset();
87 
88   const auto RI = CachedRanges.find(Ranges);
89   if (RI != CachedRanges.end())
90     return RI->second;
91 
92   const uint64_t EntryOffset = addRanges(Ranges);
93   CachedRanges.emplace(std::move(Ranges), EntryOffset);
94 
95   return EntryOffset;
96 }
97 
98 uint64_t
99 DebugRangesSectionWriter::addRanges(const DebugAddressRangesVector &Ranges) {
100   if (Ranges.empty())
101     return getEmptyRangesOffset();
102 
103   // Reading the SectionOffset and updating it should be atomic to guarantee
104   // unique and correct offsets in patches.
105   std::lock_guard<std::mutex> Lock(WriterMutex);
106   const uint32_t EntryOffset = SectionOffset;
107   SectionOffset += writeAddressRanges(*RangesStream.get(), Ranges);
108 
109   return EntryOffset;
110 }
111 
112 uint64_t DebugRangesSectionWriter::getSectionOffset() {
113   std::lock_guard<std::mutex> Lock(WriterMutex);
114   return SectionOffset;
115 }
116 
117 void DebugARangesSectionWriter::addCURanges(uint64_t CUOffset,
118                                             DebugAddressRangesVector &&Ranges) {
119   std::lock_guard<std::mutex> Lock(CUAddressRangesMutex);
120   CUAddressRanges.emplace(CUOffset, std::move(Ranges));
121 }
122 
123 void DebugARangesSectionWriter::writeARangesSection(
124     raw_svector_ostream &RangesStream, const CUOffsetMap &CUMap) const {
125   // For reference on the format of the .debug_aranges section, see the DWARF4
126   // specification, section 6.1.4 Lookup by Address
127   // http://www.dwarfstd.org/doc/DWARF4.pdf
128   for (const auto &CUOffsetAddressRangesPair : CUAddressRanges) {
129     const uint64_t Offset = CUOffsetAddressRangesPair.first;
130     const DebugAddressRangesVector &AddressRanges =
131         CUOffsetAddressRangesPair.second;
132 
133     // Emit header.
134 
135     // Size of this set: 8 (size of the header) + 4 (padding after header)
136     // + 2*sizeof(uint64_t) bytes for each of the ranges, plus an extra
137     // pair of uint64_t's for the terminating, zero-length range.
138     // Does not include size field itself.
139     uint32_t Size = 8 + 4 + 2 * sizeof(uint64_t) * (AddressRanges.size() + 1);
140 
141     // Header field #1: set size.
142     support::endian::write(RangesStream, Size, support::little);
143 
144     // Header field #2: version number, 2 as per the specification.
145     support::endian::write(RangesStream, static_cast<uint16_t>(2),
146                            support::little);
147 
148     assert(CUMap.count(Offset) && "Original CU offset is not found in CU Map");
149     // Header field #3: debug info offset of the correspondent compile unit.
150     support::endian::write(
151         RangesStream, static_cast<uint32_t>(CUMap.find(Offset)->second.Offset),
152         support::little);
153 
154     // Header field #4: address size.
155     // 8 since we only write ELF64 binaries for now.
156     RangesStream << char(8);
157 
158     // Header field #5: segment size of target architecture.
159     RangesStream << char(0);
160 
161     // Padding before address table - 4 bytes in the 64-bit-pointer case.
162     support::endian::write(RangesStream, static_cast<uint32_t>(0),
163                            support::little);
164 
165     writeAddressRanges(RangesStream, AddressRanges, true);
166   }
167 }
168 
169 DebugAddrWriter::DebugAddrWriter(BinaryContext *Bc) { BC = Bc; }
170 
171 void DebugAddrWriter::AddressForDWOCU::dump() {
172   std::vector<IndexAddressPair> SortedMap(indexToAddressBegin(),
173                                           indexToAdddessEnd());
174   // Sorting address in increasing order of indices.
175   std::sort(SortedMap.begin(), SortedMap.end(),
176             [](const IndexAddressPair &A, const IndexAddressPair &B) {
177               return A.first < B.first;
178             });
179   for (auto &Pair : SortedMap)
180     dbgs() << Twine::utohexstr(Pair.second) << "\t" << Pair.first << "\n";
181 }
182 uint32_t DebugAddrWriter::getIndexFromAddress(uint64_t Address,
183                                               uint64_t DWOId) {
184   std::lock_guard<std::mutex> Lock(WriterMutex);
185   if (!AddressMaps.count(DWOId))
186     AddressMaps[DWOId] = AddressForDWOCU();
187 
188   AddressForDWOCU &Map = AddressMaps[DWOId];
189   auto Entry = Map.find(Address);
190   if (Entry == Map.end()) {
191     auto Index = Map.getNextIndex();
192     Entry = Map.insert(Address, Index).first;
193   }
194   return Entry->second;
195 }
196 
197 // Case1) Address is not in map insert in to AddresToIndex and IndexToAddres
198 // Case2) Address is in the map but Index is higher or equal. Need to update
199 // IndexToAddrss. Case3) Address is in the map but Index is lower. Need to
200 // update AddressToIndex and IndexToAddress
201 void DebugAddrWriter::addIndexAddress(uint64_t Address, uint32_t Index,
202                                       uint64_t DWOId) {
203   std::lock_guard<std::mutex> Lock(WriterMutex);
204   AddressForDWOCU &Map = AddressMaps[DWOId];
205   auto Entry = Map.find(Address);
206   if (Entry != Map.end()) {
207     if (Entry->second > Index)
208       Map.updateAddressToIndex(Address, Index);
209     Map.updateIndexToAddrss(Address, Index);
210   } else {
211     Map.insert(Address, Index);
212   }
213 }
214 
215 AddressSectionBuffer DebugAddrWriter::finalize() {
216   // Need to layout all sections within .debug_addr
217   // Within each section sort Address by index.
218   AddressSectionBuffer Buffer;
219   raw_svector_ostream AddressStream(Buffer);
220   for (std::unique_ptr<DWARFUnit> &CU : BC->DwCtx->compile_units()) {
221     Optional<uint64_t> DWOId = CU->getDWOId();
222     // Handling the case wehre debug information is a mix of Debug fission and
223     // monolitic.
224     if (!DWOId)
225       continue;
226     auto AM = AddressMaps.find(*DWOId);
227     // Adding to map even if it did not contribute to .debug_addr.
228     // The Skeleton CU will still have DW_AT_GNU_addr_base.
229     DWOIdToOffsetMap[*DWOId] = Buffer.size();
230     // If does not exist this CUs DWO section didn't contribute to .debug_addr.
231     if (AM == AddressMaps.end())
232       continue;
233     std::vector<IndexAddressPair> SortedMap(AM->second.indexToAddressBegin(),
234                                             AM->second.indexToAdddessEnd());
235     // Sorting address in increasing order of indices.
236     std::sort(SortedMap.begin(), SortedMap.end(),
237               [](const IndexAddressPair &A, const IndexAddressPair &B) {
238                 return A.first < B.first;
239               });
240 
241     uint8_t AddrSize = CU->getAddressByteSize();
242     uint32_t Counter = 0;
243     auto WriteAddress = [&](uint64_t Address) -> void {
244       ++Counter;
245       switch (AddrSize) {
246       default:
247         assert(false && "Address Size is invalid.");
248         break;
249       case 4:
250         support::endian::write(AddressStream, static_cast<uint32_t>(Address),
251                                support::little);
252         break;
253       case 8:
254         support::endian::write(AddressStream, Address, support::little);
255         break;
256       }
257     };
258 
259     for (const IndexAddressPair &Val : SortedMap) {
260       while (Val.first > Counter)
261         WriteAddress(0);
262       WriteAddress(Val.second);
263     }
264   }
265 
266   return Buffer;
267 }
268 
269 uint64_t DebugAddrWriter::getOffset(uint64_t DWOId) {
270   auto Iter = DWOIdToOffsetMap.find(DWOId);
271   assert(Iter != DWOIdToOffsetMap.end() &&
272          "Offset in to.debug_addr was not found for DWO ID.");
273   return Iter->second;
274 }
275 
276 DebugLocWriter::DebugLocWriter(BinaryContext *BC) {
277   LocBuffer = std::make_unique<DebugBufferVector>();
278   LocStream = std::make_unique<raw_svector_ostream>(*LocBuffer);
279 }
280 
281 void DebugLocWriter::addList(uint64_t AttrOffset,
282                              DebugLocationsVector &&LocList) {
283   if (LocList.empty()) {
284     EmptyAttrLists.push_back(AttrOffset);
285     return;
286   }
287   // Since there is a separate DebugLocWriter for each thread,
288   // we don't need a lock to read the SectionOffset and update it.
289   const uint32_t EntryOffset = SectionOffset;
290 
291   for (const DebugLocationEntry &Entry : LocList) {
292     support::endian::write(*LocStream, static_cast<uint64_t>(Entry.LowPC),
293                            support::little);
294     support::endian::write(*LocStream, static_cast<uint64_t>(Entry.HighPC),
295                            support::little);
296     support::endian::write(*LocStream, static_cast<uint16_t>(Entry.Expr.size()),
297                            support::little);
298     *LocStream << StringRef(reinterpret_cast<const char *>(Entry.Expr.data()),
299                             Entry.Expr.size());
300     SectionOffset += 2 * 8 + 2 + Entry.Expr.size();
301   }
302   LocStream->write_zeros(16);
303   SectionOffset += 16;
304   LocListDebugInfoPatches.push_back({AttrOffset, EntryOffset});
305 }
306 
307 void DebugLoclistWriter::addList(uint64_t AttrOffset,
308                                  DebugLocationsVector &&LocList) {
309   Patches.push_back({AttrOffset, std::move(LocList)});
310 }
311 
312 std::unique_ptr<DebugBufferVector> DebugLocWriter::getBuffer() {
313   return std::move(LocBuffer);
314 }
315 
316 // DWARF 4: 2.6.2
317 void DebugLocWriter::finalize(uint64_t SectionOffset,
318                               SimpleBinaryPatcher &DebugInfoPatcher) {
319   for (const auto LocListDebugInfoPatchType : LocListDebugInfoPatches) {
320     uint64_t Offset = SectionOffset + LocListDebugInfoPatchType.LocListOffset;
321     DebugInfoPatcher.addLE32Patch(LocListDebugInfoPatchType.DebugInfoAttrOffset,
322                                   Offset);
323   }
324 
325   for (uint64_t DebugInfoAttrOffset : EmptyAttrLists)
326     DebugInfoPatcher.addLE32Patch(DebugInfoAttrOffset,
327                                   DebugLocWriter::EmptyListOffset);
328 }
329 
330 void DebugLoclistWriter::finalize(uint64_t SectionOffset,
331                                   SimpleBinaryPatcher &DebugInfoPatcher) {
332   for (LocPatch &Patch : Patches) {
333     if (Patch.LocList.empty()) {
334       DebugInfoPatcher.addLE32Patch(Patch.AttrOffset,
335                                     DebugLocWriter::EmptyListOffset);
336       continue;
337     }
338     const uint32_t EntryOffset = LocBuffer->size();
339     for (const DebugLocationEntry &Entry : Patch.LocList) {
340       support::endian::write(*LocStream,
341                              static_cast<uint8_t>(dwarf::DW_LLE_startx_length),
342                              support::little);
343       uint32_t Index = AddrWriter->getIndexFromAddress(Entry.LowPC, DWOId);
344       encodeULEB128(Index, *LocStream);
345 
346       // TODO: Support DWARF5
347       support::endian::write(*LocStream,
348                              static_cast<uint32_t>(Entry.HighPC - Entry.LowPC),
349                              support::little);
350       support::endian::write(*LocStream,
351                              static_cast<uint16_t>(Entry.Expr.size()),
352                              support::little);
353       *LocStream << StringRef(reinterpret_cast<const char *>(Entry.Expr.data()),
354                               Entry.Expr.size());
355     }
356     support::endian::write(*LocStream,
357                            static_cast<uint8_t>(dwarf::DW_LLE_end_of_list),
358                            support::little);
359     DebugInfoPatcher.addLE32Patch(Patch.AttrOffset, EntryOffset);
360     clearList(Patch.LocList);
361   }
362   clearList(Patches);
363 }
364 
365 DebugAddrWriter *DebugLoclistWriter::AddrWriter = nullptr;
366 
367 void DebugInfoBinaryPatcher::addUnitBaseOffsetLabel(uint64_t Offset) {
368   Offset -= DWPUnitOffset;
369   std::lock_guard<std::mutex> Lock(WriterMutex);
370   DebugPatches.emplace_back(new DWARFUnitOffsetBaseLabel(Offset));
371 }
372 
373 void DebugInfoBinaryPatcher::addDestinationReferenceLabel(uint64_t Offset) {
374   Offset -= DWPUnitOffset;
375   std::lock_guard<std::mutex> Lock(WriterMutex);
376   auto RetVal = DestinationLabels.insert(Offset);
377   if (!RetVal.second)
378     return;
379 
380   DebugPatches.emplace_back(new DestinationReferenceLabel(Offset));
381 }
382 
383 void DebugInfoBinaryPatcher::addReferenceToPatch(uint64_t Offset,
384                                                  uint32_t DestinationOffset,
385                                                  uint32_t OldValueSize,
386                                                  dwarf::Form Form) {
387   Offset -= DWPUnitOffset;
388   DestinationOffset -= DWPUnitOffset;
389   std::lock_guard<std::mutex> Lock(WriterMutex);
390   DebugPatches.emplace_back(
391       new DebugPatchReference(Offset, OldValueSize, DestinationOffset, Form));
392 }
393 
394 void DebugInfoBinaryPatcher::addUDataPatch(uint64_t Offset, uint64_t NewValue,
395                                            uint32_t OldValueSize) {
396   Offset -= DWPUnitOffset;
397   std::lock_guard<std::mutex> Lock(WriterMutex);
398   DebugPatches.emplace_back(
399       new DebugPatchVariableSize(Offset, OldValueSize, NewValue));
400 }
401 
402 void DebugInfoBinaryPatcher::addLE64Patch(uint64_t Offset, uint64_t NewValue) {
403   Offset -= DWPUnitOffset;
404   std::lock_guard<std::mutex> Lock(WriterMutex);
405   DebugPatches.emplace_back(new DebugPatch64(Offset, NewValue));
406 }
407 
408 void DebugInfoBinaryPatcher::addLE32Patch(uint64_t Offset, uint32_t NewValue,
409                                           uint32_t OldValueSize) {
410   Offset -= DWPUnitOffset;
411   std::lock_guard<std::mutex> Lock(WriterMutex);
412   if (OldValueSize == 4)
413     DebugPatches.emplace_back(new DebugPatch32(Offset, NewValue));
414   else
415     DebugPatches.emplace_back(new DebugPatch64to32(Offset, NewValue));
416 }
417 
418 void SimpleBinaryPatcher::addBinaryPatch(uint64_t Offset,
419                                          std::string &&NewValue,
420                                          uint32_t OldValueSize) {
421   Patches.emplace_back(Offset, std::move(NewValue));
422 }
423 
424 void SimpleBinaryPatcher::addBytePatch(uint64_t Offset, uint8_t Value) {
425   auto Str = std::string(1, Value);
426   Patches.emplace_back(Offset, std::move(Str));
427 }
428 
429 static std::string encodeLE(size_t ByteSize, uint64_t NewValue) {
430   std::string LE64(ByteSize, 0);
431   for (size_t I = 0; I < ByteSize; ++I) {
432     LE64[I] = NewValue & 0xff;
433     NewValue >>= 8;
434   }
435   return LE64;
436 }
437 
438 void SimpleBinaryPatcher::addLEPatch(uint64_t Offset, uint64_t NewValue,
439                                      size_t ByteSize) {
440   Patches.emplace_back(Offset, encodeLE(ByteSize, NewValue));
441 }
442 
443 void SimpleBinaryPatcher::addUDataPatch(uint64_t Offset, uint64_t Value,
444                                         uint32_t OldValueSize) {
445   std::string Buff;
446   raw_string_ostream OS(Buff);
447   encodeULEB128(Value, OS, OldValueSize);
448 
449   Patches.emplace_back(Offset, std::move(Buff));
450 }
451 
452 void SimpleBinaryPatcher::addLE64Patch(uint64_t Offset, uint64_t NewValue) {
453   addLEPatch(Offset, NewValue, 8);
454 }
455 
456 void SimpleBinaryPatcher::addLE32Patch(uint64_t Offset, uint32_t NewValue,
457                                        uint32_t OldValueSize) {
458   addLEPatch(Offset, NewValue, 4);
459 }
460 
461 std::string SimpleBinaryPatcher::patchBinary(StringRef BinaryContents) {
462   std::string BinaryContentsStr = std::string(BinaryContents);
463   for (const auto &Patch : Patches) {
464     uint32_t Offset = Patch.first;
465     const std::string &ByteSequence = Patch.second;
466     assert(Offset + ByteSequence.size() <= BinaryContents.size() &&
467            "Applied patch runs over binary size.");
468     for (uint64_t I = 0, Size = ByteSequence.size(); I < Size; ++I) {
469       BinaryContentsStr[Offset + I] = ByteSequence[I];
470     }
471   }
472   return BinaryContentsStr;
473 }
474 
475 CUOffsetMap DebugInfoBinaryPatcher::computeNewOffsets(DWARFContext &DWCtx,
476                                                       bool IsDWOContext) {
477   CUOffsetMap CUMap;
478   std::sort(DebugPatches.begin(), DebugPatches.end(),
479             [](const UniquePatchPtrType &V1, const UniquePatchPtrType &V2) {
480               return V1.get()->Offset < V2.get()->Offset;
481             });
482 
483   DWARFUnitVector::compile_unit_range CompileUnits =
484       IsDWOContext ? DWCtx.dwo_compile_units() : DWCtx.compile_units();
485 
486   for (const std::unique_ptr<DWARFUnit> &CU : CompileUnits)
487     CUMap[CU->getOffset()] = {static_cast<uint32_t>(CU->getOffset()),
488                               static_cast<uint32_t>(CU->getLength())};
489 
490   // Calculating changes in .debug_info size from Patches to build a map of old
491   // to updated reference destination offsets.
492   uint32_t PreviousOffset = 0;
493   int32_t PreviousChangeInSize = 0;
494   for (UniquePatchPtrType &PatchBase : DebugPatches) {
495     Patch *P = PatchBase.get();
496     switch (P->Kind) {
497     default:
498       continue;
499     case DebugPatchKind::PatchValue64to32: {
500       PreviousChangeInSize -= 4;
501       break;
502     }
503     case DebugPatchKind::PatchValueVariable: {
504       DebugPatchVariableSize *DPV =
505           reinterpret_cast<DebugPatchVariableSize *>(P);
506       std::string Temp;
507       raw_string_ostream OS(Temp);
508       encodeULEB128(DPV->Value, OS);
509       PreviousChangeInSize += Temp.size() - DPV->OldValueSize;
510       break;
511     }
512     case DebugPatchKind::DestinationReferenceLabel: {
513       DestinationReferenceLabel *DRL =
514           reinterpret_cast<DestinationReferenceLabel *>(P);
515       OldToNewOffset[DRL->Offset] =
516           DRL->Offset + ChangeInSize + PreviousChangeInSize;
517       break;
518     }
519     case DebugPatchKind::ReferencePatchValue: {
520       // This doesn't look to be a common case, so will always encode as 4 bytes
521       // to reduce algorithmic complexity.
522       DebugPatchReference *RDP = reinterpret_cast<DebugPatchReference *>(P);
523       if (RDP->PatchInfo.IndirectRelative) {
524         PreviousChangeInSize += 4 - RDP->PatchInfo.OldValueSize;
525         assert(RDP->PatchInfo.OldValueSize <= 4 &&
526                "Variable encoding reference greater than 4 bytes.");
527       }
528       break;
529     }
530     case DebugPatchKind::DWARFUnitOffsetBaseLabel: {
531       DWARFUnitOffsetBaseLabel *BaseLabel =
532           reinterpret_cast<DWARFUnitOffsetBaseLabel *>(P);
533       uint32_t CUOffset = BaseLabel->Offset;
534       ChangeInSize += PreviousChangeInSize;
535       uint32_t CUOffsetUpdate = CUOffset + ChangeInSize;
536       CUMap[CUOffset].Offset = CUOffsetUpdate;
537       CUMap[PreviousOffset].Length += PreviousChangeInSize;
538       PreviousChangeInSize = 0;
539       PreviousOffset = CUOffset;
540     }
541     }
542   }
543   CUMap[PreviousOffset].Length += PreviousChangeInSize;
544   return CUMap;
545 }
546 
547 std::string DebugInfoBinaryPatcher::patchBinary(StringRef BinaryContents) {
548   std::string NewBinaryContents;
549   NewBinaryContents.reserve(BinaryContents.size() + ChangeInSize);
550   uint32_t StartOffset = 0;
551   uint32_t DwarfUnitBaseOffset = 0;
552   uint32_t OldValueSize = 0;
553   uint32_t Offset = 0;
554   std::string ByteSequence;
555   std::vector<std::pair<uint32_t, uint32_t>> LengthPatches;
556   // Wasting one entry to avoid checks for first.
557   LengthPatches.push_back({0, 0});
558 
559   // Applying all the patches replacing current entry.
560   // This might change the size of .debug_info section.
561   for (const UniquePatchPtrType &PatchBase : DebugPatches) {
562     Patch *P = PatchBase.get();
563     switch (P->Kind) {
564     default:
565       continue;
566     case DebugPatchKind::ReferencePatchValue: {
567       DebugPatchReference *RDP = reinterpret_cast<DebugPatchReference *>(P);
568       uint32_t DestinationOffset = RDP->DestinationOffset;
569       assert(OldToNewOffset.count(DestinationOffset) &&
570              "Destination Offset for reference not updated.");
571       uint32_t UpdatedOffset = OldToNewOffset[DestinationOffset];
572       Offset = RDP->Offset;
573       OldValueSize = RDP->PatchInfo.OldValueSize;
574       if (RDP->PatchInfo.DirectRelative) {
575         UpdatedOffset -= DwarfUnitBaseOffset;
576         ByteSequence = encodeLE(OldValueSize, UpdatedOffset);
577         // In theory reference for DW_FORM_ref{1,2,4,8} can be right on the edge
578         // and overflow if later debug information grows.
579         if (ByteSequence.size() > OldValueSize)
580           errs() << "BOLT-ERROR: Relative reference of size "
581                  << Twine::utohexstr(OldValueSize)
582                  << " overflows with the new encoding.\n";
583       } else if (RDP->PatchInfo.DirectAbsolute) {
584         ByteSequence = encodeLE(OldValueSize, UpdatedOffset);
585       } else if (RDP->PatchInfo.IndirectRelative) {
586         UpdatedOffset -= DwarfUnitBaseOffset;
587         ByteSequence.clear();
588         raw_string_ostream OS(ByteSequence);
589         encodeULEB128(UpdatedOffset, OS, 4);
590       } else {
591         llvm_unreachable("Invalid Reference form.");
592       }
593       break;
594     }
595     case DebugPatchKind::PatchValue32: {
596       DebugPatch32 *P32 = reinterpret_cast<DebugPatch32 *>(P);
597       Offset = P32->Offset;
598       OldValueSize = 4;
599       ByteSequence = encodeLE(4, P32->Value);
600       break;
601     }
602     case DebugPatchKind::PatchValue64to32: {
603       DebugPatch64to32 *P64to32 = reinterpret_cast<DebugPatch64to32 *>(P);
604       Offset = P64to32->Offset;
605       OldValueSize = 8;
606       ByteSequence = encodeLE(4, P64to32->Value);
607       break;
608     }
609     case DebugPatchKind::PatchValueVariable: {
610       DebugPatchVariableSize *PV =
611           reinterpret_cast<DebugPatchVariableSize *>(P);
612       Offset = PV->Offset;
613       OldValueSize = PV->OldValueSize;
614       ByteSequence.clear();
615       raw_string_ostream OS(ByteSequence);
616       encodeULEB128(PV->Value, OS);
617       break;
618     }
619     case DebugPatchKind::PatchValue64: {
620       DebugPatch64 *P64 = reinterpret_cast<DebugPatch64 *>(P);
621       Offset = P64->Offset;
622       OldValueSize = 8;
623       ByteSequence = encodeLE(8, P64->Value);
624       break;
625     }
626     case DebugPatchKind::DWARFUnitOffsetBaseLabel: {
627       DWARFUnitOffsetBaseLabel *BaseLabel =
628           reinterpret_cast<DWARFUnitOffsetBaseLabel *>(P);
629       Offset = BaseLabel->Offset;
630       OldValueSize = 0;
631       ByteSequence.clear();
632       auto &Patch = LengthPatches.back();
633       // Length to copy between last patch entry and next compile unit.
634       uint32_t RemainingLength = Offset - StartOffset;
635       uint32_t NewCUOffset = NewBinaryContents.size() + RemainingLength;
636       DwarfUnitBaseOffset = NewCUOffset;
637       // Length of previous CU = This CU Offset - sizeof(length) - last CU
638       // Offset.
639       Patch.second = NewCUOffset - 4 - Patch.first;
640       LengthPatches.push_back({NewCUOffset, 0});
641       break;
642     }
643     }
644 
645     assert(Offset + ByteSequence.size() <= BinaryContents.size() &&
646            "Applied patch runs over binary size.");
647     uint32_t Length = Offset - StartOffset;
648     NewBinaryContents.append(BinaryContents.substr(StartOffset, Length).data(),
649                              Length);
650     NewBinaryContents.append(ByteSequence.data(), ByteSequence.size());
651     StartOffset = Offset + OldValueSize;
652   }
653   uint32_t Length = BinaryContents.size() - StartOffset;
654   NewBinaryContents.append(BinaryContents.substr(StartOffset, Length).data(),
655                            Length);
656   DebugPatches.clear();
657 
658   // Patching lengths of CUs
659   auto &Patch = LengthPatches.back();
660   Patch.second = NewBinaryContents.size() - 4 - Patch.first;
661   for (uint32_t J = 1, Size = LengthPatches.size(); J < Size; ++J) {
662     const auto &Patch = LengthPatches[J];
663     ByteSequence = encodeLE(4, Patch.second);
664     Offset = Patch.first;
665     for (uint64_t I = 0, Size = ByteSequence.size(); I < Size; ++I)
666       NewBinaryContents[Offset + I] = ByteSequence[I];
667   }
668 
669   return NewBinaryContents;
670 }
671 
672 void DebugStrWriter::create() {
673   StrBuffer = std::make_unique<DebugStrBufferVector>();
674   StrStream = std::make_unique<raw_svector_ostream>(*StrBuffer);
675 }
676 
677 void DebugStrWriter::initialize() {
678   auto StrSection = BC->DwCtx->getDWARFObj().getStrSection();
679   (*StrStream) << StrSection;
680 }
681 
682 uint32_t DebugStrWriter::addString(StringRef Str) {
683   std::lock_guard<std::mutex> Lock(WriterMutex);
684   if (StrBuffer->empty())
685     initialize();
686   auto Offset = StrBuffer->size();
687   (*StrStream) << Str;
688   StrStream->write_zeros(1);
689   return Offset;
690 }
691 
692 void DebugAbbrevWriter::addUnitAbbreviations(DWARFUnit &Unit) {
693   const DWARFAbbreviationDeclarationSet *Abbrevs = Unit.getAbbreviations();
694   if (!Abbrevs)
695     return;
696 
697   // Multiple units may share the same abbreviations. Only add abbreviations
698   // for the first unit and reuse them.
699   const uint64_t AbbrevOffset = Unit.getAbbreviationsOffset();
700   if (UnitsAbbrevData.find(AbbrevOffset) != UnitsAbbrevData.end())
701     return;
702 
703   AbbrevData &UnitData = UnitsAbbrevData[AbbrevOffset];
704   UnitData.Buffer = std::make_unique<DebugBufferVector>();
705   UnitData.Stream = std::make_unique<raw_svector_ostream>(*UnitData.Buffer);
706 
707   const PatchesTy &UnitPatches = Patches[&Unit];
708 
709   raw_svector_ostream &OS = *UnitData.Stream.get();
710 
711   // Take a fast path if there are no patches to apply. Simply copy the original
712   // contents.
713   if (UnitPatches.empty()) {
714     StringRef AbbrevSectionContents =
715         Unit.isDWOUnit() ? Unit.getContext().getDWARFObj().getAbbrevDWOSection()
716                          : Unit.getContext().getDWARFObj().getAbbrevSection();
717     StringRef AbbrevContents;
718 
719     const DWARFUnitIndex &CUIndex = Unit.getContext().getCUIndex();
720     if (!CUIndex.getRows().empty()) {
721       // Handle DWP section contribution.
722       const DWARFUnitIndex::Entry *DWOEntry =
723           CUIndex.getFromHash(*Unit.getDWOId());
724       if (!DWOEntry)
725         return;
726 
727       const DWARFUnitIndex::Entry::SectionContribution *DWOContrubution =
728           DWOEntry->getContribution(DWARFSectionKind::DW_SECT_ABBREV);
729       AbbrevContents = AbbrevSectionContents.substr(DWOContrubution->Offset,
730                                                     DWOContrubution->Length);
731     } else if (!Unit.isDWOUnit()) {
732       const uint64_t StartOffset = Unit.getAbbreviationsOffset();
733 
734       // We know where the unit's abbreviation set starts, but not where it ends
735       // as such data is not readily available. Hence, we have to build a sorted
736       // list of start addresses and find the next starting address to determine
737       // the set boundaries.
738       //
739       // FIXME: if we had a full access to DWARFDebugAbbrev::AbbrDeclSets
740       // we wouldn't have to build our own sorted list for the quick lookup.
741       if (AbbrevSetOffsets.empty()) {
742         for_each(
743             *Unit.getContext().getDebugAbbrev(),
744             [&](const std::pair<uint64_t, DWARFAbbreviationDeclarationSet> &P) {
745               AbbrevSetOffsets.push_back(P.first);
746             });
747         sort(AbbrevSetOffsets);
748       }
749       auto It = upper_bound(AbbrevSetOffsets, StartOffset);
750       const uint64_t EndOffset =
751           It == AbbrevSetOffsets.end() ? AbbrevSectionContents.size() : *It;
752       AbbrevContents = AbbrevSectionContents.slice(StartOffset, EndOffset);
753     } else {
754       // For DWO unit outside of DWP, we expect the entire section to hold
755       // abbreviations for this unit only.
756       AbbrevContents = AbbrevSectionContents;
757     }
758 
759     OS.reserveExtraSpace(AbbrevContents.size());
760     OS << AbbrevContents;
761 
762     return;
763   }
764 
765   for (auto I = Abbrevs->begin(), E = Abbrevs->end(); I != E; ++I) {
766     const DWARFAbbreviationDeclaration &Abbrev = *I;
767     auto Patch = UnitPatches.find(&Abbrev);
768 
769     encodeULEB128(Abbrev.getCode(), OS);
770     encodeULEB128(Abbrev.getTag(), OS);
771     encodeULEB128(Abbrev.hasChildren(), OS);
772     for (const DWARFAbbreviationDeclaration::AttributeSpec &AttrSpec :
773          Abbrev.attributes()) {
774       if (Patch != UnitPatches.end()) {
775         bool Patched = false;
776         // Patches added later take a precedence over earlier ones.
777         for (auto I = Patch->second.rbegin(), E = Patch->second.rend(); I != E;
778              ++I) {
779           if (I->OldAttr != AttrSpec.Attr)
780             continue;
781 
782           encodeULEB128(I->NewAttr, OS);
783           encodeULEB128(I->NewAttrForm, OS);
784           Patched = true;
785           break;
786         }
787         if (Patched)
788           continue;
789       }
790 
791       encodeULEB128(AttrSpec.Attr, OS);
792       encodeULEB128(AttrSpec.Form, OS);
793       if (AttrSpec.isImplicitConst())
794         encodeSLEB128(AttrSpec.getImplicitConstValue(), OS);
795     }
796 
797     encodeULEB128(0, OS);
798     encodeULEB128(0, OS);
799   }
800   encodeULEB128(0, OS);
801 }
802 
803 std::unique_ptr<DebugBufferVector> DebugAbbrevWriter::finalize() {
804   if (DWOId) {
805     // We expect abbrev_offset to always be zero for DWO units as there
806     // should be one CU per DWO, and TUs should share the same abbreviation
807     // set with the CU.
808     // For DWP AbbreviationsOffset is an Abbrev contribution in the DWP file, so
809     // can be none zero. Thus we are skipping the check for DWP.
810     bool IsDWP = !Context.getCUIndex().getRows().empty();
811     if (!IsDWP) {
812       for (const std::unique_ptr<DWARFUnit> &Unit : Context.dwo_units()) {
813         if (Unit->getAbbreviationsOffset() != 0) {
814           errs() << "BOLT-ERROR: detected DWO unit with non-zero abbr_offset. "
815                     "Unable to update debug info.\n";
816           exit(1);
817         }
818       }
819     }
820 
821     // Issue abbreviations for the DWO CU only.
822     addUnitAbbreviations(*Context.getDWOCompileUnitForHash(*DWOId));
823   } else {
824     // Add abbreviations from compile and type non-DWO units.
825     for (const std::unique_ptr<DWARFUnit> &Unit : Context.normal_units())
826       addUnitAbbreviations(*Unit);
827   }
828 
829   DebugBufferVector ReturnBuffer;
830 
831   // Pre-calculate the total size of abbrev section.
832   uint64_t Size = 0;
833   for (const auto &KV : UnitsAbbrevData) {
834     const AbbrevData &UnitData = KV.second;
835     Size += UnitData.Buffer->size();
836   }
837   ReturnBuffer.reserve(Size);
838 
839   uint64_t Pos = 0;
840   for (auto &KV : UnitsAbbrevData) {
841     AbbrevData &UnitData = KV.second;
842     ReturnBuffer.append(*UnitData.Buffer);
843     UnitData.Offset = Pos;
844     Pos += UnitData.Buffer->size();
845 
846     UnitData.Buffer.reset();
847     UnitData.Stream.reset();
848   }
849 
850   return std::make_unique<DebugBufferVector>(ReturnBuffer);
851 }
852 
853 static void emitDwarfSetLineAddrAbs(MCStreamer &OS,
854                                     MCDwarfLineTableParams Params,
855                                     int64_t LineDelta, uint64_t Address,
856                                     int PointerSize) {
857   // emit the sequence to set the address
858   OS.emitIntValue(dwarf::DW_LNS_extended_op, 1);
859   OS.emitULEB128IntValue(PointerSize + 1);
860   OS.emitIntValue(dwarf::DW_LNE_set_address, 1);
861   OS.emitIntValue(Address, PointerSize);
862 
863   // emit the sequence for the LineDelta (from 1) and a zero address delta.
864   MCDwarfLineAddr::Emit(&OS, Params, LineDelta, 0);
865 }
866 
867 static inline void emitBinaryDwarfLineTable(
868     MCStreamer *MCOS, MCDwarfLineTableParams Params,
869     const DWARFDebugLine::LineTable *Table,
870     const std::vector<DwarfLineTable::RowSequence> &InputSequences) {
871   if (InputSequences.empty())
872     return;
873 
874   constexpr uint64_t InvalidAddress = UINT64_MAX;
875   unsigned FileNum = 1;
876   unsigned LastLine = 1;
877   unsigned Column = 0;
878   unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
879   unsigned Isa = 0;
880   unsigned Discriminator = 0;
881   uint64_t LastAddress = InvalidAddress;
882   uint64_t PrevEndOfSequence = InvalidAddress;
883   const MCAsmInfo *AsmInfo = MCOS->getContext().getAsmInfo();
884 
885   auto emitEndOfSequence = [&](uint64_t Address) {
886     MCDwarfLineAddr::Emit(MCOS, Params, INT64_MAX, Address - LastAddress);
887     FileNum = 1;
888     LastLine = 1;
889     Column = 0;
890     Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
891     Isa = 0;
892     Discriminator = 0;
893     LastAddress = InvalidAddress;
894   };
895 
896   for (const DwarfLineTable::RowSequence &Sequence : InputSequences) {
897     const uint64_t SequenceStart =
898         Table->Rows[Sequence.FirstIndex].Address.Address;
899 
900     // Check if we need to mark the end of the sequence.
901     if (PrevEndOfSequence != InvalidAddress && LastAddress != InvalidAddress &&
902         PrevEndOfSequence != SequenceStart) {
903       emitEndOfSequence(PrevEndOfSequence);
904     }
905 
906     for (uint32_t RowIndex = Sequence.FirstIndex;
907          RowIndex <= Sequence.LastIndex; ++RowIndex) {
908       const DWARFDebugLine::Row &Row = Table->Rows[RowIndex];
909       int64_t LineDelta = static_cast<int64_t>(Row.Line) - LastLine;
910       const uint64_t Address = Row.Address.Address;
911 
912       if (FileNum != Row.File) {
913         FileNum = Row.File;
914         MCOS->emitInt8(dwarf::DW_LNS_set_file);
915         MCOS->emitULEB128IntValue(FileNum);
916       }
917       if (Column != Row.Column) {
918         Column = Row.Column;
919         MCOS->emitInt8(dwarf::DW_LNS_set_column);
920         MCOS->emitULEB128IntValue(Column);
921       }
922       if (Discriminator != Row.Discriminator &&
923           MCOS->getContext().getDwarfVersion() >= 4) {
924         Discriminator = Row.Discriminator;
925         unsigned Size = getULEB128Size(Discriminator);
926         MCOS->emitInt8(dwarf::DW_LNS_extended_op);
927         MCOS->emitULEB128IntValue(Size + 1);
928         MCOS->emitInt8(dwarf::DW_LNE_set_discriminator);
929         MCOS->emitULEB128IntValue(Discriminator);
930       }
931       if (Isa != Row.Isa) {
932         Isa = Row.Isa;
933         MCOS->emitInt8(dwarf::DW_LNS_set_isa);
934         MCOS->emitULEB128IntValue(Isa);
935       }
936       if (Row.IsStmt != Flags) {
937         Flags = Row.IsStmt;
938         MCOS->emitInt8(dwarf::DW_LNS_negate_stmt);
939       }
940       if (Row.BasicBlock)
941         MCOS->emitInt8(dwarf::DW_LNS_set_basic_block);
942       if (Row.PrologueEnd)
943         MCOS->emitInt8(dwarf::DW_LNS_set_prologue_end);
944       if (Row.EpilogueBegin)
945         MCOS->emitInt8(dwarf::DW_LNS_set_epilogue_begin);
946 
947       // The end of the sequence is not normal in the middle of the input
948       // sequence, but could happen, e.g. for assembly code.
949       if (Row.EndSequence) {
950         emitEndOfSequence(Address);
951       } else {
952         if (LastAddress == InvalidAddress)
953           emitDwarfSetLineAddrAbs(*MCOS, Params, LineDelta, Address,
954                                   AsmInfo->getCodePointerSize());
955         else
956           MCDwarfLineAddr::Emit(MCOS, Params, LineDelta, Address - LastAddress);
957 
958         LastAddress = Address;
959         LastLine = Row.Line;
960       }
961 
962       Discriminator = 0;
963     }
964     PrevEndOfSequence = Sequence.EndAddress;
965   }
966 
967   // Finish with the end of the sequence.
968   if (LastAddress != InvalidAddress)
969     emitEndOfSequence(PrevEndOfSequence);
970 }
971 
972 // This function is similar to the one from MCDwarfLineTable, except it handles
973 // end-of-sequence entries differently by utilizing line entries with
974 // DWARF2_FLAG_END_SEQUENCE flag.
975 static inline void emitDwarfLineTable(
976     MCStreamer *MCOS, MCSection *Section,
977     const MCLineSection::MCDwarfLineEntryCollection &LineEntries) {
978   unsigned FileNum = 1;
979   unsigned LastLine = 1;
980   unsigned Column = 0;
981   unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
982   unsigned Isa = 0;
983   unsigned Discriminator = 0;
984   MCSymbol *LastLabel = nullptr;
985   const MCAsmInfo *AsmInfo = MCOS->getContext().getAsmInfo();
986 
987   // Loop through each MCDwarfLineEntry and encode the dwarf line number table.
988   for (const MCDwarfLineEntry &LineEntry : LineEntries) {
989     if (LineEntry.getFlags() & DWARF2_FLAG_END_SEQUENCE) {
990       MCOS->emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, LineEntry.getLabel(),
991                                      AsmInfo->getCodePointerSize());
992       FileNum = 1;
993       LastLine = 1;
994       Column = 0;
995       Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
996       Isa = 0;
997       Discriminator = 0;
998       LastLabel = nullptr;
999       continue;
1000     }
1001 
1002     int64_t LineDelta = static_cast<int64_t>(LineEntry.getLine()) - LastLine;
1003 
1004     if (FileNum != LineEntry.getFileNum()) {
1005       FileNum = LineEntry.getFileNum();
1006       MCOS->emitInt8(dwarf::DW_LNS_set_file);
1007       MCOS->emitULEB128IntValue(FileNum);
1008     }
1009     if (Column != LineEntry.getColumn()) {
1010       Column = LineEntry.getColumn();
1011       MCOS->emitInt8(dwarf::DW_LNS_set_column);
1012       MCOS->emitULEB128IntValue(Column);
1013     }
1014     if (Discriminator != LineEntry.getDiscriminator() &&
1015         MCOS->getContext().getDwarfVersion() >= 4) {
1016       Discriminator = LineEntry.getDiscriminator();
1017       unsigned Size = getULEB128Size(Discriminator);
1018       MCOS->emitInt8(dwarf::DW_LNS_extended_op);
1019       MCOS->emitULEB128IntValue(Size + 1);
1020       MCOS->emitInt8(dwarf::DW_LNE_set_discriminator);
1021       MCOS->emitULEB128IntValue(Discriminator);
1022     }
1023     if (Isa != LineEntry.getIsa()) {
1024       Isa = LineEntry.getIsa();
1025       MCOS->emitInt8(dwarf::DW_LNS_set_isa);
1026       MCOS->emitULEB128IntValue(Isa);
1027     }
1028     if ((LineEntry.getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
1029       Flags = LineEntry.getFlags();
1030       MCOS->emitInt8(dwarf::DW_LNS_negate_stmt);
1031     }
1032     if (LineEntry.getFlags() & DWARF2_FLAG_BASIC_BLOCK)
1033       MCOS->emitInt8(dwarf::DW_LNS_set_basic_block);
1034     if (LineEntry.getFlags() & DWARF2_FLAG_PROLOGUE_END)
1035       MCOS->emitInt8(dwarf::DW_LNS_set_prologue_end);
1036     if (LineEntry.getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
1037       MCOS->emitInt8(dwarf::DW_LNS_set_epilogue_begin);
1038 
1039     MCSymbol *Label = LineEntry.getLabel();
1040 
1041     // At this point we want to emit/create the sequence to encode the delta
1042     // in line numbers and the increment of the address from the previous
1043     // Label and the current Label.
1044     MCOS->emitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
1045                                    AsmInfo->getCodePointerSize());
1046     Discriminator = 0;
1047     LastLine = LineEntry.getLine();
1048     LastLabel = Label;
1049   }
1050 
1051   assert(LastLabel == nullptr && "end of sequence expected");
1052 }
1053 
1054 void DwarfLineTable::emitCU(MCStreamer *MCOS, MCDwarfLineTableParams Params,
1055                             Optional<MCDwarfLineStr> &LineStr,
1056                             BinaryContext &BC) const {
1057   if (!RawData.empty()) {
1058     assert(MCLineSections.getMCLineEntries().empty() &&
1059            InputSequences.empty() &&
1060            "cannot combine raw data with new line entries");
1061     MCOS->emitLabel(getLabel());
1062     MCOS->emitBytes(RawData);
1063 
1064     // Emit fake relocation for RuntimeDyld to always allocate the section.
1065     //
1066     // FIXME: remove this once RuntimeDyld stops skipping allocatable sections
1067     //        without relocations.
1068     MCOS->emitRelocDirective(
1069         *MCConstantExpr::create(0, *BC.Ctx), "BFD_RELOC_NONE",
1070         MCSymbolRefExpr::create(getLabel(), *BC.Ctx), SMLoc(), *BC.STI);
1071 
1072     return;
1073   }
1074 
1075   MCSymbol *LineEndSym = Header.Emit(MCOS, Params, LineStr).second;
1076 
1077   // Put out the line tables.
1078   for (const auto &LineSec : MCLineSections.getMCLineEntries())
1079     emitDwarfLineTable(MCOS, LineSec.first, LineSec.second);
1080 
1081   // Emit line tables for the original code.
1082   emitBinaryDwarfLineTable(MCOS, Params, InputTable, InputSequences);
1083 
1084   // This is the end of the section, so set the value of the symbol at the end
1085   // of this section (that was used in a previous expression).
1086   MCOS->emitLabel(LineEndSym);
1087 }
1088 
1089 void DwarfLineTable::emit(BinaryContext &BC, MCStreamer &Streamer) {
1090   MCAssembler &Assembler =
1091       static_cast<MCObjectStreamer *>(&Streamer)->getAssembler();
1092 
1093   MCDwarfLineTableParams Params = Assembler.getDWARFLinetableParams();
1094 
1095   auto &LineTables = BC.getDwarfLineTables();
1096 
1097   // Bail out early so we don't switch to the debug_line section needlessly and
1098   // in doing so create an unnecessary (if empty) section.
1099   if (LineTables.empty())
1100     return;
1101 
1102   // In a v5 non-split line table, put the strings in a separate section.
1103   Optional<MCDwarfLineStr> LineStr(None);
1104   if (BC.Ctx->getDwarfVersion() >= 5)
1105     LineStr = MCDwarfLineStr(*BC.Ctx);
1106 
1107   // Switch to the section where the table will be emitted into.
1108   Streamer.SwitchSection(BC.MOFI->getDwarfLineSection());
1109 
1110   // Handle the rest of the Compile Units.
1111   for (auto &CUIDTablePair : LineTables) {
1112     CUIDTablePair.second.emitCU(&Streamer, Params, LineStr, BC);
1113   }
1114 }
1115 
1116 } // namespace bolt
1117 } // namespace llvm
1118