1//===- lib/MC/MCObjectStreamer.cpp - Object File MCStreamer Interface -----===//
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#include "llvm/MC/MCObjectStreamer.h"
10#include "llvm/MC/MCAsmBackend.h"
11#include "llvm/MC/MCAsmInfo.h"
12#include "llvm/MC/MCAssembler.h"
13#include "llvm/MC/MCCodeEmitter.h"
14#include "llvm/MC/MCCodeView.h"
15#include "llvm/MC/MCContext.h"
16#include "llvm/MC/MCDwarf.h"
17#include "llvm/MC/MCExpr.h"
18#include "llvm/MC/MCObjectFileInfo.h"
19#include "llvm/MC/MCObjectWriter.h"
20#include "llvm/MC/MCSection.h"
21#include "llvm/MC/MCSymbol.h"
22#include "llvm/MC/MCValue.h"
23#include "llvm/Support/ErrorHandling.h"
24#include "llvm/Support/SourceMgr.h"
25using namespace llvm;
26
27MCObjectStreamer::MCObjectStreamer(MCContext &Context,
28 std::unique_ptr<MCAsmBackend> TAB,
29 std::unique_ptr<MCObjectWriter> OW,
30 std::unique_ptr<MCCodeEmitter> Emitter)
31 : MCStreamer(Context),
32 Assembler(std::make_unique<MCAssembler>(
33 args&: Context, args: std::move(TAB), args: std::move(Emitter), args: std::move(OW))),
34 EmitEHFrame(true), EmitDebugFrame(false) {
35 assert(Assembler->getBackendPtr() && Assembler->getEmitterPtr());
36 setAllowAutoPadding(Assembler->getBackend().allowAutoPadding());
37 if (Context.getTargetOptions() && Context.getTargetOptions()->MCRelaxAll)
38 Assembler->setRelaxAll(true);
39}
40
41MCObjectStreamer::~MCObjectStreamer() = default;
42
43MCAssembler *MCObjectStreamer::getAssemblerPtr() {
44 if (getUseAssemblerInfoForParsing())
45 return Assembler.get();
46 return nullptr;
47}
48
49// When fixup's offset is a forward declared label, e.g.:
50//
51// .reloc 1f, R_MIPS_JALR, foo
52// 1: nop
53//
54// postpone adding it to Fixups vector until the label is defined and its offset
55// is known.
56void MCObjectStreamer::resolvePendingFixups() {
57 for (PendingMCFixup &PendingFixup : PendingFixups) {
58 if (!PendingFixup.Sym || PendingFixup.Sym->isUndefined ()) {
59 getContext().reportError(L: PendingFixup.Fixup.getLoc(),
60 Msg: "unresolved relocation offset");
61 continue;
62 }
63 PendingFixup.Fixup.setOffset(PendingFixup.Sym->getOffset() +
64 PendingFixup.Fixup.getOffset());
65
66 // If the location symbol to relocate is in MCEncodedFragmentWithFixups,
67 // put the Fixup into location symbol's fragment. Otherwise
68 // put into PendingFixup.DF
69 MCFragment *SymFragment = PendingFixup.Sym->getFragment();
70 switch (SymFragment->getKind()) {
71 case MCFragment::FT_Relaxable:
72 case MCFragment::FT_Dwarf:
73 case MCFragment::FT_PseudoProbe:
74 cast<MCEncodedFragmentWithFixups<8, 1>>(Val: SymFragment)
75 ->getFixups()
76 .push_back(Elt: PendingFixup.Fixup);
77 break;
78 case MCFragment::FT_Data:
79 case MCFragment::FT_CVDefRange:
80 cast<MCEncodedFragmentWithFixups<32, 4>>(Val: SymFragment)
81 ->getFixups()
82 .push_back(Elt: PendingFixup.Fixup);
83 break;
84 default:
85 PendingFixup.DF->getFixups().push_back(Elt: PendingFixup.Fixup);
86 break;
87 }
88 }
89 PendingFixups.clear();
90}
91
92// As a compile-time optimization, avoid allocating and evaluating an MCExpr
93// tree for (Hi - Lo) when Hi and Lo are offsets into the same fragment.
94static std::optional<uint64_t> absoluteSymbolDiff(const MCSymbol *Hi,
95 const MCSymbol *Lo) {
96 assert(Hi && Lo);
97 if (!Hi->getFragment() || Hi->getFragment() != Lo->getFragment() ||
98 Hi->isVariable() || Lo->isVariable())
99 return std::nullopt;
100
101 return Hi->getOffset() - Lo->getOffset();
102}
103
104void MCObjectStreamer::emitAbsoluteSymbolDiff(const MCSymbol *Hi,
105 const MCSymbol *Lo,
106 unsigned Size) {
107 if (!getAssembler().getContext().getTargetTriple().isRISCV())
108 if (std::optional<uint64_t> Diff = absoluteSymbolDiff(Hi, Lo))
109 return emitIntValue(Value: *Diff, Size);
110 MCStreamer::emitAbsoluteSymbolDiff(Hi, Lo, Size);
111}
112
113void MCObjectStreamer::emitAbsoluteSymbolDiffAsULEB128(const MCSymbol *Hi,
114 const MCSymbol *Lo) {
115 if (!getAssembler().getContext().getTargetTriple().isRISCV())
116 if (std::optional<uint64_t> Diff = absoluteSymbolDiff(Hi, Lo)) {
117 emitULEB128IntValue(Value: *Diff);
118 return;
119 }
120 MCStreamer::emitAbsoluteSymbolDiffAsULEB128(Hi, Lo);
121}
122
123void MCObjectStreamer::reset() {
124 if (Assembler) {
125 Assembler->reset();
126 if (getContext().getTargetOptions())
127 Assembler->setRelaxAll(getContext().getTargetOptions()->MCRelaxAll);
128 }
129 EmitEHFrame = true;
130 EmitDebugFrame = false;
131 MCStreamer::reset();
132}
133
134void MCObjectStreamer::emitFrames(MCAsmBackend *MAB) {
135 if (!getNumFrameInfos())
136 return;
137
138 if (EmitEHFrame)
139 MCDwarfFrameEmitter::Emit(streamer&: *this, MAB, isEH: true);
140
141 if (EmitDebugFrame)
142 MCDwarfFrameEmitter::Emit(streamer&: *this, MAB, isEH: false);
143}
144
145static bool canReuseDataFragment(const MCDataFragment &F,
146 const MCAssembler &Assembler,
147 const MCSubtargetInfo *STI) {
148 if (!F.hasInstructions())
149 return true;
150 // Do not add data after a linker-relaxable instruction. The difference
151 // between a new label and a label at or before the linker-relaxable
152 // instruction cannot be resolved at assemble-time.
153 if (F.isLinkerRelaxable())
154 return false;
155 // When bundling is enabled, we don't want to add data to a fragment that
156 // already has instructions (see MCELFStreamer::emitInstToData for details)
157 if (Assembler.isBundlingEnabled())
158 return false;
159 // If the subtarget is changed mid fragment we start a new fragment to record
160 // the new STI.
161 return !STI || F.getSubtargetInfo() == STI;
162}
163
164MCDataFragment *
165MCObjectStreamer::getOrCreateDataFragment(const MCSubtargetInfo *STI) {
166 auto *F = dyn_cast<MCDataFragment>(Val: getCurrentFragment());
167 if (!F || !canReuseDataFragment(F: *F, Assembler: *Assembler, STI)) {
168 F = getContext().allocFragment<MCDataFragment>();
169 insert(F);
170 }
171 return F;
172}
173
174void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
175 Assembler->registerSymbol(Symbol: Sym);
176}
177
178void MCObjectStreamer::emitCFISections(bool EH, bool Debug) {
179 MCStreamer::emitCFISections(EH, Debug);
180 EmitEHFrame = EH;
181 EmitDebugFrame = Debug;
182}
183
184void MCObjectStreamer::emitValueImpl(const MCExpr *Value, unsigned Size,
185 SMLoc Loc) {
186 MCStreamer::emitValueImpl(Value, Size, Loc);
187 MCDataFragment *DF = getOrCreateDataFragment();
188
189 MCDwarfLineEntry::make(MCOS: this, Section: getCurrentSectionOnly());
190
191 // Avoid fixups when possible.
192 int64_t AbsValue;
193 if (Value->evaluateAsAbsolute(Res&: AbsValue, Asm: getAssemblerPtr())) {
194 if (!isUIntN(N: 8 * Size, x: AbsValue) && !isIntN(N: 8 * Size, x: AbsValue)) {
195 getContext().reportError(
196 L: Loc, Msg: "value evaluated as " + Twine(AbsValue) + " is out of range.");
197 return;
198 }
199 emitIntValue(Value: AbsValue, Size);
200 return;
201 }
202 DF->getFixups().push_back(
203 Elt: MCFixup::create(Offset: DF->getContents().size(), Value,
204 Kind: MCFixup::getKindForSize(Size, IsPCRel: false), Loc));
205 DF->getContents().resize(N: DF->getContents().size() + Size, NV: 0);
206}
207
208MCSymbol *MCObjectStreamer::emitCFILabel() {
209 MCSymbol *Label = getContext().createTempSymbol(Name: "cfi");
210 emitLabel(Symbol: Label);
211 return Label;
212}
213
214void MCObjectStreamer::emitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
215 // We need to create a local symbol to avoid relocations.
216 Frame.Begin = getContext().createTempSymbol();
217 emitLabel(Symbol: Frame.Begin);
218}
219
220void MCObjectStreamer::emitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
221 Frame.End = getContext().createTempSymbol();
222 emitLabel(Symbol: Frame.End);
223}
224
225void MCObjectStreamer::emitLabel(MCSymbol *Symbol, SMLoc Loc) {
226 MCStreamer::emitLabel(Symbol, Loc);
227
228 getAssembler().registerSymbol(Symbol: *Symbol);
229
230 // If there is a current fragment, mark the symbol as pointing into it.
231 // Otherwise queue the label and set its fragment pointer when we emit the
232 // next fragment.
233 MCDataFragment *F = getOrCreateDataFragment();
234 Symbol->setFragment(F);
235 Symbol->setOffset(F->getContents().size());
236
237 emitPendingAssignments(Symbol);
238}
239
240void MCObjectStreamer::emitPendingAssignments(MCSymbol *Symbol) {
241 auto Assignments = pendingAssignments.find(Val: Symbol);
242 if (Assignments != pendingAssignments.end()) {
243 for (const PendingAssignment &A : Assignments->second)
244 emitAssignment(Symbol: A.Symbol, Value: A.Value);
245
246 pendingAssignments.erase(I: Assignments);
247 }
248}
249
250// Emit a label at a previously emitted fragment/offset position. This must be
251// within the currently-active section.
252void MCObjectStreamer::emitLabelAtPos(MCSymbol *Symbol, SMLoc Loc,
253 MCDataFragment &F, uint64_t Offset) {
254 assert(F.getParent() == getCurrentSectionOnly());
255 MCStreamer::emitLabel(Symbol, Loc);
256 getAssembler().registerSymbol(Symbol: *Symbol);
257 Symbol->setFragment(&F);
258 Symbol->setOffset(Offset);
259}
260
261void MCObjectStreamer::emitULEB128Value(const MCExpr *Value) {
262 int64_t IntValue;
263 if (Value->evaluateAsAbsolute(Res&: IntValue, Asm: getAssemblerPtr())) {
264 emitULEB128IntValue(Value: IntValue);
265 return;
266 }
267 insert(F: getContext().allocFragment<MCLEBFragment>(args: *Value, args: false));
268}
269
270void MCObjectStreamer::emitSLEB128Value(const MCExpr *Value) {
271 int64_t IntValue;
272 if (Value->evaluateAsAbsolute(Res&: IntValue, Asm: getAssemblerPtr())) {
273 emitSLEB128IntValue(Value: IntValue);
274 return;
275 }
276 insert(F: getContext().allocFragment<MCLEBFragment>(args: *Value, args: true));
277}
278
279void MCObjectStreamer::emitWeakReference(MCSymbol *Alias,
280 const MCSymbol *Symbol) {
281 report_fatal_error(reason: "This file format doesn't support weak aliases.");
282}
283
284void MCObjectStreamer::changeSection(MCSection *Section, uint32_t Subsection) {
285 changeSectionImpl(Section, Subsection);
286}
287
288bool MCObjectStreamer::changeSectionImpl(MCSection *Section,
289 uint32_t Subsection) {
290 assert(Section && "Cannot switch to a null section!");
291 getContext().clearDwarfLocSeen();
292
293 auto &Subsections = Section->Subsections;
294 size_t I = 0, E = Subsections.size();
295 while (I != E && Subsections[I].first < Subsection)
296 ++I;
297 // If the subsection number is not in the sorted Subsections list, create a
298 // new fragment list.
299 if (I == E || Subsections[I].first != Subsection) {
300 auto *F = getContext().allocFragment<MCDataFragment>();
301 F->setParent(Section);
302 Subsections.insert(I: Subsections.begin() + I,
303 Elt: {Subsection, MCSection::FragList{.Head: F, .Tail: F}});
304 }
305 Section->CurFragList = &Subsections[I].second;
306 CurFrag = Section->CurFragList->Tail;
307
308 return getAssembler().registerSection(Section&: *Section);
309}
310
311void MCObjectStreamer::switchSectionNoPrint(MCSection *Section) {
312 MCStreamer::switchSectionNoPrint(Section);
313 changeSection(Section, Subsection: 0);
314}
315
316void MCObjectStreamer::emitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
317 getAssembler().registerSymbol(Symbol: *Symbol);
318 MCStreamer::emitAssignment(Symbol, Value);
319 emitPendingAssignments(Symbol);
320}
321
322void MCObjectStreamer::emitConditionalAssignment(MCSymbol *Symbol,
323 const MCExpr *Value) {
324 const MCSymbol *Target = &cast<MCSymbolRefExpr>(Val: *Value).getSymbol();
325
326 // If the symbol already exists, emit the assignment. Otherwise, emit it
327 // later only if the symbol is also emitted.
328 if (Target->isRegistered())
329 emitAssignment(Symbol, Value);
330 else
331 pendingAssignments[Target].push_back(Elt: {.Symbol: Symbol, .Value: Value});
332}
333
334bool MCObjectStreamer::mayHaveInstructions(MCSection &Sec) const {
335 return Sec.hasInstructions();
336}
337
338void MCObjectStreamer::emitInstruction(const MCInst &Inst,
339 const MCSubtargetInfo &STI) {
340 const MCSection &Sec = *getCurrentSectionOnly();
341 if (Sec.isVirtualSection()) {
342 getContext().reportError(L: Inst.getLoc(), Msg: Twine(Sec.getVirtualSectionKind()) +
343 " section '" + Sec.getName() +
344 "' cannot have instructions");
345 return;
346 }
347 emitInstructionImpl(Inst, STI);
348}
349
350void MCObjectStreamer::emitInstructionImpl(const MCInst &Inst,
351 const MCSubtargetInfo &STI) {
352 MCStreamer::emitInstruction(Inst, STI);
353
354 MCSection *Sec = getCurrentSectionOnly();
355 Sec->setHasInstructions(true);
356
357 // Now that a machine instruction has been assembled into this section, make
358 // a line entry for any .loc directive that has been seen.
359 MCDwarfLineEntry::make(MCOS: this, Section: getCurrentSectionOnly());
360
361 // If this instruction doesn't need relaxation, just emit it as data.
362 MCAssembler &Assembler = getAssembler();
363 MCAsmBackend &Backend = Assembler.getBackend();
364 if (!(Backend.mayNeedRelaxation(Inst, STI) ||
365 Backend.allowEnhancedRelaxation())) {
366 emitInstToData(Inst, STI);
367 return;
368 }
369
370 // Otherwise, relax and emit it as data if either:
371 // - The RelaxAll flag was passed
372 // - Bundling is enabled and this instruction is inside a bundle-locked
373 // group. We want to emit all such instructions into the same data
374 // fragment.
375 if (Assembler.getRelaxAll() ||
376 (Assembler.isBundlingEnabled() && Sec->isBundleLocked())) {
377 MCInst Relaxed = Inst;
378 while (Backend.mayNeedRelaxation(Inst: Relaxed, STI))
379 Backend.relaxInstruction(Inst&: Relaxed, STI);
380 emitInstToData(Inst: Relaxed, STI);
381 return;
382 }
383
384 // Otherwise emit to a separate fragment.
385 emitInstToFragment(Inst, STI);
386}
387
388void MCObjectStreamer::emitInstToFragment(const MCInst &Inst,
389 const MCSubtargetInfo &STI) {
390 // Always create a new, separate fragment here, because its size can change
391 // during relaxation.
392 MCRelaxableFragment *IF =
393 getContext().allocFragment<MCRelaxableFragment>(args: Inst, args: STI);
394 insert(F: IF);
395
396 getAssembler().getEmitter().encodeInstruction(Inst, CB&: IF->getContents(),
397 Fixups&: IF->getFixups(), STI);
398}
399
400#ifndef NDEBUG
401static const char *const BundlingNotImplementedMsg =
402 "Aligned bundling is not implemented for this object format";
403#endif
404
405void MCObjectStreamer::emitBundleAlignMode(Align Alignment) {
406 llvm_unreachable(BundlingNotImplementedMsg);
407}
408
409void MCObjectStreamer::emitBundleLock(bool AlignToEnd) {
410 llvm_unreachable(BundlingNotImplementedMsg);
411}
412
413void MCObjectStreamer::emitBundleUnlock() {
414 llvm_unreachable(BundlingNotImplementedMsg);
415}
416
417void MCObjectStreamer::emitDwarfLocDirective(unsigned FileNo, unsigned Line,
418 unsigned Column, unsigned Flags,
419 unsigned Isa,
420 unsigned Discriminator,
421 StringRef FileName) {
422 // In case we see two .loc directives in a row, make sure the
423 // first one gets a line entry.
424 MCDwarfLineEntry::make(MCOS: this, Section: getCurrentSectionOnly());
425
426 this->MCStreamer::emitDwarfLocDirective(FileNo, Line, Column, Flags, Isa,
427 Discriminator, FileName);
428}
429
430static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
431 const MCSymbol *B, SMLoc Loc) {
432 MCContext &Context = OS.getContext();
433 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
434 const MCExpr *ARef = MCSymbolRefExpr::create(Symbol: A, Kind: Variant, Ctx&: Context);
435 const MCExpr *BRef = MCSymbolRefExpr::create(Symbol: B, Kind: Variant, Ctx&: Context);
436 const MCExpr *AddrDelta =
437 MCBinaryExpr::create(Op: MCBinaryExpr::Sub, LHS: ARef, RHS: BRef, Ctx&: Context, Loc);
438 return AddrDelta;
439}
440
441static void emitDwarfSetLineAddr(MCObjectStreamer &OS,
442 MCDwarfLineTableParams Params,
443 int64_t LineDelta, const MCSymbol *Label,
444 int PointerSize) {
445 // emit the sequence to set the address
446 OS.emitIntValue(Value: dwarf::DW_LNS_extended_op, Size: 1);
447 OS.emitULEB128IntValue(Value: PointerSize + 1);
448 OS.emitIntValue(Value: dwarf::DW_LNE_set_address, Size: 1);
449 OS.emitSymbolValue(Sym: Label, Size: PointerSize);
450
451 // emit the sequence for the LineDelta (from 1) and a zero address delta.
452 MCDwarfLineAddr::Emit(MCOS: &OS, Params, LineDelta, AddrDelta: 0);
453}
454
455void MCObjectStreamer::emitDwarfAdvanceLineAddr(int64_t LineDelta,
456 const MCSymbol *LastLabel,
457 const MCSymbol *Label,
458 unsigned PointerSize) {
459 if (!LastLabel) {
460 emitDwarfSetLineAddr(OS&: *this, Params: Assembler->getDWARFLinetableParams(), LineDelta,
461 Label, PointerSize);
462 return;
463 }
464 const MCExpr *AddrDelta = buildSymbolDiff(OS&: *this, A: Label, B: LastLabel, Loc: SMLoc());
465 insert(F: getContext().allocFragment<MCDwarfLineAddrFragment>(args&: LineDelta,
466 args: *AddrDelta));
467}
468
469void MCObjectStreamer::emitDwarfLineEndEntry(MCSection *Section,
470 MCSymbol *LastLabel) {
471 // Emit a DW_LNE_end_sequence for the end of the section.
472 // Use the section end label to compute the address delta and use INT64_MAX
473 // as the line delta which is the signal that this is actually a
474 // DW_LNE_end_sequence.
475 MCSymbol *SectionEnd = endSection(Section);
476
477 // Switch back the dwarf line section, in case endSection had to switch the
478 // section.
479 MCContext &Ctx = getContext();
480 switchSection(Section: Ctx.getObjectFileInfo()->getDwarfLineSection());
481
482 const MCAsmInfo *AsmInfo = Ctx.getAsmInfo();
483 emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, Label: SectionEnd,
484 PointerSize: AsmInfo->getCodePointerSize());
485}
486
487void MCObjectStreamer::emitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
488 const MCSymbol *Label,
489 SMLoc Loc) {
490 const MCExpr *AddrDelta = buildSymbolDiff(OS&: *this, A: Label, B: LastLabel, Loc);
491 insert(F: getContext().allocFragment<MCDwarfCallFrameFragment>(args: *AddrDelta));
492}
493
494void MCObjectStreamer::emitCVLocDirective(unsigned FunctionId, unsigned FileNo,
495 unsigned Line, unsigned Column,
496 bool PrologueEnd, bool IsStmt,
497 StringRef FileName, SMLoc Loc) {
498 // Validate the directive.
499 if (!checkCVLocSection(FuncId: FunctionId, FileNo, Loc))
500 return;
501
502 // Emit a label at the current position and record it in the CodeViewContext.
503 MCSymbol *LineSym = getContext().createTempSymbol();
504 emitLabel(Symbol: LineSym);
505 getContext().getCVContext().recordCVLoc(Ctx&: getContext(), Label: LineSym, FunctionId,
506 FileNo, Line, Column, PrologueEnd,
507 IsStmt);
508}
509
510void MCObjectStreamer::emitCVLinetableDirective(unsigned FunctionId,
511 const MCSymbol *Begin,
512 const MCSymbol *End) {
513 getContext().getCVContext().emitLineTableForFunction(OS&: *this, FuncId: FunctionId, FuncBegin: Begin,
514 FuncEnd: End);
515 this->MCStreamer::emitCVLinetableDirective(FunctionId, FnStart: Begin, FnEnd: End);
516}
517
518void MCObjectStreamer::emitCVInlineLinetableDirective(
519 unsigned PrimaryFunctionId, unsigned SourceFileId, unsigned SourceLineNum,
520 const MCSymbol *FnStartSym, const MCSymbol *FnEndSym) {
521 getContext().getCVContext().emitInlineLineTableForFunction(
522 OS&: *this, PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym,
523 FnEndSym);
524 this->MCStreamer::emitCVInlineLinetableDirective(
525 PrimaryFunctionId, SourceFileId, SourceLineNum, FnStartSym, FnEndSym);
526}
527
528void MCObjectStreamer::emitCVDefRangeDirective(
529 ArrayRef<std::pair<const MCSymbol *, const MCSymbol *>> Ranges,
530 StringRef FixedSizePortion) {
531 getContext().getCVContext().emitDefRange(OS&: *this, Ranges, FixedSizePortion);
532 // Attach labels that were pending before we created the defrange fragment to
533 // the beginning of the new fragment.
534 this->MCStreamer::emitCVDefRangeDirective(Ranges, FixedSizePortion);
535}
536
537void MCObjectStreamer::emitCVStringTableDirective() {
538 getContext().getCVContext().emitStringTable(OS&: *this);
539}
540void MCObjectStreamer::emitCVFileChecksumsDirective() {
541 getContext().getCVContext().emitFileChecksums(OS&: *this);
542}
543
544void MCObjectStreamer::emitCVFileChecksumOffsetDirective(unsigned FileNo) {
545 getContext().getCVContext().emitFileChecksumOffset(OS&: *this, FileNo);
546}
547
548void MCObjectStreamer::emitBytes(StringRef Data) {
549 MCDwarfLineEntry::make(MCOS: this, Section: getCurrentSectionOnly());
550 MCDataFragment *DF = getOrCreateDataFragment();
551 DF->getContents().append(in_start: Data.begin(), in_end: Data.end());
552}
553
554void MCObjectStreamer::emitValueToAlignment(Align Alignment, int64_t Value,
555 unsigned ValueSize,
556 unsigned MaxBytesToEmit) {
557 if (MaxBytesToEmit == 0)
558 MaxBytesToEmit = Alignment.value();
559 insert(F: getContext().allocFragment<MCAlignFragment>(
560 args&: Alignment, args&: Value, args&: ValueSize, args&: MaxBytesToEmit));
561
562 // Update the maximum alignment on the current section if necessary.
563 MCSection *CurSec = getCurrentSectionOnly();
564 CurSec->ensureMinAlignment(MinAlignment: Alignment);
565}
566
567void MCObjectStreamer::emitCodeAlignment(Align Alignment,
568 const MCSubtargetInfo *STI,
569 unsigned MaxBytesToEmit) {
570 emitValueToAlignment(Alignment, Value: 0, ValueSize: 1, MaxBytesToEmit);
571 cast<MCAlignFragment>(Val: getCurrentFragment())->setEmitNops(Value: true, STI);
572}
573
574void MCObjectStreamer::emitValueToOffset(const MCExpr *Offset,
575 unsigned char Value,
576 SMLoc Loc) {
577 insert(F: getContext().allocFragment<MCOrgFragment>(args: *Offset, args&: Value, args&: Loc));
578}
579
580// Associate DTPRel32 fixup with data and resize data area
581void MCObjectStreamer::emitDTPRel32Value(const MCExpr *Value) {
582 MCDataFragment *DF = getOrCreateDataFragment();
583 DF->getFixups().push_back(Elt: MCFixup::create(Offset: DF->getContents().size(),
584 Value, Kind: FK_DTPRel_4));
585 DF->getContents().resize(N: DF->getContents().size() + 4, NV: 0);
586}
587
588// Associate DTPRel64 fixup with data and resize data area
589void MCObjectStreamer::emitDTPRel64Value(const MCExpr *Value) {
590 MCDataFragment *DF = getOrCreateDataFragment();
591 DF->getFixups().push_back(Elt: MCFixup::create(Offset: DF->getContents().size(),
592 Value, Kind: FK_DTPRel_8));
593 DF->getContents().resize(N: DF->getContents().size() + 8, NV: 0);
594}
595
596// Associate TPRel32 fixup with data and resize data area
597void MCObjectStreamer::emitTPRel32Value(const MCExpr *Value) {
598 MCDataFragment *DF = getOrCreateDataFragment();
599 DF->getFixups().push_back(Elt: MCFixup::create(Offset: DF->getContents().size(),
600 Value, Kind: FK_TPRel_4));
601 DF->getContents().resize(N: DF->getContents().size() + 4, NV: 0);
602}
603
604// Associate TPRel64 fixup with data and resize data area
605void MCObjectStreamer::emitTPRel64Value(const MCExpr *Value) {
606 MCDataFragment *DF = getOrCreateDataFragment();
607 DF->getFixups().push_back(Elt: MCFixup::create(Offset: DF->getContents().size(),
608 Value, Kind: FK_TPRel_8));
609 DF->getContents().resize(N: DF->getContents().size() + 8, NV: 0);
610}
611
612// Associate GPRel32 fixup with data and resize data area
613void MCObjectStreamer::emitGPRel32Value(const MCExpr *Value) {
614 MCDataFragment *DF = getOrCreateDataFragment();
615 DF->getFixups().push_back(
616 Elt: MCFixup::create(Offset: DF->getContents().size(), Value, Kind: FK_GPRel_4));
617 DF->getContents().resize(N: DF->getContents().size() + 4, NV: 0);
618}
619
620// Associate GPRel64 fixup with data and resize data area
621void MCObjectStreamer::emitGPRel64Value(const MCExpr *Value) {
622 MCDataFragment *DF = getOrCreateDataFragment();
623 DF->getFixups().push_back(
624 Elt: MCFixup::create(Offset: DF->getContents().size(), Value, Kind: FK_GPRel_4));
625 DF->getContents().resize(N: DF->getContents().size() + 8, NV: 0);
626}
627
628static std::optional<std::pair<bool, std::string>>
629getOffsetAndDataFragment(const MCSymbol &Symbol, uint32_t &RelocOffset,
630 MCDataFragment *&DF) {
631 if (Symbol.isVariable()) {
632 const MCExpr *SymbolExpr = Symbol.getVariableValue();
633 MCValue OffsetVal;
634 if(!SymbolExpr->evaluateAsRelocatable(Res&: OffsetVal, Asm: nullptr, Fixup: nullptr))
635 return std::make_pair(x: false,
636 y: std::string("symbol in .reloc offset is not "
637 "relocatable"));
638 if (OffsetVal.isAbsolute()) {
639 RelocOffset = OffsetVal.getConstant();
640 MCFragment *Fragment = Symbol.getFragment();
641 // FIXME Support symbols with no DF. For example:
642 // .reloc .data, ENUM_VALUE, <some expr>
643 if (!Fragment || Fragment->getKind() != MCFragment::FT_Data)
644 return std::make_pair(x: false,
645 y: std::string("symbol in offset has no data "
646 "fragment"));
647 DF = cast<MCDataFragment>(Val: Fragment);
648 return std::nullopt;
649 }
650
651 if (OffsetVal.getSymB())
652 return std::make_pair(x: false,
653 y: std::string(".reloc symbol offset is not "
654 "representable"));
655
656 const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(Val: *OffsetVal.getSymA());
657 if (!SRE.getSymbol().isDefined())
658 return std::make_pair(x: false,
659 y: std::string("symbol used in the .reloc offset is "
660 "not defined"));
661
662 if (SRE.getSymbol().isVariable())
663 return std::make_pair(x: false,
664 y: std::string("symbol used in the .reloc offset is "
665 "variable"));
666
667 MCFragment *Fragment = SRE.getSymbol().getFragment();
668 // FIXME Support symbols with no DF. For example:
669 // .reloc .data, ENUM_VALUE, <some expr>
670 if (!Fragment || Fragment->getKind() != MCFragment::FT_Data)
671 return std::make_pair(x: false,
672 y: std::string("symbol in offset has no data "
673 "fragment"));
674 RelocOffset = SRE.getSymbol().getOffset() + OffsetVal.getConstant();
675 DF = cast<MCDataFragment>(Val: Fragment);
676 } else {
677 RelocOffset = Symbol.getOffset();
678 MCFragment *Fragment = Symbol.getFragment();
679 // FIXME Support symbols with no DF. For example:
680 // .reloc .data, ENUM_VALUE, <some expr>
681 if (!Fragment || Fragment->getKind() != MCFragment::FT_Data)
682 return std::make_pair(x: false,
683 y: std::string("symbol in offset has no data "
684 "fragment"));
685 DF = cast<MCDataFragment>(Val: Fragment);
686 }
687 return std::nullopt;
688}
689
690std::optional<std::pair<bool, std::string>>
691MCObjectStreamer::emitRelocDirective(const MCExpr &Offset, StringRef Name,
692 const MCExpr *Expr, SMLoc Loc,
693 const MCSubtargetInfo &STI) {
694 std::optional<MCFixupKind> MaybeKind =
695 Assembler->getBackend().getFixupKind(Name);
696 if (!MaybeKind)
697 return std::make_pair(x: true, y: std::string("unknown relocation name"));
698
699 MCFixupKind Kind = *MaybeKind;
700 if (Expr)
701 visitUsedExpr(Expr: *Expr);
702 else
703 Expr =
704 MCSymbolRefExpr::create(Symbol: getContext().createTempSymbol(), Ctx&: getContext());
705
706 MCDataFragment *DF = getOrCreateDataFragment(STI: &STI);
707 MCValue OffsetVal;
708 if (!Offset.evaluateAsRelocatable(Res&: OffsetVal, Asm: nullptr, Fixup: nullptr))
709 return std::make_pair(x: false,
710 y: std::string(".reloc offset is not relocatable"));
711 if (OffsetVal.isAbsolute()) {
712 if (OffsetVal.getConstant() < 0)
713 return std::make_pair(x: false, y: std::string(".reloc offset is negative"));
714 DF->getFixups().push_back(
715 Elt: MCFixup::create(Offset: OffsetVal.getConstant(), Value: Expr, Kind, Loc));
716 return std::nullopt;
717 }
718 if (OffsetVal.getSymB())
719 return std::make_pair(x: false,
720 y: std::string(".reloc offset is not representable"));
721
722 const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(Val: *OffsetVal.getSymA());
723 const MCSymbol &Symbol = SRE.getSymbol();
724 if (Symbol.isDefined()) {
725 uint32_t SymbolOffset = 0;
726 std::optional<std::pair<bool, std::string>> Error =
727 getOffsetAndDataFragment(Symbol, RelocOffset&: SymbolOffset, DF);
728
729 if (Error != std::nullopt)
730 return Error;
731
732 DF->getFixups().push_back(
733 Elt: MCFixup::create(Offset: SymbolOffset + OffsetVal.getConstant(),
734 Value: Expr, Kind, Loc));
735 return std::nullopt;
736 }
737
738 PendingFixups.emplace_back(
739 Args: &SRE.getSymbol(), Args&: DF,
740 Args: MCFixup::create(Offset: OffsetVal.getConstant(), Value: Expr, Kind, Loc));
741 return std::nullopt;
742}
743
744void MCObjectStreamer::emitFill(const MCExpr &NumBytes, uint64_t FillValue,
745 SMLoc Loc) {
746 assert(getCurrentSectionOnly() && "need a section");
747 insert(
748 F: getContext().allocFragment<MCFillFragment>(args&: FillValue, args: 1, args: NumBytes, args&: Loc));
749}
750
751void MCObjectStreamer::emitFill(const MCExpr &NumValues, int64_t Size,
752 int64_t Expr, SMLoc Loc) {
753 int64_t IntNumValues;
754 // Do additional checking now if we can resolve the value.
755 if (NumValues.evaluateAsAbsolute(Res&: IntNumValues, Asm: getAssemblerPtr())) {
756 if (IntNumValues < 0) {
757 getContext().getSourceManager()->PrintMessage(
758 Loc, Kind: SourceMgr::DK_Warning,
759 Msg: "'.fill' directive with negative repeat count has no effect");
760 return;
761 }
762 // Emit now if we can for better errors.
763 int64_t NonZeroSize = Size > 4 ? 4 : Size;
764 Expr &= ~0ULL >> (64 - NonZeroSize * 8);
765 for (uint64_t i = 0, e = IntNumValues; i != e; ++i) {
766 emitIntValue(Value: Expr, Size: NonZeroSize);
767 if (NonZeroSize < Size)
768 emitIntValue(Value: 0, Size: Size - NonZeroSize);
769 }
770 return;
771 }
772
773 // Otherwise emit as fragment.
774 assert(getCurrentSectionOnly() && "need a section");
775 insert(
776 F: getContext().allocFragment<MCFillFragment>(args&: Expr, args&: Size, args: NumValues, args&: Loc));
777}
778
779void MCObjectStreamer::emitNops(int64_t NumBytes, int64_t ControlledNopLength,
780 SMLoc Loc, const MCSubtargetInfo &STI) {
781 assert(getCurrentSectionOnly() && "need a section");
782 insert(F: getContext().allocFragment<MCNopsFragment>(
783 args&: NumBytes, args&: ControlledNopLength, args&: Loc, args: STI));
784}
785
786void MCObjectStreamer::emitFileDirective(StringRef Filename) {
787 MCAssembler &Asm = getAssembler();
788 Asm.getWriter().addFileName(Asm, FileName: Filename);
789}
790
791void MCObjectStreamer::emitFileDirective(StringRef Filename,
792 StringRef CompilerVersion,
793 StringRef TimeStamp,
794 StringRef Description) {
795 MCObjectWriter &W = getAssembler().getWriter();
796 W.addFileName(Asm&: getAssembler(), FileName: Filename);
797 if (CompilerVersion.size())
798 W.setCompilerVersion(CompilerVersion);
799 // TODO: add TimeStamp and Description to .file symbol table entry
800 // with the integrated assembler.
801}
802
803void MCObjectStreamer::emitAddrsig() {
804 getAssembler().getWriter().emitAddrsigSection();
805}
806
807void MCObjectStreamer::emitAddrsigSym(const MCSymbol *Sym) {
808 getAssembler().getWriter().addAddrsigSymbol(Sym);
809}
810
811void MCObjectStreamer::finishImpl() {
812 getContext().RemapDebugPaths();
813
814 // If we are generating dwarf for assembly source files dump out the sections.
815 if (getContext().getGenDwarfForAssembly())
816 MCGenDwarfInfo::Emit(MCOS: this);
817
818 // Dump out the dwarf file & directory tables and line tables.
819 MCDwarfLineTable::emit(MCOS: this, Params: getAssembler().getDWARFLinetableParams());
820
821 // Emit pseudo probes for the current module.
822 MCPseudoProbeTable::emit(MCOS: this);
823
824 resolvePendingFixups();
825 getAssembler().Finish();
826}
827