xref: /llvm-project/bolt/lib/Core/BinaryEmitter.cpp (revision 986e5dedf2e0b505e43b57436037401479927326)
1 //===- bolt/Core/BinaryEmitter.cpp - Emit code and data -------------------===//
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 the collection of functions and classes used for
10 // emission of code and data into object/binary file.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "bolt/Core/BinaryEmitter.h"
15 #include "bolt/Core/BinaryContext.h"
16 #include "bolt/Core/BinaryFunction.h"
17 #include "bolt/Core/DebugData.h"
18 #include "bolt/Utils/CommandLineOpts.h"
19 #include "bolt/Utils/Utils.h"
20 #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
21 #include "llvm/MC/MCSection.h"
22 #include "llvm/MC/MCStreamer.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/LEB128.h"
25 #include "llvm/Support/SMLoc.h"
26 
27 #define DEBUG_TYPE "bolt"
28 
29 using namespace llvm;
30 using namespace bolt;
31 
32 namespace opts {
33 
34 extern cl::opt<JumpTableSupportLevel> JumpTables;
35 extern cl::opt<bool> PreserveBlocksAlignment;
36 
37 cl::opt<bool>
38 AlignBlocks("align-blocks",
39   cl::desc("align basic blocks"),
40   cl::init(false),
41   cl::ZeroOrMore,
42   cl::cat(BoltOptCategory));
43 
44 cl::opt<MacroFusionType>
45 AlignMacroOpFusion("align-macro-fusion",
46   cl::desc("fix instruction alignment for macro-fusion (x86 relocation mode)"),
47   cl::init(MFT_HOT),
48   cl::values(clEnumValN(MFT_NONE, "none",
49                "do not insert alignment no-ops for macro-fusion"),
50              clEnumValN(MFT_HOT, "hot",
51                "only insert alignment no-ops on hot execution paths (default)"),
52              clEnumValN(MFT_ALL, "all",
53                "always align instructions to allow macro-fusion")),
54   cl::ZeroOrMore,
55   cl::cat(BoltRelocCategory));
56 
57 static cl::list<std::string>
58 BreakFunctionNames("break-funcs",
59   cl::CommaSeparated,
60   cl::desc("list of functions to core dump on (debugging)"),
61   cl::value_desc("func1,func2,func3,..."),
62   cl::Hidden,
63   cl::cat(BoltCategory));
64 
65 static cl::list<std::string>
66 FunctionPadSpec("pad-funcs",
67   cl::CommaSeparated,
68   cl::desc("list of functions to pad with amount of bytes"),
69   cl::value_desc("func1:pad1,func2:pad2,func3:pad3,..."),
70   cl::Hidden,
71   cl::cat(BoltCategory));
72 
73 static cl::opt<bool>
74 MarkFuncs("mark-funcs",
75   cl::desc("mark function boundaries with break instruction to make "
76            "sure we accidentally don't cross them"),
77   cl::ReallyHidden,
78   cl::ZeroOrMore,
79   cl::cat(BoltCategory));
80 
81 static cl::opt<bool>
82 PrintJumpTables("print-jump-tables",
83   cl::desc("print jump tables"),
84   cl::ZeroOrMore,
85   cl::Hidden,
86   cl::cat(BoltCategory));
87 
88 static cl::opt<bool>
89 X86AlignBranchBoundaryHotOnly("x86-align-branch-boundary-hot-only",
90   cl::desc("only apply branch boundary alignment in hot code"),
91   cl::init(true),
92   cl::cat(BoltOptCategory));
93 
94 size_t padFunction(const BinaryFunction &Function) {
95   static std::map<std::string, size_t> FunctionPadding;
96 
97   if (FunctionPadding.empty() && !FunctionPadSpec.empty()) {
98     for (std::string &Spec : FunctionPadSpec) {
99       size_t N = Spec.find(':');
100       if (N == std::string::npos)
101         continue;
102       std::string Name = Spec.substr(0, N);
103       size_t Padding = std::stoull(Spec.substr(N + 1));
104       FunctionPadding[Name] = Padding;
105     }
106   }
107 
108   for (auto &FPI : FunctionPadding) {
109     std::string Name = FPI.first;
110     size_t Padding = FPI.second;
111     if (Function.hasNameRegex(Name))
112       return Padding;
113   }
114 
115   return 0;
116 }
117 
118 } // namespace opts
119 
120 namespace {
121 using JumpTable = bolt::JumpTable;
122 
123 class BinaryEmitter {
124 private:
125   BinaryEmitter(const BinaryEmitter &) = delete;
126   BinaryEmitter &operator=(const BinaryEmitter &) = delete;
127 
128   MCStreamer &Streamer;
129   BinaryContext &BC;
130 
131 public:
132   BinaryEmitter(MCStreamer &Streamer, BinaryContext &BC)
133       : Streamer(Streamer), BC(BC) {}
134 
135   /// Emit all code and data.
136   void emitAll(StringRef OrgSecPrefix);
137 
138   /// Emit function code. The caller is responsible for emitting function
139   /// symbol(s) and setting the section to emit the code to.
140   void emitFunctionBody(BinaryFunction &BF, bool EmitColdPart,
141                         bool EmitCodeOnly = false);
142 
143 private:
144   /// Emit function code.
145   void emitFunctions();
146 
147   /// Emit a single function.
148   bool emitFunction(BinaryFunction &BF, bool EmitColdPart);
149 
150   /// Helper for emitFunctionBody to write data inside a function
151   /// (used for AArch64)
152   void emitConstantIslands(BinaryFunction &BF, bool EmitColdPart,
153                            BinaryFunction *OnBehalfOf = nullptr);
154 
155   /// Emit jump tables for the function.
156   void emitJumpTables(const BinaryFunction &BF);
157 
158   /// Emit jump table data. Callee supplies sections for the data.
159   void emitJumpTable(const JumpTable &JT, MCSection *HotSection,
160                      MCSection *ColdSection);
161 
162   void emitCFIInstruction(const MCCFIInstruction &Inst) const;
163 
164   /// Emit exception handling ranges for the function.
165   void emitLSDA(BinaryFunction &BF, bool EmitColdPart);
166 
167   /// Emit line number information corresponding to \p NewLoc. \p PrevLoc
168   /// provides a context for de-duplication of line number info.
169   /// \p FirstInstr indicates if \p NewLoc represents the first instruction
170   /// in a sequence, such as a function fragment.
171   ///
172   /// Return new current location which is either \p NewLoc or \p PrevLoc.
173   SMLoc emitLineInfo(const BinaryFunction &BF, SMLoc NewLoc, SMLoc PrevLoc,
174                      bool FirstInstr);
175 
176   /// Use \p FunctionEndSymbol to mark the end of the line info sequence.
177   /// Note that it does not automatically result in the insertion of the EOS
178   /// marker in the line table program, but provides one to the DWARF generator
179   /// when it needs it.
180   void emitLineInfoEnd(const BinaryFunction &BF, MCSymbol *FunctionEndSymbol);
181 
182   /// Emit debug line info for unprocessed functions from CUs that include
183   /// emitted functions.
184   void emitDebugLineInfoForOriginalFunctions();
185 
186   /// Emit debug line for CUs that were not modified.
187   void emitDebugLineInfoForUnprocessedCUs();
188 
189   /// Emit data sections that have code references in them.
190   void emitDataSections(StringRef OrgSecPrefix);
191 };
192 
193 } // anonymous namespace
194 
195 void BinaryEmitter::emitAll(StringRef OrgSecPrefix) {
196   Streamer.initSections(false, *BC.STI);
197 
198   if (opts::UpdateDebugSections && BC.isELF()) {
199     // Force the emission of debug line info into allocatable section to ensure
200     // RuntimeDyld will process it without ProcessAllSections flag.
201     //
202     // NB: on MachO all sections are required for execution, hence no need
203     //     to change flags/attributes.
204     MCSectionELF *ELFDwarfLineSection =
205         static_cast<MCSectionELF *>(BC.MOFI->getDwarfLineSection());
206     ELFDwarfLineSection->setFlags(ELF::SHF_ALLOC);
207   }
208 
209   if (RuntimeLibrary *RtLibrary = BC.getRuntimeLibrary())
210     RtLibrary->emitBinary(BC, Streamer);
211 
212   BC.getTextSection()->setAlignment(Align(opts::AlignText));
213 
214   emitFunctions();
215 
216   if (opts::UpdateDebugSections) {
217     emitDebugLineInfoForOriginalFunctions();
218     DwarfLineTable::emit(BC, Streamer);
219   }
220 
221   emitDataSections(OrgSecPrefix);
222 
223   Streamer.emitLabel(BC.Ctx->getOrCreateSymbol("_end"));
224 }
225 
226 void BinaryEmitter::emitFunctions() {
227   auto emit = [&](const std::vector<BinaryFunction *> &Functions) {
228     const bool HasProfile = BC.NumProfiledFuncs > 0;
229     const bool OriginalAllowAutoPadding = Streamer.getAllowAutoPadding();
230     for (BinaryFunction *Function : Functions) {
231       if (!BC.shouldEmit(*Function))
232         continue;
233 
234       LLVM_DEBUG(dbgs() << "BOLT: generating code for function \"" << *Function
235                         << "\" : " << Function->getFunctionNumber() << '\n');
236 
237       // Was any part of the function emitted.
238       bool Emitted = false;
239 
240       // Turn off Intel JCC Erratum mitigation for cold code if requested
241       if (HasProfile && opts::X86AlignBranchBoundaryHotOnly &&
242           !Function->hasValidProfile())
243         Streamer.setAllowAutoPadding(false);
244 
245       Emitted |= emitFunction(*Function, /*EmitColdPart=*/false);
246 
247       if (Function->isSplit()) {
248         if (opts::X86AlignBranchBoundaryHotOnly)
249           Streamer.setAllowAutoPadding(false);
250         Emitted |= emitFunction(*Function, /*EmitColdPart=*/true);
251       }
252       Streamer.setAllowAutoPadding(OriginalAllowAutoPadding);
253 
254       if (Emitted)
255         Function->setEmitted(/*KeepCFG=*/opts::PrintCacheMetrics);
256     }
257   };
258 
259   // Mark the start of hot text.
260   if (opts::HotText) {
261     Streamer.SwitchSection(BC.getTextSection());
262     Streamer.emitLabel(BC.getHotTextStartSymbol());
263   }
264 
265   // Emit functions in sorted order.
266   std::vector<BinaryFunction *> SortedFunctions = BC.getSortedFunctions();
267   emit(SortedFunctions);
268 
269   // Emit functions added by BOLT.
270   emit(BC.getInjectedBinaryFunctions());
271 
272   // Mark the end of hot text.
273   if (opts::HotText) {
274     Streamer.SwitchSection(BC.getTextSection());
275     Streamer.emitLabel(BC.getHotTextEndSymbol());
276   }
277 }
278 
279 bool BinaryEmitter::emitFunction(BinaryFunction &Function, bool EmitColdPart) {
280   if (Function.size() == 0 && !Function.hasIslandsInfo())
281     return false;
282 
283   if (Function.getState() == BinaryFunction::State::Empty)
284     return false;
285 
286   MCSection *Section =
287       BC.getCodeSection(EmitColdPart ? Function.getColdCodeSectionName()
288                                      : Function.getCodeSectionName());
289   Streamer.SwitchSection(Section);
290   Section->setHasInstructions(true);
291   BC.Ctx->addGenDwarfSection(Section);
292 
293   if (BC.HasRelocations) {
294     // Set section alignment to at least maximum possible object alignment.
295     // We need this to support LongJmp and other passes that calculates
296     // tentative layout.
297     if (Section->getAlignment() < opts::AlignFunctions)
298       Section->setAlignment(Align(opts::AlignFunctions));
299 
300     Streamer.emitCodeAlignment(BinaryFunction::MinAlign, &*BC.STI);
301     uint16_t MaxAlignBytes = EmitColdPart ? Function.getMaxColdAlignmentBytes()
302                                           : Function.getMaxAlignmentBytes();
303     if (MaxAlignBytes > 0)
304       Streamer.emitCodeAlignment(Function.getAlignment(), &*BC.STI,
305                                  MaxAlignBytes);
306   } else {
307     Streamer.emitCodeAlignment(Function.getAlignment(), &*BC.STI);
308   }
309 
310   MCContext &Context = Streamer.getContext();
311   const MCAsmInfo *MAI = Context.getAsmInfo();
312 
313   MCSymbol *StartSymbol = nullptr;
314 
315   // Emit all symbols associated with the main function entry.
316   if (!EmitColdPart) {
317     StartSymbol = Function.getSymbol();
318     for (MCSymbol *Symbol : Function.getSymbols()) {
319       Streamer.emitSymbolAttribute(Symbol, MCSA_ELF_TypeFunction);
320       Streamer.emitLabel(Symbol);
321     }
322   } else {
323     StartSymbol = Function.getColdSymbol();
324     Streamer.emitSymbolAttribute(StartSymbol, MCSA_ELF_TypeFunction);
325     Streamer.emitLabel(StartSymbol);
326   }
327 
328   // Emit CFI start
329   if (Function.hasCFI()) {
330     Streamer.emitCFIStartProc(/*IsSimple=*/false);
331     if (Function.getPersonalityFunction() != nullptr)
332       Streamer.emitCFIPersonality(Function.getPersonalityFunction(),
333                                   Function.getPersonalityEncoding());
334     MCSymbol *LSDASymbol =
335         EmitColdPart ? Function.getColdLSDASymbol() : Function.getLSDASymbol();
336     if (LSDASymbol)
337       Streamer.emitCFILsda(LSDASymbol, BC.LSDAEncoding);
338     else
339       Streamer.emitCFILsda(0, dwarf::DW_EH_PE_omit);
340     // Emit CFI instructions relative to the CIE
341     for (const MCCFIInstruction &CFIInstr : Function.cie()) {
342       // Only write CIE CFI insns that LLVM will not already emit
343       const std::vector<MCCFIInstruction> &FrameInstrs =
344           MAI->getInitialFrameState();
345       if (std::find(FrameInstrs.begin(), FrameInstrs.end(), CFIInstr) ==
346           FrameInstrs.end())
347         emitCFIInstruction(CFIInstr);
348     }
349   }
350 
351   assert((Function.empty() || !(*Function.begin()).isCold()) &&
352          "first basic block should never be cold");
353 
354   // Emit UD2 at the beginning if requested by user.
355   if (!opts::BreakFunctionNames.empty()) {
356     for (std::string &Name : opts::BreakFunctionNames) {
357       if (Function.hasNameRegex(Name)) {
358         Streamer.emitIntValue(0x0B0F, 2); // UD2: 0F 0B
359         break;
360       }
361     }
362   }
363 
364   // Emit code.
365   emitFunctionBody(Function, EmitColdPart, /*EmitCodeOnly=*/false);
366 
367   // Emit padding if requested.
368   if (size_t Padding = opts::padFunction(Function)) {
369     LLVM_DEBUG(dbgs() << "BOLT-DEBUG: padding function " << Function << " with "
370                       << Padding << " bytes\n");
371     Streamer.emitFill(Padding, MAI->getTextAlignFillValue());
372   }
373 
374   if (opts::MarkFuncs)
375     Streamer.emitIntValue(BC.MIB->getTrapFillValue(), 1);
376 
377   // Emit CFI end
378   if (Function.hasCFI())
379     Streamer.emitCFIEndProc();
380 
381   MCSymbol *EndSymbol = EmitColdPart ? Function.getFunctionColdEndLabel()
382                                      : Function.getFunctionEndLabel();
383   Streamer.emitLabel(EndSymbol);
384 
385   if (MAI->hasDotTypeDotSizeDirective()) {
386     const MCExpr *SizeExpr = MCBinaryExpr::createSub(
387         MCSymbolRefExpr::create(EndSymbol, Context),
388         MCSymbolRefExpr::create(StartSymbol, Context), Context);
389     Streamer.emitELFSize(StartSymbol, SizeExpr);
390   }
391 
392   if (opts::UpdateDebugSections && Function.getDWARFUnit())
393     emitLineInfoEnd(Function, EndSymbol);
394 
395   // Exception handling info for the function.
396   emitLSDA(Function, EmitColdPart);
397 
398   if (!EmitColdPart && opts::JumpTables > JTS_NONE)
399     emitJumpTables(Function);
400 
401   return true;
402 }
403 
404 void BinaryEmitter::emitFunctionBody(BinaryFunction &BF, bool EmitColdPart,
405                                      bool EmitCodeOnly) {
406   if (!EmitCodeOnly && EmitColdPart && BF.hasConstantIsland())
407     BF.duplicateConstantIslands();
408 
409   // Track the first emitted instruction with debug info.
410   bool FirstInstr = true;
411   for (BinaryBasicBlock *BB : BF.layout()) {
412     if (EmitColdPart != BB->isCold())
413       continue;
414 
415     if ((opts::AlignBlocks || opts::PreserveBlocksAlignment) &&
416         BB->getAlignment() > 1)
417       Streamer.emitCodeAlignment(BB->getAlignment(), &*BC.STI,
418                                  BB->getAlignmentMaxBytes());
419     Streamer.emitLabel(BB->getLabel());
420     if (!EmitCodeOnly) {
421       if (MCSymbol *EntrySymbol = BF.getSecondaryEntryPointSymbol(*BB))
422         Streamer.emitLabel(EntrySymbol);
423     }
424 
425     // Check if special alignment for macro-fusion is needed.
426     bool MayNeedMacroFusionAlignment =
427         (opts::AlignMacroOpFusion == MFT_ALL) ||
428         (opts::AlignMacroOpFusion == MFT_HOT && BB->getKnownExecutionCount());
429     BinaryBasicBlock::const_iterator MacroFusionPair;
430     if (MayNeedMacroFusionAlignment) {
431       MacroFusionPair = BB->getMacroOpFusionPair();
432       if (MacroFusionPair == BB->end())
433         MayNeedMacroFusionAlignment = false;
434     }
435 
436     SMLoc LastLocSeen;
437     // Remember if the last instruction emitted was a prefix.
438     bool LastIsPrefix = false;
439     for (auto I = BB->begin(), E = BB->end(); I != E; ++I) {
440       MCInst &Instr = *I;
441 
442       if (EmitCodeOnly && BC.MIB->isPseudo(Instr))
443         continue;
444 
445       // Handle pseudo instructions.
446       if (BC.MIB->isEHLabel(Instr)) {
447         const MCSymbol *Label = BC.MIB->getTargetSymbol(Instr);
448         assert(Instr.getNumOperands() >= 1 && Label &&
449                "bad EH_LABEL instruction");
450         Streamer.emitLabel(const_cast<MCSymbol *>(Label));
451         continue;
452       }
453       if (BC.MIB->isCFI(Instr)) {
454         emitCFIInstruction(*BF.getCFIFor(Instr));
455         continue;
456       }
457 
458       // Handle macro-fusion alignment. If we emitted a prefix as
459       // the last instruction, we should've already emitted the associated
460       // alignment hint, so don't emit it twice.
461       if (MayNeedMacroFusionAlignment && !LastIsPrefix &&
462           I == MacroFusionPair) {
463         // This assumes the second instruction in the macro-op pair will get
464         // assigned to its own MCRelaxableFragment. Since all JCC instructions
465         // are relaxable, we should be safe.
466       }
467 
468       if (!EmitCodeOnly && opts::UpdateDebugSections && BF.getDWARFUnit()) {
469         LastLocSeen = emitLineInfo(BF, Instr.getLoc(), LastLocSeen, FirstInstr);
470         FirstInstr = false;
471       }
472 
473       // Prepare to tag this location with a label if we need to keep track of
474       // the location of calls/returns for BOLT address translation maps
475       if (!EmitCodeOnly && BF.requiresAddressTranslation() &&
476           BC.MIB->getOffset(Instr)) {
477         const uint32_t Offset = *BC.MIB->getOffset(Instr);
478         MCSymbol *LocSym = BC.Ctx->createTempSymbol();
479         Streamer.emitLabel(LocSym);
480         BB->getLocSyms().emplace_back(Offset, LocSym);
481       }
482 
483       Streamer.emitInstruction(Instr, *BC.STI);
484       LastIsPrefix = BC.MIB->isPrefix(Instr);
485     }
486   }
487 
488   if (!EmitCodeOnly)
489     emitConstantIslands(BF, EmitColdPart);
490 }
491 
492 void BinaryEmitter::emitConstantIslands(BinaryFunction &BF, bool EmitColdPart,
493                                         BinaryFunction *OnBehalfOf) {
494   if (!BF.hasIslandsInfo())
495     return;
496 
497   BinaryFunction::IslandInfo &Islands = BF.getIslandInfo();
498   if (Islands.DataOffsets.empty() && Islands.Dependency.empty())
499     return;
500 
501   // AArch64 requires CI to be aligned to 8 bytes due to access instructions
502   // restrictions. E.g. the ldr with imm, where imm must be aligned to 8 bytes.
503   const uint16_t Alignment = OnBehalfOf
504                                  ? OnBehalfOf->getConstantIslandAlignment()
505                                  : BF.getConstantIslandAlignment();
506   Streamer.emitCodeAlignment(Alignment, &*BC.STI);
507 
508   if (!OnBehalfOf) {
509     if (!EmitColdPart)
510       Streamer.emitLabel(BF.getFunctionConstantIslandLabel());
511     else
512       Streamer.emitLabel(BF.getFunctionColdConstantIslandLabel());
513   }
514 
515   assert((!OnBehalfOf || Islands.Proxies[OnBehalfOf].size() > 0) &&
516          "spurious OnBehalfOf constant island emission");
517 
518   assert(!BF.isInjected() &&
519          "injected functions should not have constant islands");
520   // Raw contents of the function.
521   StringRef SectionContents = BF.getOriginSection()->getContents();
522 
523   // Raw contents of the function.
524   StringRef FunctionContents = SectionContents.substr(
525       BF.getAddress() - BF.getOriginSection()->getAddress(), BF.getMaxSize());
526 
527   if (opts::Verbosity && !OnBehalfOf)
528     outs() << "BOLT-INFO: emitting constant island for function " << BF << "\n";
529 
530   // We split the island into smaller blocks and output labels between them.
531   auto IS = Islands.Offsets.begin();
532   for (auto DataIter = Islands.DataOffsets.begin();
533        DataIter != Islands.DataOffsets.end(); ++DataIter) {
534     uint64_t FunctionOffset = *DataIter;
535     uint64_t EndOffset = 0ULL;
536 
537     // Determine size of this data chunk
538     auto NextData = std::next(DataIter);
539     auto CodeIter = Islands.CodeOffsets.lower_bound(*DataIter);
540     if (CodeIter == Islands.CodeOffsets.end() &&
541         NextData == Islands.DataOffsets.end())
542       EndOffset = BF.getMaxSize();
543     else if (CodeIter == Islands.CodeOffsets.end())
544       EndOffset = *NextData;
545     else if (NextData == Islands.DataOffsets.end())
546       EndOffset = *CodeIter;
547     else
548       EndOffset = (*CodeIter > *NextData) ? *NextData : *CodeIter;
549 
550     if (FunctionOffset == EndOffset)
551       continue; // Size is zero, nothing to emit
552 
553     auto emitCI = [&](uint64_t &FunctionOffset, uint64_t EndOffset) {
554       if (FunctionOffset >= EndOffset)
555         return;
556 
557       for (auto It = Islands.Relocations.lower_bound(FunctionOffset);
558            It != Islands.Relocations.end(); ++It) {
559         if (It->first >= EndOffset)
560           break;
561 
562         const Relocation &Relocation = It->second;
563         if (FunctionOffset < Relocation.Offset) {
564           Streamer.emitBytes(
565               FunctionContents.slice(FunctionOffset, Relocation.Offset));
566           FunctionOffset = Relocation.Offset;
567         }
568 
569         LLVM_DEBUG(
570             dbgs() << "BOLT-DEBUG: emitting constant island relocation"
571                    << " for " << BF << " at offset 0x"
572                    << Twine::utohexstr(Relocation.Offset) << " with size "
573                    << Relocation::getSizeForType(Relocation.Type) << '\n');
574 
575         FunctionOffset += Relocation.emit(&Streamer);
576       }
577 
578       assert(FunctionOffset <= EndOffset && "overflow error");
579       if (FunctionOffset < EndOffset) {
580         Streamer.emitBytes(FunctionContents.slice(FunctionOffset, EndOffset));
581         FunctionOffset = EndOffset;
582       }
583     };
584 
585     // Emit labels, relocs and data
586     while (IS != Islands.Offsets.end() && IS->first < EndOffset) {
587       auto NextLabelOffset =
588           IS == Islands.Offsets.end() ? EndOffset : IS->first;
589       auto NextStop = std::min(NextLabelOffset, EndOffset);
590       assert(NextStop <= EndOffset && "internal overflow error");
591       emitCI(FunctionOffset, NextStop);
592       if (IS != Islands.Offsets.end() && FunctionOffset == IS->first) {
593         // This is a slightly complex code to decide which label to emit. We
594         // have 4 cases to handle: regular symbol, cold symbol, regular or cold
595         // symbol being emitted on behalf of an external function.
596         if (!OnBehalfOf) {
597           if (!EmitColdPart) {
598             LLVM_DEBUG(dbgs() << "BOLT-DEBUG: emitted label "
599                               << IS->second->getName() << " at offset 0x"
600                               << Twine::utohexstr(IS->first) << '\n');
601             if (IS->second->isUndefined())
602               Streamer.emitLabel(IS->second);
603             else
604               assert(BF.hasName(std::string(IS->second->getName())));
605           } else if (Islands.ColdSymbols.count(IS->second) != 0) {
606             LLVM_DEBUG(dbgs()
607                        << "BOLT-DEBUG: emitted label "
608                        << Islands.ColdSymbols[IS->second]->getName() << '\n');
609             if (Islands.ColdSymbols[IS->second]->isUndefined())
610               Streamer.emitLabel(Islands.ColdSymbols[IS->second]);
611           }
612         } else {
613           if (!EmitColdPart) {
614             if (MCSymbol *Sym = Islands.Proxies[OnBehalfOf][IS->second]) {
615               LLVM_DEBUG(dbgs() << "BOLT-DEBUG: emitted label "
616                                 << Sym->getName() << '\n');
617               Streamer.emitLabel(Sym);
618             }
619           } else if (MCSymbol *Sym =
620                          Islands.ColdProxies[OnBehalfOf][IS->second]) {
621             LLVM_DEBUG(dbgs() << "BOLT-DEBUG: emitted label " << Sym->getName()
622                               << '\n');
623             Streamer.emitLabel(Sym);
624           }
625         }
626         ++IS;
627       }
628     }
629     assert(FunctionOffset <= EndOffset && "overflow error");
630     emitCI(FunctionOffset, EndOffset);
631   }
632   assert(IS == Islands.Offsets.end() && "some symbols were not emitted!");
633 
634   if (OnBehalfOf)
635     return;
636   // Now emit constant islands from other functions that we may have used in
637   // this function.
638   for (BinaryFunction *ExternalFunc : Islands.Dependency)
639     emitConstantIslands(*ExternalFunc, EmitColdPart, &BF);
640 }
641 
642 SMLoc BinaryEmitter::emitLineInfo(const BinaryFunction &BF, SMLoc NewLoc,
643                                   SMLoc PrevLoc, bool FirstInstr) {
644   DWARFUnit *FunctionCU = BF.getDWARFUnit();
645   const DWARFDebugLine::LineTable *FunctionLineTable = BF.getDWARFLineTable();
646   assert(FunctionCU && "cannot emit line info for function without CU");
647 
648   DebugLineTableRowRef RowReference = DebugLineTableRowRef::fromSMLoc(NewLoc);
649 
650   // Check if no new line info needs to be emitted.
651   if (RowReference == DebugLineTableRowRef::NULL_ROW ||
652       NewLoc.getPointer() == PrevLoc.getPointer())
653     return PrevLoc;
654 
655   unsigned CurrentFilenum = 0;
656   const DWARFDebugLine::LineTable *CurrentLineTable = FunctionLineTable;
657 
658   // If the CU id from the current instruction location does not
659   // match the CU id from the current function, it means that we
660   // have come across some inlined code.  We must look up the CU
661   // for the instruction's original function and get the line table
662   // from that.
663   const uint64_t FunctionUnitIndex = FunctionCU->getOffset();
664   const uint32_t CurrentUnitIndex = RowReference.DwCompileUnitIndex;
665   if (CurrentUnitIndex != FunctionUnitIndex) {
666     CurrentLineTable = BC.DwCtx->getLineTableForUnit(
667         BC.DwCtx->getCompileUnitForOffset(CurrentUnitIndex));
668     // Add filename from the inlined function to the current CU.
669     CurrentFilenum = BC.addDebugFilenameToUnit(
670         FunctionUnitIndex, CurrentUnitIndex,
671         CurrentLineTable->Rows[RowReference.RowIndex - 1].File);
672   }
673 
674   const DWARFDebugLine::Row &CurrentRow =
675       CurrentLineTable->Rows[RowReference.RowIndex - 1];
676   if (!CurrentFilenum)
677     CurrentFilenum = CurrentRow.File;
678 
679   unsigned Flags = (DWARF2_FLAG_IS_STMT * CurrentRow.IsStmt) |
680                    (DWARF2_FLAG_BASIC_BLOCK * CurrentRow.BasicBlock) |
681                    (DWARF2_FLAG_PROLOGUE_END * CurrentRow.PrologueEnd) |
682                    (DWARF2_FLAG_EPILOGUE_BEGIN * CurrentRow.EpilogueBegin);
683 
684   // Always emit is_stmt at the beginning of function fragment.
685   if (FirstInstr)
686     Flags |= DWARF2_FLAG_IS_STMT;
687 
688   BC.Ctx->setCurrentDwarfLoc(CurrentFilenum, CurrentRow.Line, CurrentRow.Column,
689                              Flags, CurrentRow.Isa, CurrentRow.Discriminator);
690   const MCDwarfLoc &DwarfLoc = BC.Ctx->getCurrentDwarfLoc();
691   BC.Ctx->clearDwarfLocSeen();
692 
693   MCSymbol *LineSym = BC.Ctx->createTempSymbol();
694   Streamer.emitLabel(LineSym);
695 
696   BC.getDwarfLineTable(FunctionUnitIndex)
697       .getMCLineSections()
698       .addLineEntry(MCDwarfLineEntry(LineSym, DwarfLoc),
699                     Streamer.getCurrentSectionOnly());
700 
701   return NewLoc;
702 }
703 
704 void BinaryEmitter::emitLineInfoEnd(const BinaryFunction &BF,
705                                     MCSymbol *FunctionEndLabel) {
706   DWARFUnit *FunctionCU = BF.getDWARFUnit();
707   assert(FunctionCU && "DWARF unit expected");
708   BC.Ctx->setCurrentDwarfLoc(0, 0, 0, DWARF2_FLAG_END_SEQUENCE, 0, 0);
709   const MCDwarfLoc &DwarfLoc = BC.Ctx->getCurrentDwarfLoc();
710   BC.Ctx->clearDwarfLocSeen();
711   BC.getDwarfLineTable(FunctionCU->getOffset())
712       .getMCLineSections()
713       .addLineEntry(MCDwarfLineEntry(FunctionEndLabel, DwarfLoc),
714                     Streamer.getCurrentSectionOnly());
715 }
716 
717 void BinaryEmitter::emitJumpTables(const BinaryFunction &BF) {
718   MCSection *ReadOnlySection = BC.MOFI->getReadOnlySection();
719   MCSection *ReadOnlyColdSection = BC.MOFI->getContext().getELFSection(
720       ".rodata.cold", ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
721 
722   if (!BF.hasJumpTables())
723     return;
724 
725   if (opts::PrintJumpTables)
726     outs() << "BOLT-INFO: jump tables for function " << BF << ":\n";
727 
728   for (auto &JTI : BF.jumpTables()) {
729     JumpTable &JT = *JTI.second;
730     if (opts::PrintJumpTables)
731       JT.print(outs());
732     if ((opts::JumpTables == JTS_BASIC || !BF.isSimple()) &&
733         BC.HasRelocations) {
734       JT.updateOriginal();
735     } else {
736       MCSection *HotSection, *ColdSection;
737       if (opts::JumpTables == JTS_BASIC) {
738         // In non-relocation mode we have to emit jump tables in local sections.
739         // This way we only overwrite them when the corresponding function is
740         // overwritten.
741         std::string Name = ".local." + JT.Labels[0]->getName().str();
742         std::replace(Name.begin(), Name.end(), '/', '.');
743         BinarySection &Section =
744             BC.registerOrUpdateSection(Name, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
745         Section.setAnonymous(true);
746         JT.setOutputSection(Section);
747         HotSection = BC.getDataSection(Name);
748         ColdSection = HotSection;
749       } else {
750         if (BF.isSimple()) {
751           HotSection = ReadOnlySection;
752           ColdSection = ReadOnlyColdSection;
753         } else {
754           HotSection = BF.hasProfile() ? ReadOnlySection : ReadOnlyColdSection;
755           ColdSection = HotSection;
756         }
757       }
758       emitJumpTable(JT, HotSection, ColdSection);
759     }
760   }
761 }
762 
763 void BinaryEmitter::emitJumpTable(const JumpTable &JT, MCSection *HotSection,
764                                   MCSection *ColdSection) {
765   // Pre-process entries for aggressive splitting.
766   // Each label represents a separate switch table and gets its own count
767   // determining its destination.
768   std::map<MCSymbol *, uint64_t> LabelCounts;
769   if (opts::JumpTables > JTS_SPLIT && !JT.Counts.empty()) {
770     MCSymbol *CurrentLabel = JT.Labels.at(0);
771     uint64_t CurrentLabelCount = 0;
772     for (unsigned Index = 0; Index < JT.Entries.size(); ++Index) {
773       auto LI = JT.Labels.find(Index * JT.EntrySize);
774       if (LI != JT.Labels.end()) {
775         LabelCounts[CurrentLabel] = CurrentLabelCount;
776         CurrentLabel = LI->second;
777         CurrentLabelCount = 0;
778       }
779       CurrentLabelCount += JT.Counts[Index].Count;
780     }
781     LabelCounts[CurrentLabel] = CurrentLabelCount;
782   } else {
783     Streamer.SwitchSection(JT.Count > 0 ? HotSection : ColdSection);
784     Streamer.emitValueToAlignment(JT.EntrySize);
785   }
786   MCSymbol *LastLabel = nullptr;
787   uint64_t Offset = 0;
788   for (MCSymbol *Entry : JT.Entries) {
789     auto LI = JT.Labels.find(Offset);
790     if (LI != JT.Labels.end()) {
791       LLVM_DEBUG(dbgs() << "BOLT-DEBUG: emitting jump table "
792                         << LI->second->getName()
793                         << " (originally was at address 0x"
794                         << Twine::utohexstr(JT.getAddress() + Offset)
795                         << (Offset ? "as part of larger jump table\n" : "\n"));
796       if (!LabelCounts.empty()) {
797         LLVM_DEBUG(dbgs() << "BOLT-DEBUG: jump table count: "
798                           << LabelCounts[LI->second] << '\n');
799         if (LabelCounts[LI->second] > 0)
800           Streamer.SwitchSection(HotSection);
801         else
802           Streamer.SwitchSection(ColdSection);
803         Streamer.emitValueToAlignment(JT.EntrySize);
804       }
805       Streamer.emitLabel(LI->second);
806       LastLabel = LI->second;
807     }
808     if (JT.Type == JumpTable::JTT_NORMAL) {
809       Streamer.emitSymbolValue(Entry, JT.OutputEntrySize);
810     } else { // JTT_PIC
811       const MCSymbolRefExpr *JTExpr =
812           MCSymbolRefExpr::create(LastLabel, Streamer.getContext());
813       const MCSymbolRefExpr *E =
814           MCSymbolRefExpr::create(Entry, Streamer.getContext());
815       const MCBinaryExpr *Value =
816           MCBinaryExpr::createSub(E, JTExpr, Streamer.getContext());
817       Streamer.emitValue(Value, JT.EntrySize);
818     }
819     Offset += JT.EntrySize;
820   }
821 }
822 
823 void BinaryEmitter::emitCFIInstruction(const MCCFIInstruction &Inst) const {
824   switch (Inst.getOperation()) {
825   default:
826     llvm_unreachable("Unexpected instruction");
827   case MCCFIInstruction::OpDefCfaOffset:
828     Streamer.emitCFIDefCfaOffset(Inst.getOffset());
829     break;
830   case MCCFIInstruction::OpAdjustCfaOffset:
831     Streamer.emitCFIAdjustCfaOffset(Inst.getOffset());
832     break;
833   case MCCFIInstruction::OpDefCfa:
834     Streamer.emitCFIDefCfa(Inst.getRegister(), Inst.getOffset());
835     break;
836   case MCCFIInstruction::OpDefCfaRegister:
837     Streamer.emitCFIDefCfaRegister(Inst.getRegister());
838     break;
839   case MCCFIInstruction::OpOffset:
840     Streamer.emitCFIOffset(Inst.getRegister(), Inst.getOffset());
841     break;
842   case MCCFIInstruction::OpRegister:
843     Streamer.emitCFIRegister(Inst.getRegister(), Inst.getRegister2());
844     break;
845   case MCCFIInstruction::OpWindowSave:
846     Streamer.emitCFIWindowSave();
847     break;
848   case MCCFIInstruction::OpNegateRAState:
849     Streamer.emitCFINegateRAState();
850     break;
851   case MCCFIInstruction::OpSameValue:
852     Streamer.emitCFISameValue(Inst.getRegister());
853     break;
854   case MCCFIInstruction::OpGnuArgsSize:
855     Streamer.emitCFIGnuArgsSize(Inst.getOffset());
856     break;
857   case MCCFIInstruction::OpEscape:
858     Streamer.AddComment(Inst.getComment());
859     Streamer.emitCFIEscape(Inst.getValues());
860     break;
861   case MCCFIInstruction::OpRestore:
862     Streamer.emitCFIRestore(Inst.getRegister());
863     break;
864   case MCCFIInstruction::OpUndefined:
865     Streamer.emitCFIUndefined(Inst.getRegister());
866     break;
867   }
868 }
869 
870 // The code is based on EHStreamer::emitExceptionTable().
871 void BinaryEmitter::emitLSDA(BinaryFunction &BF, bool EmitColdPart) {
872   const BinaryFunction::CallSitesType *Sites =
873       EmitColdPart ? &BF.getColdCallSites() : &BF.getCallSites();
874   if (Sites->empty())
875     return;
876 
877   // Calculate callsite table size. Size of each callsite entry is:
878   //
879   //  sizeof(start) + sizeof(length) + sizeof(LP) + sizeof(uleb128(action))
880   //
881   // or
882   //
883   //  sizeof(dwarf::DW_EH_PE_data4) * 3 + sizeof(uleb128(action))
884   uint64_t CallSiteTableLength = Sites->size() * 4 * 3;
885   for (const BinaryFunction::CallSite &CallSite : *Sites)
886     CallSiteTableLength += getULEB128Size(CallSite.Action);
887 
888   Streamer.SwitchSection(BC.MOFI->getLSDASection());
889 
890   const unsigned TTypeEncoding = BC.TTypeEncoding;
891   const unsigned TTypeEncodingSize = BC.getDWARFEncodingSize(TTypeEncoding);
892   const uint16_t TTypeAlignment = 4;
893 
894   // Type tables have to be aligned at 4 bytes.
895   Streamer.emitValueToAlignment(TTypeAlignment);
896 
897   // Emit the LSDA label.
898   MCSymbol *LSDASymbol =
899       EmitColdPart ? BF.getColdLSDASymbol() : BF.getLSDASymbol();
900   assert(LSDASymbol && "no LSDA symbol set");
901   Streamer.emitLabel(LSDASymbol);
902 
903   // Corresponding FDE start.
904   const MCSymbol *StartSymbol =
905       EmitColdPart ? BF.getColdSymbol() : BF.getSymbol();
906 
907   // Emit the LSDA header.
908 
909   // If LPStart is omitted, then the start of the FDE is used as a base for
910   // landing pad displacements. Then if a cold fragment starts with
911   // a landing pad, this means that the first landing pad offset will be 0.
912   // As a result, the exception handling runtime will ignore this landing pad
913   // because zero offset denotes the absence of a landing pad.
914   // For this reason, when the binary has fixed starting address we emit LPStart
915   // as 0 and output the absolute value of the landing pad in the table.
916   //
917   // If the base address can change, we cannot use absolute addresses for
918   // landing pads (at least not without runtime relocations). Hence, we fall
919   // back to emitting landing pads relative to the FDE start.
920   // As we are emitting label differences, we have to guarantee both labels are
921   // defined in the same section and hence cannot place the landing pad into a
922   // cold fragment when the corresponding call site is in the hot fragment.
923   // Because of this issue and the previously described issue of possible
924   // zero-offset landing pad we disable splitting of exception-handling
925   // code for shared objects.
926   std::function<void(const MCSymbol *)> emitLandingPad;
927   if (BC.HasFixedLoadAddress) {
928     Streamer.emitIntValue(dwarf::DW_EH_PE_udata4, 1); // LPStart format
929     Streamer.emitIntValue(0, 4);                      // LPStart
930     emitLandingPad = [&](const MCSymbol *LPSymbol) {
931       if (!LPSymbol)
932         Streamer.emitIntValue(0, 4);
933       else
934         Streamer.emitSymbolValue(LPSymbol, 4);
935     };
936   } else {
937     assert(!EmitColdPart &&
938            "cannot have exceptions in cold fragment for shared object");
939     Streamer.emitIntValue(dwarf::DW_EH_PE_omit, 1); // LPStart format
940     emitLandingPad = [&](const MCSymbol *LPSymbol) {
941       if (!LPSymbol)
942         Streamer.emitIntValue(0, 4);
943       else
944         Streamer.emitAbsoluteSymbolDiff(LPSymbol, StartSymbol, 4);
945     };
946   }
947 
948   Streamer.emitIntValue(TTypeEncoding, 1); // TType format
949 
950   // See the comment in EHStreamer::emitExceptionTable() on to use
951   // uleb128 encoding (which can use variable number of bytes to encode the same
952   // value) to ensure type info table is properly aligned at 4 bytes without
953   // iteratively fixing sizes of the tables.
954   unsigned CallSiteTableLengthSize = getULEB128Size(CallSiteTableLength);
955   unsigned TTypeBaseOffset =
956       sizeof(int8_t) +                 // Call site format
957       CallSiteTableLengthSize +        // Call site table length size
958       CallSiteTableLength +            // Call site table length
959       BF.getLSDAActionTable().size() + // Actions table size
960       BF.getLSDATypeTable().size() * TTypeEncodingSize; // Types table size
961   unsigned TTypeBaseOffsetSize = getULEB128Size(TTypeBaseOffset);
962   unsigned TotalSize = sizeof(int8_t) +      // LPStart format
963                        sizeof(int8_t) +      // TType format
964                        TTypeBaseOffsetSize + // TType base offset size
965                        TTypeBaseOffset;      // TType base offset
966   unsigned SizeAlign = (4 - TotalSize) & 3;
967 
968   // Account for any extra padding that will be added to the call site table
969   // length.
970   Streamer.emitULEB128IntValue(TTypeBaseOffset,
971                                /*PadTo=*/TTypeBaseOffsetSize + SizeAlign);
972 
973   // Emit the landing pad call site table. We use signed data4 since we can emit
974   // a landing pad in a different part of the split function that could appear
975   // earlier in the address space than LPStart.
976   Streamer.emitIntValue(dwarf::DW_EH_PE_sdata4, 1);
977   Streamer.emitULEB128IntValue(CallSiteTableLength);
978 
979   for (const BinaryFunction::CallSite &CallSite : *Sites) {
980     const MCSymbol *BeginLabel = CallSite.Start;
981     const MCSymbol *EndLabel = CallSite.End;
982 
983     assert(BeginLabel && "start EH label expected");
984     assert(EndLabel && "end EH label expected");
985 
986     // Start of the range is emitted relative to the start of current
987     // function split part.
988     Streamer.emitAbsoluteSymbolDiff(BeginLabel, StartSymbol, 4);
989     Streamer.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
990     emitLandingPad(CallSite.LP);
991     Streamer.emitULEB128IntValue(CallSite.Action);
992   }
993 
994   // Write out action, type, and type index tables at the end.
995   //
996   // For action and type index tables there's no need to change the original
997   // table format unless we are doing function splitting, in which case we can
998   // split and optimize the tables.
999   //
1000   // For type table we (re-)encode the table using TTypeEncoding matching
1001   // the current assembler mode.
1002   for (uint8_t const &Byte : BF.getLSDAActionTable())
1003     Streamer.emitIntValue(Byte, 1);
1004 
1005   const BinaryFunction::LSDATypeTableTy &TypeTable =
1006       (TTypeEncoding & dwarf::DW_EH_PE_indirect) ? BF.getLSDATypeAddressTable()
1007                                                  : BF.getLSDATypeTable();
1008   assert(TypeTable.size() == BF.getLSDATypeTable().size() &&
1009          "indirect type table size mismatch");
1010 
1011   for (int Index = TypeTable.size() - 1; Index >= 0; --Index) {
1012     const uint64_t TypeAddress = TypeTable[Index];
1013     switch (TTypeEncoding & 0x70) {
1014     default:
1015       llvm_unreachable("unsupported TTypeEncoding");
1016     case dwarf::DW_EH_PE_absptr:
1017       Streamer.emitIntValue(TypeAddress, TTypeEncodingSize);
1018       break;
1019     case dwarf::DW_EH_PE_pcrel: {
1020       if (TypeAddress) {
1021         const MCSymbol *TypeSymbol =
1022             BC.getOrCreateGlobalSymbol(TypeAddress, "TI", 0, TTypeAlignment);
1023         MCSymbol *DotSymbol = BC.Ctx->createNamedTempSymbol();
1024         Streamer.emitLabel(DotSymbol);
1025         const MCBinaryExpr *SubDotExpr = MCBinaryExpr::createSub(
1026             MCSymbolRefExpr::create(TypeSymbol, *BC.Ctx),
1027             MCSymbolRefExpr::create(DotSymbol, *BC.Ctx), *BC.Ctx);
1028         Streamer.emitValue(SubDotExpr, TTypeEncodingSize);
1029       } else {
1030         Streamer.emitIntValue(0, TTypeEncodingSize);
1031       }
1032       break;
1033     }
1034     }
1035   }
1036   for (uint8_t const &Byte : BF.getLSDATypeIndexTable())
1037     Streamer.emitIntValue(Byte, 1);
1038 }
1039 
1040 void BinaryEmitter::emitDebugLineInfoForOriginalFunctions() {
1041   // If a function is in a CU containing at least one processed function, we
1042   // have to rewrite the whole line table for that CU. For unprocessed functions
1043   // we use data from the input line table.
1044   for (auto &It : BC.getBinaryFunctions()) {
1045     const BinaryFunction &Function = It.second;
1046 
1047     // If the function was emitted, its line info was emitted with it.
1048     if (Function.isEmitted())
1049       continue;
1050 
1051     const DWARFDebugLine::LineTable *LineTable = Function.getDWARFLineTable();
1052     if (!LineTable)
1053       continue; // nothing to update for this function
1054 
1055     const uint64_t Address = Function.getAddress();
1056     std::vector<uint32_t> Results;
1057     if (!LineTable->lookupAddressRange(
1058             {Address, object::SectionedAddress::UndefSection},
1059             Function.getSize(), Results))
1060       continue;
1061 
1062     if (Results.empty())
1063       continue;
1064 
1065     // The first row returned could be the last row matching the start address.
1066     // Find the first row with the same address that is not the end of the
1067     // sequence.
1068     uint64_t FirstRow = Results.front();
1069     while (FirstRow > 0) {
1070       const DWARFDebugLine::Row &PrevRow = LineTable->Rows[FirstRow - 1];
1071       if (PrevRow.Address.Address != Address || PrevRow.EndSequence)
1072         break;
1073       --FirstRow;
1074     }
1075 
1076     const uint64_t EndOfSequenceAddress =
1077         Function.getAddress() + Function.getMaxSize();
1078     BC.getDwarfLineTable(Function.getDWARFUnit()->getOffset())
1079         .addLineTableSequence(LineTable, FirstRow, Results.back(),
1080                               EndOfSequenceAddress);
1081   }
1082 
1083   // For units that are completely unprocessed, use original debug line contents
1084   // eliminating the need to regenerate line info program.
1085   emitDebugLineInfoForUnprocessedCUs();
1086 }
1087 
1088 void BinaryEmitter::emitDebugLineInfoForUnprocessedCUs() {
1089   // Sorted list of section offsets provides boundaries for section fragments,
1090   // where each fragment is the unit's contribution to debug line section.
1091   std::vector<uint64_t> StmtListOffsets;
1092   StmtListOffsets.reserve(BC.DwCtx->getNumCompileUnits());
1093   for (const std::unique_ptr<DWARFUnit> &CU : BC.DwCtx->compile_units()) {
1094     DWARFDie CUDie = CU->getUnitDIE();
1095     auto StmtList = dwarf::toSectionOffset(CUDie.find(dwarf::DW_AT_stmt_list));
1096     if (!StmtList)
1097       continue;
1098 
1099     StmtListOffsets.push_back(*StmtList);
1100   }
1101   std::sort(StmtListOffsets.begin(), StmtListOffsets.end());
1102 
1103   // For each CU that was not processed, emit its line info as a binary blob.
1104   for (const std::unique_ptr<DWARFUnit> &CU : BC.DwCtx->compile_units()) {
1105     if (BC.ProcessedCUs.count(CU.get()))
1106       continue;
1107 
1108     DWARFDie CUDie = CU->getUnitDIE();
1109     auto StmtList = dwarf::toSectionOffset(CUDie.find(dwarf::DW_AT_stmt_list));
1110     if (!StmtList)
1111       continue;
1112 
1113     StringRef DebugLineContents = CU->getLineSection().Data;
1114 
1115     const uint64_t Begin = *StmtList;
1116 
1117     // Statement list ends where the next unit contribution begins, or at the
1118     // end of the section.
1119     auto It =
1120         std::upper_bound(StmtListOffsets.begin(), StmtListOffsets.end(), Begin);
1121     const uint64_t End =
1122         It == StmtListOffsets.end() ? DebugLineContents.size() : *It;
1123 
1124     BC.getDwarfLineTable(CU->getOffset())
1125         .addRawContents(DebugLineContents.slice(Begin, End));
1126   }
1127 }
1128 
1129 void BinaryEmitter::emitDataSections(StringRef OrgSecPrefix) {
1130   for (BinarySection &Section : BC.sections()) {
1131     if (!Section.hasRelocations() || !Section.hasSectionRef())
1132       continue;
1133 
1134     StringRef SectionName = Section.getName();
1135     std::string EmitName = Section.isReordered()
1136                                ? std::string(Section.getOutputName())
1137                                : OrgSecPrefix.str() + std::string(SectionName);
1138     Section.emitAsData(Streamer, EmitName);
1139     Section.clearRelocations();
1140   }
1141 }
1142 
1143 namespace llvm {
1144 namespace bolt {
1145 
1146 void emitBinaryContext(MCStreamer &Streamer, BinaryContext &BC,
1147                        StringRef OrgSecPrefix) {
1148   BinaryEmitter(Streamer, BC).emitAll(OrgSecPrefix);
1149 }
1150 
1151 void emitFunctionBody(MCStreamer &Streamer, BinaryFunction &BF,
1152                       bool EmitColdPart, bool EmitCodeOnly) {
1153   BinaryEmitter(Streamer, BF.getBinaryContext())
1154       .emitFunctionBody(BF, EmitColdPart, EmitCodeOnly);
1155 }
1156 
1157 } // namespace bolt
1158 } // namespace llvm
1159