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/Rewrite/RewriteInstance.h"
16 #include "bolt/Utils/Utils.h"
17 #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
18 #include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
19 #include "llvm/DebugInfo/DWARF/DWARFDebugAddr.h"
20 #include "llvm/MC/MCAssembler.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCObjectStreamer.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/EndianStream.h"
25 #include "llvm/Support/LEB128.h"
26 #include "llvm/Support/SHA1.h"
27 #include <algorithm>
28 #include <cassert>
29 #include <cstdint>
30 #include <limits>
31 #include <unordered_map>
32 #include <vector>
33 
34 #define DEBUG_TYPE "bolt-debug-info"
35 
36 namespace opts {
37 extern llvm::cl::opt<unsigned> Verbosity;
38 } // namespace opts
39 
40 namespace llvm {
41 class MCSymbol;
42 
43 namespace bolt {
44 
45 /// Finds attributes FormValue and Offset.
46 ///
47 /// \param DIE die to look up in.
48 /// \param Index the attribute index to extract.
49 /// \return an optional AttrInfo with DWARFFormValue and Offset.
50 Optional<AttrInfo>
51 findAttributeInfo(const DWARFDie DIE,
52                   const DWARFAbbreviationDeclaration *AbbrevDecl,
53                   uint32_t Index) {
54   const DWARFUnit &U = *DIE.getDwarfUnit();
55   uint64_t Offset =
56       AbbrevDecl->getAttributeOffsetFromIndex(Index, DIE.getOffset(), U);
57   Optional<DWARFFormValue> Value =
58       AbbrevDecl->getAttributeValueFromOffset(Index, Offset, U);
59   if (!Value)
60     return None;
61   // AttributeSpec
62   const DWARFAbbreviationDeclaration::AttributeSpec *AttrVal =
63       AbbrevDecl->attributes().begin() + Index;
64   uint32_t ValSize = 0;
65   Optional<int64_t> ValSizeOpt = AttrVal->getByteSize(U);
66   if (ValSizeOpt) {
67     ValSize = static_cast<uint32_t>(*ValSizeOpt);
68   } else {
69     DWARFDataExtractor DebugInfoData = U.getDebugInfoExtractor();
70     uint64_t NewOffset = Offset;
71     DWARFFormValue::skipValue(Value->getForm(), DebugInfoData, &NewOffset,
72                               U.getFormParams());
73     // This includes entire size of the entry, which might not be just the
74     // encoding part. For example for DW_AT_loc it will include expression
75     // location.
76     ValSize = NewOffset - Offset;
77   }
78 
79   return AttrInfo{*Value, Offset, ValSize};
80 }
81 
82 const DebugLineTableRowRef DebugLineTableRowRef::NULL_ROW{0, 0};
83 
84 namespace {
85 
86 LLVM_ATTRIBUTE_UNUSED
87 static void printLE64(const std::string &S) {
88   for (uint32_t I = 0, Size = S.size(); I < Size; ++I) {
89     errs() << Twine::utohexstr(S[I]);
90     errs() << Twine::utohexstr((int8_t)S[I]);
91   }
92   errs() << "\n";
93 }
94 
95 // Writes address ranges to Writer as pairs of 64-bit (address, size).
96 // If RelativeRange is true, assumes the address range to be written must be of
97 // the form (begin address, range size), otherwise (begin address, end address).
98 // Terminates the list by writing a pair of two zeroes.
99 // Returns the number of written bytes.
100 uint64_t writeAddressRanges(raw_svector_ostream &Stream,
101                             const DebugAddressRangesVector &AddressRanges,
102                             const bool WriteRelativeRanges = false) {
103   for (const DebugAddressRange &Range : AddressRanges) {
104     support::endian::write(Stream, Range.LowPC, support::little);
105     support::endian::write(
106         Stream, WriteRelativeRanges ? Range.HighPC - Range.LowPC : Range.HighPC,
107         support::little);
108   }
109   // Finish with 0 entries.
110   support::endian::write(Stream, 0ULL, support::little);
111   support::endian::write(Stream, 0ULL, support::little);
112   return AddressRanges.size() * 16 + 16;
113 }
114 
115 } // namespace
116 
117 DebugRangesSectionWriter::DebugRangesSectionWriter() {
118   RangesBuffer = std::make_unique<DebugBufferVector>();
119   RangesStream = std::make_unique<raw_svector_ostream>(*RangesBuffer);
120 
121   // Add an empty range as the first entry;
122   SectionOffset +=
123       writeAddressRanges(*RangesStream.get(), DebugAddressRangesVector{});
124   Kind = RangesWriterKind::DebugRangesWriter;
125 }
126 
127 uint64_t DebugRangesSectionWriter::addRanges(
128     DebugAddressRangesVector &&Ranges,
129     std::map<DebugAddressRangesVector, uint64_t> &CachedRanges) {
130   if (Ranges.empty())
131     return getEmptyRangesOffset();
132 
133   const auto RI = CachedRanges.find(Ranges);
134   if (RI != CachedRanges.end())
135     return RI->second;
136 
137   const uint64_t EntryOffset = addRanges(Ranges);
138   CachedRanges.emplace(std::move(Ranges), EntryOffset);
139 
140   return EntryOffset;
141 }
142 
143 uint64_t
144 DebugRangesSectionWriter::addRanges(const DebugAddressRangesVector &Ranges) {
145   if (Ranges.empty())
146     return getEmptyRangesOffset();
147 
148   // Reading the SectionOffset and updating it should be atomic to guarantee
149   // unique and correct offsets in patches.
150   std::lock_guard<std::mutex> Lock(WriterMutex);
151   const uint32_t EntryOffset = SectionOffset;
152   SectionOffset += writeAddressRanges(*RangesStream.get(), Ranges);
153 
154   return EntryOffset;
155 }
156 
157 uint64_t DebugRangesSectionWriter::getSectionOffset() {
158   std::lock_guard<std::mutex> Lock(WriterMutex);
159   return SectionOffset;
160 }
161 
162 DebugAddrWriter *DebugRangeListsSectionWriter::AddrWriter = nullptr;
163 
164 uint64_t DebugRangeListsSectionWriter::addRanges(
165     DebugAddressRangesVector &&Ranges,
166     std::map<DebugAddressRangesVector, uint64_t> &CachedRanges) {
167   return addRanges(Ranges);
168 }
169 
170 struct LocListsRangelistsHeader {
171   UnitLengthType UnitLength; // Size of loclist entris section, not including
172                              // size of header.
173   VersionType Version;
174   AddressSizeType AddressSize;
175   SegmentSelectorType SegmentSelector;
176   OffsetEntryCountType OffsetEntryCount;
177 };
178 
179 static std::unique_ptr<DebugBufferVector>
180 getDWARF5Header(const LocListsRangelistsHeader &Header) {
181   std::unique_ptr<DebugBufferVector> HeaderBuffer =
182       std::make_unique<DebugBufferVector>();
183   std::unique_ptr<raw_svector_ostream> HeaderStream =
184       std::make_unique<raw_svector_ostream>(*HeaderBuffer);
185 
186   // 7.29 length of the set of entries for this compilation unit, not including
187   // the length field itself
188   const uint32_t HeaderSize =
189       getDWARF5RngListLocListHeaderSize() - sizeof(UnitLengthType);
190 
191   support::endian::write(*HeaderStream, Header.UnitLength + HeaderSize,
192                          support::little);
193   support::endian::write(*HeaderStream, Header.Version, support::little);
194   support::endian::write(*HeaderStream, Header.AddressSize, support::little);
195   support::endian::write(*HeaderStream, Header.SegmentSelector,
196                          support::little);
197   support::endian::write(*HeaderStream, Header.OffsetEntryCount,
198                          support::little);
199   return HeaderBuffer;
200 }
201 
202 uint64_t DebugRangeListsSectionWriter::addRanges(
203     const DebugAddressRangesVector &Ranges) {
204   std::lock_guard<std::mutex> Lock(WriterMutex);
205 
206   RangeEntries.push_back(CurrentOffset);
207   for (const DebugAddressRange &Range : Ranges) {
208     support::endian::write(*CUBodyStream,
209                            static_cast<uint8_t>(dwarf::DW_RLE_startx_length),
210                            support::little);
211     uint32_t Index = AddrWriter->getIndexFromAddress(Range.LowPC, *CU);
212     encodeULEB128(Index, *CUBodyStream);
213     encodeULEB128(Range.HighPC - Range.LowPC, *CUBodyStream);
214   }
215   support::endian::write(*CUBodyStream,
216                          static_cast<uint8_t>(dwarf::DW_RLE_end_of_list),
217                          support::little);
218   CurrentOffset = CUBodyBuffer->size();
219   return RangeEntries.size() - 1;
220 }
221 
222 void DebugRangeListsSectionWriter::finalizeSection() {
223   std::unique_ptr<DebugBufferVector> CUArrayBuffer =
224       std::make_unique<DebugBufferVector>();
225   std::unique_ptr<raw_svector_ostream> CUArrayStream =
226       std::make_unique<raw_svector_ostream>(*CUArrayBuffer);
227   constexpr uint32_t SizeOfArrayEntry = 4;
228   const uint32_t SizeOfArraySection = RangeEntries.size() * SizeOfArrayEntry;
229   for (uint32_t Offset : RangeEntries)
230     support::endian::write(*CUArrayStream, Offset + SizeOfArraySection,
231                            support::little);
232 
233   std::unique_ptr<DebugBufferVector> Header = getDWARF5Header(
234       {static_cast<uint32_t>(SizeOfArraySection + CUBodyBuffer.get()->size()),
235        5, 8, 0, static_cast<uint32_t>(RangeEntries.size())});
236   *RangesStream << *Header;
237   *RangesStream << *CUArrayBuffer;
238   *RangesStream << *CUBodyBuffer;
239   SectionOffset = RangesBuffer->size();
240 }
241 
242 void DebugRangeListsSectionWriter::initSection(DWARFUnit &Unit) {
243   CUBodyBuffer = std::make_unique<DebugBufferVector>();
244   CUBodyStream = std::make_unique<raw_svector_ostream>(*CUBodyBuffer);
245   RangeEntries.clear();
246   CurrentOffset = 0;
247   CU = &Unit;
248 }
249 
250 void DebugARangesSectionWriter::addCURanges(uint64_t CUOffset,
251                                             DebugAddressRangesVector &&Ranges) {
252   std::lock_guard<std::mutex> Lock(CUAddressRangesMutex);
253   CUAddressRanges.emplace(CUOffset, std::move(Ranges));
254 }
255 
256 void DebugARangesSectionWriter::writeARangesSection(
257     raw_svector_ostream &RangesStream, const CUOffsetMap &CUMap) const {
258   // For reference on the format of the .debug_aranges section, see the DWARF4
259   // specification, section 6.1.4 Lookup by Address
260   // http://www.dwarfstd.org/doc/DWARF4.pdf
261   for (const auto &CUOffsetAddressRangesPair : CUAddressRanges) {
262     const uint64_t Offset = CUOffsetAddressRangesPair.first;
263     const DebugAddressRangesVector &AddressRanges =
264         CUOffsetAddressRangesPair.second;
265 
266     // Emit header.
267 
268     // Size of this set: 8 (size of the header) + 4 (padding after header)
269     // + 2*sizeof(uint64_t) bytes for each of the ranges, plus an extra
270     // pair of uint64_t's for the terminating, zero-length range.
271     // Does not include size field itself.
272     uint32_t Size = 8 + 4 + 2 * sizeof(uint64_t) * (AddressRanges.size() + 1);
273 
274     // Header field #1: set size.
275     support::endian::write(RangesStream, Size, support::little);
276 
277     // Header field #2: version number, 2 as per the specification.
278     support::endian::write(RangesStream, static_cast<uint16_t>(2),
279                            support::little);
280 
281     assert(CUMap.count(Offset) && "Original CU offset is not found in CU Map");
282     // Header field #3: debug info offset of the correspondent compile unit.
283     support::endian::write(
284         RangesStream, static_cast<uint32_t>(CUMap.find(Offset)->second.Offset),
285         support::little);
286 
287     // Header field #4: address size.
288     // 8 since we only write ELF64 binaries for now.
289     RangesStream << char(8);
290 
291     // Header field #5: segment size of target architecture.
292     RangesStream << char(0);
293 
294     // Padding before address table - 4 bytes in the 64-bit-pointer case.
295     support::endian::write(RangesStream, static_cast<uint32_t>(0),
296                            support::little);
297 
298     writeAddressRanges(RangesStream, AddressRanges, true);
299   }
300 }
301 
302 DebugAddrWriter::DebugAddrWriter(BinaryContext *Bc) { BC = Bc; }
303 
304 void DebugAddrWriter::AddressForDWOCU::dump() {
305   std::vector<IndexAddressPair> SortedMap(indexToAddressBegin(),
306                                           indexToAdddessEnd());
307   // Sorting address in increasing order of indices.
308   std::sort(SortedMap.begin(), SortedMap.end(),
309             [](const IndexAddressPair &A, const IndexAddressPair &B) {
310               return A.first < B.first;
311             });
312   for (auto &Pair : SortedMap)
313     dbgs() << Twine::utohexstr(Pair.second) << "\t" << Pair.first << "\n";
314 }
315 uint32_t DebugAddrWriter::getIndexFromAddress(uint64_t Address, DWARFUnit &CU) {
316   std::lock_guard<std::mutex> Lock(WriterMutex);
317   const uint64_t CUID = getCUID(CU);
318   if (!AddressMaps.count(CUID))
319     AddressMaps[CUID] = AddressForDWOCU();
320 
321   AddressForDWOCU &Map = AddressMaps[CUID];
322   auto Entry = Map.find(Address);
323   if (Entry == Map.end()) {
324     auto Index = Map.getNextIndex();
325     Entry = Map.insert(Address, Index).first;
326   }
327   return Entry->second;
328 }
329 
330 // Case1) Address is not in map insert in to AddresToIndex and IndexToAddres
331 // Case2) Address is in the map but Index is higher or equal. Need to update
332 // IndexToAddrss. Case3) Address is in the map but Index is lower. Need to
333 // update AddressToIndex and IndexToAddress
334 void DebugAddrWriter::addIndexAddress(uint64_t Address, uint32_t Index,
335                                       DWARFUnit &CU) {
336   std::lock_guard<std::mutex> Lock(WriterMutex);
337   const uint64_t CUID = getCUID(CU);
338   AddressForDWOCU &Map = AddressMaps[CUID];
339   auto Entry = Map.find(Address);
340   if (Entry != Map.end()) {
341     if (Entry->second > Index)
342       Map.updateAddressToIndex(Address, Index);
343     Map.updateIndexToAddrss(Address, Index);
344   } else {
345     Map.insert(Address, Index);
346   }
347 }
348 
349 AddressSectionBuffer DebugAddrWriter::finalize() {
350   // Need to layout all sections within .debug_addr
351   // Within each section sort Address by index.
352   AddressSectionBuffer Buffer;
353   raw_svector_ostream AddressStream(Buffer);
354   for (std::unique_ptr<DWARFUnit> &CU : BC->DwCtx->compile_units()) {
355     // Handling the case wehre debug information is a mix of Debug fission and
356     // monolitic.
357     if (!CU->getDWOId())
358       continue;
359     const uint64_t CUID = getCUID(*CU.get());
360     auto AM = AddressMaps.find(CUID);
361     // Adding to map even if it did not contribute to .debug_addr.
362     // The Skeleton CU might still have DW_AT_GNU_addr_base.
363     DWOIdToOffsetMap[CUID] = Buffer.size();
364     // If does not exist this CUs DWO section didn't contribute to .debug_addr.
365     if (AM == AddressMaps.end())
366       continue;
367     std::vector<IndexAddressPair> SortedMap(AM->second.indexToAddressBegin(),
368                                             AM->second.indexToAdddessEnd());
369     // Sorting address in increasing order of indices.
370     std::sort(SortedMap.begin(), SortedMap.end(),
371               [](const IndexAddressPair &A, const IndexAddressPair &B) {
372                 return A.first < B.first;
373               });
374 
375     uint8_t AddrSize = CU->getAddressByteSize();
376     uint32_t Counter = 0;
377     auto WriteAddress = [&](uint64_t Address) -> void {
378       ++Counter;
379       switch (AddrSize) {
380       default:
381         assert(false && "Address Size is invalid.");
382         break;
383       case 4:
384         support::endian::write(AddressStream, static_cast<uint32_t>(Address),
385                                support::little);
386         break;
387       case 8:
388         support::endian::write(AddressStream, Address, support::little);
389         break;
390       }
391     };
392 
393     for (const IndexAddressPair &Val : SortedMap) {
394       while (Val.first > Counter)
395         WriteAddress(0);
396       WriteAddress(Val.second);
397     }
398   }
399 
400   return Buffer;
401 }
402 AddressSectionBuffer DebugAddrWriterDwarf5::finalize() {
403   // Need to layout all sections within .debug_addr
404   // Within each section sort Address by index.
405   AddressSectionBuffer Buffer;
406   raw_svector_ostream AddressStream(Buffer);
407   const endianness Endian =
408       BC->DwCtx->isLittleEndian() ? support::little : support::big;
409   const DWARFSection &AddrSec = BC->DwCtx->getDWARFObj().getAddrSection();
410   DWARFDataExtractor AddrData(BC->DwCtx->getDWARFObj(), AddrSec, Endian, 0);
411   DWARFDebugAddrTable AddrTable;
412   DIDumpOptions DumpOpts;
413   constexpr uint32_t HeaderSize = 8;
414   for (std::unique_ptr<DWARFUnit> &CU : BC->DwCtx->compile_units()) {
415     const uint64_t CUID = getCUID(*CU.get());
416     const uint8_t AddrSize = CU->getAddressByteSize();
417     auto AMIter = AddressMaps.find(CUID);
418     // A case where CU has entry in .debug_addr, but we don't modify addresses
419     // for it.
420     if (AMIter == AddressMaps.end()) {
421       AMIter = AddressMaps.insert({CUID, AddressForDWOCU()}).first;
422       Optional<uint64_t> BaseOffset = CU->getAddrOffsetSectionBase();
423       if (!BaseOffset)
424         continue;
425       // Address base offset is to the first entry.
426       // The size of header is 8 bytes.
427       uint64_t Offset = *BaseOffset - HeaderSize;
428       if (Error Err = AddrTable.extract(AddrData, &Offset, 5, AddrSize,
429                                         DumpOpts.WarningHandler)) {
430         DumpOpts.RecoverableErrorHandler(std::move(Err));
431         continue;
432       }
433       uint32_t Index = 0;
434       for (uint64_t Addr : AddrTable.getAddressEntries())
435         AMIter->second.insert(Addr, Index++);
436     }
437 
438     DWOIdToOffsetMap[CUID] = Buffer.size() + HeaderSize;
439 
440     std::vector<IndexAddressPair> SortedMap(
441         AMIter->second.indexToAddressBegin(),
442         AMIter->second.indexToAdddessEnd());
443     // Sorting address in increasing order of indices.
444     std::sort(SortedMap.begin(), SortedMap.end(),
445               [](const IndexAddressPair &A, const IndexAddressPair &B) {
446                 return A.first < B.first;
447               });
448     // Writing out Header
449     const uint32_t Length = SortedMap.size() * AddrSize + 4;
450     support::endian::write(AddressStream, Length, Endian);
451     support::endian::write(AddressStream, static_cast<uint16_t>(5), Endian);
452     support::endian::write(AddressStream, static_cast<uint8_t>(AddrSize),
453                            Endian);
454     support::endian::write(AddressStream, static_cast<uint8_t>(0), Endian);
455 
456     uint32_t Counter = 0;
457     auto writeAddress = [&](uint64_t Address) -> void {
458       ++Counter;
459       switch (AddrSize) {
460       default:
461         llvm_unreachable("Address Size is invalid.");
462         break;
463       case 4:
464         support::endian::write(AddressStream, static_cast<uint32_t>(Address),
465                                Endian);
466         break;
467       case 8:
468         support::endian::write(AddressStream, Address, Endian);
469         break;
470       }
471     };
472 
473     for (const IndexAddressPair &Val : SortedMap) {
474       while (Val.first > Counter)
475         writeAddress(0);
476       writeAddress(Val.second);
477     }
478   }
479 
480   return Buffer;
481 }
482 
483 uint64_t DebugAddrWriter::getOffset(DWARFUnit &Unit) {
484   const uint64_t CUID = getCUID(Unit);
485   assert(CUID && "Can't get offset, not a skeleton CU.");
486   auto Iter = DWOIdToOffsetMap.find(CUID);
487   assert(Iter != DWOIdToOffsetMap.end() &&
488          "Offset in to.debug_addr was not found for DWO ID.");
489   return Iter->second;
490 }
491 
492 uint64_t DebugAddrWriterDwarf5::getOffset(DWARFUnit &Unit) {
493   auto Iter = DWOIdToOffsetMap.find(getCUID(Unit));
494   assert(Iter != DWOIdToOffsetMap.end() &&
495          "Offset in to.debug_addr was not found for CU ID.");
496   return Iter->second;
497 }
498 
499 DebugLocWriter::DebugLocWriter(BinaryContext *BC) {
500   LocBuffer = std::make_unique<DebugBufferVector>();
501   LocStream = std::make_unique<raw_svector_ostream>(*LocBuffer);
502 }
503 
504 void DebugLocWriter::addList(uint64_t AttrOffset, uint32_t LocListIndex,
505                              DebugLocationsVector &&LocList) {
506   if (LocList.empty()) {
507     EmptyAttrLists.push_back(AttrOffset);
508     return;
509   }
510   // Since there is a separate DebugLocWriter for each thread,
511   // we don't need a lock to read the SectionOffset and update it.
512   const uint32_t EntryOffset = SectionOffset;
513 
514   for (const DebugLocationEntry &Entry : LocList) {
515     support::endian::write(*LocStream, static_cast<uint64_t>(Entry.LowPC),
516                            support::little);
517     support::endian::write(*LocStream, static_cast<uint64_t>(Entry.HighPC),
518                            support::little);
519     support::endian::write(*LocStream, static_cast<uint16_t>(Entry.Expr.size()),
520                            support::little);
521     *LocStream << StringRef(reinterpret_cast<const char *>(Entry.Expr.data()),
522                             Entry.Expr.size());
523     SectionOffset += 2 * 8 + 2 + Entry.Expr.size();
524   }
525   LocStream->write_zeros(16);
526   SectionOffset += 16;
527   LocListDebugInfoPatches.push_back({AttrOffset, EntryOffset});
528 }
529 
530 void DebugLoclistWriter::addList(uint64_t AttrOffset, uint32_t LocListIndex,
531                                  DebugLocationsVector &&LocList) {
532   Patches.push_back({AttrOffset, LocListIndex, std::move(LocList)});
533 }
534 
535 std::unique_ptr<DebugBufferVector> DebugLocWriter::getBuffer() {
536   return std::move(LocBuffer);
537 }
538 
539 // DWARF 4: 2.6.2
540 void DebugLocWriter::finalize(uint64_t SectionOffset,
541                               SimpleBinaryPatcher &DebugInfoPatcher) {
542   for (const auto LocListDebugInfoPatchType : LocListDebugInfoPatches) {
543     uint64_t Offset = SectionOffset + LocListDebugInfoPatchType.LocListOffset;
544     DebugInfoPatcher.addLE32Patch(LocListDebugInfoPatchType.DebugInfoAttrOffset,
545                                   Offset);
546   }
547 
548   for (uint64_t DebugInfoAttrOffset : EmptyAttrLists)
549     DebugInfoPatcher.addLE32Patch(DebugInfoAttrOffset,
550                                   DebugLocWriter::EmptyListOffset);
551 }
552 
553 static void writeEmptyListDwarf5(raw_svector_ostream &Stream) {
554   support::endian::write(Stream, static_cast<uint32_t>(4), support::little);
555   support::endian::write(Stream, static_cast<uint8_t>(dwarf::DW_LLE_start_end),
556                          support::little);
557 
558   const char Zeroes[16] = {0};
559   Stream << StringRef(Zeroes, 16);
560   encodeULEB128(0, Stream);
561   support::endian::write(
562       Stream, static_cast<uint8_t>(dwarf::DW_LLE_end_of_list), support::little);
563 }
564 
565 void DebugLoclistWriter::finalizeDWARF5(uint64_t SectionOffset,
566                                         SimpleBinaryPatcher &DebugInfoPatcher) {
567 
568   std::unique_ptr<DebugBufferVector> LocArrayBuffer =
569       std::make_unique<DebugBufferVector>();
570   std::unique_ptr<raw_svector_ostream> LocArrayStream =
571       std::make_unique<raw_svector_ostream>(*LocArrayBuffer);
572   std::unique_ptr<DebugBufferVector> LocBodyBuffer =
573       std::make_unique<DebugBufferVector>();
574   std::unique_ptr<raw_svector_ostream> LocBodyStream =
575       std::make_unique<raw_svector_ostream>(*LocBodyBuffer);
576 
577   const uint32_t SizeOfArraySection = Patches.size() * sizeof(uint32_t);
578   std::sort(Patches.begin(), Patches.end(),
579             [](const LocPatch &P1, const LocPatch &P2) -> bool {
580               return P1.Index < P2.Index;
581             });
582 
583   if (LocListsBaseAttrOffset != InvalidLocListsBaseAttrOffset)
584     DebugInfoPatcher.addLE32Patch(LocListsBaseAttrOffset,
585                                   SectionOffset +
586                                       getDWARF5RngListLocListHeaderSize());
587 
588   uint32_t Index{0};
589   for (LocPatch &Patch : Patches) {
590     const uint32_t EntryOffset = LocBodyBuffer->size();
591     if (Patch.LocList.empty()) {
592       if (Patch.Index == DebugLoclistWriter::InvalidIndex)
593         DebugInfoPatcher.addLE32Patch(Patch.AttrOffset, EntryOffset);
594 
595       writeEmptyListDwarf5(*LocBodyStream);
596       continue;
597     }
598 
599     assert(Patch.Index == DebugLoclistWriter::InvalidIndex ||
600            Patch.Index == Index++ && "Gap in LocList Index Array.");
601 
602     std::vector<uint64_t> OffsetsArray;
603     for (const DebugLocationEntry &Entry : Patch.LocList) {
604       support::endian::write(*LocBodyStream,
605                              static_cast<uint8_t>(dwarf::DW_LLE_startx_length),
606                              support::little);
607       const uint32_t Index = AddrWriter->getIndexFromAddress(Entry.LowPC, CU);
608       encodeULEB128(Index, *LocBodyStream);
609       encodeULEB128(Entry.HighPC - Entry.LowPC, *LocBodyStream);
610       encodeULEB128(Entry.Expr.size(), *LocBodyStream);
611       *LocBodyStream << StringRef(
612           reinterpret_cast<const char *>(Entry.Expr.data()), Entry.Expr.size());
613     }
614     support::endian::write(*LocBodyStream,
615                            static_cast<uint8_t>(dwarf::DW_LLE_end_of_list),
616                            support::little);
617 
618     // Write out IndexArray
619     support::endian::write(
620         *LocArrayStream,
621         static_cast<uint32_t>(SizeOfArraySection + EntryOffset),
622         support::little);
623     // Don't need to patch Index since we are re-using them.
624     if (Patch.Index == DebugLoclistWriter::InvalidIndex)
625       DebugInfoPatcher.addLE32Patch(Patch.AttrOffset, EntryOffset);
626     clearList(Patch.LocList);
627   }
628   if (!Patches.empty()) {
629     std::unique_ptr<DebugBufferVector> Header =
630         getDWARF5Header({static_cast<uint32_t>(SizeOfArraySection +
631                                                LocBodyBuffer.get()->size()),
632                          5, 8, 0, static_cast<uint32_t>(Patches.size())});
633     *LocStream << *Header;
634     *LocStream << *LocArrayBuffer;
635     *LocStream << *LocBodyBuffer;
636   }
637   clearList(Patches);
638 }
639 
640 void DebugLoclistWriter::finalizeDWARFLegacy(
641     uint64_t SectionOffset, SimpleBinaryPatcher &DebugInfoPatcher) {
642   for (LocPatch &Patch : Patches) {
643     if (Patch.LocList.empty()) {
644       DebugInfoPatcher.addLE32Patch(Patch.AttrOffset,
645                                     DebugLocWriter::EmptyListOffset);
646       continue;
647     }
648     const uint32_t EntryOffset = LocBuffer->size();
649     for (const DebugLocationEntry &Entry : Patch.LocList) {
650       support::endian::write(*LocStream,
651                              static_cast<uint8_t>(dwarf::DW_LLE_startx_length),
652                              support::little);
653       const uint32_t Index = AddrWriter->getIndexFromAddress(Entry.LowPC, CU);
654       encodeULEB128(Index, *LocStream);
655 
656       // TODO: Support DWARF5
657       support::endian::write(*LocStream,
658                              static_cast<uint32_t>(Entry.HighPC - Entry.LowPC),
659                              support::little);
660       support::endian::write(*LocStream,
661                              static_cast<uint16_t>(Entry.Expr.size()),
662                              support::little);
663       *LocStream << StringRef(reinterpret_cast<const char *>(Entry.Expr.data()),
664                               Entry.Expr.size());
665     }
666     support::endian::write(*LocStream,
667                            static_cast<uint8_t>(dwarf::DW_LLE_end_of_list),
668                            support::little);
669     DebugInfoPatcher.addLE32Patch(Patch.AttrOffset, EntryOffset);
670     clearList(Patch.LocList);
671   }
672   clearList(Patches);
673 }
674 
675 void DebugLoclistWriter::finalize(uint64_t SectionOffset,
676                                   SimpleBinaryPatcher &DebugInfoPatcher) {
677   if (DwarfVersion < 5)
678     finalizeDWARFLegacy(SectionOffset, DebugInfoPatcher);
679   else
680     finalizeDWARF5(SectionOffset, DebugInfoPatcher);
681 }
682 
683 DebugAddrWriter *DebugLoclistWriter::AddrWriter = nullptr;
684 
685 void DebugInfoBinaryPatcher::addUnitBaseOffsetLabel(uint64_t Offset) {
686   Offset -= DWPUnitOffset;
687   std::lock_guard<std::mutex> Lock(WriterMutex);
688   DebugPatches.emplace_back(new DWARFUnitOffsetBaseLabel(Offset));
689 }
690 
691 void DebugInfoBinaryPatcher::addDestinationReferenceLabel(uint64_t Offset) {
692   Offset -= DWPUnitOffset;
693   std::lock_guard<std::mutex> Lock(WriterMutex);
694   auto RetVal = DestinationLabels.insert(Offset);
695   if (!RetVal.second)
696     return;
697 
698   DebugPatches.emplace_back(new DestinationReferenceLabel(Offset));
699 }
700 
701 static std::string encodeLE(size_t ByteSize, uint64_t NewValue) {
702   std::string LE64(ByteSize, 0);
703   for (size_t I = 0; I < ByteSize; ++I) {
704     LE64[I] = NewValue & 0xff;
705     NewValue >>= 8;
706   }
707   return LE64;
708 }
709 
710 void DebugInfoBinaryPatcher::insertNewEntry(const DWARFDie &DIE,
711                                             uint32_t Value) {
712   std::string StrValue = encodeLE(4, Value);
713   insertNewEntry(DIE, std::move(StrValue));
714 }
715 
716 void DebugInfoBinaryPatcher::insertNewEntry(const DWARFDie &DIE,
717                                             std::string &&Value) {
718   const DWARFAbbreviationDeclaration *AbbrevDecl =
719       DIE.getAbbreviationDeclarationPtr();
720 
721   // In case this DIE has no attributes.
722   uint32_t Offset = DIE.getOffset() + 1;
723   size_t NumOfAttributes = AbbrevDecl->getNumAttributes();
724   if (NumOfAttributes) {
725     Optional<AttrInfo> Val =
726         findAttributeInfo(DIE, AbbrevDecl, NumOfAttributes - 1);
727     assert(Val && "Invalid Value.");
728 
729     Offset = Val->Offset + Val->Size - DWPUnitOffset;
730   }
731   std::lock_guard<std::mutex> Lock(WriterMutex);
732   DebugPatches.emplace_back(new NewDebugEntry(Offset, std::move(Value)));
733 }
734 
735 void DebugInfoBinaryPatcher::addReferenceToPatch(uint64_t Offset,
736                                                  uint32_t DestinationOffset,
737                                                  uint32_t OldValueSize,
738                                                  dwarf::Form Form) {
739   Offset -= DWPUnitOffset;
740   DestinationOffset -= DWPUnitOffset;
741   std::lock_guard<std::mutex> Lock(WriterMutex);
742   DebugPatches.emplace_back(
743       new DebugPatchReference(Offset, OldValueSize, DestinationOffset, Form));
744 }
745 
746 void DebugInfoBinaryPatcher::addUDataPatch(uint64_t Offset, uint64_t NewValue,
747                                            uint32_t OldValueSize) {
748   Offset -= DWPUnitOffset;
749   std::lock_guard<std::mutex> Lock(WriterMutex);
750   DebugPatches.emplace_back(
751       new DebugPatchVariableSize(Offset, OldValueSize, NewValue));
752 }
753 
754 void DebugInfoBinaryPatcher::addLE64Patch(uint64_t Offset, uint64_t NewValue) {
755   Offset -= DWPUnitOffset;
756   std::lock_guard<std::mutex> Lock(WriterMutex);
757   DebugPatches.emplace_back(new DebugPatch64(Offset, NewValue));
758 }
759 
760 void DebugInfoBinaryPatcher::addLE32Patch(uint64_t Offset, uint32_t NewValue,
761                                           uint32_t OldValueSize) {
762   Offset -= DWPUnitOffset;
763   std::lock_guard<std::mutex> Lock(WriterMutex);
764   if (OldValueSize == 4)
765     DebugPatches.emplace_back(new DebugPatch32(Offset, NewValue));
766   else if (OldValueSize == 8)
767     DebugPatches.emplace_back(new DebugPatch64to32(Offset, NewValue));
768   else
769     DebugPatches.emplace_back(
770         new DebugPatch32GenericSize(Offset, NewValue, OldValueSize));
771 }
772 
773 void SimpleBinaryPatcher::addBinaryPatch(uint64_t Offset,
774                                          std::string &&NewValue,
775                                          uint32_t OldValueSize) {
776   Patches.emplace_back(Offset, std::move(NewValue));
777 }
778 
779 void SimpleBinaryPatcher::addBytePatch(uint64_t Offset, uint8_t Value) {
780   auto Str = std::string(1, Value);
781   Patches.emplace_back(Offset, std::move(Str));
782 }
783 
784 void SimpleBinaryPatcher::addLEPatch(uint64_t Offset, uint64_t NewValue,
785                                      size_t ByteSize) {
786   Patches.emplace_back(Offset, encodeLE(ByteSize, NewValue));
787 }
788 
789 void SimpleBinaryPatcher::addUDataPatch(uint64_t Offset, uint64_t Value,
790                                         uint32_t OldValueSize) {
791   std::string Buff;
792   raw_string_ostream OS(Buff);
793   encodeULEB128(Value, OS, OldValueSize);
794 
795   Patches.emplace_back(Offset, std::move(Buff));
796 }
797 
798 void SimpleBinaryPatcher::addLE64Patch(uint64_t Offset, uint64_t NewValue) {
799   addLEPatch(Offset, NewValue, 8);
800 }
801 
802 void SimpleBinaryPatcher::addLE32Patch(uint64_t Offset, uint32_t NewValue,
803                                        uint32_t OldValueSize) {
804   addLEPatch(Offset, NewValue, 4);
805 }
806 
807 std::string SimpleBinaryPatcher::patchBinary(StringRef BinaryContents) {
808   std::string BinaryContentsStr = std::string(BinaryContents);
809   for (const auto &Patch : Patches) {
810     uint32_t Offset = Patch.first;
811     const std::string &ByteSequence = Patch.second;
812     assert(Offset + ByteSequence.size() <= BinaryContents.size() &&
813            "Applied patch runs over binary size.");
814     for (uint64_t I = 0, Size = ByteSequence.size(); I < Size; ++I) {
815       BinaryContentsStr[Offset + I] = ByteSequence[I];
816     }
817   }
818   return BinaryContentsStr;
819 }
820 
821 CUOffsetMap DebugInfoBinaryPatcher::computeNewOffsets(DWARFContext &DWCtx,
822                                                       bool IsDWOContext) {
823   CUOffsetMap CUMap;
824   std::sort(DebugPatches.begin(), DebugPatches.end(),
825             [](const UniquePatchPtrType &V1, const UniquePatchPtrType &V2) {
826               if (V1.get()->Offset == V2.get()->Offset) {
827                 if (V1->Kind == DebugPatchKind::NewDebugEntry &&
828                     V2->Kind == DebugPatchKind::NewDebugEntry)
829                   return reinterpret_cast<const NewDebugEntry *>(V1.get())
830                              ->CurrentOrder <
831                          reinterpret_cast<const NewDebugEntry *>(V2.get())
832                              ->CurrentOrder;
833 
834                 // This is a case where we are modifying first entry of next
835                 // DIE, and adding a new one.
836                 return V1->Kind == DebugPatchKind::NewDebugEntry;
837               }
838               return V1.get()->Offset < V2.get()->Offset;
839             });
840 
841   DWARFUnitVector::compile_unit_range CompileUnits =
842       IsDWOContext ? DWCtx.dwo_compile_units() : DWCtx.compile_units();
843 
844   for (const std::unique_ptr<DWARFUnit> &CU : CompileUnits)
845     CUMap[CU->getOffset()] = {static_cast<uint32_t>(CU->getOffset()),
846                               static_cast<uint32_t>(CU->getLength())};
847 
848   // Calculating changes in .debug_info size from Patches to build a map of old
849   // to updated reference destination offsets.
850   uint32_t PreviousOffset = 0;
851   int32_t PreviousChangeInSize = 0;
852   for (UniquePatchPtrType &PatchBase : DebugPatches) {
853     Patch *P = PatchBase.get();
854     switch (P->Kind) {
855     default:
856       continue;
857     case DebugPatchKind::PatchValue64to32: {
858       PreviousChangeInSize -= 4;
859       break;
860     }
861     case DebugPatchKind::PatchValue32GenericSize: {
862       DebugPatch32GenericSize *DPVS =
863           reinterpret_cast<DebugPatch32GenericSize *>(P);
864       PreviousChangeInSize += 4 - DPVS->OldValueSize;
865       break;
866     }
867     case DebugPatchKind::PatchValueVariable: {
868       DebugPatchVariableSize *DPV =
869           reinterpret_cast<DebugPatchVariableSize *>(P);
870       std::string Temp;
871       raw_string_ostream OS(Temp);
872       encodeULEB128(DPV->Value, OS);
873       PreviousChangeInSize += Temp.size() - DPV->OldValueSize;
874       break;
875     }
876     case DebugPatchKind::DestinationReferenceLabel: {
877       DestinationReferenceLabel *DRL =
878           reinterpret_cast<DestinationReferenceLabel *>(P);
879       OldToNewOffset[DRL->Offset] =
880           DRL->Offset + ChangeInSize + PreviousChangeInSize;
881       break;
882     }
883     case DebugPatchKind::ReferencePatchValue: {
884       // This doesn't look to be a common case, so will always encode as 4 bytes
885       // to reduce algorithmic complexity.
886       DebugPatchReference *RDP = reinterpret_cast<DebugPatchReference *>(P);
887       if (RDP->PatchInfo.IndirectRelative) {
888         PreviousChangeInSize += 4 - RDP->PatchInfo.OldValueSize;
889         assert(RDP->PatchInfo.OldValueSize <= 4 &&
890                "Variable encoding reference greater than 4 bytes.");
891       }
892       break;
893     }
894     case DebugPatchKind::DWARFUnitOffsetBaseLabel: {
895       DWARFUnitOffsetBaseLabel *BaseLabel =
896           reinterpret_cast<DWARFUnitOffsetBaseLabel *>(P);
897       uint32_t CUOffset = BaseLabel->Offset;
898       ChangeInSize += PreviousChangeInSize;
899       uint32_t CUOffsetUpdate = CUOffset + ChangeInSize;
900       CUMap[CUOffset].Offset = CUOffsetUpdate;
901       CUMap[PreviousOffset].Length += PreviousChangeInSize;
902       PreviousChangeInSize = 0;
903       PreviousOffset = CUOffset;
904       break;
905     }
906     case DebugPatchKind::NewDebugEntry: {
907       NewDebugEntry *NDE = reinterpret_cast<NewDebugEntry *>(P);
908       PreviousChangeInSize += NDE->Value.size();
909       break;
910     }
911     }
912   }
913   CUMap[PreviousOffset].Length += PreviousChangeInSize;
914   return CUMap;
915 }
916 uint32_t DebugInfoBinaryPatcher::NewDebugEntry::OrderCounter = 0;
917 
918 std::string DebugInfoBinaryPatcher::patchBinary(StringRef BinaryContents) {
919   std::string NewBinaryContents;
920   NewBinaryContents.reserve(BinaryContents.size() + ChangeInSize);
921   uint32_t StartOffset = 0;
922   uint32_t DwarfUnitBaseOffset = 0;
923   uint32_t OldValueSize = 0;
924   uint32_t Offset = 0;
925   std::string ByteSequence;
926   std::vector<std::pair<uint32_t, uint32_t>> LengthPatches;
927   // Wasting one entry to avoid checks for first.
928   LengthPatches.push_back({0, 0});
929 
930   // Applying all the patches replacing current entry.
931   // This might change the size of .debug_info section.
932   for (const UniquePatchPtrType &PatchBase : DebugPatches) {
933     Patch *P = PatchBase.get();
934     switch (P->Kind) {
935     default:
936       continue;
937     case DebugPatchKind::ReferencePatchValue: {
938       DebugPatchReference *RDP = reinterpret_cast<DebugPatchReference *>(P);
939       uint32_t DestinationOffset = RDP->DestinationOffset;
940       assert(OldToNewOffset.count(DestinationOffset) &&
941              "Destination Offset for reference not updated.");
942       uint32_t UpdatedOffset = OldToNewOffset[DestinationOffset];
943       Offset = RDP->Offset;
944       OldValueSize = RDP->PatchInfo.OldValueSize;
945       if (RDP->PatchInfo.DirectRelative) {
946         UpdatedOffset -= DwarfUnitBaseOffset;
947         ByteSequence = encodeLE(OldValueSize, UpdatedOffset);
948         // In theory reference for DW_FORM_ref{1,2,4,8} can be right on the edge
949         // and overflow if later debug information grows.
950         if (ByteSequence.size() > OldValueSize)
951           errs() << "BOLT-ERROR: Relative reference of size "
952                  << Twine::utohexstr(OldValueSize)
953                  << " overflows with the new encoding.\n";
954       } else if (RDP->PatchInfo.DirectAbsolute) {
955         ByteSequence = encodeLE(OldValueSize, UpdatedOffset);
956       } else if (RDP->PatchInfo.IndirectRelative) {
957         UpdatedOffset -= DwarfUnitBaseOffset;
958         ByteSequence.clear();
959         raw_string_ostream OS(ByteSequence);
960         encodeULEB128(UpdatedOffset, OS, 4);
961       } else {
962         llvm_unreachable("Invalid Reference form.");
963       }
964       break;
965     }
966     case DebugPatchKind::PatchValue32: {
967       DebugPatch32 *P32 = reinterpret_cast<DebugPatch32 *>(P);
968       Offset = P32->Offset;
969       OldValueSize = 4;
970       ByteSequence = encodeLE(4, P32->Value);
971       break;
972     }
973     case DebugPatchKind::PatchValue64to32: {
974       DebugPatch64to32 *P64to32 = reinterpret_cast<DebugPatch64to32 *>(P);
975       Offset = P64to32->Offset;
976       OldValueSize = 8;
977       ByteSequence = encodeLE(4, P64to32->Value);
978       break;
979     }
980     case DebugPatchKind::PatchValue32GenericSize: {
981       DebugPatch32GenericSize *DPVS =
982           reinterpret_cast<DebugPatch32GenericSize *>(P);
983       Offset = DPVS->Offset;
984       OldValueSize = DPVS->OldValueSize;
985       ByteSequence = encodeLE(4, DPVS->Value);
986       break;
987     }
988     case DebugPatchKind::PatchValueVariable: {
989       DebugPatchVariableSize *PV =
990           reinterpret_cast<DebugPatchVariableSize *>(P);
991       Offset = PV->Offset;
992       OldValueSize = PV->OldValueSize;
993       ByteSequence.clear();
994       raw_string_ostream OS(ByteSequence);
995       encodeULEB128(PV->Value, OS);
996       break;
997     }
998     case DebugPatchKind::PatchValue64: {
999       DebugPatch64 *P64 = reinterpret_cast<DebugPatch64 *>(P);
1000       Offset = P64->Offset;
1001       OldValueSize = 8;
1002       ByteSequence = encodeLE(8, P64->Value);
1003       break;
1004     }
1005     case DebugPatchKind::DWARFUnitOffsetBaseLabel: {
1006       DWARFUnitOffsetBaseLabel *BaseLabel =
1007           reinterpret_cast<DWARFUnitOffsetBaseLabel *>(P);
1008       Offset = BaseLabel->Offset;
1009       OldValueSize = 0;
1010       ByteSequence.clear();
1011       auto &Patch = LengthPatches.back();
1012       // Length to copy between last patch entry and next compile unit.
1013       uint32_t RemainingLength = Offset - StartOffset;
1014       uint32_t NewCUOffset = NewBinaryContents.size() + RemainingLength;
1015       DwarfUnitBaseOffset = NewCUOffset;
1016       // Length of previous CU = This CU Offset - sizeof(length) - last CU
1017       // Offset.
1018       Patch.second = NewCUOffset - 4 - Patch.first;
1019       LengthPatches.push_back({NewCUOffset, 0});
1020       break;
1021     }
1022     case DebugPatchKind::NewDebugEntry: {
1023       NewDebugEntry *NDE = reinterpret_cast<NewDebugEntry *>(P);
1024       Offset = NDE->Offset;
1025       OldValueSize = 0;
1026       ByteSequence = NDE->Value;
1027       break;
1028     }
1029     }
1030 
1031     assert((P->Kind == DebugPatchKind::NewDebugEntry ||
1032             Offset + ByteSequence.size() <= BinaryContents.size()) &&
1033            "Applied patch runs over binary size.");
1034     uint32_t Length = Offset - StartOffset;
1035     NewBinaryContents.append(BinaryContents.substr(StartOffset, Length).data(),
1036                              Length);
1037     NewBinaryContents.append(ByteSequence.data(), ByteSequence.size());
1038     StartOffset = Offset + OldValueSize;
1039   }
1040   uint32_t Length = BinaryContents.size() - StartOffset;
1041   NewBinaryContents.append(BinaryContents.substr(StartOffset, Length).data(),
1042                            Length);
1043   DebugPatches.clear();
1044 
1045   // Patching lengths of CUs
1046   auto &Patch = LengthPatches.back();
1047   Patch.second = NewBinaryContents.size() - 4 - Patch.first;
1048   for (uint32_t J = 1, Size = LengthPatches.size(); J < Size; ++J) {
1049     const auto &Patch = LengthPatches[J];
1050     ByteSequence = encodeLE(4, Patch.second);
1051     Offset = Patch.first;
1052     for (uint64_t I = 0, Size = ByteSequence.size(); I < Size; ++I)
1053       NewBinaryContents[Offset + I] = ByteSequence[I];
1054   }
1055 
1056   return NewBinaryContents;
1057 }
1058 
1059 void DebugStrOffsetsWriter::initialize(
1060     const DWARFSection &StrOffsetsSection,
1061     const Optional<StrOffsetsContributionDescriptor> Contr) {
1062   if (!Contr)
1063     return;
1064 
1065   const uint8_t DwarfOffsetByteSize = Contr->getDwarfOffsetByteSize();
1066   assert(DwarfOffsetByteSize == 4 &&
1067          "Dwarf String Offsets Byte Size is not supported.");
1068   uint32_t Index = 0;
1069   for (uint64_t Offset = 0; Offset < Contr->Size; Offset += DwarfOffsetByteSize)
1070     IndexToAddressMap[Index++] = *reinterpret_cast<const uint32_t *>(
1071         StrOffsetsSection.Data.data() + Contr->Base + Offset);
1072 }
1073 
1074 void DebugStrOffsetsWriter::updateAddressMap(uint32_t Index, uint32_t Address) {
1075   assert(IndexToAddressMap.count(Index) > 0 && "Index is not found.");
1076   IndexToAddressMap[Index] = Address;
1077 }
1078 
1079 void DebugStrOffsetsWriter::finalizeSection() {
1080   if (IndexToAddressMap.empty())
1081     return;
1082   // Writing out the header for each section.
1083   support::endian::write(*StrOffsetsStream, CurrentSectionSize + 4,
1084                          support::little);
1085   support::endian::write(*StrOffsetsStream, static_cast<uint16_t>(5),
1086                          support::little);
1087   support::endian::write(*StrOffsetsStream, static_cast<uint16_t>(0),
1088                          support::little);
1089   for (const auto &Entry : IndexToAddressMap)
1090     support::endian::write(*StrOffsetsStream, Entry.second, support::little);
1091   IndexToAddressMap.clear();
1092 }
1093 
1094 void DebugStrWriter::create() {
1095   StrBuffer = std::make_unique<DebugStrBufferVector>();
1096   StrStream = std::make_unique<raw_svector_ostream>(*StrBuffer);
1097 }
1098 
1099 void DebugStrWriter::initialize() {
1100   auto StrSection = BC.DwCtx->getDWARFObj().getStrSection();
1101   (*StrStream) << StrSection;
1102 }
1103 
1104 uint32_t DebugStrWriter::addString(StringRef Str) {
1105   std::lock_guard<std::mutex> Lock(WriterMutex);
1106   if (StrBuffer->empty())
1107     initialize();
1108   auto Offset = StrBuffer->size();
1109   (*StrStream) << Str;
1110   StrStream->write_zeros(1);
1111   return Offset;
1112 }
1113 
1114 void DebugAbbrevWriter::addUnitAbbreviations(DWARFUnit &Unit) {
1115   const DWARFAbbreviationDeclarationSet *Abbrevs = Unit.getAbbreviations();
1116   if (!Abbrevs)
1117     return;
1118 
1119   const PatchesTy &UnitPatches = Patches[&Unit];
1120   const AbbrevEntryTy &AbbrevEntries = NewAbbrevEntries[&Unit];
1121 
1122   // We are duplicating abbrev sections, to handle the case where for one CU we
1123   // modify it, but for another we don't.
1124   auto UnitDataPtr = std::make_unique<AbbrevData>();
1125   AbbrevData &UnitData = *UnitDataPtr.get();
1126   UnitData.Buffer = std::make_unique<DebugBufferVector>();
1127   UnitData.Stream = std::make_unique<raw_svector_ostream>(*UnitData.Buffer);
1128 
1129   raw_svector_ostream &OS = *UnitData.Stream.get();
1130 
1131   // Returns true if AbbrevData is re-used, false otherwise.
1132   auto hashAndAddAbbrev = [&](StringRef AbbrevData) -> bool {
1133     llvm::SHA1 Hasher;
1134     Hasher.update(AbbrevData);
1135     std::array<uint8_t, 20> Hash = Hasher.final();
1136     StringRef Key((const char *)Hash.data(), Hash.size());
1137     auto Iter = AbbrevDataCache.find(Key);
1138     if (Iter != AbbrevDataCache.end()) {
1139       UnitsAbbrevData[&Unit] = Iter->second.get();
1140       return true;
1141     }
1142     AbbrevDataCache[Key] = std::move(UnitDataPtr);
1143     UnitsAbbrevData[&Unit] = &UnitData;
1144     return false;
1145   };
1146   // Take a fast path if there are no patches to apply. Simply copy the original
1147   // contents.
1148   if (UnitPatches.empty() && AbbrevEntries.empty()) {
1149     StringRef AbbrevSectionContents =
1150         Unit.isDWOUnit() ? Unit.getContext().getDWARFObj().getAbbrevDWOSection()
1151                          : Unit.getContext().getDWARFObj().getAbbrevSection();
1152     StringRef AbbrevContents;
1153 
1154     const DWARFUnitIndex &CUIndex = Unit.getContext().getCUIndex();
1155     if (!CUIndex.getRows().empty()) {
1156       // Handle DWP section contribution.
1157       const DWARFUnitIndex::Entry *DWOEntry =
1158           CUIndex.getFromHash(*Unit.getDWOId());
1159       if (!DWOEntry)
1160         return;
1161 
1162       const DWARFUnitIndex::Entry::SectionContribution *DWOContrubution =
1163           DWOEntry->getContribution(DWARFSectionKind::DW_SECT_ABBREV);
1164       AbbrevContents = AbbrevSectionContents.substr(DWOContrubution->Offset,
1165                                                     DWOContrubution->Length);
1166     } else if (!Unit.isDWOUnit()) {
1167       const uint64_t StartOffset = Unit.getAbbreviationsOffset();
1168 
1169       // We know where the unit's abbreviation set starts, but not where it ends
1170       // as such data is not readily available. Hence, we have to build a sorted
1171       // list of start addresses and find the next starting address to determine
1172       // the set boundaries.
1173       //
1174       // FIXME: if we had a full access to DWARFDebugAbbrev::AbbrDeclSets
1175       // we wouldn't have to build our own sorted list for the quick lookup.
1176       if (AbbrevSetOffsets.empty()) {
1177         for_each(
1178             *Unit.getContext().getDebugAbbrev(),
1179             [&](const std::pair<uint64_t, DWARFAbbreviationDeclarationSet> &P) {
1180               AbbrevSetOffsets.push_back(P.first);
1181             });
1182         sort(AbbrevSetOffsets);
1183       }
1184       auto It = upper_bound(AbbrevSetOffsets, StartOffset);
1185       const uint64_t EndOffset =
1186           It == AbbrevSetOffsets.end() ? AbbrevSectionContents.size() : *It;
1187       AbbrevContents = AbbrevSectionContents.slice(StartOffset, EndOffset);
1188     } else {
1189       // For DWO unit outside of DWP, we expect the entire section to hold
1190       // abbreviations for this unit only.
1191       AbbrevContents = AbbrevSectionContents;
1192     }
1193 
1194     if (!hashAndAddAbbrev(AbbrevContents)) {
1195       OS.reserveExtraSpace(AbbrevContents.size());
1196       OS << AbbrevContents;
1197     }
1198     return;
1199   }
1200 
1201   for (auto I = Abbrevs->begin(), E = Abbrevs->end(); I != E; ++I) {
1202     const DWARFAbbreviationDeclaration &Abbrev = *I;
1203     auto Patch = UnitPatches.find(&Abbrev);
1204 
1205     encodeULEB128(Abbrev.getCode(), OS);
1206     encodeULEB128(Abbrev.getTag(), OS);
1207     encodeULEB128(Abbrev.hasChildren(), OS);
1208     for (const DWARFAbbreviationDeclaration::AttributeSpec &AttrSpec :
1209          Abbrev.attributes()) {
1210       if (Patch != UnitPatches.end()) {
1211         bool Patched = false;
1212         // Patches added later take a precedence over earlier ones.
1213         for (auto I = Patch->second.rbegin(), E = Patch->second.rend(); I != E;
1214              ++I) {
1215           if (I->OldAttr != AttrSpec.Attr)
1216             continue;
1217 
1218           encodeULEB128(I->NewAttr, OS);
1219           encodeULEB128(I->NewAttrForm, OS);
1220           Patched = true;
1221           break;
1222         }
1223         if (Patched)
1224           continue;
1225       }
1226 
1227       encodeULEB128(AttrSpec.Attr, OS);
1228       encodeULEB128(AttrSpec.Form, OS);
1229       if (AttrSpec.isImplicitConst())
1230         encodeSLEB128(AttrSpec.getImplicitConstValue(), OS);
1231     }
1232     const auto Entries = AbbrevEntries.find(&Abbrev);
1233     // Adding new Abbrevs for inserted entries.
1234     if (Entries != AbbrevEntries.end()) {
1235       for (const AbbrevEntry &Entry : Entries->second) {
1236         encodeULEB128(Entry.Attr, OS);
1237         encodeULEB128(Entry.Form, OS);
1238       }
1239     }
1240     encodeULEB128(0, OS);
1241     encodeULEB128(0, OS);
1242   }
1243   encodeULEB128(0, OS);
1244 
1245   hashAndAddAbbrev(OS.str());
1246 }
1247 
1248 std::unique_ptr<DebugBufferVector> DebugAbbrevWriter::finalize() {
1249   // Used to create determinism for writing out abbrevs.
1250   std::vector<AbbrevData *> Abbrevs;
1251   if (DWOId) {
1252     // We expect abbrev_offset to always be zero for DWO units as there
1253     // should be one CU per DWO, and TUs should share the same abbreviation
1254     // set with the CU.
1255     // For DWP AbbreviationsOffset is an Abbrev contribution in the DWP file, so
1256     // can be none zero. Thus we are skipping the check for DWP.
1257     bool IsDWP = !Context.getCUIndex().getRows().empty();
1258     if (!IsDWP) {
1259       for (const std::unique_ptr<DWARFUnit> &Unit : Context.dwo_units()) {
1260         if (Unit->getAbbreviationsOffset() != 0) {
1261           errs() << "BOLT-ERROR: detected DWO unit with non-zero abbr_offset. "
1262                     "Unable to update debug info.\n";
1263           exit(1);
1264         }
1265       }
1266     }
1267 
1268     DWARFUnit *Unit = Context.getDWOCompileUnitForHash(*DWOId);
1269     // Issue abbreviations for the DWO CU only.
1270     addUnitAbbreviations(*Unit);
1271     AbbrevData *Abbrev = UnitsAbbrevData[Unit];
1272     Abbrevs.push_back(Abbrev);
1273   } else {
1274     Abbrevs.reserve(Context.getNumCompileUnits() + Context.getNumTypeUnits());
1275     std::unordered_set<AbbrevData *> ProcessedAbbrevs;
1276     // Add abbreviations from compile and type non-DWO units.
1277     for (const std::unique_ptr<DWARFUnit> &Unit : Context.normal_units()) {
1278       addUnitAbbreviations(*Unit);
1279       AbbrevData *Abbrev = UnitsAbbrevData[Unit.get()];
1280       if (!ProcessedAbbrevs.insert(Abbrev).second)
1281         continue;
1282       Abbrevs.push_back(Abbrev);
1283     }
1284   }
1285 
1286   DebugBufferVector ReturnBuffer;
1287   // Pre-calculate the total size of abbrev section.
1288   uint64_t Size = 0;
1289   for (const AbbrevData *UnitData : Abbrevs)
1290     Size += UnitData->Buffer->size();
1291 
1292   ReturnBuffer.reserve(Size);
1293 
1294   uint64_t Pos = 0;
1295   for (AbbrevData *UnitData : Abbrevs) {
1296     ReturnBuffer.append(*UnitData->Buffer);
1297     UnitData->Offset = Pos;
1298     Pos += UnitData->Buffer->size();
1299 
1300     UnitData->Buffer.reset();
1301     UnitData->Stream.reset();
1302   }
1303 
1304   return std::make_unique<DebugBufferVector>(ReturnBuffer);
1305 }
1306 
1307 static void emitDwarfSetLineAddrAbs(MCStreamer &OS,
1308                                     MCDwarfLineTableParams Params,
1309                                     int64_t LineDelta, uint64_t Address,
1310                                     int PointerSize) {
1311   // emit the sequence to set the address
1312   OS.emitIntValue(dwarf::DW_LNS_extended_op, 1);
1313   OS.emitULEB128IntValue(PointerSize + 1);
1314   OS.emitIntValue(dwarf::DW_LNE_set_address, 1);
1315   OS.emitIntValue(Address, PointerSize);
1316 
1317   // emit the sequence for the LineDelta (from 1) and a zero address delta.
1318   MCDwarfLineAddr::Emit(&OS, Params, LineDelta, 0);
1319 }
1320 
1321 static inline void emitBinaryDwarfLineTable(
1322     MCStreamer *MCOS, MCDwarfLineTableParams Params,
1323     const DWARFDebugLine::LineTable *Table,
1324     const std::vector<DwarfLineTable::RowSequence> &InputSequences) {
1325   if (InputSequences.empty())
1326     return;
1327 
1328   constexpr uint64_t InvalidAddress = UINT64_MAX;
1329   unsigned FileNum = 1;
1330   unsigned LastLine = 1;
1331   unsigned Column = 0;
1332   unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
1333   unsigned Isa = 0;
1334   unsigned Discriminator = 0;
1335   uint64_t LastAddress = InvalidAddress;
1336   uint64_t PrevEndOfSequence = InvalidAddress;
1337   const MCAsmInfo *AsmInfo = MCOS->getContext().getAsmInfo();
1338 
1339   auto emitEndOfSequence = [&](uint64_t Address) {
1340     MCDwarfLineAddr::Emit(MCOS, Params, INT64_MAX, Address - LastAddress);
1341     FileNum = 1;
1342     LastLine = 1;
1343     Column = 0;
1344     Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
1345     Isa = 0;
1346     Discriminator = 0;
1347     LastAddress = InvalidAddress;
1348   };
1349 
1350   for (const DwarfLineTable::RowSequence &Sequence : InputSequences) {
1351     const uint64_t SequenceStart =
1352         Table->Rows[Sequence.FirstIndex].Address.Address;
1353 
1354     // Check if we need to mark the end of the sequence.
1355     if (PrevEndOfSequence != InvalidAddress && LastAddress != InvalidAddress &&
1356         PrevEndOfSequence != SequenceStart) {
1357       emitEndOfSequence(PrevEndOfSequence);
1358     }
1359 
1360     for (uint32_t RowIndex = Sequence.FirstIndex;
1361          RowIndex <= Sequence.LastIndex; ++RowIndex) {
1362       const DWARFDebugLine::Row &Row = Table->Rows[RowIndex];
1363       int64_t LineDelta = static_cast<int64_t>(Row.Line) - LastLine;
1364       const uint64_t Address = Row.Address.Address;
1365 
1366       if (FileNum != Row.File) {
1367         FileNum = Row.File;
1368         MCOS->emitInt8(dwarf::DW_LNS_set_file);
1369         MCOS->emitULEB128IntValue(FileNum);
1370       }
1371       if (Column != Row.Column) {
1372         Column = Row.Column;
1373         MCOS->emitInt8(dwarf::DW_LNS_set_column);
1374         MCOS->emitULEB128IntValue(Column);
1375       }
1376       if (Discriminator != Row.Discriminator &&
1377           MCOS->getContext().getDwarfVersion() >= 4) {
1378         Discriminator = Row.Discriminator;
1379         unsigned Size = getULEB128Size(Discriminator);
1380         MCOS->emitInt8(dwarf::DW_LNS_extended_op);
1381         MCOS->emitULEB128IntValue(Size + 1);
1382         MCOS->emitInt8(dwarf::DW_LNE_set_discriminator);
1383         MCOS->emitULEB128IntValue(Discriminator);
1384       }
1385       if (Isa != Row.Isa) {
1386         Isa = Row.Isa;
1387         MCOS->emitInt8(dwarf::DW_LNS_set_isa);
1388         MCOS->emitULEB128IntValue(Isa);
1389       }
1390       if (Row.IsStmt != Flags) {
1391         Flags = Row.IsStmt;
1392         MCOS->emitInt8(dwarf::DW_LNS_negate_stmt);
1393       }
1394       if (Row.BasicBlock)
1395         MCOS->emitInt8(dwarf::DW_LNS_set_basic_block);
1396       if (Row.PrologueEnd)
1397         MCOS->emitInt8(dwarf::DW_LNS_set_prologue_end);
1398       if (Row.EpilogueBegin)
1399         MCOS->emitInt8(dwarf::DW_LNS_set_epilogue_begin);
1400 
1401       // The end of the sequence is not normal in the middle of the input
1402       // sequence, but could happen, e.g. for assembly code.
1403       if (Row.EndSequence) {
1404         emitEndOfSequence(Address);
1405       } else {
1406         if (LastAddress == InvalidAddress)
1407           emitDwarfSetLineAddrAbs(*MCOS, Params, LineDelta, Address,
1408                                   AsmInfo->getCodePointerSize());
1409         else
1410           MCDwarfLineAddr::Emit(MCOS, Params, LineDelta, Address - LastAddress);
1411 
1412         LastAddress = Address;
1413         LastLine = Row.Line;
1414       }
1415 
1416       Discriminator = 0;
1417     }
1418     PrevEndOfSequence = Sequence.EndAddress;
1419   }
1420 
1421   // Finish with the end of the sequence.
1422   if (LastAddress != InvalidAddress)
1423     emitEndOfSequence(PrevEndOfSequence);
1424 }
1425 
1426 // This function is similar to the one from MCDwarfLineTable, except it handles
1427 // end-of-sequence entries differently by utilizing line entries with
1428 // DWARF2_FLAG_END_SEQUENCE flag.
1429 static inline void emitDwarfLineTable(
1430     MCStreamer *MCOS, MCSection *Section,
1431     const MCLineSection::MCDwarfLineEntryCollection &LineEntries) {
1432   unsigned FileNum = 1;
1433   unsigned LastLine = 1;
1434   unsigned Column = 0;
1435   unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
1436   unsigned Isa = 0;
1437   unsigned Discriminator = 0;
1438   MCSymbol *LastLabel = nullptr;
1439   const MCAsmInfo *AsmInfo = MCOS->getContext().getAsmInfo();
1440 
1441   // Loop through each MCDwarfLineEntry and encode the dwarf line number table.
1442   for (const MCDwarfLineEntry &LineEntry : LineEntries) {
1443     if (LineEntry.getFlags() & DWARF2_FLAG_END_SEQUENCE) {
1444       MCOS->emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, LineEntry.getLabel(),
1445                                      AsmInfo->getCodePointerSize());
1446       FileNum = 1;
1447       LastLine = 1;
1448       Column = 0;
1449       Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
1450       Isa = 0;
1451       Discriminator = 0;
1452       LastLabel = nullptr;
1453       continue;
1454     }
1455 
1456     int64_t LineDelta = static_cast<int64_t>(LineEntry.getLine()) - LastLine;
1457 
1458     if (FileNum != LineEntry.getFileNum()) {
1459       FileNum = LineEntry.getFileNum();
1460       MCOS->emitInt8(dwarf::DW_LNS_set_file);
1461       MCOS->emitULEB128IntValue(FileNum);
1462     }
1463     if (Column != LineEntry.getColumn()) {
1464       Column = LineEntry.getColumn();
1465       MCOS->emitInt8(dwarf::DW_LNS_set_column);
1466       MCOS->emitULEB128IntValue(Column);
1467     }
1468     if (Discriminator != LineEntry.getDiscriminator() &&
1469         MCOS->getContext().getDwarfVersion() >= 2) {
1470       Discriminator = LineEntry.getDiscriminator();
1471       unsigned Size = getULEB128Size(Discriminator);
1472       MCOS->emitInt8(dwarf::DW_LNS_extended_op);
1473       MCOS->emitULEB128IntValue(Size + 1);
1474       MCOS->emitInt8(dwarf::DW_LNE_set_discriminator);
1475       MCOS->emitULEB128IntValue(Discriminator);
1476     }
1477     if (Isa != LineEntry.getIsa()) {
1478       Isa = LineEntry.getIsa();
1479       MCOS->emitInt8(dwarf::DW_LNS_set_isa);
1480       MCOS->emitULEB128IntValue(Isa);
1481     }
1482     if ((LineEntry.getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
1483       Flags = LineEntry.getFlags();
1484       MCOS->emitInt8(dwarf::DW_LNS_negate_stmt);
1485     }
1486     if (LineEntry.getFlags() & DWARF2_FLAG_BASIC_BLOCK)
1487       MCOS->emitInt8(dwarf::DW_LNS_set_basic_block);
1488     if (LineEntry.getFlags() & DWARF2_FLAG_PROLOGUE_END)
1489       MCOS->emitInt8(dwarf::DW_LNS_set_prologue_end);
1490     if (LineEntry.getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
1491       MCOS->emitInt8(dwarf::DW_LNS_set_epilogue_begin);
1492 
1493     MCSymbol *Label = LineEntry.getLabel();
1494 
1495     // At this point we want to emit/create the sequence to encode the delta
1496     // in line numbers and the increment of the address from the previous
1497     // Label and the current Label.
1498     MCOS->emitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
1499                                    AsmInfo->getCodePointerSize());
1500     Discriminator = 0;
1501     LastLine = LineEntry.getLine();
1502     LastLabel = Label;
1503   }
1504 
1505   assert(LastLabel == nullptr && "end of sequence expected");
1506 }
1507 
1508 void DwarfLineTable::emitCU(MCStreamer *MCOS, MCDwarfLineTableParams Params,
1509                             Optional<MCDwarfLineStr> &LineStr,
1510                             BinaryContext &BC) const {
1511   if (!RawData.empty()) {
1512     assert(MCLineSections.getMCLineEntries().empty() &&
1513            InputSequences.empty() &&
1514            "cannot combine raw data with new line entries");
1515     MCOS->emitLabel(getLabel());
1516     MCOS->emitBytes(RawData);
1517 
1518     // Emit fake relocation for RuntimeDyld to always allocate the section.
1519     //
1520     // FIXME: remove this once RuntimeDyld stops skipping allocatable sections
1521     //        without relocations.
1522     MCOS->emitRelocDirective(
1523         *MCConstantExpr::create(0, *BC.Ctx), "BFD_RELOC_NONE",
1524         MCSymbolRefExpr::create(getLabel(), *BC.Ctx), SMLoc(), *BC.STI);
1525 
1526     return;
1527   }
1528 
1529   MCSymbol *LineEndSym = Header.Emit(MCOS, Params, LineStr).second;
1530 
1531   // Put out the line tables.
1532   for (const auto &LineSec : MCLineSections.getMCLineEntries())
1533     emitDwarfLineTable(MCOS, LineSec.first, LineSec.second);
1534 
1535   // Emit line tables for the original code.
1536   emitBinaryDwarfLineTable(MCOS, Params, InputTable, InputSequences);
1537 
1538   // This is the end of the section, so set the value of the symbol at the end
1539   // of this section (that was used in a previous expression).
1540   MCOS->emitLabel(LineEndSym);
1541 }
1542 
1543 // Helper function to parse .debug_line_str, and populate one we are using.
1544 // For functions that we do not modify we output them as raw data.
1545 // Re-constructing .debug_line_str so that offsets are correct for those
1546 // debut line tables.
1547 // Bonus is that when we output a final binary we can re-use .debug_line_str
1548 // section. So we don't have to do the SHF_ALLOC trick we did with
1549 // .debug_line.
1550 static void parseAndPopulateDebugLineStr(BinarySection &LineStrSection,
1551                                          MCDwarfLineStr &LineStr,
1552                                          BinaryContext &BC,
1553                                          MCStreamer &Streamer) {
1554   DataExtractor StrData(LineStrSection.getContents(),
1555                         BC.DwCtx->isLittleEndian(), 0);
1556   uint64_t Offset = 0;
1557   while (StrData.isValidOffset(Offset)) {
1558     Error Err = Error::success();
1559     const char *CStr = StrData.getCStr(&Offset, &Err);
1560     if (Err) {
1561       errs() << "BOLT-ERROR: could not extract string from .debug_line_str";
1562       continue;
1563     }
1564     LineStr.emitRef(&Streamer, CStr);
1565   }
1566 }
1567 
1568 void DwarfLineTable::emit(BinaryContext &BC, MCStreamer &Streamer) {
1569   MCAssembler &Assembler =
1570       static_cast<MCObjectStreamer *>(&Streamer)->getAssembler();
1571 
1572   MCDwarfLineTableParams Params = Assembler.getDWARFLinetableParams();
1573 
1574   auto &LineTables = BC.getDwarfLineTables();
1575 
1576   // Bail out early so we don't switch to the debug_line section needlessly and
1577   // in doing so create an unnecessary (if empty) section.
1578   if (LineTables.empty())
1579     return;
1580   // In a v5 non-split line table, put the strings in a separate section.
1581   Optional<MCDwarfLineStr> LineStr(None);
1582   ErrorOr<BinarySection &> LineStrSection =
1583       BC.getUniqueSectionByName(".debug_line_str");
1584   // Some versions of GCC output DWARF5 .debug_info, but DWARF4 or lower
1585   // .debug_line
1586   if (LineStrSection) {
1587     LineStr = MCDwarfLineStr(*BC.Ctx);
1588     parseAndPopulateDebugLineStr(*LineStrSection, *LineStr, BC, Streamer);
1589   }
1590 
1591   // Switch to the section where the table will be emitted into.
1592   Streamer.SwitchSection(BC.MOFI->getDwarfLineSection());
1593 
1594   const uint16_t DwarfVersion = BC.Ctx->getDwarfVersion();
1595   // Handle the rest of the Compile Units.
1596   for (auto &CUIDTablePair : LineTables) {
1597     Streamer.getContext().setDwarfVersion(
1598         CUIDTablePair.second.getDwarfVersion());
1599     CUIDTablePair.second.emitCU(&Streamer, Params, LineStr, BC);
1600   }
1601 
1602   // Resetting DWARF version for rest of the flow.
1603   BC.Ctx->setDwarfVersion(DwarfVersion);
1604 
1605   // Still need to write the section out for the ExecutionEngine, and temp in
1606   // memory object we are constructing.
1607   if (LineStr) {
1608     LineStr->emitSection(&Streamer);
1609     SmallString<0> Data = LineStr->getFinalizedData();
1610     BC.registerOrUpdateNoteSection(".debug_line_str", copyByteArray(Data.str()),
1611                                    Data.size());
1612   }
1613 }
1614 
1615 } // namespace bolt
1616 } // namespace llvm
1617