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 EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
129 unsigned ValueSize = 1,
130 unsigned MaxBytesToEmit = 0);
131 virtual void EmitCodeAlignment(unsigned ByteAlignment,
132 unsigned MaxBytesToEmit = 0);
133 virtual void EmitValueToOffset(const MCExpr *Offset,
134 unsigned char Value = 0);
136 virtual void EmitFileDirective(StringRef Filename);
138 virtual void Finish();
141 virtual void EmitInstToFragment(const MCInst &Inst);
142 virtual void EmitInstToData(const MCInst &Inst);
144 void fixSymbolsInTLSFixups(const MCExpr *expr);
149 unsigned ByteAlignment;
151 std::vector<LocalCommon> LocalCommons;
153 SmallPtrSet<MCSymbol *, 16> BindingExplicitlySet;
155 void SetSection(StringRef Section, unsigned Type, unsigned Flags,
157 SwitchSection(getContext().getELFSection(Section, Type, Flags, Kind));
160 void SetSectionData() {
161 SetSection(".data", MCSectionELF::SHT_PROGBITS,
162 MCSectionELF::SHF_WRITE |MCSectionELF::SHF_ALLOC,
163 SectionKind::getDataRel());
164 EmitCodeAlignment(4, 0);
166 void SetSectionText() {
167 SetSection(".text", MCSectionELF::SHT_PROGBITS,
168 MCSectionELF::SHF_EXECINSTR |
169 MCSectionELF::SHF_ALLOC, SectionKind::getText());
170 EmitCodeAlignment(4, 0);
172 void SetSectionBss() {
173 SetSection(".bss", MCSectionELF::SHT_NOBITS,
174 MCSectionELF::SHF_WRITE |
175 MCSectionELF::SHF_ALLOC, SectionKind::getBSS());
176 EmitCodeAlignment(4, 0);
180 } // end anonymous namespace.
182 void MCELFStreamer::InitSections() {
183 // This emulates the same behavior of GNU as. This makes it easier
184 // to compare the output as the major sections are in the same order.
191 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
192 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
194 MCObjectStreamer::EmitLabel(Symbol);
196 const MCSectionELF &Section =
197 static_cast<const MCSectionELF&>(Symbol->getSection());
198 MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
199 if (Section.getFlags() & MCSectionELF::SHF_TLS)
200 SetType(SD, ELF::STT_TLS);
203 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
205 case MCAF_SyntaxUnified: return; // no-op here.
206 case MCAF_Code16: return; // no-op here.
207 case MCAF_Code32: return; // no-op here.
208 case MCAF_SubsectionsViaSymbols:
209 getAssembler().setSubsectionsViaSymbols(true);
213 assert(0 && "invalid assembler flag!");
216 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
217 // FIXME: Anything needed here to flag the function as thumb?
220 void MCELFStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
221 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
223 // FIXME: Lift context changes into super class.
224 getAssembler().getOrCreateSymbolData(*Symbol);
225 Symbol->setVariableValue(AddValueSymbols(Value));
228 void MCELFStreamer::SwitchSection(const MCSection *Section) {
229 const MCSymbol *Grp = static_cast<const MCSectionELF *>(Section)->getGroup();
231 getAssembler().getOrCreateSymbolData(*Grp);
232 this->MCObjectStreamer::SwitchSection(Section);
235 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
236 getAssembler().getOrCreateSymbolData(*Symbol);
237 MCSymbolData &AliasSD = getAssembler().getOrCreateSymbolData(*Alias);
238 AliasSD.setFlags(AliasSD.getFlags() | ELF_Other_Weakref);
239 const MCExpr *Value = MCSymbolRefExpr::Create(Symbol, getContext());
240 Alias->setVariableValue(Value);
243 void MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
244 MCSymbolAttr Attribute) {
245 // Indirect symbols are handled differently, to match how 'as' handles
246 // them. This makes writing matching .o files easier.
247 if (Attribute == MCSA_IndirectSymbol) {
248 // Note that we intentionally cannot use the symbol data here; this is
249 // important for matching the string table that 'as' generates.
250 IndirectSymbolData ISD;
252 ISD.SectionData = getCurrentSectionData();
253 getAssembler().getIndirectSymbols().push_back(ISD);
257 // Adding a symbol attribute always introduces the symbol, note that an
258 // important side effect of calling getOrCreateSymbolData here is to register
259 // the symbol with the assembler.
260 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
262 // The implementation of symbol attributes is designed to match 'as', but it
263 // leaves much to desired. It doesn't really make sense to arbitrarily add and
264 // remove flags, but 'as' allows this (in particular, see .desc).
266 // In the future it might be worth trying to make these operations more well
269 case MCSA_LazyReference:
271 case MCSA_NoDeadStrip:
272 case MCSA_SymbolResolver:
273 case MCSA_PrivateExtern:
274 case MCSA_WeakDefinition:
275 case MCSA_WeakDefAutoPrivate:
277 case MCSA_ELF_TypeIndFunction:
278 case MCSA_IndirectSymbol:
279 assert(0 && "Invalid symbol attribute for ELF!");
282 case MCSA_ELF_TypeGnuUniqueObject:
287 SetBinding(SD, ELF::STB_GLOBAL);
288 SD.setExternal(true);
289 BindingExplicitlySet.insert(Symbol);
292 case MCSA_WeakReference:
294 SetBinding(SD, ELF::STB_WEAK);
295 SD.setExternal(true);
296 BindingExplicitlySet.insert(Symbol);
300 SetBinding(SD, ELF::STB_LOCAL);
301 SD.setExternal(false);
302 BindingExplicitlySet.insert(Symbol);
305 case MCSA_ELF_TypeFunction:
306 SetType(SD, ELF::STT_FUNC);
309 case MCSA_ELF_TypeObject:
310 SetType(SD, ELF::STT_OBJECT);
313 case MCSA_ELF_TypeTLS:
314 SetType(SD, ELF::STT_TLS);
317 case MCSA_ELF_TypeCommon:
318 SetType(SD, ELF::STT_COMMON);
321 case MCSA_ELF_TypeNoType:
322 SetType(SD, ELF::STT_NOTYPE);
326 SetVisibility(SD, ELF::STV_PROTECTED);
330 SetVisibility(SD, ELF::STV_HIDDEN);
334 SetVisibility(SD, ELF::STV_INTERNAL);
339 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
340 unsigned ByteAlignment) {
341 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
343 if (!BindingExplicitlySet.count(Symbol)) {
344 SetBinding(SD, ELF::STB_GLOBAL);
345 SD.setExternal(true);
348 SetType(SD, ELF::STT_OBJECT);
350 if (GetBinding(SD) == ELF_STB_Local) {
351 const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
352 MCSectionELF::SHT_NOBITS,
353 MCSectionELF::SHF_WRITE |
354 MCSectionELF::SHF_ALLOC,
355 SectionKind::getBSS());
356 Symbol->setSection(*Section);
358 struct LocalCommon L = {&SD, Size, ByteAlignment};
359 LocalCommons.push_back(L);
361 SD.setCommon(Size, ByteAlignment);
364 SD.setSize(MCConstantExpr::Create(Size, getContext()));
367 void MCELFStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
368 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
370 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
373 void MCELFStreamer::EmitValue(const MCExpr *Value, unsigned Size,
374 unsigned AddrSpace) {
375 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
377 MCDataFragment *DF = getOrCreateDataFragment();
379 // Avoid fixups when possible.
381 if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
382 // FIXME: Endianness assumption.
383 for (unsigned i = 0; i != Size; ++i)
384 DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
386 DF->addFixup(MCFixup::Create(DF->getContents().size(), AddValueSymbols(Value),
387 MCFixup::getKindForSize(Size, false)));
388 DF->getContents().resize(DF->getContents().size() + Size, 0);
392 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
393 int64_t Value, unsigned ValueSize,
394 unsigned MaxBytesToEmit) {
395 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
397 if (MaxBytesToEmit == 0)
398 MaxBytesToEmit = ByteAlignment;
399 new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
400 getCurrentSectionData());
402 // Update the maximum alignment on the current section if necessary.
403 if (ByteAlignment > getCurrentSectionData()->getAlignment())
404 getCurrentSectionData()->setAlignment(ByteAlignment);
407 void MCELFStreamer::EmitCodeAlignment(unsigned ByteAlignment,
408 unsigned MaxBytesToEmit) {
409 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
411 if (MaxBytesToEmit == 0)
412 MaxBytesToEmit = ByteAlignment;
413 MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
414 getCurrentSectionData());
415 F->setEmitNops(true);
417 // Update the maximum alignment on the current section if necessary.
418 if (ByteAlignment > getCurrentSectionData()->getAlignment())
419 getCurrentSectionData()->setAlignment(ByteAlignment);
422 void MCELFStreamer::EmitValueToOffset(const MCExpr *Offset,
423 unsigned char Value) {
424 // TODO: This is exactly the same as MCMachOStreamer. Consider merging into
426 new MCOrgFragment(*Offset, Value, getCurrentSectionData());
429 // Add a symbol for the file name of this module. This is the second
430 // entry in the module's symbol table (the first being the null symbol).
431 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
432 MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
433 Symbol->setSection(*CurSection);
434 Symbol->setAbsolute();
436 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
438 SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
441 void MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
442 switch (expr->getKind()) {
443 case MCExpr::Target: llvm_unreachable("Can't handle target exprs yet!");
444 case MCExpr::Constant:
447 case MCExpr::Binary: {
448 const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
449 fixSymbolsInTLSFixups(be->getLHS());
450 fixSymbolsInTLSFixups(be->getRHS());
454 case MCExpr::SymbolRef: {
455 const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
456 switch (symRef.getKind()) {
459 case MCSymbolRefExpr::VK_NTPOFF:
460 case MCSymbolRefExpr::VK_GOTNTPOFF:
461 case MCSymbolRefExpr::VK_TLSGD:
462 case MCSymbolRefExpr::VK_TLSLDM:
463 case MCSymbolRefExpr::VK_TPOFF:
464 case MCSymbolRefExpr::VK_DTPOFF:
465 case MCSymbolRefExpr::VK_GOTTPOFF:
466 case MCSymbolRefExpr::VK_TLSLD:
467 case MCSymbolRefExpr::VK_ARM_TLSGD:
470 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(symRef.getSymbol());
471 SetType(SD, ELF::STT_TLS);
476 fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
481 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
482 MCInstFragment *IF = new MCInstFragment(Inst, getCurrentSectionData());
484 // Add the fixups and data.
486 // FIXME: Revisit this design decision when relaxation is done, we may be
487 // able to get away with not storing any extra data in the MCInst.
488 SmallVector<MCFixup, 4> Fixups;
489 SmallString<256> Code;
490 raw_svector_ostream VecOS(Code);
491 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
494 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
495 fixSymbolsInTLSFixups(Fixups[i].getValue());
497 IF->getCode() = Code;
498 IF->getFixups() = Fixups;
501 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
502 MCDataFragment *DF = getOrCreateDataFragment();
504 SmallVector<MCFixup, 4> Fixups;
505 SmallString<256> Code;
506 raw_svector_ostream VecOS(Code);
507 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
510 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
511 fixSymbolsInTLSFixups(Fixups[i].getValue());
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());
529 getAssembler().getOrCreateSectionData(*DwarfLineSection);
530 int PointerSize = getAssembler().getBackend().getPointerSize();
531 MCDwarfFileTable::Emit(this, DwarfLineSection, &DLS, PointerSize);
534 for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
535 e = LocalCommons.end();
537 MCSymbolData *SD = i->SD;
538 uint64_t Size = i->Size;
539 unsigned ByteAlignment = i->ByteAlignment;
540 const MCSymbol &Symbol = SD->getSymbol();
541 const MCSection &Section = Symbol.getSection();
543 MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
544 new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
546 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
549 // Update the maximum alignment of the section if necessary.
550 if (ByteAlignment > SectData.getAlignment())
551 SectData.setAlignment(ByteAlignment);
554 this->MCObjectStreamer::Finish();
557 MCStreamer *llvm::createELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
558 raw_ostream &OS, MCCodeEmitter *CE,
560 MCELFStreamer *S = new MCELFStreamer(Context, TAB, OS, CE);
562 S->getAssembler().setRelaxAll(true);