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