1 //===- lib/MC/MCELFStreamer.cpp - ELF Object Output ------------===//
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 // This file assembles .s files and emits ELF .o object files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/MC/MCStreamer.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/MC/MCAssembler.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCCodeEmitter.h"
20 #include "llvm/MC/MCELFSymbolFlags.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/MC/MCObjectStreamer.h"
24 #include "llvm/MC/MCSection.h"
25 #include "llvm/MC/MCSectionELF.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/MC/MCValue.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ELF.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetAsmBackend.h"
38 class MCELFStreamer : public MCObjectStreamer {
40 MCELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
41 raw_ostream &OS, MCCodeEmitter *Emitter)
42 : MCObjectStreamer(Context, TAB, OS, Emitter, false) {}
46 /// @name MCStreamer Interface
49 virtual void InitSections();
50 virtual void EmitLabel(MCSymbol *Symbol);
51 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
52 virtual void EmitThumbFunc(MCSymbol *Func);
53 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
54 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
55 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
56 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
57 assert(0 && "ELF doesn't support this directive");
59 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
60 unsigned ByteAlignment);
61 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
62 assert(0 && "ELF doesn't support this directive");
65 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
66 assert(0 && "ELF doesn't support this directive");
69 virtual void EmitCOFFSymbolType(int Type) {
70 assert(0 && "ELF doesn't support this directive");
73 virtual void EndCOFFSymbolDef() {
74 assert(0 && "ELF doesn't support this directive");
77 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
78 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
82 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
83 assert(0 && "ELF doesn't support this directive");
85 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
86 unsigned Size = 0, unsigned ByteAlignment = 0) {
87 assert(0 && "ELF doesn't support this directive");
89 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
90 uint64_t Size, unsigned ByteAlignment = 0) {
91 assert(0 && "ELF doesn't support this directive");
93 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
94 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
95 virtual void EmitGPRel32Value(const MCExpr *Value) {
96 assert(0 && "ELF doesn't support this directive");
98 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
99 unsigned ValueSize = 1,
100 unsigned MaxBytesToEmit = 0);
101 virtual void EmitCodeAlignment(unsigned ByteAlignment,
102 unsigned MaxBytesToEmit = 0);
103 virtual void EmitValueToOffset(const MCExpr *Offset,
104 unsigned char Value = 0);
106 virtual void EmitFileDirective(StringRef Filename);
107 virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
108 DEBUG(dbgs() << "FIXME: MCELFStreamer:EmitDwarfFileDirective not implemented\n");
111 virtual void Finish();
114 virtual void EmitInstToFragment(const MCInst &Inst);
115 virtual void EmitInstToData(const MCInst &Inst);
120 unsigned ByteAlignment;
122 std::vector<LocalCommon> LocalCommons;
124 SmallPtrSet<MCSymbol *, 16> BindingExplicitlySet;
126 void SetSection(StringRef Section, unsigned Type, unsigned Flags,
128 SwitchSection(getContext().getELFSection(Section, Type, Flags, Kind));
131 void SetSectionData() {
132 SetSection(".data", MCSectionELF::SHT_PROGBITS,
133 MCSectionELF::SHF_WRITE |MCSectionELF::SHF_ALLOC,
134 SectionKind::getDataRel());
135 EmitCodeAlignment(4, 0);
137 void SetSectionText() {
138 SetSection(".text", MCSectionELF::SHT_PROGBITS,
139 MCSectionELF::SHF_EXECINSTR |
140 MCSectionELF::SHF_ALLOC, SectionKind::getText());
141 EmitCodeAlignment(4, 0);
143 void SetSectionBss() {
144 SetSection(".bss", MCSectionELF::SHT_NOBITS,
145 MCSectionELF::SHF_WRITE |
146 MCSectionELF::SHF_ALLOC, SectionKind::getBSS());
147 EmitCodeAlignment(4, 0);
151 } // end anonymous namespace.
153 void MCELFStreamer::InitSections() {
154 // This emulates the same behavior of GNU as. This makes it easier
155 // to compare the output as the major sections are in the same order.
162 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
163 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
165 Symbol->setSection(*CurSection);
167 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
169 // FIXME: This is wasteful, we don't necessarily need to create a data
170 // fragment. Instead, we should mark the symbol as pointing into the data
171 // fragment if it exists, otherwise we should just queue the label and set its
172 // fragment pointer when we emit the next fragment.
173 MCDataFragment *F = getOrCreateDataFragment();
175 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
177 SD.setOffset(F->getContents().size());
180 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
182 case MCAF_SyntaxUnified: return; // no-op here.
183 case MCAF_Code16: return; // no-op here.
184 case MCAF_Code32: return; // no-op here.
185 case MCAF_SubsectionsViaSymbols:
186 getAssembler().setSubsectionsViaSymbols(true);
190 assert(0 && "invalid assembler flag!");
193 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
194 // FIXME: Anything needed here to flag the function as thumb?
197 void MCELFStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
198 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
200 // FIXME: Lift context changes into super class.
201 getAssembler().getOrCreateSymbolData(*Symbol);
202 Symbol->setVariableValue(AddValueSymbols(Value));
205 // This is a hack. To be able to implement weakrefs the writer has to be able
212 // since the first case should produce a weak undefined reference and the second
214 // If we created foo as a regular alias pointing to bar (foo = bar), then
215 // MCExpr::EvaluateAsRelocatable would recurse on foo and the writer would
216 // never see it used in a relocation.
217 // What we do is create a MCTargetExpr that when evaluated produces a symbol
218 // ref to a temporary symbol. This temporary symbol in turn is a variable
219 // that equals the original symbol (tmp = bar). With this hack the writer
220 // gets a relocation with tmp and can correctly implement weak references.
223 class WeakRefExpr : public MCTargetExpr {
225 const MCSymbolRefExpr *Alias;
227 explicit WeakRefExpr(const MCSymbolRefExpr *Alias_)
228 : MCTargetExpr(), Alias(Alias_) {}
231 virtual void PrintImpl(raw_ostream &OS) const {
232 llvm_unreachable("Unimplemented");
235 virtual bool EvaluateAsRelocatableImpl(MCValue &Res,
236 const MCAsmLayout *Layout) const {
237 Res = MCValue::get(Alias, 0, 0);
241 static const WeakRefExpr *Create(const MCSymbol *Alias, MCContext &Ctx) {
242 const MCSymbolRefExpr *A = MCSymbolRefExpr::Create(Alias, Ctx);
243 return new (Ctx) WeakRefExpr(A);
246 } // end anonymous namespace
248 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
249 getAssembler().getOrCreateSymbolData(*Symbol);
250 MCSymbolData &AliasSD = getAssembler().getOrCreateSymbolData(*Alias);
251 AliasSD.setFlags(AliasSD.getFlags() | ELF_Other_Weakref);
253 // Create the alias that actually points to Symbol
254 const MCSymbolRefExpr *SymRef = MCSymbolRefExpr::Create(Symbol, getContext());
255 MCSymbol *RealAlias = getContext().CreateTempSymbol();
256 RealAlias->setVariableValue(SymRef);
258 MCSymbolData &RealAliasSD = getAssembler().getOrCreateSymbolData(*RealAlias);
259 RealAliasSD.setFlags(RealAliasSD.getFlags() | ELF_Other_Weakref);
261 const MCExpr *Value = WeakRefExpr::Create(RealAlias, getContext());
262 Alias->setVariableValue(Value);
265 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
266 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
267 Binding == ELF::STB_WEAK);
268 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
269 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
272 static unsigned GetBinding(const MCSymbolData &SD) {
273 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
274 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
275 Binding == ELF::STB_WEAK);
279 static void SetType(MCSymbolData &SD, unsigned Type) {
280 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
281 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
282 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
283 Type == ELF::STT_TLS);
285 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STT_Shift);
286 SD.setFlags(OtherFlags | (Type << ELF_STT_Shift));
289 static void SetVisibility(MCSymbolData &SD, unsigned Visibility) {
290 assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
291 Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
293 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STV_Shift);
294 SD.setFlags(OtherFlags | (Visibility << ELF_STV_Shift));
297 void MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
298 MCSymbolAttr Attribute) {
299 // Indirect symbols are handled differently, to match how 'as' handles
300 // them. This makes writing matching .o files easier.
301 if (Attribute == MCSA_IndirectSymbol) {
302 // Note that we intentionally cannot use the symbol data here; this is
303 // important for matching the string table that 'as' generates.
304 IndirectSymbolData ISD;
306 ISD.SectionData = getCurrentSectionData();
307 getAssembler().getIndirectSymbols().push_back(ISD);
311 // Adding a symbol attribute always introduces the symbol, note that an
312 // important side effect of calling getOrCreateSymbolData here is to register
313 // the symbol with the assembler.
314 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
316 // The implementation of symbol attributes is designed to match 'as', but it
317 // leaves much to desired. It doesn't really make sense to arbitrarily add and
318 // remove flags, but 'as' allows this (in particular, see .desc).
320 // In the future it might be worth trying to make these operations more well
323 case MCSA_LazyReference:
325 case MCSA_NoDeadStrip:
326 case MCSA_PrivateExtern:
327 case MCSA_WeakDefinition:
328 case MCSA_WeakDefAutoPrivate:
330 case MCSA_ELF_TypeIndFunction:
331 case MCSA_IndirectSymbol:
332 assert(0 && "Invalid symbol attribute for ELF!");
336 SetBinding(SD, ELF::STB_GLOBAL);
337 SD.setExternal(true);
338 BindingExplicitlySet.insert(Symbol);
341 case MCSA_WeakReference:
343 SetBinding(SD, ELF::STB_WEAK);
344 SD.setExternal(true);
345 BindingExplicitlySet.insert(Symbol);
349 SetBinding(SD, ELF::STB_LOCAL);
350 SD.setExternal(false);
351 BindingExplicitlySet.insert(Symbol);
354 case MCSA_ELF_TypeFunction:
355 SetType(SD, ELF::STT_FUNC);
358 case MCSA_ELF_TypeObject:
359 SetType(SD, ELF::STT_OBJECT);
362 case MCSA_ELF_TypeTLS:
363 SetType(SD, ELF::STT_TLS);
366 case MCSA_ELF_TypeCommon:
367 SetType(SD, ELF::STT_COMMON);
370 case MCSA_ELF_TypeNoType:
371 SetType(SD, ELF::STT_NOTYPE);
375 SetVisibility(SD, ELF::STV_PROTECTED);
379 SetVisibility(SD, ELF::STV_HIDDEN);
383 SetVisibility(SD, ELF::STV_INTERNAL);
388 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
389 unsigned ByteAlignment) {
390 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
392 if (!BindingExplicitlySet.count(Symbol)) {
393 SetBinding(SD, ELF::STB_GLOBAL);
394 SD.setExternal(true);
397 if (GetBinding(SD) == ELF_STB_Local) {
398 const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
399 MCSectionELF::SHT_NOBITS,
400 MCSectionELF::SHF_WRITE |
401 MCSectionELF::SHF_ALLOC,
402 SectionKind::getBSS());
403 Symbol->setSection(*Section);
405 struct LocalCommon L = {&SD, Size, ByteAlignment};
406 LocalCommons.push_back(L);
408 SD.setCommon(Size, ByteAlignment);
411 SD.setSize(MCConstantExpr::Create(Size, getContext()));
414 void MCELFStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
415 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
417 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
420 void MCELFStreamer::EmitValue(const MCExpr *Value, unsigned Size,
421 unsigned AddrSpace) {
422 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
424 MCDataFragment *DF = getOrCreateDataFragment();
426 // Avoid fixups when possible.
428 if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
429 // FIXME: Endianness assumption.
430 for (unsigned i = 0; i != Size; ++i)
431 DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
433 DF->addFixup(MCFixup::Create(DF->getContents().size(), AddValueSymbols(Value),
434 MCFixup::getKindForSize(Size)));
435 DF->getContents().resize(DF->getContents().size() + Size, 0);
439 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
440 int64_t Value, unsigned ValueSize,
441 unsigned MaxBytesToEmit) {
442 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
444 if (MaxBytesToEmit == 0)
445 MaxBytesToEmit = ByteAlignment;
446 new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
447 getCurrentSectionData());
449 // Update the maximum alignment on the current section if necessary.
450 if (ByteAlignment > getCurrentSectionData()->getAlignment())
451 getCurrentSectionData()->setAlignment(ByteAlignment);
454 void MCELFStreamer::EmitCodeAlignment(unsigned ByteAlignment,
455 unsigned MaxBytesToEmit) {
456 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
458 if (MaxBytesToEmit == 0)
459 MaxBytesToEmit = ByteAlignment;
460 MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
461 getCurrentSectionData());
462 F->setEmitNops(true);
464 // Update the maximum alignment on the current section if necessary.
465 if (ByteAlignment > getCurrentSectionData()->getAlignment())
466 getCurrentSectionData()->setAlignment(ByteAlignment);
469 void MCELFStreamer::EmitValueToOffset(const MCExpr *Offset,
470 unsigned char Value) {
471 // TODO: This is exactly the same as MCMachOStreamer. Consider merging into
473 new MCOrgFragment(*Offset, Value, getCurrentSectionData());
476 // Add a symbol for the file name of this module. This is the second
477 // entry in the module's symbol table (the first being the null symbol).
478 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
479 MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
480 Symbol->setSection(*CurSection);
481 Symbol->setAbsolute();
483 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
485 SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
488 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
489 MCInstFragment *IF = new MCInstFragment(Inst, getCurrentSectionData());
491 // Add the fixups and data.
493 // FIXME: Revisit this design decision when relaxation is done, we may be
494 // able to get away with not storing any extra data in the MCInst.
495 SmallVector<MCFixup, 4> Fixups;
496 SmallString<256> Code;
497 raw_svector_ostream VecOS(Code);
498 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
501 IF->getCode() = Code;
502 IF->getFixups() = Fixups;
505 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
506 MCDataFragment *DF = getOrCreateDataFragment();
508 SmallVector<MCFixup, 4> Fixups;
509 SmallString<256> Code;
510 raw_svector_ostream VecOS(Code);
511 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
514 // Add the fixups and data.
515 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
516 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
517 DF->addFixup(Fixups[i]);
519 DF->getContents().append(Code.begin(), Code.end());
522 void MCELFStreamer::Finish() {
523 // FIXME: duplicated code with the MachO streamer.
524 // Dump out the dwarf file & directory tables and line tables.
525 if (getContext().hasDwarfFiles()) {
526 const MCSection *DwarfLineSection =
527 getContext().getELFSection(".debug_line", 0, 0,
528 SectionKind::getDataRelLocal());
529 MCDwarfFileTable::Emit(this, DwarfLineSection);
532 for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
533 e = LocalCommons.end();
535 MCSymbolData *SD = i->SD;
536 uint64_t Size = i->Size;
537 unsigned ByteAlignment = i->ByteAlignment;
538 const MCSymbol &Symbol = SD->getSymbol();
539 const MCSection &Section = Symbol.getSection();
541 MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
542 new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
544 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
547 // Update the maximum alignment of the section if necessary.
548 if (ByteAlignment > SectData.getAlignment())
549 SectData.setAlignment(ByteAlignment);
552 this->MCObjectStreamer::Finish();
555 MCStreamer *llvm::createELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
556 raw_ostream &OS, MCCodeEmitter *CE,
558 MCELFStreamer *S = new MCELFStreamer(Context, TAB, OS, CE);
560 S->getAssembler().setRelaxAll(true);