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/MC/MCAssembler.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCCodeEmitter.h"
19 #include "llvm/MC/MCELFSymbolFlags.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCInst.h"
22 #include "llvm/MC/MCObjectStreamer.h"
23 #include "llvm/MC/MCSection.h"
24 #include "llvm/MC/MCSectionELF.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ELF.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Target/TargetAsmBackend.h"
36 class MCELFStreamer : public MCObjectStreamer {
38 MCELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
39 raw_ostream &OS, MCCodeEmitter *Emitter)
40 : MCObjectStreamer(Context, TAB, OS, Emitter) {}
44 /// @name MCStreamer Interface
47 virtual void EmitLabel(MCSymbol *Symbol);
48 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
49 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
50 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
51 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
52 assert(0 && "ELF doesn't support this directive");
54 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
55 unsigned ByteAlignment);
56 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
57 assert(0 && "ELF doesn't support this directive");
60 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
61 assert(0 && "ELF doesn't support this directive");
64 virtual void EmitCOFFSymbolType(int Type) {
65 assert(0 && "ELF doesn't support this directive");
68 virtual void EndCOFFSymbolDef() {
69 assert(0 && "ELF doesn't support this directive");
72 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
73 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
77 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
78 assert(0 && "ELF doesn't support this directive");
80 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
81 unsigned Size = 0, unsigned ByteAlignment = 0) {
82 assert(0 && "ELF doesn't support this directive");
84 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
85 uint64_t Size, unsigned ByteAlignment = 0) {
86 assert(0 && "ELF doesn't support this directive");
88 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
89 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
90 virtual void EmitGPRel32Value(const MCExpr *Value) {
91 assert(0 && "ELF doesn't support this directive");
93 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
94 unsigned ValueSize = 1,
95 unsigned MaxBytesToEmit = 0);
96 virtual void EmitCodeAlignment(unsigned ByteAlignment,
97 unsigned MaxBytesToEmit = 0);
98 virtual void EmitValueToOffset(const MCExpr *Offset,
99 unsigned char Value = 0);
101 virtual void EmitFileDirective(StringRef Filename);
102 virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
103 DEBUG(dbgs() << "FIXME: MCELFStreamer:EmitDwarfFileDirective not implemented\n");
106 virtual void EmitInstruction(const MCInst &Inst);
107 virtual void Finish();
112 } // end anonymous namespace.
114 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
115 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
117 // FIXME: This is wasteful, we don't necessarily need to create a data
118 // fragment. Instead, we should mark the symbol as pointing into the data
119 // fragment if it exists, otherwise we should just queue the label and set its
120 // fragment pointer when we emit the next fragment.
121 MCDataFragment *F = getOrCreateDataFragment();
122 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
123 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
125 SD.setOffset(F->getContents().size());
127 Symbol->setSection(*CurSection);
130 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
132 case MCAF_SubsectionsViaSymbols:
133 getAssembler().setSubsectionsViaSymbols(true);
137 assert(0 && "invalid assembler flag!");
140 void MCELFStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
141 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
143 // FIXME: Lift context changes into super class.
144 getAssembler().getOrCreateSymbolData(*Symbol);
145 Symbol->setVariableValue(AddValueSymbols(Value));
148 void MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
149 MCSymbolAttr Attribute) {
150 // Indirect symbols are handled differently, to match how 'as' handles
151 // them. This makes writing matching .o files easier.
152 if (Attribute == MCSA_IndirectSymbol) {
153 // Note that we intentionally cannot use the symbol data here; this is
154 // important for matching the string table that 'as' generates.
155 IndirectSymbolData ISD;
157 ISD.SectionData = getCurrentSectionData();
158 getAssembler().getIndirectSymbols().push_back(ISD);
162 // Adding a symbol attribute always introduces the symbol, note that an
163 // important side effect of calling getOrCreateSymbolData here is to register
164 // the symbol with the assembler.
165 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
167 // The implementation of symbol attributes is designed to match 'as', but it
168 // leaves much to desired. It doesn't really make sense to arbitrarily add and
169 // remove flags, but 'as' allows this (in particular, see .desc).
171 // In the future it might be worth trying to make these operations more well
174 case MCSA_LazyReference:
176 case MCSA_NoDeadStrip:
177 case MCSA_PrivateExtern:
178 case MCSA_WeakReference:
179 case MCSA_WeakDefinition:
181 case MCSA_ELF_TypeIndFunction:
182 case MCSA_IndirectSymbol:
183 assert(0 && "Invalid symbol attribute for ELF!");
187 SD.setFlags(SD.getFlags() | ELF_STB_Global);
188 SD.setExternal(true);
192 SD.setFlags(SD.getFlags() | ELF_STB_Weak);
196 SD.setFlags(SD.getFlags() | ELF_STB_Local);
199 case MCSA_ELF_TypeFunction:
200 SD.setFlags(SD.getFlags() | ELF_STT_Func);
203 case MCSA_ELF_TypeObject:
204 SD.setFlags(SD.getFlags() | ELF_STT_Object);
207 case MCSA_ELF_TypeTLS:
208 SD.setFlags(SD.getFlags() | ELF_STT_Tls);
211 case MCSA_ELF_TypeCommon:
212 SD.setFlags(SD.getFlags() | ELF_STT_Common);
215 case MCSA_ELF_TypeNoType:
216 SD.setFlags(SD.getFlags() | ELF_STT_Notype);
220 SD.setFlags(SD.getFlags() | ELF_STV_Protected);
224 SD.setFlags(SD.getFlags() | ELF_STV_Hidden);
228 SD.setFlags(SD.getFlags() | ELF_STV_Internal);
233 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
234 unsigned ByteAlignment) {
235 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
237 if ((SD.getFlags() & (0xf << ELF_STB_Shift)) == ELF_STB_Local) {
238 const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
239 MCSectionELF::SHT_NOBITS,
240 MCSectionELF::SHF_WRITE |
241 MCSectionELF::SHF_ALLOC,
242 SectionKind::getBSS());
244 MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
245 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
247 Symbol->setSection(*Section);
248 SD.setSize(MCConstantExpr::Create(Size, getContext()));
250 SD.setExternal(true);
253 SD.setCommon(Size, ByteAlignment);
256 void MCELFStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
257 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
259 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
262 void MCELFStreamer::EmitValue(const MCExpr *Value, unsigned Size,
263 unsigned AddrSpace) {
264 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
266 MCDataFragment *DF = getOrCreateDataFragment();
268 // Avoid fixups when possible.
270 if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
271 // FIXME: Endianness assumption.
272 for (unsigned i = 0; i != Size; ++i)
273 DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
275 DF->addFixup(MCFixup::Create(DF->getContents().size(), AddValueSymbols(Value),
276 MCFixup::getKindForSize(Size)));
277 DF->getContents().resize(DF->getContents().size() + Size, 0);
281 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
282 int64_t Value, unsigned ValueSize,
283 unsigned MaxBytesToEmit) {
284 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
286 if (MaxBytesToEmit == 0)
287 MaxBytesToEmit = ByteAlignment;
288 new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
289 getCurrentSectionData());
291 // Update the maximum alignment on the current section if necessary.
292 if (ByteAlignment > getCurrentSectionData()->getAlignment())
293 getCurrentSectionData()->setAlignment(ByteAlignment);
296 void MCELFStreamer::EmitCodeAlignment(unsigned ByteAlignment,
297 unsigned MaxBytesToEmit) {
298 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
300 if (MaxBytesToEmit == 0)
301 MaxBytesToEmit = ByteAlignment;
302 MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
303 getCurrentSectionData());
304 F->setEmitNops(true);
306 // Update the maximum alignment on the current section if necessary.
307 if (ByteAlignment > getCurrentSectionData()->getAlignment())
308 getCurrentSectionData()->setAlignment(ByteAlignment);
311 void MCELFStreamer::EmitValueToOffset(const MCExpr *Offset,
312 unsigned char Value) {
313 // TODO: This is exactly the same as MCMachOStreamer. Consider merging into
315 new MCOrgFragment(*Offset, Value, getCurrentSectionData());
318 // Add a symbol for the file name of this module. This is the second
319 // entry in the module's symbol table (the first being the null symbol).
320 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
321 MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
322 Symbol->setSection(*CurSection);
323 Symbol->setAbsolute();
325 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
327 SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
330 void MCELFStreamer::EmitInstruction(const MCInst &Inst) {
332 for (unsigned i = 0; i != Inst.getNumOperands(); ++i)
333 if (Inst.getOperand(i).isExpr())
334 AddValueSymbols(Inst.getOperand(i).getExpr());
336 getCurrentSectionData()->setHasInstructions(true);
338 // FIXME-PERF: Common case is that we don't need to relax, encode directly
339 // onto the data fragments buffers.
341 SmallVector<MCFixup, 4> Fixups;
342 SmallString<256> Code;
343 raw_svector_ostream VecOS(Code);
344 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
347 // FIXME: Eliminate this copy.
348 SmallVector<MCFixup, 4> AsmFixups;
349 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
350 MCFixup &F = Fixups[i];
351 AsmFixups.push_back(MCFixup::Create(F.getOffset(), F.getValue(),
355 // See if we might need to relax this instruction, if so it needs its own
358 // FIXME-PERF: Support target hook to do a fast path that avoids the encoder,
359 // when we can immediately tell that we will get something which might need
360 // relaxation (and compute its size).
362 // FIXME-PERF: We should also be smart about immediately relaxing instructions
363 // which we can already show will never possibly fit (we can also do a very
364 // good job of this before we do the first relaxation pass, because we have
365 // total knowledge about undefined symbols at that point). Even now, though,
366 // we can do a decent job, especially on Darwin where scattering means that we
367 // are going to often know that we can never fully resolve a fixup.
368 if (getAssembler().getBackend().MayNeedRelaxation(Inst)) {
369 MCInstFragment *IF = new MCInstFragment(Inst, getCurrentSectionData());
371 // Add the fixups and data.
373 // FIXME: Revisit this design decision when relaxation is done, we may be
374 // able to get away with not storing any extra data in the MCInst.
375 IF->getCode() = Code;
376 IF->getFixups() = AsmFixups;
381 // Add the fixups and data.
382 MCDataFragment *DF = getOrCreateDataFragment();
383 for (unsigned i = 0, e = AsmFixups.size(); i != e; ++i) {
384 AsmFixups[i].setOffset(AsmFixups[i].getOffset() + DF->getContents().size());
385 DF->addFixup(AsmFixups[i]);
387 DF->getContents().append(Code.begin(), Code.end());
390 void MCELFStreamer::Finish() {
391 getAssembler().Finish();
394 MCStreamer *llvm::createELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
395 raw_ostream &OS, MCCodeEmitter *CE,
397 MCELFStreamer *S = new MCELFStreamer(Context, TAB, OS, CE);
399 S->getAssembler().setRelaxAll(true);