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