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/MCSymbol.h"
21 #include "llvm/MC/MCSection.h"
22 #include "llvm/Support/ErrorHandling.h"
25 MCObjectStreamer::MCObjectStreamer(MCContext &Context,
26 MCTargetStreamer *TargetStreamer,
27 MCAsmBackend &TAB, raw_ostream &OS,
28 MCCodeEmitter *Emitter_)
29 : MCStreamer(Context, TargetStreamer),
30 Assembler(new MCAssembler(Context, TAB, *Emitter_,
31 *TAB.createObjectWriter(OS), OS)),
34 MCObjectStreamer::MCObjectStreamer(MCContext &Context,
35 MCTargetStreamer *TargetStreamer,
36 MCAsmBackend &TAB, raw_ostream &OS,
37 MCCodeEmitter *Emitter_,
38 MCAssembler *_Assembler)
39 : MCStreamer(Context, TargetStreamer), Assembler(_Assembler),
42 MCObjectStreamer::~MCObjectStreamer() {
43 delete &Assembler->getBackend();
44 delete &Assembler->getEmitter();
45 delete &Assembler->getWriter();
49 void MCObjectStreamer::reset() {
53 CurInsertionPoint = MCSectionData::iterator();
57 MCFragment *MCObjectStreamer::getCurrentFragment() const {
58 assert(getCurrentSectionData() && "No current section!");
60 if (CurInsertionPoint != getCurrentSectionData()->getFragmentList().begin())
61 return prior(CurInsertionPoint);
66 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() const {
67 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
68 // When bundling is enabled, we don't want to add data to a fragment that
69 // already has instructions (see MCELFStreamer::EmitInstToData for details)
70 if (!F || (Assembler->isBundlingEnabled() && F->hasInstructions())) {
71 F = new MCDataFragment();
77 const MCExpr *MCObjectStreamer::AddValueSymbols(const MCExpr *Value) {
78 switch (Value->getKind()) {
80 cast<MCTargetExpr>(Value)->AddValueSymbols(Assembler);
83 case MCExpr::Constant:
86 case MCExpr::Binary: {
87 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
88 AddValueSymbols(BE->getLHS());
89 AddValueSymbols(BE->getRHS());
93 case MCExpr::SymbolRef:
94 Assembler->getOrCreateSymbolData(cast<MCSymbolRefExpr>(Value)->getSymbol());
98 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
105 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size) {
106 MCDataFragment *DF = getOrCreateDataFragment();
108 MCLineEntry::Make(this, getCurrentSection().first);
110 // Avoid fixups when possible.
112 if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue, getAssembler())) {
113 EmitIntValue(AbsValue, Size);
116 DF->getFixups().push_back(
117 MCFixup::Create(DF->getContents().size(), Value,
118 MCFixup::getKindForSize(Size, false)));
119 DF->getContents().resize(DF->getContents().size() + Size, 0);
122 void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
123 RecordProcStart(Frame);
126 void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
127 RecordProcEnd(Frame);
130 void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
131 MCStreamer::EmitLabel(Symbol);
133 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
135 // FIXME: This is wasteful, we don't necessarily need to create a data
136 // fragment. Instead, we should mark the symbol as pointing into the data
137 // fragment if it exists, otherwise we should just queue the label and set its
138 // fragment pointer when we emit the next fragment.
139 MCDataFragment *F = getOrCreateDataFragment();
140 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
142 SD.setOffset(F->getContents().size());
145 void MCObjectStreamer::EmitDebugLabel(MCSymbol *Symbol) {
149 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
151 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
152 EmitULEB128IntValue(IntValue);
155 Value = ForceExpAbs(Value);
156 insert(new MCLEBFragment(*Value, false));
159 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
161 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
162 EmitSLEB128IntValue(IntValue);
165 Value = ForceExpAbs(Value);
166 insert(new MCLEBFragment(*Value, true));
169 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
170 const MCSymbol *Symbol) {
171 report_fatal_error("This file format doesn't support weak aliases.");
174 void MCObjectStreamer::ChangeSection(const MCSection *Section,
175 const MCExpr *Subsection) {
176 assert(Section && "Cannot switch to a null section!");
178 CurSectionData = &getAssembler().getOrCreateSectionData(*Section);
180 int64_t IntSubsection = 0;
182 !Subsection->EvaluateAsAbsolute(IntSubsection, getAssembler()))
183 report_fatal_error("Cannot evaluate subsection number");
184 if (IntSubsection < 0 || IntSubsection > 8192)
185 report_fatal_error("Subsection number out of range");
187 CurSectionData->getSubsectionInsertionPoint(unsigned(IntSubsection));
190 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
191 getAssembler().getOrCreateSymbolData(*Symbol);
192 Symbol->setVariableValue(AddValueSymbols(Value));
195 void MCObjectStreamer::EmitInstruction(const MCInst &Inst) {
197 for (unsigned i = Inst.getNumOperands(); i--; )
198 if (Inst.getOperand(i).isExpr())
199 AddValueSymbols(Inst.getOperand(i).getExpr());
201 MCSectionData *SD = getCurrentSectionData();
202 SD->setHasInstructions(true);
204 // Now that a machine instruction has been assembled into this section, make
205 // a line entry for any .loc directive that has been seen.
206 MCLineEntry::Make(this, getCurrentSection().first);
208 // If this instruction doesn't need relaxation, just emit it as data.
209 MCAssembler &Assembler = getAssembler();
210 if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
211 EmitInstToData(Inst);
215 // Otherwise, relax and emit it as data if either:
216 // - The RelaxAll flag was passed
217 // - Bundling is enabled and this instruction is inside a bundle-locked
218 // group. We want to emit all such instructions into the same data
220 if (Assembler.getRelaxAll() ||
221 (Assembler.isBundlingEnabled() && SD->isBundleLocked())) {
223 getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
224 while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
225 getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
226 EmitInstToData(Relaxed);
230 // Otherwise emit to a separate fragment.
231 EmitInstToFragment(Inst);
234 void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst) {
235 // Always create a new, separate fragment here, because its size can change
236 // during relaxation.
237 MCRelaxableFragment *IF = new MCRelaxableFragment(Inst);
240 SmallString<128> Code;
241 raw_svector_ostream VecOS(Code);
242 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, IF->getFixups());
244 IF->getContents().append(Code.begin(), Code.end());
248 static const char *const BundlingNotImplementedMsg =
249 "Aligned bundling is not implemented for this object format";
252 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
253 llvm_unreachable(BundlingNotImplementedMsg);
256 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
257 llvm_unreachable(BundlingNotImplementedMsg);
260 void MCObjectStreamer::EmitBundleUnlock() {
261 llvm_unreachable(BundlingNotImplementedMsg);
264 void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
265 unsigned Column, unsigned Flags,
267 unsigned Discriminator,
268 StringRef FileName) {
269 // In case we see two .loc directives in a row, make sure the
270 // first one gets a line entry.
271 MCLineEntry::Make(this, getCurrentSection().first);
273 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
274 Isa, Discriminator, FileName);
277 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
278 const MCSymbol *LastLabel,
279 const MCSymbol *Label,
280 unsigned PointerSize) {
282 EmitDwarfSetLineAddr(LineDelta, Label, PointerSize);
285 const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
287 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
288 MCDwarfLineAddr::Emit(this, LineDelta, Res);
291 AddrDelta = ForceExpAbs(AddrDelta);
292 insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
295 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
296 const MCSymbol *Label) {
297 const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
299 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
300 MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
303 AddrDelta = ForceExpAbs(AddrDelta);
304 insert(new MCDwarfCallFrameFragment(*AddrDelta));
307 void MCObjectStreamer::EmitBytes(StringRef Data) {
308 MCLineEntry::Make(this, getCurrentSection().first);
309 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
312 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
315 unsigned MaxBytesToEmit) {
316 if (MaxBytesToEmit == 0)
317 MaxBytesToEmit = ByteAlignment;
318 insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
320 // Update the maximum alignment on the current section if necessary.
321 if (ByteAlignment > getCurrentSectionData()->getAlignment())
322 getCurrentSectionData()->setAlignment(ByteAlignment);
325 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
326 unsigned MaxBytesToEmit) {
327 EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
328 cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
331 bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
332 unsigned char Value) {
334 if (Offset->EvaluateAsAbsolute(Res, getAssembler())) {
335 insert(new MCOrgFragment(*Offset, Value));
339 MCSymbol *CurrentPos = getContext().CreateTempSymbol();
340 EmitLabel(CurrentPos);
341 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
343 MCSymbolRefExpr::Create(CurrentPos, Variant, getContext());
344 const MCExpr *Delta =
345 MCBinaryExpr::Create(MCBinaryExpr::Sub, Offset, Ref, getContext());
347 if (!Delta->EvaluateAsAbsolute(Res, getAssembler()))
349 EmitFill(Res, Value);
353 // Associate GPRel32 fixup with data and resize data area
354 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
355 MCDataFragment *DF = getOrCreateDataFragment();
357 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
359 DF->getContents().resize(DF->getContents().size() + 4, 0);
362 // Associate GPRel32 fixup with data and resize data area
363 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
364 MCDataFragment *DF = getOrCreateDataFragment();
366 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
368 DF->getContents().resize(DF->getContents().size() + 8, 0);
371 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) {
372 // FIXME: A MCFillFragment would be more memory efficient but MCExpr has
373 // problems evaluating expressions across multiple fragments.
374 getOrCreateDataFragment()->getContents().append(NumBytes, FillValue);
377 void MCObjectStreamer::EmitZeros(uint64_t NumBytes) {
378 unsigned ItemSize = getCurrentSection().first->isVirtualSection() ? 0 : 1;
379 insert(new MCFillFragment(0, ItemSize, NumBytes));
382 void MCObjectStreamer::FinishImpl() {
383 // Dump out the dwarf file & directory tables and line tables.
384 const MCSymbol *LineSectionSymbol = NULL;
385 if (getContext().hasDwarfFiles())
386 LineSectionSymbol = MCDwarfFileTable::Emit(this);
388 // If we are generating dwarf for assembly source files dump out the sections.
389 if (getContext().getGenDwarfForAssembly())
390 MCGenDwarfInfo::Emit(this, LineSectionSymbol);
392 getAssembler().Finish();