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