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 EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
88 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
89 assert(0 && "ELF doesn't support this directive");
91 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
92 unsigned ByteAlignment);
93 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
94 assert(0 && "ELF doesn't support this directive");
97 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
98 assert(0 && "ELF doesn't support this directive");
101 virtual void EmitCOFFSymbolType(int Type) {
102 assert(0 && "ELF doesn't support this directive");
105 virtual void EndCOFFSymbolDef() {
106 assert(0 && "ELF doesn't support this directive");
109 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
110 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
114 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
115 assert(0 && "ELF doesn't support this directive");
117 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
118 unsigned Size = 0, unsigned ByteAlignment = 0) {
119 assert(0 && "ELF doesn't support this directive");
121 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
122 uint64_t Size, unsigned ByteAlignment = 0) {
123 assert(0 && "ELF doesn't support this directive");
125 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
126 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
127 virtual void EmitGPRel32Value(const MCExpr *Value) {
128 assert(0 && "ELF doesn't support this directive");
130 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
131 unsigned ValueSize = 1,
132 unsigned MaxBytesToEmit = 0);
133 virtual void EmitCodeAlignment(unsigned ByteAlignment,
134 unsigned MaxBytesToEmit = 0);
135 virtual void EmitValueToOffset(const MCExpr *Offset,
136 unsigned char Value = 0);
138 virtual void EmitFileDirective(StringRef Filename);
139 virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
140 DEBUG(dbgs() << "FIXME: MCELFStreamer:EmitDwarfFileDirective not implemented\n");
143 virtual void Finish();
146 virtual void EmitInstToFragment(const MCInst &Inst);
147 virtual void EmitInstToData(const MCInst &Inst);
152 unsigned ByteAlignment;
154 std::vector<LocalCommon> LocalCommons;
156 SmallPtrSet<MCSymbol *, 16> BindingExplicitlySet;
158 void SetSection(StringRef Section, unsigned Type, unsigned Flags,
160 SwitchSection(getContext().getELFSection(Section, Type, Flags, Kind));
163 void SetSectionData() {
164 SetSection(".data", MCSectionELF::SHT_PROGBITS,
165 MCSectionELF::SHF_WRITE |MCSectionELF::SHF_ALLOC,
166 SectionKind::getDataRel());
167 EmitCodeAlignment(4, 0);
169 void SetSectionText() {
170 SetSection(".text", MCSectionELF::SHT_PROGBITS,
171 MCSectionELF::SHF_EXECINSTR |
172 MCSectionELF::SHF_ALLOC, SectionKind::getText());
173 EmitCodeAlignment(4, 0);
175 void SetSectionBss() {
176 SetSection(".bss", MCSectionELF::SHT_NOBITS,
177 MCSectionELF::SHF_WRITE |
178 MCSectionELF::SHF_ALLOC, SectionKind::getBSS());
179 EmitCodeAlignment(4, 0);
183 } // end anonymous namespace.
185 void MCELFStreamer::InitSections() {
186 // This emulates the same behavior of GNU as. This makes it easier
187 // to compare the output as the major sections are in the same order.
194 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
195 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
197 Symbol->setSection(*CurSection);
199 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
201 const MCSectionELF &Section =
202 static_cast<const MCSectionELF&>(Symbol->getSection());
203 if (Section.getFlags() & MCSectionELF::SHF_TLS)
204 SetType(SD, ELF::STT_TLS);
206 // FIXME: This is wasteful, we don't necessarily need to create a data
207 // fragment. Instead, we should mark the symbol as pointing into the data
208 // fragment if it exists, otherwise we should just queue the label and set its
209 // fragment pointer when we emit the next fragment.
210 MCDataFragment *F = getOrCreateDataFragment();
212 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
214 SD.setOffset(F->getContents().size());
217 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
219 case MCAF_SyntaxUnified: return; // no-op here.
220 case MCAF_Code16: return; // no-op here.
221 case MCAF_Code32: return; // no-op here.
222 case MCAF_SubsectionsViaSymbols:
223 getAssembler().setSubsectionsViaSymbols(true);
227 assert(0 && "invalid assembler flag!");
230 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
231 // FIXME: Anything needed here to flag the function as thumb?
234 void MCELFStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
235 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
237 // FIXME: Lift context changes into super class.
238 getAssembler().getOrCreateSymbolData(*Symbol);
239 Symbol->setVariableValue(AddValueSymbols(Value));
242 // This is a hack. To be able to implement weakrefs the writer has to be able
249 // since the first case should produce a weak undefined reference and the second
251 // If we created foo as a regular alias pointing to bar (foo = bar), then
252 // MCExpr::EvaluateAsRelocatable would recurse on foo and the writer would
253 // never see it used in a relocation.
254 // What we do is create a MCTargetExpr that when evaluated produces a symbol
255 // ref to a temporary symbol. This temporary symbol in turn is a variable
256 // that equals the original symbol (tmp = bar). With this hack the writer
257 // gets a relocation with tmp and can correctly implement weak references.
260 class WeakRefExpr : public MCTargetExpr {
262 const MCSymbolRefExpr *Alias;
264 explicit WeakRefExpr(const MCSymbolRefExpr *Alias_)
265 : MCTargetExpr(), Alias(Alias_) {}
268 virtual void PrintImpl(raw_ostream &OS) const {
269 llvm_unreachable("Unimplemented");
272 virtual bool EvaluateAsRelocatableImpl(MCValue &Res,
273 const MCAsmLayout *Layout) const {
274 Res = MCValue::get(Alias, 0, 0);
278 static const WeakRefExpr *Create(const MCSymbol *Alias, MCContext &Ctx) {
279 const MCSymbolRefExpr *A = MCSymbolRefExpr::Create(Alias, Ctx);
280 return new (Ctx) WeakRefExpr(A);
283 } // end anonymous namespace
285 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
286 getAssembler().getOrCreateSymbolData(*Symbol);
287 MCSymbolData &AliasSD = getAssembler().getOrCreateSymbolData(*Alias);
288 AliasSD.setFlags(AliasSD.getFlags() | ELF_Other_Weakref);
290 // Create the alias that actually points to Symbol
291 const MCSymbolRefExpr *SymRef = MCSymbolRefExpr::Create(Symbol, getContext());
292 MCSymbol *RealAlias = getContext().CreateTempSymbol();
293 RealAlias->setVariableValue(SymRef);
295 MCSymbolData &RealAliasSD = getAssembler().getOrCreateSymbolData(*RealAlias);
296 RealAliasSD.setFlags(RealAliasSD.getFlags() | ELF_Other_Weakref);
298 const MCExpr *Value = WeakRefExpr::Create(RealAlias, getContext());
299 Alias->setVariableValue(Value);
302 void MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
303 MCSymbolAttr Attribute) {
304 // Indirect symbols are handled differently, to match how 'as' handles
305 // them. This makes writing matching .o files easier.
306 if (Attribute == MCSA_IndirectSymbol) {
307 // Note that we intentionally cannot use the symbol data here; this is
308 // important for matching the string table that 'as' generates.
309 IndirectSymbolData ISD;
311 ISD.SectionData = getCurrentSectionData();
312 getAssembler().getIndirectSymbols().push_back(ISD);
316 // Adding a symbol attribute always introduces the symbol, note that an
317 // important side effect of calling getOrCreateSymbolData here is to register
318 // the symbol with the assembler.
319 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
321 // The implementation of symbol attributes is designed to match 'as', but it
322 // leaves much to desired. It doesn't really make sense to arbitrarily add and
323 // remove flags, but 'as' allows this (in particular, see .desc).
325 // In the future it might be worth trying to make these operations more well
328 case MCSA_LazyReference:
330 case MCSA_NoDeadStrip:
331 case MCSA_PrivateExtern:
332 case MCSA_WeakDefinition:
333 case MCSA_WeakDefAutoPrivate:
335 case MCSA_ELF_TypeIndFunction:
336 case MCSA_IndirectSymbol:
337 assert(0 && "Invalid symbol attribute for ELF!");
340 case MCSA_ELF_TypeGnuUniqueObject:
345 SetBinding(SD, ELF::STB_GLOBAL);
346 SD.setExternal(true);
347 BindingExplicitlySet.insert(Symbol);
350 case MCSA_WeakReference:
352 SetBinding(SD, ELF::STB_WEAK);
353 SD.setExternal(true);
354 BindingExplicitlySet.insert(Symbol);
358 SetBinding(SD, ELF::STB_LOCAL);
359 SD.setExternal(false);
360 BindingExplicitlySet.insert(Symbol);
363 case MCSA_ELF_TypeFunction:
364 SetType(SD, ELF::STT_FUNC);
367 case MCSA_ELF_TypeObject:
368 SetType(SD, ELF::STT_OBJECT);
371 case MCSA_ELF_TypeTLS:
372 SetType(SD, ELF::STT_TLS);
375 case MCSA_ELF_TypeCommon:
376 SetType(SD, ELF::STT_COMMON);
379 case MCSA_ELF_TypeNoType:
380 SetType(SD, ELF::STT_NOTYPE);
384 SetVisibility(SD, ELF::STV_PROTECTED);
388 SetVisibility(SD, ELF::STV_HIDDEN);
392 SetVisibility(SD, ELF::STV_INTERNAL);
397 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
398 unsigned ByteAlignment) {
399 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
401 if (!BindingExplicitlySet.count(Symbol)) {
402 SetBinding(SD, ELF::STB_GLOBAL);
403 SD.setExternal(true);
406 if (GetBinding(SD) == ELF_STB_Local) {
407 const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
408 MCSectionELF::SHT_NOBITS,
409 MCSectionELF::SHF_WRITE |
410 MCSectionELF::SHF_ALLOC,
411 SectionKind::getBSS());
412 Symbol->setSection(*Section);
414 struct LocalCommon L = {&SD, Size, ByteAlignment};
415 LocalCommons.push_back(L);
417 SD.setCommon(Size, ByteAlignment);
420 SD.setSize(MCConstantExpr::Create(Size, getContext()));
423 void MCELFStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
424 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
426 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
429 void MCELFStreamer::EmitValue(const MCExpr *Value, unsigned Size,
430 unsigned AddrSpace) {
431 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
433 MCDataFragment *DF = getOrCreateDataFragment();
435 // Avoid fixups when possible.
437 if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
438 // FIXME: Endianness assumption.
439 for (unsigned i = 0; i != Size; ++i)
440 DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
442 DF->addFixup(MCFixup::Create(DF->getContents().size(), AddValueSymbols(Value),
443 MCFixup::getKindForSize(Size)));
444 DF->getContents().resize(DF->getContents().size() + Size, 0);
448 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
449 int64_t Value, unsigned ValueSize,
450 unsigned MaxBytesToEmit) {
451 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
453 if (MaxBytesToEmit == 0)
454 MaxBytesToEmit = ByteAlignment;
455 new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
456 getCurrentSectionData());
458 // Update the maximum alignment on the current section if necessary.
459 if (ByteAlignment > getCurrentSectionData()->getAlignment())
460 getCurrentSectionData()->setAlignment(ByteAlignment);
463 void MCELFStreamer::EmitCodeAlignment(unsigned ByteAlignment,
464 unsigned MaxBytesToEmit) {
465 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
467 if (MaxBytesToEmit == 0)
468 MaxBytesToEmit = ByteAlignment;
469 MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
470 getCurrentSectionData());
471 F->setEmitNops(true);
473 // Update the maximum alignment on the current section if necessary.
474 if (ByteAlignment > getCurrentSectionData()->getAlignment())
475 getCurrentSectionData()->setAlignment(ByteAlignment);
478 void MCELFStreamer::EmitValueToOffset(const MCExpr *Offset,
479 unsigned char Value) {
480 // TODO: This is exactly the same as MCMachOStreamer. Consider merging into
482 new MCOrgFragment(*Offset, Value, getCurrentSectionData());
485 // Add a symbol for the file name of this module. This is the second
486 // entry in the module's symbol table (the first being the null symbol).
487 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
488 MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
489 Symbol->setSection(*CurSection);
490 Symbol->setAbsolute();
492 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
494 SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
497 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
498 MCInstFragment *IF = new MCInstFragment(Inst, getCurrentSectionData());
500 // Add the fixups and data.
502 // FIXME: Revisit this design decision when relaxation is done, we may be
503 // able to get away with not storing any extra data in the MCInst.
504 SmallVector<MCFixup, 4> Fixups;
505 SmallString<256> Code;
506 raw_svector_ostream VecOS(Code);
507 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
510 IF->getCode() = Code;
511 IF->getFixups() = Fixups;
514 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
515 MCDataFragment *DF = getOrCreateDataFragment();
517 SmallVector<MCFixup, 4> Fixups;
518 SmallString<256> Code;
519 raw_svector_ostream VecOS(Code);
520 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
523 // Add the fixups and data.
524 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
525 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
526 DF->addFixup(Fixups[i]);
528 DF->getContents().append(Code.begin(), Code.end());
531 void MCELFStreamer::Finish() {
532 // FIXME: duplicated code with the MachO streamer.
533 // Dump out the dwarf file & directory tables and line tables.
534 if (getContext().hasDwarfFiles()) {
535 const MCSection *DwarfLineSection =
536 getContext().getELFSection(".debug_line", 0, 0,
537 SectionKind::getDataRelLocal());
538 MCDwarfFileTable::Emit(this, DwarfLineSection);
541 for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
542 e = LocalCommons.end();
544 MCSymbolData *SD = i->SD;
545 uint64_t Size = i->Size;
546 unsigned ByteAlignment = i->ByteAlignment;
547 const MCSymbol &Symbol = SD->getSymbol();
548 const MCSection &Section = Symbol.getSection();
550 MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
551 new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
553 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
556 // Update the maximum alignment of the section if necessary.
557 if (ByteAlignment > SectData.getAlignment())
558 SectData.setAlignment(ByteAlignment);
561 this->MCObjectStreamer::Finish();
564 MCStreamer *llvm::createELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
565 raw_ostream &OS, MCCodeEmitter *CE,
567 MCELFStreamer *S = new MCELFStreamer(Context, TAB, OS, CE);
569 S->getAssembler().setRelaxAll(true);