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