1//===- lib/MC/MCObjectStreamer.cpp - Object File MCStreamer Interface -----===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/MC/MCObjectStreamer.h"
11#include "llvm/ADT/STLExtras.h"
12#include "llvm/MC/MCAsmBackend.h"
13#include "llvm/MC/MCAsmInfo.h"
14#include "llvm/MC/MCAssembler.h"
15#include "llvm/MC/MCCodeEmitter.h"
16#include "llvm/MC/MCContext.h"
17#include "llvm/MC/MCDwarf.h"
18#include "llvm/MC/MCExpr.h"
19#include "llvm/MC/MCObjectWriter.h"
20#include "llvm/MC/MCSection.h"
21#include "llvm/MC/MCSymbol.h"
22#include "llvm/Support/ErrorHandling.h"
23#include "llvm/Support/TargetRegistry.h"
24using namespace llvm;
25
26MCObjectStreamer::MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB,
27                                   raw_pwrite_stream &OS,
28                                   MCCodeEmitter *Emitter_)
29    : MCStreamer(Context),
30      Assembler(new MCAssembler(Context, TAB, *Emitter_,
31                                *TAB.createObjectWriter(OS))),
32      EmitEHFrame(true), EmitDebugFrame(false) {}
33
34MCObjectStreamer::~MCObjectStreamer() {
35  delete &Assembler->getBackend();
36  delete &Assembler->getEmitter();
37  delete &Assembler->getWriter();
38  delete Assembler;
39}
40
41void MCObjectStreamer::flushPendingLabels(MCFragment *F, uint64_t FOffset) {
42  if (PendingLabels.empty())
43    return;
44  if (!F) {
45    F = new MCDataFragment();
46    MCSection *CurSection = getCurrentSectionOnly();
47    CurSection->getFragmentList().insert(CurInsertionPoint, F);
48    F->setParent(CurSection);
49  }
50  for (MCSymbol *Sym : PendingLabels) {
51    Sym->setFragment(F);
52    Sym->setOffset(FOffset);
53  }
54  PendingLabels.clear();
55}
56
57void MCObjectStreamer::emitAbsoluteSymbolDiff(const MCSymbol *Hi,
58                                              const MCSymbol *Lo,
59                                              unsigned Size) {
60  // If not assigned to the same (valid) fragment, fallback.
61  if (!Hi->getFragment() || Hi->getFragment() != Lo->getFragment() ||
62      Hi->isVariable() || Lo->isVariable()) {
63    MCStreamer::emitAbsoluteSymbolDiff(Hi, Lo, Size);
64    return;
65  }
66
67  EmitIntValue(Hi->getOffset() - Lo->getOffset(), Size);
68}
69
70void MCObjectStreamer::reset() {
71  if (Assembler)
72    Assembler->reset();
73  CurInsertionPoint = MCSection::iterator();
74  EmitEHFrame = true;
75  EmitDebugFrame = false;
76  PendingLabels.clear();
77  MCStreamer::reset();
78}
79
80void MCObjectStreamer::EmitFrames(MCAsmBackend *MAB) {
81  if (!getNumFrameInfos())
82    return;
83
84  if (EmitEHFrame)
85    MCDwarfFrameEmitter::Emit(*this, MAB, true);
86
87  if (EmitDebugFrame)
88    MCDwarfFrameEmitter::Emit(*this, MAB, false);
89}
90
91MCFragment *MCObjectStreamer::getCurrentFragment() const {
92  assert(getCurrentSectionOnly() && "No current section!");
93
94  if (CurInsertionPoint != getCurrentSectionOnly()->getFragmentList().begin())
95    return &*std::prev(CurInsertionPoint);
96
97  return nullptr;
98}
99
100MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() {
101  MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
102  // When bundling is enabled, we don't want to add data to a fragment that
103  // already has instructions (see MCELFStreamer::EmitInstToData for details)
104  if (!F || (Assembler->isBundlingEnabled() && !Assembler->getRelaxAll() &&
105             F->hasInstructions())) {
106    F = new MCDataFragment();
107    insert(F);
108  }
109  return F;
110}
111
112void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
113  Assembler->registerSymbol(Sym);
114}
115
116void MCObjectStreamer::EmitCFISections(bool EH, bool Debug) {
117  MCStreamer::EmitCFISections(EH, Debug);
118  EmitEHFrame = EH;
119  EmitDebugFrame = Debug;
120}
121
122void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
123                                     SMLoc Loc) {
124  MCStreamer::EmitValueImpl(Value, Size, Loc);
125  MCDataFragment *DF = getOrCreateDataFragment();
126  flushPendingLabels(DF, DF->getContents().size());
127
128  MCLineEntry::Make(this, getCurrentSection().first);
129
130  // Avoid fixups when possible.
131  int64_t AbsValue;
132  if (Value->evaluateAsAbsolute(AbsValue, getAssembler())) {
133    EmitIntValue(AbsValue, Size);
134    return;
135  }
136  DF->getFixups().push_back(
137      MCFixup::create(DF->getContents().size(), Value,
138                      MCFixup::getKindForSize(Size, false), Loc));
139  DF->getContents().resize(DF->getContents().size() + Size, 0);
140}
141
142void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
143  // We need to create a local symbol to avoid relocations.
144  Frame.Begin = getContext().createTempSymbol();
145  EmitLabel(Frame.Begin);
146}
147
148void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
149  Frame.End = getContext().createTempSymbol();
150  EmitLabel(Frame.End);
151}
152
153void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
154  MCStreamer::EmitLabel(Symbol);
155
156  getAssembler().registerSymbol(*Symbol);
157
158  // If there is a current fragment, mark the symbol as pointing into it.
159  // Otherwise queue the label and set its fragment pointer when we emit the
160  // next fragment.
161  auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
162  if (F && !(getAssembler().isBundlingEnabled() &&
163             getAssembler().getRelaxAll())) {
164    Symbol->setFragment(F);
165    Symbol->setOffset(F->getContents().size());
166  } else {
167    PendingLabels.push_back(Symbol);
168  }
169}
170
171void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
172  int64_t IntValue;
173  if (Value->evaluateAsAbsolute(IntValue, getAssembler())) {
174    EmitULEB128IntValue(IntValue);
175    return;
176  }
177  insert(new MCLEBFragment(*Value, false));
178}
179
180void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
181  int64_t IntValue;
182  if (Value->evaluateAsAbsolute(IntValue, getAssembler())) {
183    EmitSLEB128IntValue(IntValue);
184    return;
185  }
186  insert(new MCLEBFragment(*Value, true));
187}
188
189void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
190                                         const MCSymbol *Symbol) {
191  report_fatal_error("This file format doesn't support weak aliases.");
192}
193
194void MCObjectStreamer::ChangeSection(MCSection *Section,
195                                     const MCExpr *Subsection) {
196  changeSectionImpl(Section, Subsection);
197}
198
199bool MCObjectStreamer::changeSectionImpl(MCSection *Section,
200                                         const MCExpr *Subsection) {
201  assert(Section && "Cannot switch to a null section!");
202  flushPendingLabels(nullptr);
203
204  bool Created = getAssembler().registerSection(*Section);
205
206  int64_t IntSubsection = 0;
207  if (Subsection &&
208      !Subsection->evaluateAsAbsolute(IntSubsection, getAssembler()))
209    report_fatal_error("Cannot evaluate subsection number");
210  if (IntSubsection < 0 || IntSubsection > 8192)
211    report_fatal_error("Subsection number out of range");
212  CurInsertionPoint =
213      Section->getSubsectionInsertionPoint(unsigned(IntSubsection));
214  return Created;
215}
216
217void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
218  getAssembler().registerSymbol(*Symbol);
219  MCStreamer::EmitAssignment(Symbol, Value);
220}
221
222bool MCObjectStreamer::mayHaveInstructions(MCSection &Sec) const {
223  return Sec.hasInstructions();
224}
225
226void MCObjectStreamer::EmitInstruction(const MCInst &Inst,
227                                       const MCSubtargetInfo &STI) {
228  MCStreamer::EmitInstruction(Inst, STI);
229
230  MCSection *Sec = getCurrentSectionOnly();
231  Sec->setHasInstructions(true);
232
233  // Now that a machine instruction has been assembled into this section, make
234  // a line entry for any .loc directive that has been seen.
235  MCLineEntry::Make(this, getCurrentSection().first);
236
237  // If this instruction doesn't need relaxation, just emit it as data.
238  MCAssembler &Assembler = getAssembler();
239  if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
240    EmitInstToData(Inst, STI);
241    return;
242  }
243
244  // Otherwise, relax and emit it as data if either:
245  // - The RelaxAll flag was passed
246  // - Bundling is enabled and this instruction is inside a bundle-locked
247  //   group. We want to emit all such instructions into the same data
248  //   fragment.
249  if (Assembler.getRelaxAll() ||
250      (Assembler.isBundlingEnabled() && Sec->isBundleLocked())) {
251    MCInst Relaxed;
252    getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
253    while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
254      getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
255    EmitInstToData(Relaxed, STI);
256    return;
257  }
258
259  // Otherwise emit to a separate fragment.
260  EmitInstToFragment(Inst, STI);
261}
262
263void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst,
264                                          const MCSubtargetInfo &STI) {
265  if (getAssembler().getRelaxAll() && getAssembler().isBundlingEnabled())
266    llvm_unreachable("All instructions should have already been relaxed");
267
268  // Always create a new, separate fragment here, because its size can change
269  // during relaxation.
270  MCRelaxableFragment *IF = new MCRelaxableFragment(Inst, STI);
271  insert(IF);
272
273  SmallString<128> Code;
274  raw_svector_ostream VecOS(Code);
275  getAssembler().getEmitter().encodeInstruction(Inst, VecOS, IF->getFixups(),
276                                                STI);
277  IF->getContents().append(Code.begin(), Code.end());
278}
279
280#ifndef NDEBUG
281static const char *const BundlingNotImplementedMsg =
282  "Aligned bundling is not implemented for this object format";
283#endif
284
285void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
286  llvm_unreachable(BundlingNotImplementedMsg);
287}
288
289void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
290  llvm_unreachable(BundlingNotImplementedMsg);
291}
292
293void MCObjectStreamer::EmitBundleUnlock() {
294  llvm_unreachable(BundlingNotImplementedMsg);
295}
296
297void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
298                                             unsigned Column, unsigned Flags,
299                                             unsigned Isa,
300                                             unsigned Discriminator,
301                                             StringRef FileName) {
302  // In case we see two .loc directives in a row, make sure the
303  // first one gets a line entry.
304  MCLineEntry::Make(this, getCurrentSection().first);
305
306  this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
307                                          Isa, Discriminator, FileName);
308}
309
310static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
311                                     const MCSymbol *B) {
312  MCContext &Context = OS.getContext();
313  MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
314  const MCExpr *ARef = MCSymbolRefExpr::create(A, Variant, Context);
315  const MCExpr *BRef = MCSymbolRefExpr::create(B, Variant, Context);
316  const MCExpr *AddrDelta =
317      MCBinaryExpr::create(MCBinaryExpr::Sub, ARef, BRef, Context);
318  return AddrDelta;
319}
320
321static void emitDwarfSetLineAddr(MCObjectStreamer &OS,
322                                 MCDwarfLineTableParams Params,
323                                 int64_t LineDelta, const MCSymbol *Label,
324                                 int PointerSize) {
325  // emit the sequence to set the address
326  OS.EmitIntValue(dwarf::DW_LNS_extended_op, 1);
327  OS.EmitULEB128IntValue(PointerSize + 1);
328  OS.EmitIntValue(dwarf::DW_LNE_set_address, 1);
329  OS.EmitSymbolValue(Label, PointerSize);
330
331  // emit the sequence for the LineDelta (from 1) and a zero address delta.
332  MCDwarfLineAddr::Emit(&OS, Params, LineDelta, 0);
333}
334
335void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
336                                                const MCSymbol *LastLabel,
337                                                const MCSymbol *Label,
338                                                unsigned PointerSize) {
339  if (!LastLabel) {
340    emitDwarfSetLineAddr(*this, Assembler->getDWARFLinetableParams(), LineDelta,
341                         Label, PointerSize);
342    return;
343  }
344  const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
345  int64_t Res;
346  if (AddrDelta->evaluateAsAbsolute(Res, getAssembler())) {
347    MCDwarfLineAddr::Emit(this, Assembler->getDWARFLinetableParams(), LineDelta,
348                          Res);
349    return;
350  }
351  insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
352}
353
354void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
355                                                 const MCSymbol *Label) {
356  const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
357  int64_t Res;
358  if (AddrDelta->evaluateAsAbsolute(Res, getAssembler())) {
359    MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
360    return;
361  }
362  insert(new MCDwarfCallFrameFragment(*AddrDelta));
363}
364
365void MCObjectStreamer::EmitBytes(StringRef Data) {
366  MCLineEntry::Make(this, getCurrentSection().first);
367  MCDataFragment *DF = getOrCreateDataFragment();
368  flushPendingLabels(DF, DF->getContents().size());
369  DF->getContents().append(Data.begin(), Data.end());
370}
371
372void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
373                                            int64_t Value,
374                                            unsigned ValueSize,
375                                            unsigned MaxBytesToEmit) {
376  if (MaxBytesToEmit == 0)
377    MaxBytesToEmit = ByteAlignment;
378  insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
379
380  // Update the maximum alignment on the current section if necessary.
381  MCSection *CurSec = getCurrentSection().first;
382  if (ByteAlignment > CurSec->getAlignment())
383    CurSec->setAlignment(ByteAlignment);
384}
385
386void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
387                                         unsigned MaxBytesToEmit) {
388  EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
389  cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
390}
391
392void MCObjectStreamer::emitValueToOffset(const MCExpr *Offset,
393                                         unsigned char Value) {
394  insert(new MCOrgFragment(*Offset, Value));
395}
396
397// Associate GPRel32 fixup with data and resize data area
398void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
399  MCDataFragment *DF = getOrCreateDataFragment();
400  flushPendingLabels(DF, DF->getContents().size());
401
402  DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
403                                            Value, FK_GPRel_4));
404  DF->getContents().resize(DF->getContents().size() + 4, 0);
405}
406
407// Associate GPRel32 fixup with data and resize data area
408void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
409  MCDataFragment *DF = getOrCreateDataFragment();
410  flushPendingLabels(DF, DF->getContents().size());
411
412  DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
413                                            Value, FK_GPRel_4));
414  DF->getContents().resize(DF->getContents().size() + 8, 0);
415}
416
417bool MCObjectStreamer::EmitRelocDirective(const MCExpr &Offset, StringRef Name,
418                                          const MCExpr *Expr, SMLoc Loc) {
419  int64_t OffsetValue;
420  if (!Offset.evaluateAsAbsolute(OffsetValue))
421    llvm_unreachable("Offset is not absolute");
422
423  MCDataFragment *DF = getOrCreateDataFragment();
424  flushPendingLabels(DF, DF->getContents().size());
425
426  MCFixupKind Kind;
427  if (!Assembler->getBackend().getFixupKind(Name, Kind))
428    return true;
429
430  if (Expr == nullptr)
431    Expr =
432        MCSymbolRefExpr::create(getContext().createTempSymbol(), getContext());
433  DF->getFixups().push_back(MCFixup::create(OffsetValue, Expr, Kind, Loc));
434  return false;
435}
436
437void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
438  const MCSection *Sec = getCurrentSection().first;
439  assert(Sec && "need a section");
440  unsigned ItemSize = Sec->isVirtualSection() ? 0 : 1;
441  insert(new MCFillFragment(FillValue, ItemSize, NumBytes));
442}
443
444void MCObjectStreamer::FinishImpl() {
445  // If we are generating dwarf for assembly source files dump out the sections.
446  if (getContext().getGenDwarfForAssembly())
447    MCGenDwarfInfo::Emit(this);
448
449  // Dump out the dwarf file & directory tables and line tables.
450  MCDwarfLineTable::Emit(this, getAssembler().getDWARFLinetableParams());
451
452  flushPendingLabels(nullptr);
453  getAssembler().Finish();
454}
455