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"
33 #include "llvm/Target/TargetAsmInfo.h"
39 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
40 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
41 Binding == ELF::STB_WEAK);
42 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
43 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
46 static unsigned GetBinding(const MCSymbolData &SD) {
47 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
48 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
49 Binding == ELF::STB_WEAK);
53 static void SetType(MCSymbolData &SD, unsigned Type) {
54 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
55 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
56 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
57 Type == ELF::STT_TLS);
59 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STT_Shift);
60 SD.setFlags(OtherFlags | (Type << ELF_STT_Shift));
63 static void SetVisibility(MCSymbolData &SD, unsigned Visibility) {
64 assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
65 Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
67 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STV_Shift);
68 SD.setFlags(OtherFlags | (Visibility << ELF_STV_Shift));
71 class MCELFStreamer : public MCObjectStreamer {
73 MCELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
74 raw_ostream &OS, MCCodeEmitter *Emitter)
75 : MCObjectStreamer(Context, TAB, OS, Emitter) {}
79 /// @name MCStreamer Interface
82 virtual void InitSections();
83 virtual void ChangeSection(const MCSection *Section);
84 virtual void EmitLabel(MCSymbol *Symbol);
85 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
86 virtual void EmitThumbFunc(MCSymbol *Func);
87 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
88 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
89 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
90 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
91 assert(0 && "ELF doesn't support this directive");
93 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
94 unsigned ByteAlignment);
95 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
96 assert(0 && "ELF doesn't support this directive");
99 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
100 assert(0 && "ELF doesn't support this directive");
103 virtual void EmitCOFFSymbolType(int Type) {
104 assert(0 && "ELF doesn't support this directive");
107 virtual void EndCOFFSymbolDef() {
108 assert(0 && "ELF doesn't support this directive");
111 virtual void EmitCOFFSecRel32(MCSymbol const *Symbol) {
112 assert(0 && "ELF doesn't support this directive");
115 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
116 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
120 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size);
122 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
123 unsigned Size = 0, unsigned ByteAlignment = 0) {
124 assert(0 && "ELF doesn't support this directive");
126 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
127 uint64_t Size, unsigned ByteAlignment = 0) {
128 assert(0 && "ELF doesn't support this directive");
130 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
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);
137 virtual void EmitFileDirective(StringRef Filename);
139 virtual void Finish();
142 virtual void EmitInstToFragment(const MCInst &Inst);
143 virtual void EmitInstToData(const MCInst &Inst);
145 void fixSymbolsInTLSFixups(const MCExpr *expr);
150 unsigned ByteAlignment;
152 std::vector<LocalCommon> LocalCommons;
154 SmallPtrSet<MCSymbol *, 16> BindingExplicitlySet;
156 void SetSection(StringRef Section, unsigned Type, unsigned Flags,
158 SwitchSection(getContext().getELFSection(Section, Type, Flags, Kind));
161 void SetSectionData() {
162 SetSection(".data", ELF::SHT_PROGBITS,
163 ELF::SHF_WRITE |ELF::SHF_ALLOC,
164 SectionKind::getDataRel());
165 EmitCodeAlignment(4, 0);
167 void SetSectionText() {
168 SetSection(".text", ELF::SHT_PROGBITS,
170 ELF::SHF_ALLOC, SectionKind::getText());
171 EmitCodeAlignment(4, 0);
173 void SetSectionBss() {
174 SetSection(".bss", ELF::SHT_NOBITS,
176 ELF::SHF_ALLOC, SectionKind::getBSS());
177 EmitCodeAlignment(4, 0);
181 } // end anonymous namespace.
183 void MCELFStreamer::InitSections() {
184 // This emulates the same behavior of GNU as. This makes it easier
185 // to compare the output as the major sections are in the same order.
192 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
193 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
195 MCObjectStreamer::EmitLabel(Symbol);
197 const MCSectionELF &Section =
198 static_cast<const MCSectionELF&>(Symbol->getSection());
199 MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
200 if (Section.getFlags() & ELF::SHF_TLS)
201 SetType(SD, ELF::STT_TLS);
204 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
206 case MCAF_SyntaxUnified: return; // no-op here.
207 case MCAF_Code16: return; // no-op here.
208 case MCAF_Code32: return; // no-op here.
209 case MCAF_SubsectionsViaSymbols:
210 getAssembler().setSubsectionsViaSymbols(true);
214 assert(0 && "invalid assembler flag!");
217 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
218 // FIXME: Anything needed here to flag the function as thumb?
221 void MCELFStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
222 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
224 // FIXME: Lift context changes into super class.
225 getAssembler().getOrCreateSymbolData(*Symbol);
226 Symbol->setVariableValue(AddValueSymbols(Value));
229 void MCELFStreamer::ChangeSection(const MCSection *Section) {
230 const MCSymbol *Grp = static_cast<const MCSectionELF *>(Section)->getGroup();
232 getAssembler().getOrCreateSymbolData(*Grp);
233 this->MCObjectStreamer::ChangeSection(Section);
236 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
237 getAssembler().getOrCreateSymbolData(*Symbol);
238 MCSymbolData &AliasSD = getAssembler().getOrCreateSymbolData(*Alias);
239 AliasSD.setFlags(AliasSD.getFlags() | ELF_Other_Weakref);
240 const MCExpr *Value = MCSymbolRefExpr::Create(Symbol, getContext());
241 Alias->setVariableValue(Value);
244 void MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
245 MCSymbolAttr Attribute) {
246 // Indirect symbols are handled differently, to match how 'as' handles
247 // them. This makes writing matching .o files easier.
248 if (Attribute == MCSA_IndirectSymbol) {
249 // Note that we intentionally cannot use the symbol data here; this is
250 // important for matching the string table that 'as' generates.
251 IndirectSymbolData ISD;
253 ISD.SectionData = getCurrentSectionData();
254 getAssembler().getIndirectSymbols().push_back(ISD);
258 // Adding a symbol attribute always introduces the symbol, note that an
259 // important side effect of calling getOrCreateSymbolData here is to register
260 // the symbol with the assembler.
261 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
263 // The implementation of symbol attributes is designed to match 'as', but it
264 // leaves much to desired. It doesn't really make sense to arbitrarily add and
265 // remove flags, but 'as' allows this (in particular, see .desc).
267 // In the future it might be worth trying to make these operations more well
270 case MCSA_LazyReference:
272 case MCSA_NoDeadStrip:
273 case MCSA_SymbolResolver:
274 case MCSA_PrivateExtern:
275 case MCSA_WeakDefinition:
276 case MCSA_WeakDefAutoPrivate:
278 case MCSA_ELF_TypeIndFunction:
279 case MCSA_IndirectSymbol:
280 assert(0 && "Invalid symbol attribute for ELF!");
283 case MCSA_ELF_TypeGnuUniqueObject:
288 SetBinding(SD, ELF::STB_GLOBAL);
289 SD.setExternal(true);
290 BindingExplicitlySet.insert(Symbol);
293 case MCSA_WeakReference:
295 SetBinding(SD, ELF::STB_WEAK);
296 SD.setExternal(true);
297 BindingExplicitlySet.insert(Symbol);
301 SetBinding(SD, ELF::STB_LOCAL);
302 SD.setExternal(false);
303 BindingExplicitlySet.insert(Symbol);
306 case MCSA_ELF_TypeFunction:
307 SetType(SD, ELF::STT_FUNC);
310 case MCSA_ELF_TypeObject:
311 SetType(SD, ELF::STT_OBJECT);
314 case MCSA_ELF_TypeTLS:
315 SetType(SD, ELF::STT_TLS);
318 case MCSA_ELF_TypeCommon:
319 SetType(SD, ELF::STT_COMMON);
322 case MCSA_ELF_TypeNoType:
323 SetType(SD, ELF::STT_NOTYPE);
327 SetVisibility(SD, ELF::STV_PROTECTED);
331 SetVisibility(SD, ELF::STV_HIDDEN);
335 SetVisibility(SD, ELF::STV_INTERNAL);
340 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
341 unsigned ByteAlignment) {
342 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
344 if (!BindingExplicitlySet.count(Symbol)) {
345 SetBinding(SD, ELF::STB_GLOBAL);
346 SD.setExternal(true);
349 SetType(SD, ELF::STT_OBJECT);
351 if (GetBinding(SD) == ELF_STB_Local) {
352 const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
356 SectionKind::getBSS());
357 Symbol->setSection(*Section);
359 struct LocalCommon L = {&SD, Size, ByteAlignment};
360 LocalCommons.push_back(L);
362 SD.setCommon(Size, ByteAlignment);
365 SD.setSize(MCConstantExpr::Create(Size, getContext()));
368 void MCELFStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
369 // FIXME: Should this be caught and done earlier?
370 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
371 SetBinding(SD, ELF::STB_LOCAL);
372 SD.setExternal(false);
373 BindingExplicitlySet.insert(Symbol);
374 // FIXME: ByteAlignment is not needed here, but is required.
375 EmitCommonSymbol(Symbol, Size, 1);
378 void MCELFStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
379 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
381 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
384 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
385 int64_t Value, unsigned ValueSize,
386 unsigned MaxBytesToEmit) {
387 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
389 if (MaxBytesToEmit == 0)
390 MaxBytesToEmit = ByteAlignment;
391 new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
392 getCurrentSectionData());
394 // Update the maximum alignment on the current section if necessary.
395 if (ByteAlignment > getCurrentSectionData()->getAlignment())
396 getCurrentSectionData()->setAlignment(ByteAlignment);
399 void MCELFStreamer::EmitCodeAlignment(unsigned ByteAlignment,
400 unsigned MaxBytesToEmit) {
401 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
403 if (MaxBytesToEmit == 0)
404 MaxBytesToEmit = ByteAlignment;
405 MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
406 getCurrentSectionData());
407 F->setEmitNops(true);
409 // Update the maximum alignment on the current section if necessary.
410 if (ByteAlignment > getCurrentSectionData()->getAlignment())
411 getCurrentSectionData()->setAlignment(ByteAlignment);
414 // Add a symbol for the file name of this module. This is the second
415 // entry in the module's symbol table (the first being the null symbol).
416 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
417 MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
418 Symbol->setSection(*getCurrentSection());
419 Symbol->setAbsolute();
421 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
423 SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
426 void MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
427 switch (expr->getKind()) {
428 case MCExpr::Target: llvm_unreachable("Can't handle target exprs yet!");
429 case MCExpr::Constant:
432 case MCExpr::Binary: {
433 const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
434 fixSymbolsInTLSFixups(be->getLHS());
435 fixSymbolsInTLSFixups(be->getRHS());
439 case MCExpr::SymbolRef: {
440 const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
441 switch (symRef.getKind()) {
444 case MCSymbolRefExpr::VK_NTPOFF:
445 case MCSymbolRefExpr::VK_GOTNTPOFF:
446 case MCSymbolRefExpr::VK_TLSGD:
447 case MCSymbolRefExpr::VK_TLSLDM:
448 case MCSymbolRefExpr::VK_TPOFF:
449 case MCSymbolRefExpr::VK_DTPOFF:
450 case MCSymbolRefExpr::VK_GOTTPOFF:
451 case MCSymbolRefExpr::VK_TLSLD:
452 case MCSymbolRefExpr::VK_ARM_TLSGD:
455 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(symRef.getSymbol());
456 SetType(SD, ELF::STT_TLS);
461 fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
466 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
467 this->MCObjectStreamer::EmitInstToFragment(Inst);
468 MCInstFragment &F = *cast<MCInstFragment>(getCurrentFragment());
470 for (unsigned i = 0, e = F.getFixups().size(); i != e; ++i)
471 fixSymbolsInTLSFixups(F.getFixups()[i].getValue());
474 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
475 MCDataFragment *DF = getOrCreateDataFragment();
477 SmallVector<MCFixup, 4> Fixups;
478 SmallString<256> Code;
479 raw_svector_ostream VecOS(Code);
480 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
483 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
484 fixSymbolsInTLSFixups(Fixups[i].getValue());
486 // Add the fixups and data.
487 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
488 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
489 DF->addFixup(Fixups[i]);
491 DF->getContents().append(Code.begin(), Code.end());
494 void MCELFStreamer::Finish() {
495 if (getNumFrameInfos())
496 MCDwarfFrameEmitter::Emit(*this);
498 for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
499 e = LocalCommons.end();
501 MCSymbolData *SD = i->SD;
502 uint64_t Size = i->Size;
503 unsigned ByteAlignment = i->ByteAlignment;
504 const MCSymbol &Symbol = SD->getSymbol();
505 const MCSection &Section = Symbol.getSection();
507 MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
508 new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
510 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
513 // Update the maximum alignment of the section if necessary.
514 if (ByteAlignment > SectData.getAlignment())
515 SectData.setAlignment(ByteAlignment);
518 this->MCObjectStreamer::Finish();
521 MCStreamer *llvm::createELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
522 raw_ostream &OS, MCCodeEmitter *CE,
523 bool RelaxAll, bool NoExecStack) {
524 MCELFStreamer *S = new MCELFStreamer(Context, TAB, OS, CE);
526 S->getAssembler().setRelaxAll(true);
528 S->getAssembler().setNoExecStack(true);