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 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
39 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
40 Binding == ELF::STB_WEAK);
41 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
42 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
45 static unsigned GetBinding(const MCSymbolData &SD) {
46 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
47 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
48 Binding == ELF::STB_WEAK);
52 static void SetType(MCSymbolData &SD, unsigned Type) {
53 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
54 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
55 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
56 Type == ELF::STT_TLS);
58 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STT_Shift);
59 SD.setFlags(OtherFlags | (Type << ELF_STT_Shift));
62 static void SetVisibility(MCSymbolData &SD, unsigned Visibility) {
63 assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
64 Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
66 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STV_Shift);
67 SD.setFlags(OtherFlags | (Visibility << ELF_STV_Shift));
70 class MCELFStreamer : public MCObjectStreamer {
72 MCELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
73 raw_ostream &OS, MCCodeEmitter *Emitter)
74 : MCObjectStreamer(Context, TAB, OS, Emitter, false) {}
78 /// @name MCStreamer Interface
81 virtual void InitSections();
82 virtual void EmitLabel(MCSymbol *Symbol);
83 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
84 virtual void EmitThumbFunc(MCSymbol *Func);
85 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
86 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
87 virtual void SwitchSection(const MCSection *Section);
88 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
89 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
90 assert(0 && "ELF doesn't support this directive");
92 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
93 unsigned ByteAlignment);
94 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
95 assert(0 && "ELF doesn't support this directive");
98 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
99 assert(0 && "ELF doesn't support this directive");
102 virtual void EmitCOFFSymbolType(int Type) {
103 assert(0 && "ELF doesn't support this directive");
106 virtual void EndCOFFSymbolDef() {
107 assert(0 && "ELF doesn't support this directive");
110 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
111 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
115 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
116 assert(0 && "ELF doesn't support this directive");
118 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
119 unsigned Size = 0, unsigned ByteAlignment = 0) {
120 assert(0 && "ELF doesn't support this directive");
122 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
123 uint64_t Size, unsigned ByteAlignment = 0) {
124 assert(0 && "ELF doesn't support this directive");
126 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
127 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
128 virtual void EmitGPRel32Value(const MCExpr *Value) {
129 assert(0 && "ELF doesn't support this directive");
131 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
132 unsigned ValueSize = 1,
133 unsigned MaxBytesToEmit = 0);
134 virtual void EmitCodeAlignment(unsigned ByteAlignment,
135 unsigned MaxBytesToEmit = 0);
136 virtual void EmitValueToOffset(const MCExpr *Offset,
137 unsigned char Value = 0);
139 virtual void EmitFileDirective(StringRef Filename);
140 virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
141 DEBUG(dbgs() << "FIXME: MCELFStreamer:EmitDwarfFileDirective not implemented\n");
144 virtual void Finish();
147 virtual void EmitInstToFragment(const MCInst &Inst);
148 virtual void EmitInstToData(const MCInst &Inst);
153 unsigned ByteAlignment;
155 std::vector<LocalCommon> LocalCommons;
157 SmallPtrSet<MCSymbol *, 16> BindingExplicitlySet;
159 void SetSection(StringRef Section, unsigned Type, unsigned Flags,
161 SwitchSection(getContext().getELFSection(Section, Type, Flags, Kind));
164 void SetSectionData() {
165 SetSection(".data", MCSectionELF::SHT_PROGBITS,
166 MCSectionELF::SHF_WRITE |MCSectionELF::SHF_ALLOC,
167 SectionKind::getDataRel());
168 EmitCodeAlignment(4, 0);
170 void SetSectionText() {
171 SetSection(".text", MCSectionELF::SHT_PROGBITS,
172 MCSectionELF::SHF_EXECINSTR |
173 MCSectionELF::SHF_ALLOC, SectionKind::getText());
174 EmitCodeAlignment(4, 0);
176 void SetSectionBss() {
177 SetSection(".bss", MCSectionELF::SHT_NOBITS,
178 MCSectionELF::SHF_WRITE |
179 MCSectionELF::SHF_ALLOC, SectionKind::getBSS());
180 EmitCodeAlignment(4, 0);
184 } // end anonymous namespace.
186 void MCELFStreamer::InitSections() {
187 // This emulates the same behavior of GNU as. This makes it easier
188 // to compare the output as the major sections are in the same order.
195 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
196 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
198 Symbol->setSection(*CurSection);
200 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
202 const MCSectionELF &Section =
203 static_cast<const MCSectionELF&>(Symbol->getSection());
204 if (Section.getFlags() & MCSectionELF::SHF_TLS)
205 SetType(SD, ELF::STT_TLS);
207 // FIXME: This is wasteful, we don't necessarily need to create a data
208 // fragment. Instead, we should mark the symbol as pointing into the data
209 // fragment if it exists, otherwise we should just queue the label and set its
210 // fragment pointer when we emit the next fragment.
211 MCDataFragment *F = getOrCreateDataFragment();
213 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
215 SD.setOffset(F->getContents().size());
218 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
220 case MCAF_SyntaxUnified: return; // no-op here.
221 case MCAF_Code16: return; // no-op here.
222 case MCAF_Code32: return; // no-op here.
223 case MCAF_SubsectionsViaSymbols:
224 getAssembler().setSubsectionsViaSymbols(true);
228 assert(0 && "invalid assembler flag!");
231 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
232 // FIXME: Anything needed here to flag the function as thumb?
235 void MCELFStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
236 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
238 // FIXME: Lift context changes into super class.
239 getAssembler().getOrCreateSymbolData(*Symbol);
240 Symbol->setVariableValue(AddValueSymbols(Value));
243 // This is a hack. To be able to implement weakrefs the writer has to be able
250 // since the first case should produce a weak undefined reference and the second
252 // If we created foo as a regular alias pointing to bar (foo = bar), then
253 // MCExpr::EvaluateAsRelocatable would recurse on foo and the writer would
254 // never see it used in a relocation.
255 // What we do is create a MCTargetExpr that when evaluated produces a symbol
256 // ref to a temporary symbol. This temporary symbol in turn is a variable
257 // that equals the original symbol (tmp = bar). With this hack the writer
258 // gets a relocation with tmp and can correctly implement weak references.
261 class WeakRefExpr : public MCTargetExpr {
263 const MCSymbolRefExpr *Alias;
265 explicit WeakRefExpr(const MCSymbolRefExpr *Alias_)
266 : MCTargetExpr(), Alias(Alias_) {}
269 virtual void PrintImpl(raw_ostream &OS) const {
270 llvm_unreachable("Unimplemented");
273 virtual bool EvaluateAsRelocatableImpl(MCValue &Res,
274 const MCAsmLayout *Layout) const {
275 Res = MCValue::get(Alias, 0, 0);
279 static const WeakRefExpr *Create(const MCSymbol *Alias, MCContext &Ctx) {
280 const MCSymbolRefExpr *A = MCSymbolRefExpr::Create(Alias, Ctx);
281 return new (Ctx) WeakRefExpr(A);
284 } // end anonymous namespace
286 void MCELFStreamer::SwitchSection(const MCSection *Section) {
287 const MCSymbol *Grp = static_cast<const MCSectionELF *>(Section)->getGroup();
289 getAssembler().getOrCreateSymbolData(*Grp);
290 this->MCObjectStreamer::SwitchSection(Section);
293 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
294 getAssembler().getOrCreateSymbolData(*Symbol);
295 MCSymbolData &AliasSD = getAssembler().getOrCreateSymbolData(*Alias);
296 AliasSD.setFlags(AliasSD.getFlags() | ELF_Other_Weakref);
298 // Create the alias that actually points to Symbol
299 const MCSymbolRefExpr *SymRef = MCSymbolRefExpr::Create(Symbol, getContext());
300 MCSymbol *RealAlias = getContext().CreateTempSymbol();
301 RealAlias->setVariableValue(SymRef);
303 MCSymbolData &RealAliasSD = getAssembler().getOrCreateSymbolData(*RealAlias);
304 RealAliasSD.setFlags(RealAliasSD.getFlags() | ELF_Other_Weakref);
306 const MCExpr *Value = WeakRefExpr::Create(RealAlias, getContext());
307 Alias->setVariableValue(Value);
310 void MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
311 MCSymbolAttr Attribute) {
312 // Indirect symbols are handled differently, to match how 'as' handles
313 // them. This makes writing matching .o files easier.
314 if (Attribute == MCSA_IndirectSymbol) {
315 // Note that we intentionally cannot use the symbol data here; this is
316 // important for matching the string table that 'as' generates.
317 IndirectSymbolData ISD;
319 ISD.SectionData = getCurrentSectionData();
320 getAssembler().getIndirectSymbols().push_back(ISD);
324 // Adding a symbol attribute always introduces the symbol, note that an
325 // important side effect of calling getOrCreateSymbolData here is to register
326 // the symbol with the assembler.
327 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
329 // The implementation of symbol attributes is designed to match 'as', but it
330 // leaves much to desired. It doesn't really make sense to arbitrarily add and
331 // remove flags, but 'as' allows this (in particular, see .desc).
333 // In the future it might be worth trying to make these operations more well
336 case MCSA_LazyReference:
338 case MCSA_NoDeadStrip:
339 case MCSA_PrivateExtern:
340 case MCSA_WeakDefinition:
341 case MCSA_WeakDefAutoPrivate:
343 case MCSA_ELF_TypeIndFunction:
344 case MCSA_IndirectSymbol:
345 assert(0 && "Invalid symbol attribute for ELF!");
348 case MCSA_ELF_TypeGnuUniqueObject:
353 SetBinding(SD, ELF::STB_GLOBAL);
354 SD.setExternal(true);
355 BindingExplicitlySet.insert(Symbol);
358 case MCSA_WeakReference:
360 SetBinding(SD, ELF::STB_WEAK);
361 SD.setExternal(true);
362 BindingExplicitlySet.insert(Symbol);
366 SetBinding(SD, ELF::STB_LOCAL);
367 SD.setExternal(false);
368 BindingExplicitlySet.insert(Symbol);
371 case MCSA_ELF_TypeFunction:
372 SetType(SD, ELF::STT_FUNC);
375 case MCSA_ELF_TypeObject:
376 SetType(SD, ELF::STT_OBJECT);
379 case MCSA_ELF_TypeTLS:
380 SetType(SD, ELF::STT_TLS);
383 case MCSA_ELF_TypeCommon:
384 SetType(SD, ELF::STT_COMMON);
387 case MCSA_ELF_TypeNoType:
388 SetType(SD, ELF::STT_NOTYPE);
392 SetVisibility(SD, ELF::STV_PROTECTED);
396 SetVisibility(SD, ELF::STV_HIDDEN);
400 SetVisibility(SD, ELF::STV_INTERNAL);
405 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
406 unsigned ByteAlignment) {
407 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
409 if (!BindingExplicitlySet.count(Symbol)) {
410 SetBinding(SD, ELF::STB_GLOBAL);
411 SD.setExternal(true);
412 SetType(SD, ELF::STT_OBJECT);
415 if (GetBinding(SD) == ELF_STB_Local) {
416 const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
417 MCSectionELF::SHT_NOBITS,
418 MCSectionELF::SHF_WRITE |
419 MCSectionELF::SHF_ALLOC,
420 SectionKind::getBSS());
421 Symbol->setSection(*Section);
423 struct LocalCommon L = {&SD, Size, ByteAlignment};
424 LocalCommons.push_back(L);
426 SD.setCommon(Size, ByteAlignment);
429 SD.setSize(MCConstantExpr::Create(Size, getContext()));
432 void MCELFStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
433 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
435 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
438 void MCELFStreamer::EmitValue(const MCExpr *Value, unsigned Size,
439 unsigned AddrSpace) {
440 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
442 MCDataFragment *DF = getOrCreateDataFragment();
444 // Avoid fixups when possible.
446 if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
447 // FIXME: Endianness assumption.
448 for (unsigned i = 0; i != Size; ++i)
449 DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
451 DF->addFixup(MCFixup::Create(DF->getContents().size(), AddValueSymbols(Value),
452 MCFixup::getKindForSize(Size)));
453 DF->getContents().resize(DF->getContents().size() + Size, 0);
457 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
458 int64_t Value, unsigned ValueSize,
459 unsigned MaxBytesToEmit) {
460 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
462 if (MaxBytesToEmit == 0)
463 MaxBytesToEmit = ByteAlignment;
464 new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
465 getCurrentSectionData());
467 // Update the maximum alignment on the current section if necessary.
468 if (ByteAlignment > getCurrentSectionData()->getAlignment())
469 getCurrentSectionData()->setAlignment(ByteAlignment);
472 void MCELFStreamer::EmitCodeAlignment(unsigned ByteAlignment,
473 unsigned MaxBytesToEmit) {
474 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
476 if (MaxBytesToEmit == 0)
477 MaxBytesToEmit = ByteAlignment;
478 MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
479 getCurrentSectionData());
480 F->setEmitNops(true);
482 // Update the maximum alignment on the current section if necessary.
483 if (ByteAlignment > getCurrentSectionData()->getAlignment())
484 getCurrentSectionData()->setAlignment(ByteAlignment);
487 void MCELFStreamer::EmitValueToOffset(const MCExpr *Offset,
488 unsigned char Value) {
489 // TODO: This is exactly the same as MCMachOStreamer. Consider merging into
491 new MCOrgFragment(*Offset, Value, getCurrentSectionData());
494 // Add a symbol for the file name of this module. This is the second
495 // entry in the module's symbol table (the first being the null symbol).
496 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
497 MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
498 Symbol->setSection(*CurSection);
499 Symbol->setAbsolute();
501 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
503 SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
506 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
507 MCInstFragment *IF = new MCInstFragment(Inst, getCurrentSectionData());
509 // Add the fixups and data.
511 // FIXME: Revisit this design decision when relaxation is done, we may be
512 // able to get away with not storing any extra data in the MCInst.
513 SmallVector<MCFixup, 4> Fixups;
514 SmallString<256> Code;
515 raw_svector_ostream VecOS(Code);
516 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
519 IF->getCode() = Code;
520 IF->getFixups() = Fixups;
523 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
524 MCDataFragment *DF = getOrCreateDataFragment();
526 SmallVector<MCFixup, 4> Fixups;
527 SmallString<256> Code;
528 raw_svector_ostream VecOS(Code);
529 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
532 // Add the fixups and data.
533 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
534 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
535 DF->addFixup(Fixups[i]);
537 DF->getContents().append(Code.begin(), Code.end());
540 void MCELFStreamer::Finish() {
541 // FIXME: duplicated code with the MachO streamer.
542 // Dump out the dwarf file & directory tables and line tables.
543 if (getContext().hasDwarfFiles()) {
544 const MCSection *DwarfLineSection =
545 getContext().getELFSection(".debug_line", 0, 0,
546 SectionKind::getDataRelLocal());
547 MCDwarfFileTable::Emit(this, DwarfLineSection);
550 for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
551 e = LocalCommons.end();
553 MCSymbolData *SD = i->SD;
554 uint64_t Size = i->Size;
555 unsigned ByteAlignment = i->ByteAlignment;
556 const MCSymbol &Symbol = SD->getSymbol();
557 const MCSection &Section = Symbol.getSection();
559 MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
560 new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
562 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
565 // Update the maximum alignment of the section if necessary.
566 if (ByteAlignment > SectData.getAlignment())
567 SectData.setAlignment(ByteAlignment);
570 this->MCObjectStreamer::Finish();
573 MCStreamer *llvm::createELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
574 raw_ostream &OS, MCCodeEmitter *CE,
576 MCELFStreamer *S = new MCELFStreamer(Context, TAB, OS, CE);
578 S->getAssembler().setRelaxAll(true);