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_ostream &OS, MCCodeEmitter *Emitter_)
28 : MCStreamer(Context),
29 Assembler(new MCAssembler(Context, TAB, *Emitter_,
30 *TAB.createObjectWriter(OS), OS)),
31 CurSectionData(nullptr), EmitEHFrame(true), EmitDebugFrame(false) {}
33 MCObjectStreamer::~MCObjectStreamer() {
34 delete &Assembler->getBackend();
35 delete &Assembler->getEmitter();
36 delete &Assembler->getWriter();
40 void MCObjectStreamer::flushPendingLabels(MCFragment *F, uint64_t FOffset) {
41 if (PendingLabels.size()) {
43 F = new MCDataFragment();
44 CurSectionData->getFragmentList().insert(CurInsertionPoint, F);
45 F->setParent(CurSectionData);
47 for (MCSymbolData *SD : PendingLabels) {
49 SD->setOffset(FOffset);
51 PendingLabels.clear();
55 void MCObjectStreamer::reset() {
58 CurSectionData = nullptr;
59 CurInsertionPoint = MCSectionData::iterator();
61 EmitDebugFrame = false;
62 PendingLabels.clear();
66 void MCObjectStreamer::EmitFrames(MCAsmBackend *MAB) {
67 if (!getNumFrameInfos())
71 MCDwarfFrameEmitter::Emit(*this, MAB, true);
74 MCDwarfFrameEmitter::Emit(*this, MAB, false);
77 MCFragment *MCObjectStreamer::getCurrentFragment() const {
78 assert(getCurrentSectionData() && "No current section!");
80 if (CurInsertionPoint != getCurrentSectionData()->getFragmentList().begin())
81 return std::prev(CurInsertionPoint);
86 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() {
87 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
88 // When bundling is enabled, we don't want to add data to a fragment that
89 // already has instructions (see MCELFStreamer::EmitInstToData for details)
90 if (!F || (Assembler->isBundlingEnabled() && !Assembler->getRelaxAll() &&
91 F->hasInstructions())) {
92 F = new MCDataFragment();
98 void MCObjectStreamer::visitUsedSymbol(const MCSymbol &Sym) {
99 Assembler->getOrCreateSymbolData(Sym);
102 void MCObjectStreamer::EmitCFISections(bool EH, bool Debug) {
103 MCStreamer::EmitCFISections(EH, Debug);
105 EmitDebugFrame = Debug;
108 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
110 MCStreamer::EmitValueImpl(Value, Size, Loc);
111 MCDataFragment *DF = getOrCreateDataFragment();
113 MCLineEntry::Make(this, getCurrentSection().first);
115 // Avoid fixups when possible.
117 if (Value->EvaluateAsAbsolute(AbsValue, getAssembler())) {
118 EmitIntValue(AbsValue, Size);
121 DF->getFixups().push_back(
122 MCFixup::Create(DF->getContents().size(), Value,
123 MCFixup::getKindForSize(Size, false), Loc));
124 DF->getContents().resize(DF->getContents().size() + Size, 0);
127 void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
128 // We need to create a local symbol to avoid relocations.
129 Frame.Begin = getContext().CreateTempSymbol();
130 EmitLabel(Frame.Begin);
133 void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
134 Frame.End = getContext().CreateTempSymbol();
135 EmitLabel(Frame.End);
138 void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
139 MCStreamer::EmitLabel(Symbol);
141 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
142 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
144 // If there is a current fragment, mark the symbol as pointing into it.
145 // Otherwise queue the label and set its fragment pointer when we emit the
147 auto *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
148 if (F && !(getAssembler().isBundlingEnabled() &&
149 getAssembler().getRelaxAll())) {
151 SD.setOffset(F->getContents().size());
153 PendingLabels.push_back(&SD);
157 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
159 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
160 EmitULEB128IntValue(IntValue);
163 insert(new MCLEBFragment(*Value, false));
166 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
168 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
169 EmitSLEB128IntValue(IntValue);
172 insert(new MCLEBFragment(*Value, true));
175 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
176 const MCSymbol *Symbol) {
177 report_fatal_error("This file format doesn't support weak aliases.");
180 void MCObjectStreamer::ChangeSection(const MCSection *Section,
181 const MCExpr *Subsection) {
182 changeSectionImpl(Section, Subsection);
185 bool MCObjectStreamer::changeSectionImpl(const MCSection *Section,
186 const MCExpr *Subsection) {
187 assert(Section && "Cannot switch to a null section!");
188 flushPendingLabels(nullptr);
191 CurSectionData = &getAssembler().getOrCreateSectionData(*Section, &Created);
193 int64_t IntSubsection = 0;
195 !Subsection->EvaluateAsAbsolute(IntSubsection, getAssembler()))
196 report_fatal_error("Cannot evaluate subsection number");
197 if (IntSubsection < 0 || IntSubsection > 8192)
198 report_fatal_error("Subsection number out of range");
200 CurSectionData->getSubsectionInsertionPoint(unsigned(IntSubsection));
204 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
205 getAssembler().getOrCreateSymbolData(*Symbol);
206 MCStreamer::EmitAssignment(Symbol, Value);
209 void MCObjectStreamer::EmitInstruction(const MCInst &Inst,
210 const MCSubtargetInfo &STI) {
211 MCStreamer::EmitInstruction(Inst, STI);
213 MCSectionData *SD = getCurrentSectionData();
214 SD->setHasInstructions(true);
216 // Now that a machine instruction has been assembled into this section, make
217 // a line entry for any .loc directive that has been seen.
218 MCLineEntry::Make(this, getCurrentSection().first);
220 // If this instruction doesn't need relaxation, just emit it as data.
221 MCAssembler &Assembler = getAssembler();
222 if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
223 EmitInstToData(Inst, STI);
227 // Otherwise, relax and emit it as data if either:
228 // - The RelaxAll flag was passed
229 // - Bundling is enabled and this instruction is inside a bundle-locked
230 // group. We want to emit all such instructions into the same data
232 if (Assembler.getRelaxAll() ||
233 (Assembler.isBundlingEnabled() && SD->isBundleLocked())) {
235 getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
236 while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
237 getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
238 EmitInstToData(Relaxed, STI);
242 // Otherwise emit to a separate fragment.
243 EmitInstToFragment(Inst, STI);
246 void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst,
247 const MCSubtargetInfo &STI) {
248 if (getAssembler().getRelaxAll() && getAssembler().isBundlingEnabled())
249 llvm_unreachable("All instructions should have already been relaxed");
251 // Always create a new, separate fragment here, because its size can change
252 // during relaxation.
253 MCRelaxableFragment *IF = new MCRelaxableFragment(Inst, STI);
256 SmallString<128> Code;
257 raw_svector_ostream VecOS(Code);
258 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, IF->getFixups(),
261 IF->getContents().append(Code.begin(), Code.end());
265 static const char *const BundlingNotImplementedMsg =
266 "Aligned bundling is not implemented for this object format";
269 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
270 llvm_unreachable(BundlingNotImplementedMsg);
273 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
274 llvm_unreachable(BundlingNotImplementedMsg);
277 void MCObjectStreamer::EmitBundleUnlock() {
278 llvm_unreachable(BundlingNotImplementedMsg);
281 void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
282 unsigned Column, unsigned Flags,
284 unsigned Discriminator,
285 StringRef FileName) {
286 // In case we see two .loc directives in a row, make sure the
287 // first one gets a line entry.
288 MCLineEntry::Make(this, getCurrentSection().first);
290 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
291 Isa, Discriminator, FileName);
294 static const MCExpr *buildSymbolDiff(MCObjectStreamer &OS, const MCSymbol *A,
296 MCContext &Context = OS.getContext();
297 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
298 const MCExpr *ARef = MCSymbolRefExpr::Create(A, Variant, Context);
299 const MCExpr *BRef = MCSymbolRefExpr::Create(B, Variant, Context);
300 const MCExpr *AddrDelta =
301 MCBinaryExpr::Create(MCBinaryExpr::Sub, ARef, BRef, Context);
305 static void emitDwarfSetLineAddr(MCObjectStreamer &OS, int64_t LineDelta,
306 const MCSymbol *Label, int PointerSize) {
307 // emit the sequence to set the address
308 OS.EmitIntValue(dwarf::DW_LNS_extended_op, 1);
309 OS.EmitULEB128IntValue(PointerSize + 1);
310 OS.EmitIntValue(dwarf::DW_LNE_set_address, 1);
311 OS.EmitSymbolValue(Label, PointerSize);
313 // emit the sequence for the LineDelta (from 1) and a zero address delta.
314 MCDwarfLineAddr::Emit(&OS, LineDelta, 0);
317 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
318 const MCSymbol *LastLabel,
319 const MCSymbol *Label,
320 unsigned PointerSize) {
322 emitDwarfSetLineAddr(*this, LineDelta, Label, PointerSize);
325 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
327 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
328 MCDwarfLineAddr::Emit(this, LineDelta, Res);
331 insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
334 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
335 const MCSymbol *Label) {
336 const MCExpr *AddrDelta = buildSymbolDiff(*this, Label, LastLabel);
338 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
339 MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
342 insert(new MCDwarfCallFrameFragment(*AddrDelta));
345 void MCObjectStreamer::EmitBytes(StringRef Data) {
346 MCLineEntry::Make(this, getCurrentSection().first);
347 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
350 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
353 unsigned MaxBytesToEmit) {
354 if (MaxBytesToEmit == 0)
355 MaxBytesToEmit = ByteAlignment;
356 insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
358 // Update the maximum alignment on the current section if necessary.
359 if (ByteAlignment > getCurrentSectionData()->getAlignment())
360 getCurrentSectionData()->setAlignment(ByteAlignment);
363 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
364 unsigned MaxBytesToEmit) {
365 EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
366 cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
369 bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
370 unsigned char Value) {
372 if (Offset->EvaluateAsAbsolute(Res, getAssembler())) {
373 insert(new MCOrgFragment(*Offset, Value));
377 MCSymbol *CurrentPos = getContext().CreateTempSymbol();
378 EmitLabel(CurrentPos);
379 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
381 MCSymbolRefExpr::Create(CurrentPos, Variant, getContext());
382 const MCExpr *Delta =
383 MCBinaryExpr::Create(MCBinaryExpr::Sub, Offset, Ref, getContext());
385 if (!Delta->EvaluateAsAbsolute(Res, getAssembler()))
387 EmitFill(Res, Value);
391 // Associate GPRel32 fixup with data and resize data area
392 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
393 MCDataFragment *DF = getOrCreateDataFragment();
395 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
397 DF->getContents().resize(DF->getContents().size() + 4, 0);
400 // Associate GPRel32 fixup with data and resize data area
401 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
402 MCDataFragment *DF = getOrCreateDataFragment();
404 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
406 DF->getContents().resize(DF->getContents().size() + 8, 0);
409 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
410 // FIXME: A MCFillFragment would be more memory efficient but MCExpr has
411 // problems evaluating expressions across multiple fragments.
412 getOrCreateDataFragment()->getContents().append(NumBytes, FillValue);
415 void MCObjectStreamer::EmitZeros(uint64_t NumBytes) {
416 const MCSection *Sec = getCurrentSection().first;
417 assert(Sec && "need a section");
418 unsigned ItemSize = Sec->isVirtualSection() ? 0 : 1;
419 insert(new MCFillFragment(0, ItemSize, NumBytes));
422 void MCObjectStreamer::FinishImpl() {
423 // If we are generating dwarf for assembly source files dump out the sections.
424 if (getContext().getGenDwarfForAssembly())
425 MCGenDwarfInfo::Emit(this);
427 // Dump out the dwarf file & directory tables and line tables.
428 MCDwarfLineTable::Emit(this);
430 flushPendingLabels(nullptr);
431 getAssembler().Finish();