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/Support/Debug.h"
28 #include "llvm/Support/ELF.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Target/TargetAsmBackend.h"
37 class MCELFStreamer : public MCObjectStreamer {
38 void EmitInstToFragment(const MCInst &Inst);
39 void EmitInstToData(const MCInst &Inst);
41 MCELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
42 raw_ostream &OS, MCCodeEmitter *Emitter)
43 : MCObjectStreamer(Context, TAB, OS, Emitter, false) {}
47 /// @name MCStreamer Interface
50 virtual void InitSections();
51 virtual void EmitLabel(MCSymbol *Symbol);
52 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
53 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
54 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
55 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
56 assert(0 && "ELF doesn't support this directive");
58 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
59 unsigned ByteAlignment);
60 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
61 assert(0 && "ELF doesn't support this directive");
64 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
65 assert(0 && "ELF doesn't support this directive");
68 virtual void EmitCOFFSymbolType(int Type) {
69 assert(0 && "ELF doesn't support this directive");
72 virtual void EndCOFFSymbolDef() {
73 assert(0 && "ELF doesn't support this directive");
76 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
77 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
81 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
82 assert(0 && "ELF doesn't support this directive");
84 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
85 unsigned Size = 0, unsigned ByteAlignment = 0) {
86 assert(0 && "ELF doesn't support this directive");
88 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
89 uint64_t Size, unsigned ByteAlignment = 0) {
90 assert(0 && "ELF doesn't support this directive");
92 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
93 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
94 virtual void EmitGPRel32Value(const MCExpr *Value) {
95 assert(0 && "ELF doesn't support this directive");
97 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
98 unsigned ValueSize = 1,
99 unsigned MaxBytesToEmit = 0);
100 virtual void EmitCodeAlignment(unsigned ByteAlignment,
101 unsigned MaxBytesToEmit = 0);
102 virtual void EmitValueToOffset(const MCExpr *Offset,
103 unsigned char Value = 0);
105 virtual void EmitFileDirective(StringRef Filename);
106 virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
107 DEBUG(dbgs() << "FIXME: MCELFStreamer:EmitDwarfFileDirective not implemented\n");
110 virtual void EmitInstruction(const MCInst &Inst);
111 virtual void Finish();
117 unsigned ByteAlignment;
119 std::vector<LocalCommon> LocalCommons;
121 SmallPtrSet<MCSymbol *, 16> BindingExplicitlySet;
123 void SetSection(StringRef Section, unsigned Type, unsigned Flags,
125 SwitchSection(getContext().getELFSection(Section, Type, Flags, Kind));
128 void SetSectionData() {
129 SetSection(".data", MCSectionELF::SHT_PROGBITS,
130 MCSectionELF::SHF_WRITE |MCSectionELF::SHF_ALLOC,
131 SectionKind::getDataRel());
132 EmitCodeAlignment(4, 0);
134 void SetSectionText() {
135 SetSection(".text", MCSectionELF::SHT_PROGBITS,
136 MCSectionELF::SHF_EXECINSTR |
137 MCSectionELF::SHF_ALLOC, SectionKind::getText());
138 EmitCodeAlignment(4, 0);
140 void SetSectionBss() {
141 SetSection(".bss", MCSectionELF::SHT_NOBITS,
142 MCSectionELF::SHF_WRITE |
143 MCSectionELF::SHF_ALLOC, SectionKind::getBSS());
144 EmitCodeAlignment(4, 0);
148 } // end anonymous namespace.
150 void MCELFStreamer::InitSections() {
151 // This emulates the same behavior of GNU as. This makes it easier
152 // to compare the output as the major sections are in the same order.
159 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
160 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
162 Symbol->setSection(*CurSection);
164 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
166 // FIXME: This is wasteful, we don't necessarily need to create a data
167 // fragment. Instead, we should mark the symbol as pointing into the data
168 // fragment if it exists, otherwise we should just queue the label and set its
169 // fragment pointer when we emit the next fragment.
170 MCDataFragment *F = getOrCreateDataFragment();
172 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
174 SD.setOffset(F->getContents().size());
177 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
179 case MCAF_SyntaxUnified: return; // no-op here?
180 case MCAF_SubsectionsViaSymbols:
181 getAssembler().setSubsectionsViaSymbols(true);
185 assert(0 && "invalid assembler flag!");
188 void MCELFStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
189 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
191 // FIXME: Lift context changes into super class.
192 getAssembler().getOrCreateSymbolData(*Symbol);
193 Symbol->setVariableValue(AddValueSymbols(Value));
196 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
197 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
198 Binding == ELF::STB_WEAK);
199 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
200 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
203 static unsigned GetBinding(const MCSymbolData &SD) {
204 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
205 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
206 Binding == ELF::STB_WEAK);
210 static void SetType(MCSymbolData &SD, unsigned Type) {
211 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
212 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
213 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
214 Type == ELF::STT_TLS);
216 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STT_Shift);
217 SD.setFlags(OtherFlags | (Type << ELF_STT_Shift));
220 static void SetVisibility(MCSymbolData &SD, unsigned Visibility) {
221 assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
222 Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
224 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STV_Shift);
225 SD.setFlags(OtherFlags | (Visibility << ELF_STV_Shift));
228 void MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
229 MCSymbolAttr Attribute) {
230 // Indirect symbols are handled differently, to match how 'as' handles
231 // them. This makes writing matching .o files easier.
232 if (Attribute == MCSA_IndirectSymbol) {
233 // Note that we intentionally cannot use the symbol data here; this is
234 // important for matching the string table that 'as' generates.
235 IndirectSymbolData ISD;
237 ISD.SectionData = getCurrentSectionData();
238 getAssembler().getIndirectSymbols().push_back(ISD);
242 // Adding a symbol attribute always introduces the symbol, note that an
243 // important side effect of calling getOrCreateSymbolData here is to register
244 // the symbol with the assembler.
245 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
247 // The implementation of symbol attributes is designed to match 'as', but it
248 // leaves much to desired. It doesn't really make sense to arbitrarily add and
249 // remove flags, but 'as' allows this (in particular, see .desc).
251 // In the future it might be worth trying to make these operations more well
254 case MCSA_LazyReference:
256 case MCSA_NoDeadStrip:
257 case MCSA_PrivateExtern:
258 case MCSA_WeakDefinition:
259 case MCSA_WeakDefAutoPrivate:
261 case MCSA_ELF_TypeIndFunction:
262 case MCSA_IndirectSymbol:
263 assert(0 && "Invalid symbol attribute for ELF!");
267 SetBinding(SD, ELF::STB_GLOBAL);
268 SD.setExternal(true);
269 BindingExplicitlySet.insert(Symbol);
272 case MCSA_WeakReference:
274 SetBinding(SD, ELF::STB_WEAK);
275 SD.setExternal(true);
276 BindingExplicitlySet.insert(Symbol);
280 SetBinding(SD, ELF::STB_LOCAL);
281 SD.setExternal(false);
282 BindingExplicitlySet.insert(Symbol);
285 case MCSA_ELF_TypeFunction:
286 SetType(SD, ELF::STT_FUNC);
289 case MCSA_ELF_TypeObject:
290 SetType(SD, ELF::STT_OBJECT);
293 case MCSA_ELF_TypeTLS:
294 SetType(SD, ELF::STT_TLS);
297 case MCSA_ELF_TypeCommon:
298 SetType(SD, ELF::STT_COMMON);
301 case MCSA_ELF_TypeNoType:
302 SetType(SD, ELF::STT_NOTYPE);
306 SetVisibility(SD, ELF::STV_PROTECTED);
310 SetVisibility(SD, ELF::STV_HIDDEN);
314 SetVisibility(SD, ELF::STV_INTERNAL);
319 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
320 unsigned ByteAlignment) {
321 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
323 if (!BindingExplicitlySet.count(Symbol)) {
324 SetBinding(SD, ELF::STB_GLOBAL);
325 SD.setExternal(true);
328 if (GetBinding(SD) == ELF_STB_Local) {
329 const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
330 MCSectionELF::SHT_NOBITS,
331 MCSectionELF::SHF_WRITE |
332 MCSectionELF::SHF_ALLOC,
333 SectionKind::getBSS());
334 Symbol->setSection(*Section);
336 struct LocalCommon L = {&SD, Size, ByteAlignment};
337 LocalCommons.push_back(L);
339 SD.setCommon(Size, ByteAlignment);
342 SD.setSize(MCConstantExpr::Create(Size, getContext()));
345 void MCELFStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
346 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
348 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
351 void MCELFStreamer::EmitValue(const MCExpr *Value, unsigned Size,
352 unsigned AddrSpace) {
353 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
355 MCDataFragment *DF = getOrCreateDataFragment();
357 // Avoid fixups when possible.
359 if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
360 // FIXME: Endianness assumption.
361 for (unsigned i = 0; i != Size; ++i)
362 DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
364 DF->addFixup(MCFixup::Create(DF->getContents().size(), AddValueSymbols(Value),
365 MCFixup::getKindForSize(Size)));
366 DF->getContents().resize(DF->getContents().size() + Size, 0);
370 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
371 int64_t Value, unsigned ValueSize,
372 unsigned MaxBytesToEmit) {
373 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
375 if (MaxBytesToEmit == 0)
376 MaxBytesToEmit = ByteAlignment;
377 new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
378 getCurrentSectionData());
380 // Update the maximum alignment on the current section if necessary.
381 if (ByteAlignment > getCurrentSectionData()->getAlignment())
382 getCurrentSectionData()->setAlignment(ByteAlignment);
385 void MCELFStreamer::EmitCodeAlignment(unsigned ByteAlignment,
386 unsigned MaxBytesToEmit) {
387 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
389 if (MaxBytesToEmit == 0)
390 MaxBytesToEmit = ByteAlignment;
391 MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
392 getCurrentSectionData());
393 F->setEmitNops(true);
395 // Update the maximum alignment on the current section if necessary.
396 if (ByteAlignment > getCurrentSectionData()->getAlignment())
397 getCurrentSectionData()->setAlignment(ByteAlignment);
400 void MCELFStreamer::EmitValueToOffset(const MCExpr *Offset,
401 unsigned char Value) {
402 // TODO: This is exactly the same as MCMachOStreamer. Consider merging into
404 new MCOrgFragment(*Offset, Value, getCurrentSectionData());
407 // Add a symbol for the file name of this module. This is the second
408 // entry in the module's symbol table (the first being the null symbol).
409 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
410 MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
411 Symbol->setSection(*CurSection);
412 Symbol->setAbsolute();
414 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
416 SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
419 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
420 MCInstFragment *IF = new MCInstFragment(Inst, getCurrentSectionData());
422 // Add the fixups and data.
424 // FIXME: Revisit this design decision when relaxation is done, we may be
425 // able to get away with not storing any extra data in the MCInst.
426 SmallVector<MCFixup, 4> Fixups;
427 SmallString<256> Code;
428 raw_svector_ostream VecOS(Code);
429 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
432 IF->getCode() = Code;
433 IF->getFixups() = Fixups;
436 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
437 MCDataFragment *DF = getOrCreateDataFragment();
439 SmallVector<MCFixup, 4> Fixups;
440 SmallString<256> Code;
441 raw_svector_ostream VecOS(Code);
442 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
445 // Add the fixups and data.
446 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
447 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
448 DF->addFixup(Fixups[i]);
450 DF->getContents().append(Code.begin(), Code.end());
453 void MCELFStreamer::EmitInstruction(const MCInst &Inst) {
455 for (unsigned i = 0; i != Inst.getNumOperands(); ++i)
456 if (Inst.getOperand(i).isExpr())
457 AddValueSymbols(Inst.getOperand(i).getExpr());
459 getCurrentSectionData()->setHasInstructions(true);
461 // If this instruction doesn't need relaxation, just emit it as data.
462 if (!getAssembler().getBackend().MayNeedRelaxation(Inst)) {
463 EmitInstToData(Inst);
467 // Otherwise, if we are relaxing everything, relax the instruction as much as
468 // possible and emit it as data.
469 if (getAssembler().getRelaxAll()) {
471 getAssembler().getBackend().RelaxInstruction(Inst, Relaxed);
472 while (getAssembler().getBackend().MayNeedRelaxation(Relaxed))
473 getAssembler().getBackend().RelaxInstruction(Relaxed, Relaxed);
474 EmitInstToData(Relaxed);
478 // Otherwise emit to a separate fragment.
479 EmitInstToFragment(Inst);
482 void MCELFStreamer::Finish() {
483 for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
484 e = LocalCommons.end();
486 MCSymbolData *SD = i->SD;
487 uint64_t Size = i->Size;
488 unsigned ByteAlignment = i->ByteAlignment;
489 const MCSymbol &Symbol = SD->getSymbol();
490 const MCSection &Section = Symbol.getSection();
492 MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
493 new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
495 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
498 // Update the maximum alignment of the section if necessary.
499 if (ByteAlignment > SectData.getAlignment())
500 SectData.setAlignment(ByteAlignment);
503 this->MCObjectStreamer::Finish();
506 MCStreamer *llvm::createELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
507 raw_ostream &OS, MCCodeEmitter *CE,
509 MCELFStreamer *S = new MCELFStreamer(Context, TAB, OS, CE);
511 S->getAssembler().setRelaxAll(true);