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(StreamerKind Kind, MCContext &Context,
26 MCAsmBackend &TAB, raw_ostream &OS,
27 MCCodeEmitter *Emitter_)
28 : MCStreamer(Kind, Context),
29 Assembler(new MCAssembler(Context, TAB, *Emitter_,
30 *TAB.createObjectWriter(OS), OS)),
33 MCObjectStreamer::MCObjectStreamer(StreamerKind Kind, MCContext &Context,
34 MCAsmBackend &TAB, raw_ostream &OS,
35 MCCodeEmitter *Emitter_,
36 MCAssembler *_Assembler)
37 : MCStreamer(Kind, Context), Assembler(_Assembler), CurSectionData(0) {}
39 MCObjectStreamer::~MCObjectStreamer() {
40 delete &Assembler->getBackend();
41 delete &Assembler->getEmitter();
42 delete &Assembler->getWriter();
46 void MCObjectStreamer::reset() {
50 CurInsertionPoint = MCSectionData::iterator();
54 MCFragment *MCObjectStreamer::getCurrentFragment() const {
55 assert(getCurrentSectionData() && "No current section!");
57 if (CurInsertionPoint != getCurrentSectionData()->getFragmentList().begin())
58 return prior(CurInsertionPoint);
63 MCDataFragment *MCObjectStreamer::getOrCreateDataFragment() const {
64 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
65 // When bundling is enabled, we don't want to add data to a fragment that
66 // already has instructions (see MCELFStreamer::EmitInstToData for details)
67 if (!F || (Assembler->isBundlingEnabled() && F->hasInstructions())) {
68 F = new MCDataFragment();
74 const MCExpr *MCObjectStreamer::AddValueSymbols(const MCExpr *Value) {
75 switch (Value->getKind()) {
77 cast<MCTargetExpr>(Value)->AddValueSymbols(Assembler);
80 case MCExpr::Constant:
83 case MCExpr::Binary: {
84 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
85 AddValueSymbols(BE->getLHS());
86 AddValueSymbols(BE->getRHS());
90 case MCExpr::SymbolRef:
91 Assembler->getOrCreateSymbolData(cast<MCSymbolRefExpr>(Value)->getSymbol());
95 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
102 void MCObjectStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
103 unsigned AddrSpace) {
104 assert(AddrSpace == 0 && "Address space must be 0!");
105 MCDataFragment *DF = getOrCreateDataFragment();
107 MCLineEntry::Make(this, getCurrentSection().first);
109 // Avoid fixups when possible.
111 if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue, getAssembler())) {
112 EmitIntValue(AbsValue, Size, AddrSpace);
115 DF->getFixups().push_back(
116 MCFixup::Create(DF->getContents().size(), Value,
117 MCFixup::getKindForSize(Size, false)));
118 DF->getContents().resize(DF->getContents().size() + Size, 0);
121 void MCObjectStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) {
122 RecordProcStart(Frame);
125 void MCObjectStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) {
126 RecordProcEnd(Frame);
129 void MCObjectStreamer::EmitLabel(MCSymbol *Symbol) {
130 MCStreamer::EmitLabel(Symbol);
132 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
134 // FIXME: This is wasteful, we don't necessarily need to create a data
135 // fragment. Instead, we should mark the symbol as pointing into the data
136 // fragment if it exists, otherwise we should just queue the label and set its
137 // fragment pointer when we emit the next fragment.
138 MCDataFragment *F = getOrCreateDataFragment();
139 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
141 SD.setOffset(F->getContents().size());
144 void MCObjectStreamer::EmitDebugLabel(MCSymbol *Symbol) {
148 void MCObjectStreamer::EmitULEB128Value(const MCExpr *Value) {
150 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
151 EmitULEB128IntValue(IntValue);
154 Value = ForceExpAbs(Value);
155 insert(new MCLEBFragment(*Value, false));
158 void MCObjectStreamer::EmitSLEB128Value(const MCExpr *Value) {
160 if (Value->EvaluateAsAbsolute(IntValue, getAssembler())) {
161 EmitSLEB128IntValue(IntValue);
164 Value = ForceExpAbs(Value);
165 insert(new MCLEBFragment(*Value, true));
168 void MCObjectStreamer::EmitWeakReference(MCSymbol *Alias,
169 const MCSymbol *Symbol) {
170 report_fatal_error("This file format doesn't support weak aliases.");
173 void MCObjectStreamer::ChangeSection(const MCSection *Section,
174 const MCExpr *Subsection) {
175 assert(Section && "Cannot switch to a null section!");
177 CurSectionData = &getAssembler().getOrCreateSectionData(*Section);
179 int64_t IntSubsection = 0;
181 !Subsection->EvaluateAsAbsolute(IntSubsection, getAssembler()))
182 report_fatal_error("Cannot evaluate subsection number");
183 if (IntSubsection < 0 || IntSubsection > 8192)
184 report_fatal_error("Subsection number out of range");
186 CurSectionData->getSubsectionInsertionPoint(unsigned(IntSubsection));
189 void MCObjectStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
190 getAssembler().getOrCreateSymbolData(*Symbol);
191 Symbol->setVariableValue(AddValueSymbols(Value));
194 void MCObjectStreamer::EmitInstruction(const MCInst &Inst) {
196 for (unsigned i = Inst.getNumOperands(); i--; )
197 if (Inst.getOperand(i).isExpr())
198 AddValueSymbols(Inst.getOperand(i).getExpr());
200 MCSectionData *SD = getCurrentSectionData();
201 SD->setHasInstructions(true);
203 // Now that a machine instruction has been assembled into this section, make
204 // a line entry for any .loc directive that has been seen.
205 MCLineEntry::Make(this, getCurrentSection().first);
207 // If this instruction doesn't need relaxation, just emit it as data.
208 MCAssembler &Assembler = getAssembler();
209 if (!Assembler.getBackend().mayNeedRelaxation(Inst)) {
210 EmitInstToData(Inst);
214 // Otherwise, relax and emit it as data if either:
215 // - The RelaxAll flag was passed
216 // - Bundling is enabled and this instruction is inside a bundle-locked
217 // group. We want to emit all such instructions into the same data
219 if (Assembler.getRelaxAll() ||
220 (Assembler.isBundlingEnabled() && SD->isBundleLocked())) {
222 getAssembler().getBackend().relaxInstruction(Inst, Relaxed);
223 while (getAssembler().getBackend().mayNeedRelaxation(Relaxed))
224 getAssembler().getBackend().relaxInstruction(Relaxed, Relaxed);
225 EmitInstToData(Relaxed);
229 // Otherwise emit to a separate fragment.
230 EmitInstToFragment(Inst);
233 void MCObjectStreamer::EmitInstToFragment(const MCInst &Inst) {
234 // Always create a new, separate fragment here, because its size can change
235 // during relaxation.
236 MCRelaxableFragment *IF = new MCRelaxableFragment(Inst);
239 SmallString<128> Code;
240 raw_svector_ostream VecOS(Code);
241 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, IF->getFixups());
243 IF->getContents().append(Code.begin(), Code.end());
247 static const char *BundlingNotImplementedMsg =
248 "Aligned bundling is not implemented for this object format";
251 void MCObjectStreamer::EmitBundleAlignMode(unsigned AlignPow2) {
252 llvm_unreachable(BundlingNotImplementedMsg);
255 void MCObjectStreamer::EmitBundleLock(bool AlignToEnd) {
256 llvm_unreachable(BundlingNotImplementedMsg);
259 void MCObjectStreamer::EmitBundleUnlock() {
260 llvm_unreachable(BundlingNotImplementedMsg);
263 void MCObjectStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
264 unsigned Column, unsigned Flags,
266 unsigned Discriminator,
267 StringRef FileName) {
268 // In case we see two .loc directives in a row, make sure the
269 // first one gets a line entry.
270 MCLineEntry::Make(this, getCurrentSection().first);
272 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
273 Isa, Discriminator, FileName);
276 void MCObjectStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
277 const MCSymbol *LastLabel,
278 const MCSymbol *Label,
279 unsigned PointerSize) {
281 EmitDwarfSetLineAddr(LineDelta, Label, PointerSize);
284 const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
286 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
287 MCDwarfLineAddr::Emit(this, LineDelta, Res);
290 AddrDelta = ForceExpAbs(AddrDelta);
291 insert(new MCDwarfLineAddrFragment(LineDelta, *AddrDelta));
294 void MCObjectStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
295 const MCSymbol *Label) {
296 const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
298 if (AddrDelta->EvaluateAsAbsolute(Res, getAssembler())) {
299 MCDwarfFrameEmitter::EmitAdvanceLoc(*this, Res);
302 AddrDelta = ForceExpAbs(AddrDelta);
303 insert(new MCDwarfCallFrameFragment(*AddrDelta));
306 void MCObjectStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
307 assert(AddrSpace == 0 && "Address space must be 0!");
308 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
311 void MCObjectStreamer::EmitValueToAlignment(unsigned ByteAlignment,
314 unsigned MaxBytesToEmit) {
315 if (MaxBytesToEmit == 0)
316 MaxBytesToEmit = ByteAlignment;
317 insert(new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit));
319 // Update the maximum alignment on the current section if necessary.
320 if (ByteAlignment > getCurrentSectionData()->getAlignment())
321 getCurrentSectionData()->setAlignment(ByteAlignment);
324 void MCObjectStreamer::EmitCodeAlignment(unsigned ByteAlignment,
325 unsigned MaxBytesToEmit) {
326 EmitValueToAlignment(ByteAlignment, 0, 1, MaxBytesToEmit);
327 cast<MCAlignFragment>(getCurrentFragment())->setEmitNops(true);
330 bool MCObjectStreamer::EmitValueToOffset(const MCExpr *Offset,
331 unsigned char Value) {
333 if (Offset->EvaluateAsAbsolute(Res, getAssembler())) {
334 insert(new MCOrgFragment(*Offset, Value));
338 MCSymbol *CurrentPos = getContext().CreateTempSymbol();
339 EmitLabel(CurrentPos);
340 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
342 MCSymbolRefExpr::Create(CurrentPos, Variant, getContext());
343 const MCExpr *Delta =
344 MCBinaryExpr::Create(MCBinaryExpr::Sub, Offset, Ref, getContext());
346 if (!Delta->EvaluateAsAbsolute(Res, getAssembler()))
348 EmitFill(Res, Value);
352 // Associate GPRel32 fixup with data and resize data area
353 void MCObjectStreamer::EmitGPRel32Value(const MCExpr *Value) {
354 MCDataFragment *DF = getOrCreateDataFragment();
356 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
358 DF->getContents().resize(DF->getContents().size() + 4, 0);
361 // Associate GPRel32 fixup with data and resize data area
362 void MCObjectStreamer::EmitGPRel64Value(const MCExpr *Value) {
363 MCDataFragment *DF = getOrCreateDataFragment();
365 DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
367 DF->getContents().resize(DF->getContents().size() + 8, 0);
370 void MCObjectStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
371 unsigned AddrSpace) {
372 assert(AddrSpace == 0 && "Address space must be 0!");
373 // FIXME: A MCFillFragment would be more memory efficient but MCExpr has
374 // problems evaluating expressions across multiple fragments.
375 getOrCreateDataFragment()->getContents().append(NumBytes, FillValue);
378 void MCObjectStreamer::EmitZeros(uint64_t NumBytes, unsigned AddrSpace) {
379 assert(AddrSpace == 0 && "Address space must be 0!");
380 unsigned ItemSize = getCurrentSection().first->isVirtualSection() ? 0 : 1;
381 insert(new MCFillFragment(0, ItemSize, NumBytes));
384 void MCObjectStreamer::FinishImpl() {
385 // Dump out the dwarf file & directory tables and line tables.
386 const MCSymbol *LineSectionSymbol = NULL;
387 if (getContext().hasDwarfFiles())
388 LineSectionSymbol = MCDwarfFileTable::Emit(this);
390 // If we are generating dwarf for assembly source files dump out the sections.
391 if (getContext().getGenDwarfForAssembly())
392 MCGenDwarfInfo::Emit(this, LineSectionSymbol);
394 getAssembler().Finish();