1 //===- lib/MC/MCObjectStreamer.cpp - Object File MCStreamer Interface -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
26 MCObjectStreamer::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), OS)),
32 EmitEHFrame(true), EmitDebugFrame(false) {}
34 MCObjectStreamer::~MCObjectStreamer() {
35 delete &Assembler->getBackend();
36 delete &Assembler->getEmitter();
37 delete &Assembler->getWriter();
41 void MCObjectStreamer::flushPendingLabels(MCFragment *F, uint64_t FOffset) {
42 if (PendingLabels.size()) {
44 F = new MCDataFragment();
45 MCSection *CurSection = getCurrentSectionOnly();
46 CurSection->getFragmentList().insert(CurInsertionPoint, F);
47 F->setParent(CurSection);
49 for (MCSymbol *Sym : PendingLabels) {
50 MCSymbolData *SD = &Sym->getData();
52 Sym->setOffset(FOffset);
54 PendingLabels.clear();
58 bool MCObjectStreamer::emitAbsoluteSymbolDiff(const MCSymbol *Hi,
61 // Must have symbol data.
62 if (!Assembler->hasSymbolData(*Hi) || !Assembler->hasSymbolData(*Lo))
64 auto &HiD = Hi->getData();
65 auto &LoD = Lo->getData();
67 // Must both be assigned to the same (valid) fragment.
68 if (!HiD.getFragment() || HiD.getFragment() != LoD.getFragment())
71 // Must be a data fragment.
72 if (!isa<MCDataFragment>(HiD.getFragment()))
75 assert(Hi->getOffset() >= Lo->getOffset() &&
76 "Expected Hi to be greater than Lo");
77 EmitIntValue(Hi->getOffset() - Lo->getOffset(), Size);
81 void MCObjectStreamer::reset() {
84 CurInsertionPoint = MCSection::iterator();
86 EmitDebugFrame = false;
87 PendingLabels.clear();
91 void MCObjectStreamer::EmitFrames(MCAsmBackend *MAB) {
92 if (!getNumFrameInfos())
96 MCDwarfFrameEmitter::Emit(*this, MAB, true);
99 MCDwarfFrameEmitter::Emit(*this, MAB, false);
102 MCFragment *MCObjectStreamer::getCurrentFragment() const {
103 assert(getCurrentSectionOnly() && "No current section!");
105 if (CurInsertionPoint != getCurrentSectionOnly()->getFragmentList().begin())
106 return std::prev(CurInsertionPoint);
111 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() {
112 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
113 // When bundling is enabled, we don't want to add data to a fragment that
114 // already has instructions (see MCELFStreamer::EmitInstToData for details)
115 if (!F || (Assembler->isBundlingEnabled() && !Assembler->getRelaxAll() &&
116 F->hasInstructions())) {
117 F = new MCDataFragment();
123 void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
124 Assembler->registerSymbol(Sym);
127 void MCObjectStreamer::EmitCFISections(bool EH, bool Debug) {
128 MCStreamer::EmitCFISections(EH, Debug);
130 EmitDebugFrame = Debug;
133 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
135 MCStreamer::EmitValueImpl(Value, Size, Loc);
136 MCDataFragment *DF = getOrCreateDataFragment();
138 MCLineEntry::Make(this, getCurrentSection().first);
140 // Avoid fixups when possible.
142 if (Value->EvaluateAsAbsolute(AbsValue, getAssembler())) {
143 EmitIntValue(AbsValue, Size);
146 DF->getFixups().push_back(
147 MCFixup::create(DF->getContents().size(), Value,
148 MCFixup::getKindForSize(Size, false), Loc));
149 DF->getContents().resize(DF->getContents().size() + Size, 0);
152 void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
153 // We need to create a local symbol to avoid relocations.
154 Frame.Begin = getContext().createTempSymbol();
155 EmitLabel(Frame.Begin);
158 void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
159 Frame.End = getContext().createTempSymbol();
160 EmitLabel(Frame.End);
163 void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
164 MCStreamer::EmitLabel(Symbol);
166 getAssembler().registerSymbol(*Symbol);
167 MCSymbolData &SD = Symbol->getData();
168 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
170 // If there is a current fragment, mark the symbol as pointing into it.
171 // Otherwise queue the label and set its fragment pointer when we emit the
173 auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
174 if (F && !(getAssembler().isBundlingEnabled() &&
175 getAssembler().getRelaxAll())) {
177 Symbol->setOffset(F->getContents().size());
179 PendingLabels.push_back(Symbol);
183 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
185 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
186 EmitULEB128IntValue(IntValue);
189 insert(new MCLEBFragment(*Value, false));
192 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
194 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
195 EmitSLEB128IntValue(IntValue);
198 insert(new MCLEBFragment(*Value, true));
201 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
202 const MCSymbol *Symbol) {
203 report_fatal_error("This file format doesn't support weak aliases.");
206 void MCObjectStreamer::ChangeSection(MCSection *Section,
207 const MCExpr *Subsection) {
208 changeSectionImpl(Section, Subsection);
211 bool MCObjectStreamer::changeSectionImpl(MCSection *Section,
212 const MCExpr *Subsection) {
213 assert(Section && "Cannot switch to a null section!");
214 flushPendingLabels(nullptr);
216 bool Created = getAssembler().registerSection(*Section);
218 int64_t IntSubsection = 0;
220 !Subsection->EvaluateAsAbsolute(IntSubsection, getAssembler()))
221 report_fatal_error("Cannot evaluate subsection number");
222 if (IntSubsection < 0 || IntSubsection > 8192)
223 report_fatal_error("Subsection number out of range");
225 Section->getSubsectionInsertionPoint(unsigned(IntSubsection));
229 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
230 getAssembler().registerSymbol(*Symbol);
231 MCStreamer::EmitAssignment(Symbol, Value);
234 bool MCObjectStreamer::mayHaveInstructions(MCSection &Sec) const {
235 return Sec.hasInstructions();
238 void MCObjectStreamer::EmitInstruction(const MCInst &Inst,
239 const MCSubtargetInfo &STI) {
240 MCStreamer::EmitInstruction(Inst, STI);
242 MCSection *Sec = getCurrentSectionOnly();
243 Sec->setHasInstructions(true);
245 // Now that a machine instruction has been assembled into this section, make
246 // a line entry for any .loc directive that has been seen.
247 MCLineEntry::Make(this, getCurrentSection().first);
249 // If this instruction doesn't need relaxation, just emit it as data.
250 MCAssembler &Assembler = getAssembler();
251 if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
252 EmitInstToData(Inst, STI);
256 // Otherwise, relax and emit it as data if either:
257 // - The RelaxAll flag was passed
258 // - Bundling is enabled and this instruction is inside a bundle-locked
259 // group. We want to emit all such instructions into the same data
261 if (Assembler.getRelaxAll() ||
262 (Assembler.isBundlingEnabled() && Sec->isBundleLocked())) {
264 getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
265 while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
266 getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
267 EmitInstToData(Relaxed, STI);
271 // Otherwise emit to a separate fragment.
272 EmitInstToFragment(Inst, STI);
275 void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst,
276 const MCSubtargetInfo &STI) {
277 if (getAssembler().getRelaxAll() && getAssembler().isBundlingEnabled())
278 llvm_unreachable("All instructions should have already been relaxed");
280 // Always create a new, separate fragment here, because its size can change
281 // during relaxation.
282 MCRelaxableFragment *IF = new MCRelaxableFragment(Inst, STI);
285 SmallString<128> Code;
286 raw_svector_ostream VecOS(Code);
287 getAssembler().getEmitter().encodeInstruction(Inst, VecOS, IF->getFixups(),
290 IF->getContents().append(Code.begin(), Code.end());
294 static const char *const BundlingNotImplementedMsg =
295 "Aligned bundling is not implemented for this object format";
298 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
299 llvm_unreachable(BundlingNotImplementedMsg);
302 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
303 llvm_unreachable(BundlingNotImplementedMsg);
306 void MCObjectStreamer::EmitBundleUnlock() {
307 llvm_unreachable(BundlingNotImplementedMsg);
310 void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
311 unsigned Column, unsigned Flags,
313 unsigned Discriminator,
314 StringRef FileName) {
315 // In case we see two .loc directives in a row, make sure the
316 // first one gets a line entry.
317 MCLineEntry::Make(this, getCurrentSection().first);
319 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
320 Isa, Discriminator, FileName);
323 static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
325 MCContext &Context = OS.getContext();
326 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
327 const MCExpr *ARef = MCSymbolRefExpr::Create(A, Variant, Context);
328 const MCExpr *BRef = MCSymbolRefExpr::Create(B, Variant, Context);
329 const MCExpr *AddrDelta =
330 MCBinaryExpr::Create(MCBinaryExpr::Sub, ARef, BRef, Context);
334 static void emitDwarfSetLineAddr(MCObjectStreamer &OS, int64_t LineDelta,
335 const MCSymbol *Label, int PointerSize) {
336 // emit the sequence to set the address
337 OS.EmitIntValue(dwarf::DW_LNS_extended_op, 1);
338 OS.EmitULEB128IntValue(PointerSize + 1);
339 OS.EmitIntValue(dwarf::DW_LNE_set_address, 1);
340 OS.EmitSymbolValue(Label, PointerSize);
342 // emit the sequence for the LineDelta (from 1) and a zero address delta.
343 MCDwarfLineAddr::Emit(&OS, LineDelta, 0);
346 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
347 const MCSymbol *LastLabel,
348 const MCSymbol *Label,
349 unsigned PointerSize) {
351 emitDwarfSetLineAddr(*this, LineDelta, Label, PointerSize);
354 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
356 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
357 MCDwarfLineAddr::Emit(this, LineDelta, Res);
360 insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
363 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
364 const MCSymbol *Label) {
365 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
367 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
368 MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
371 insert(new MCDwarfCallFrameFragment(*AddrDelta));
374 void MCObjectStreamer::EmitBytes(StringRef Data) {
375 MCLineEntry::Make(this, getCurrentSection().first);
376 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
379 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
382 unsigned MaxBytesToEmit) {
383 if (MaxBytesToEmit == 0)
384 MaxBytesToEmit = ByteAlignment;
385 insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
387 // Update the maximum alignment on the current section if necessary.
388 MCSection *CurSec = getCurrentSection().first;
389 if (ByteAlignment > CurSec->getAlignment())
390 CurSec->setAlignment(ByteAlignment);
393 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
394 unsigned MaxBytesToEmit) {
395 EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
396 cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
399 bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
400 unsigned char Value) {
402 if (Offset->EvaluateAsAbsolute(Res, getAssembler())) {
403 insert(new MCOrgFragment(*Offset, Value));
407 MCSymbol *CurrentPos = getContext().createTempSymbol();
408 EmitLabel(CurrentPos);
409 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
411 MCSymbolRefExpr::Create(CurrentPos, Variant, getContext());
412 const MCExpr *Delta =
413 MCBinaryExpr::Create(MCBinaryExpr::Sub, Offset, Ref, getContext());
415 if (!Delta->EvaluateAsAbsolute(Res, getAssembler()))
417 EmitFill(Res, Value);
421 // Associate GPRel32 fixup with data and resize data area
422 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
423 MCDataFragment *DF = getOrCreateDataFragment();
425 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
427 DF->getContents().resize(DF->getContents().size() + 4, 0);
430 // Associate GPRel32 fixup with data and resize data area
431 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
432 MCDataFragment *DF = getOrCreateDataFragment();
434 DF->getFixups().push_back(MCFixup::create(DF->getContents().size(),
436 DF->getContents().resize(DF->getContents().size() + 8, 0);
439 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
440 // FIXME: A MCFillFragment would be more memory efficient but MCExpr has
441 // problems evaluating expressions across multiple fragments.
442 getOrCreateDataFragment()->getContents().append(NumBytes, FillValue);
445 void MCObjectStreamer::EmitZeros(uint64_t NumBytes) {
446 const MCSection *Sec = getCurrentSection().first;
447 assert(Sec && "need a section");
448 unsigned ItemSize = Sec->isVirtualSection() ? 0 : 1;
449 insert(new MCFillFragment(0, ItemSize, NumBytes));
452 void MCObjectStreamer::FinishImpl() {
453 // If we are generating dwarf for assembly source files dump out the sections.
454 if (getContext().getGenDwarfForAssembly())
455 MCGenDwarfInfo::Emit(this);
457 // Dump out the dwarf file & directory tables and line tables.
458 MCDwarfLineTable::Emit(this);
460 flushPendingLabels(nullptr);
461 getAssembler().Finish();