blob: 2631c5f4ec618fe78db7e05fe7e3d08a25603511 [file] [log] [blame]
Matt Fleming3565a062010-08-16 18:57:57 +00001//===- lib/MC/MCELFStreamer.cpp - ELF Object Output ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file assembles .s files and emits ELF .o object files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/MC/MCStreamer.h"
15
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"
31
32using namespace llvm;
33
34namespace {
35
36class MCELFStreamer : public MCObjectStreamer {
37public:
38 MCELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
39 raw_ostream &OS, MCCodeEmitter *Emitter)
40 : MCObjectStreamer(Context, TAB, OS, Emitter) {}
41
42 ~MCELFStreamer() {}
43
44 /// @name MCStreamer Interface
45 /// @{
46
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");
53 }
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");
58 }
59
60 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
61 assert(0 && "ELF doesn't support this directive");
62 }
63
64 virtual void EmitCOFFSymbolType(int Type) {
65 assert(0 && "ELF doesn't support this directive");
66 }
67
68 virtual void EndCOFFSymbolDef() {
69 assert(0 && "ELF doesn't support this directive");
70 }
71
72 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
73 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
74 SD.setSize(Value);
75 }
76
77 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
78 assert(0 && "ELF doesn't support this directive");
79 }
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");
83 }
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");
87 }
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");
92 }
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);
100
101 virtual void EmitFileDirective(StringRef Filename);
102 virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
103 DEBUG(dbgs() << "FIXME: MCELFStreamer:EmitDwarfFileDirective not implemented\n");
104 }
105
106 virtual void EmitInstruction(const MCInst &Inst);
107 virtual void Finish();
108
109 /// @}
110};
111
112} // end anonymous namespace.
113
114void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
115 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
116
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!");
124 SD.setFragment(F);
125 SD.setOffset(F->getContents().size());
126
127 Symbol->setSection(*CurSection);
128}
129
130void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
131 switch (Flag) {
132 case MCAF_SubsectionsViaSymbols:
133 getAssembler().setSubsectionsViaSymbols(true);
134 return;
135 }
136
137 assert(0 && "invalid assembler flag!");
138}
139
140void MCELFStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
141 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
142 // MCObjectStreamer.
143 // FIXME: Lift context changes into super class.
144 getAssembler().getOrCreateSymbolData(*Symbol);
145 Symbol->setVariableValue(AddValueSymbols(Value));
146}
147
148void 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;
156 ISD.Symbol = Symbol;
157 ISD.SectionData = getCurrentSectionData();
158 getAssembler().getIndirectSymbols().push_back(ISD);
159 return;
160 }
161
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);
166
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).
170 //
171 // In the future it might be worth trying to make these operations more well
172 // defined.
173 switch (Attribute) {
174 case MCSA_LazyReference:
175 case MCSA_Reference:
176 case MCSA_NoDeadStrip:
177 case MCSA_PrivateExtern:
178 case MCSA_WeakReference:
179 case MCSA_WeakDefinition:
Eli Friedmanf8020a32010-08-16 19:15:06 +0000180 case MCSA_WeakDefAutoPrivate:
Matt Fleming3565a062010-08-16 18:57:57 +0000181 case MCSA_Invalid:
182 case MCSA_ELF_TypeIndFunction:
183 case MCSA_IndirectSymbol:
184 assert(0 && "Invalid symbol attribute for ELF!");
185 break;
186
187 case MCSA_Global:
188 SD.setFlags(SD.getFlags() | ELF_STB_Global);
189 SD.setExternal(true);
190 break;
191
192 case MCSA_Weak:
193 SD.setFlags(SD.getFlags() | ELF_STB_Weak);
194 break;
195
196 case MCSA_Local:
197 SD.setFlags(SD.getFlags() | ELF_STB_Local);
198 break;
199
200 case MCSA_ELF_TypeFunction:
201 SD.setFlags(SD.getFlags() | ELF_STT_Func);
202 break;
203
204 case MCSA_ELF_TypeObject:
205 SD.setFlags(SD.getFlags() | ELF_STT_Object);
206 break;
207
208 case MCSA_ELF_TypeTLS:
209 SD.setFlags(SD.getFlags() | ELF_STT_Tls);
210 break;
211
212 case MCSA_ELF_TypeCommon:
213 SD.setFlags(SD.getFlags() | ELF_STT_Common);
214 break;
215
216 case MCSA_ELF_TypeNoType:
217 SD.setFlags(SD.getFlags() | ELF_STT_Notype);
218 break;
219
220 case MCSA_Protected:
221 SD.setFlags(SD.getFlags() | ELF_STV_Protected);
222 break;
223
224 case MCSA_Hidden:
225 SD.setFlags(SD.getFlags() | ELF_STV_Hidden);
226 break;
227
228 case MCSA_Internal:
229 SD.setFlags(SD.getFlags() | ELF_STV_Internal);
230 break;
231 }
232}
233
234void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
235 unsigned ByteAlignment) {
236 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
237
238 if ((SD.getFlags() & (0xf << ELF_STB_Shift)) == ELF_STB_Local) {
239 const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
240 MCSectionELF::SHT_NOBITS,
241 MCSectionELF::SHF_WRITE |
242 MCSectionELF::SHF_ALLOC,
243 SectionKind::getBSS());
244
245 MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
246 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
247 SD.setFragment(F);
248 Symbol->setSection(*Section);
249 SD.setSize(MCConstantExpr::Create(Size, getContext()));
250 } else {
251 SD.setExternal(true);
252 }
253
254 SD.setCommon(Size, ByteAlignment);
255}
256
257void MCELFStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
258 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
259 // MCObjectStreamer.
260 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
261}
262
263void MCELFStreamer::EmitValue(const MCExpr *Value, unsigned Size,
264 unsigned AddrSpace) {
265 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
266 // MCObjectStreamer.
267 MCDataFragment *DF = getOrCreateDataFragment();
268
269 // Avoid fixups when possible.
270 int64_t AbsValue;
271 if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
272 // FIXME: Endianness assumption.
273 for (unsigned i = 0; i != Size; ++i)
274 DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
275 } else {
276 DF->addFixup(MCFixup::Create(DF->getContents().size(), AddValueSymbols(Value),
277 MCFixup::getKindForSize(Size)));
278 DF->getContents().resize(DF->getContents().size() + Size, 0);
279 }
280}
281
282void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
283 int64_t Value, unsigned ValueSize,
284 unsigned MaxBytesToEmit) {
285 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
286 // MCObjectStreamer.
287 if (MaxBytesToEmit == 0)
288 MaxBytesToEmit = ByteAlignment;
289 new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
290 getCurrentSectionData());
291
292 // Update the maximum alignment on the current section if necessary.
293 if (ByteAlignment > getCurrentSectionData()->getAlignment())
294 getCurrentSectionData()->setAlignment(ByteAlignment);
295}
296
297void MCELFStreamer::EmitCodeAlignment(unsigned ByteAlignment,
298 unsigned MaxBytesToEmit) {
299 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
300 // MCObjectStreamer.
301 if (MaxBytesToEmit == 0)
302 MaxBytesToEmit = ByteAlignment;
303 MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
304 getCurrentSectionData());
305 F->setEmitNops(true);
306
307 // Update the maximum alignment on the current section if necessary.
308 if (ByteAlignment > getCurrentSectionData()->getAlignment())
309 getCurrentSectionData()->setAlignment(ByteAlignment);
310}
311
312void MCELFStreamer::EmitValueToOffset(const MCExpr *Offset,
313 unsigned char Value) {
314 // TODO: This is exactly the same as MCMachOStreamer. Consider merging into
315 // MCObjectStreamer.
316 new MCOrgFragment(*Offset, Value, getCurrentSectionData());
317}
318
319// Add a symbol for the file name of this module. This is the second
320// entry in the module's symbol table (the first being the null symbol).
321void MCELFStreamer::EmitFileDirective(StringRef Filename) {
322 MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
323 Symbol->setSection(*CurSection);
324 Symbol->setAbsolute();
325
326 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
327
328 SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
329}
330
331void MCELFStreamer::EmitInstruction(const MCInst &Inst) {
332 // Scan for values.
333 for (unsigned i = 0; i != Inst.getNumOperands(); ++i)
334 if (Inst.getOperand(i).isExpr())
335 AddValueSymbols(Inst.getOperand(i).getExpr());
336
337 getCurrentSectionData()->setHasInstructions(true);
338
339 // FIXME-PERF: Common case is that we don't need to relax, encode directly
340 // onto the data fragments buffers.
341
342 SmallVector<MCFixup, 4> Fixups;
343 SmallString<256> Code;
344 raw_svector_ostream VecOS(Code);
345 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
346 VecOS.flush();
347
348 // FIXME: Eliminate this copy.
349 SmallVector<MCFixup, 4> AsmFixups;
350 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
351 MCFixup &F = Fixups[i];
352 AsmFixups.push_back(MCFixup::Create(F.getOffset(), F.getValue(),
353 F.getKind()));
354 }
355
356 // See if we might need to relax this instruction, if so it needs its own
357 // fragment.
358 //
359 // FIXME-PERF: Support target hook to do a fast path that avoids the encoder,
360 // when we can immediately tell that we will get something which might need
361 // relaxation (and compute its size).
362 //
363 // FIXME-PERF: We should also be smart about immediately relaxing instructions
364 // which we can already show will never possibly fit (we can also do a very
365 // good job of this before we do the first relaxation pass, because we have
366 // total knowledge about undefined symbols at that point). Even now, though,
367 // we can do a decent job, especially on Darwin where scattering means that we
368 // are going to often know that we can never fully resolve a fixup.
369 if (getAssembler().getBackend().MayNeedRelaxation(Inst)) {
370 MCInstFragment *IF = new MCInstFragment(Inst, getCurrentSectionData());
371
372 // Add the fixups and data.
373 //
374 // FIXME: Revisit this design decision when relaxation is done, we may be
375 // able to get away with not storing any extra data in the MCInst.
376 IF->getCode() = Code;
377 IF->getFixups() = AsmFixups;
378
379 return;
380 }
381
382 // Add the fixups and data.
383 MCDataFragment *DF = getOrCreateDataFragment();
384 for (unsigned i = 0, e = AsmFixups.size(); i != e; ++i) {
385 AsmFixups[i].setOffset(AsmFixups[i].getOffset() + DF->getContents().size());
386 DF->addFixup(AsmFixups[i]);
387 }
388 DF->getContents().append(Code.begin(), Code.end());
389}
390
391void MCELFStreamer::Finish() {
392 getAssembler().Finish();
393}
394
395MCStreamer *llvm::createELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
396 raw_ostream &OS, MCCodeEmitter *CE,
397 bool RelaxAll) {
398 MCELFStreamer *S = new MCELFStreamer(Context, TAB, OS, CE);
399 if (RelaxAll)
400 S->getAssembler().setRelaxAll(true);
401 return S;
402}