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_SubsectionsViaSymbols:
185 getAssembler().setSubsectionsViaSymbols(true);
189 assert(0 && "invalid assembler flag!");
192 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
193 // FIXME: Anything needed here to flag the function as thumb?
196 void MCELFStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
197 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
199 // FIXME: Lift context changes into super class.
200 getAssembler().getOrCreateSymbolData(*Symbol);
201 Symbol->setVariableValue(AddValueSymbols(Value));
204 // This is a hack. To be able to implement weakrefs the writer has to be able
211 // since the first case should produce a weak undefined reference and the second
213 // If we created foo as a regular alias pointing to bar (foo = bar), then
214 // MCExpr::EvaluateAsRelocatable would recurse on foo and the writer would
215 // never see it used in a relocation.
216 // What we do is create a MCTargetExpr that when evaluated produces a symbol
217 // ref to a temporary symbol. This temporary symbol in turn is a variable
218 // that equals the original symbol (tmp = bar). With this hack the writer
219 // gets a relocation with tmp and can correctly implement weak references.
222 class WeakRefExpr : public MCTargetExpr {
224 const MCSymbolRefExpr *Alias;
226 explicit WeakRefExpr(const MCSymbolRefExpr *Alias_)
227 : MCTargetExpr(), Alias(Alias_) {}
230 virtual void PrintImpl(raw_ostream &OS) const {
231 llvm_unreachable("Unimplemented");
234 virtual bool EvaluateAsRelocatableImpl(MCValue &Res,
235 const MCAsmLayout *Layout) const {
236 Res = MCValue::get(Alias, 0, 0);
240 static const WeakRefExpr *Create(const MCSymbol *Alias, MCContext &Ctx) {
241 const MCSymbolRefExpr *A = MCSymbolRefExpr::Create(Alias, Ctx);
242 return new (Ctx) WeakRefExpr(A);
245 } // end anonymous namespace
247 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
248 getAssembler().getOrCreateSymbolData(*Symbol);
249 MCSymbolData &AliasSD = getAssembler().getOrCreateSymbolData(*Alias);
250 AliasSD.setFlags(AliasSD.getFlags() | ELF_Other_Weakref);
252 // Create the alias that actually points to Symbol
253 const MCSymbolRefExpr *SymRef = MCSymbolRefExpr::Create(Symbol, getContext());
254 MCSymbol *RealAlias = getContext().CreateTempSymbol();
255 RealAlias->setVariableValue(SymRef);
257 MCSymbolData &RealAliasSD = getAssembler().getOrCreateSymbolData(*RealAlias);
258 RealAliasSD.setFlags(RealAliasSD.getFlags() | ELF_Other_Weakref);
260 const MCExpr *Value = WeakRefExpr::Create(RealAlias, getContext());
261 Alias->setVariableValue(Value);
264 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
265 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
266 Binding == ELF::STB_WEAK);
267 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
268 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
271 static unsigned GetBinding(const MCSymbolData &SD) {
272 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
273 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
274 Binding == ELF::STB_WEAK);
278 static void SetType(MCSymbolData &SD, unsigned Type) {
279 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
280 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
281 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
282 Type == ELF::STT_TLS);
284 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STT_Shift);
285 SD.setFlags(OtherFlags | (Type << ELF_STT_Shift));
288 static void SetVisibility(MCSymbolData &SD, unsigned Visibility) {
289 assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
290 Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
292 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STV_Shift);
293 SD.setFlags(OtherFlags | (Visibility << ELF_STV_Shift));
296 void MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
297 MCSymbolAttr Attribute) {
298 // Indirect symbols are handled differently, to match how 'as' handles
299 // them. This makes writing matching .o files easier.
300 if (Attribute == MCSA_IndirectSymbol) {
301 // Note that we intentionally cannot use the symbol data here; this is
302 // important for matching the string table that 'as' generates.
303 IndirectSymbolData ISD;
305 ISD.SectionData = getCurrentSectionData();
306 getAssembler().getIndirectSymbols().push_back(ISD);
310 // Adding a symbol attribute always introduces the symbol, note that an
311 // important side effect of calling getOrCreateSymbolData here is to register
312 // the symbol with the assembler.
313 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
315 // The implementation of symbol attributes is designed to match 'as', but it
316 // leaves much to desired. It doesn't really make sense to arbitrarily add and
317 // remove flags, but 'as' allows this (in particular, see .desc).
319 // In the future it might be worth trying to make these operations more well
322 case MCSA_LazyReference:
324 case MCSA_NoDeadStrip:
325 case MCSA_PrivateExtern:
326 case MCSA_WeakDefinition:
327 case MCSA_WeakDefAutoPrivate:
329 case MCSA_ELF_TypeIndFunction:
330 case MCSA_IndirectSymbol:
331 assert(0 && "Invalid symbol attribute for ELF!");
335 SetBinding(SD, ELF::STB_GLOBAL);
336 SD.setExternal(true);
337 BindingExplicitlySet.insert(Symbol);
340 case MCSA_WeakReference:
342 SetBinding(SD, ELF::STB_WEAK);
343 SD.setExternal(true);
344 BindingExplicitlySet.insert(Symbol);
348 SetBinding(SD, ELF::STB_LOCAL);
349 SD.setExternal(false);
350 BindingExplicitlySet.insert(Symbol);
353 case MCSA_ELF_TypeFunction:
354 SetType(SD, ELF::STT_FUNC);
357 case MCSA_ELF_TypeObject:
358 SetType(SD, ELF::STT_OBJECT);
361 case MCSA_ELF_TypeTLS:
362 SetType(SD, ELF::STT_TLS);
365 case MCSA_ELF_TypeCommon:
366 SetType(SD, ELF::STT_COMMON);
369 case MCSA_ELF_TypeNoType:
370 SetType(SD, ELF::STT_NOTYPE);
374 SetVisibility(SD, ELF::STV_PROTECTED);
378 SetVisibility(SD, ELF::STV_HIDDEN);
382 SetVisibility(SD, ELF::STV_INTERNAL);
387 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
388 unsigned ByteAlignment) {
389 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
391 if (!BindingExplicitlySet.count(Symbol)) {
392 SetBinding(SD, ELF::STB_GLOBAL);
393 SD.setExternal(true);
396 if (GetBinding(SD) == ELF_STB_Local) {
397 const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
398 MCSectionELF::SHT_NOBITS,
399 MCSectionELF::SHF_WRITE |
400 MCSectionELF::SHF_ALLOC,
401 SectionKind::getBSS());
402 Symbol->setSection(*Section);
404 struct LocalCommon L = {&SD, Size, ByteAlignment};
405 LocalCommons.push_back(L);
407 SD.setCommon(Size, ByteAlignment);
410 SD.setSize(MCConstantExpr::Create(Size, getContext()));
413 void MCELFStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
414 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
416 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
419 void MCELFStreamer::EmitValue(const MCExpr *Value, unsigned Size,
420 unsigned AddrSpace) {
421 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
423 MCDataFragment *DF = getOrCreateDataFragment();
425 // Avoid fixups when possible.
427 if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
428 // FIXME: Endianness assumption.
429 for (unsigned i = 0; i != Size; ++i)
430 DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
432 DF->addFixup(MCFixup::Create(DF->getContents().size(), AddValueSymbols(Value),
433 MCFixup::getKindForSize(Size)));
434 DF->getContents().resize(DF->getContents().size() + Size, 0);
438 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
439 int64_t Value, unsigned ValueSize,
440 unsigned MaxBytesToEmit) {
441 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
443 if (MaxBytesToEmit == 0)
444 MaxBytesToEmit = ByteAlignment;
445 new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
446 getCurrentSectionData());
448 // Update the maximum alignment on the current section if necessary.
449 if (ByteAlignment > getCurrentSectionData()->getAlignment())
450 getCurrentSectionData()->setAlignment(ByteAlignment);
453 void MCELFStreamer::EmitCodeAlignment(unsigned ByteAlignment,
454 unsigned MaxBytesToEmit) {
455 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
457 if (MaxBytesToEmit == 0)
458 MaxBytesToEmit = ByteAlignment;
459 MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
460 getCurrentSectionData());
461 F->setEmitNops(true);
463 // Update the maximum alignment on the current section if necessary.
464 if (ByteAlignment > getCurrentSectionData()->getAlignment())
465 getCurrentSectionData()->setAlignment(ByteAlignment);
468 void MCELFStreamer::EmitValueToOffset(const MCExpr *Offset,
469 unsigned char Value) {
470 // TODO: This is exactly the same as MCMachOStreamer. Consider merging into
472 new MCOrgFragment(*Offset, Value, getCurrentSectionData());
475 // Add a symbol for the file name of this module. This is the second
476 // entry in the module's symbol table (the first being the null symbol).
477 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
478 MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
479 Symbol->setSection(*CurSection);
480 Symbol->setAbsolute();
482 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
484 SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
487 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
488 MCInstFragment *IF = new MCInstFragment(Inst, getCurrentSectionData());
490 // Add the fixups and data.
492 // FIXME: Revisit this design decision when relaxation is done, we may be
493 // able to get away with not storing any extra data in the MCInst.
494 SmallVector<MCFixup, 4> Fixups;
495 SmallString<256> Code;
496 raw_svector_ostream VecOS(Code);
497 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
500 IF->getCode() = Code;
501 IF->getFixups() = Fixups;
504 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
505 MCDataFragment *DF = getOrCreateDataFragment();
507 SmallVector<MCFixup, 4> Fixups;
508 SmallString<256> Code;
509 raw_svector_ostream VecOS(Code);
510 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
513 // Add the fixups and data.
514 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
515 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
516 DF->addFixup(Fixups[i]);
518 DF->getContents().append(Code.begin(), Code.end());
521 void MCELFStreamer::Finish() {
522 // FIXME: duplicated code with the MachO streamer.
523 // Dump out the dwarf file & directory tables and line tables.
524 if (getContext().hasDwarfFiles()) {
525 const MCSection *DwarfLineSection =
526 getContext().getELFSection(".debug_line", 0, 0,
527 SectionKind::getDataRelLocal());
528 MCDwarfFileTable::Emit(this, DwarfLineSection);
531 for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
532 e = LocalCommons.end();
534 MCSymbolData *SD = i->SD;
535 uint64_t Size = i->Size;
536 unsigned ByteAlignment = i->ByteAlignment;
537 const MCSymbol &Symbol = SD->getSymbol();
538 const MCSection &Section = Symbol.getSection();
540 MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
541 new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
543 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
546 // Update the maximum alignment of the section if necessary.
547 if (ByteAlignment > SectData.getAlignment())
548 SectData.setAlignment(ByteAlignment);
551 this->MCObjectStreamer::Finish();
554 MCStreamer *llvm::createELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
555 raw_ostream &OS, MCCodeEmitter *CE,
557 MCELFStreamer *S = new MCELFStreamer(Context, TAB, OS, CE);
559 S->getAssembler().setRelaxAll(true);