da7257f570c73cb0f2313782dd7abf2ff24928cf
[oota-llvm.git] / lib / MC / MCELFStreamer.cpp
1 //===- 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/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
34 using namespace llvm;
35
36 namespace {
37
38 class MCELFStreamer : public MCObjectStreamer {
39 public:
40   MCELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
41                   raw_ostream &OS, MCCodeEmitter *Emitter)
42     : MCObjectStreamer(Context, TAB, OS, Emitter, false) {}
43
44   ~MCELFStreamer() {}
45
46   /// @name MCStreamer Interface
47   /// @{
48
49   virtual void InitSections();
50   virtual void EmitLabel(MCSymbol *Symbol);
51   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
52   virtual void EmitThumbFunc(MCSymbol *Func);
53   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
54   virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
55   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
56   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
57     assert(0 && "ELF doesn't support this directive");
58   }
59   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
60                                 unsigned ByteAlignment);
61   virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
62     assert(0 && "ELF doesn't support this directive");
63   }
64
65   virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
66     assert(0 && "ELF doesn't support this directive");
67   }
68
69   virtual void EmitCOFFSymbolType(int Type) {
70     assert(0 && "ELF doesn't support this directive");
71   }
72
73   virtual void EndCOFFSymbolDef() {
74     assert(0 && "ELF doesn't support this directive");
75   }
76
77   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
78      MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
79      SD.setSize(Value);
80   }
81
82   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
83     assert(0 && "ELF doesn't support this directive");
84   }
85   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
86                             unsigned Size = 0, unsigned ByteAlignment = 0) {
87     assert(0 && "ELF doesn't support this directive");
88   }
89   virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
90                               uint64_t Size, unsigned ByteAlignment = 0) {
91     assert(0 && "ELF doesn't support this directive");
92   }
93   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
94   virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
95   virtual void EmitGPRel32Value(const MCExpr *Value) {
96     assert(0 && "ELF doesn't support this directive");
97   }
98   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
99                                     unsigned ValueSize = 1,
100                                     unsigned MaxBytesToEmit = 0);
101   virtual void EmitCodeAlignment(unsigned ByteAlignment,
102                                  unsigned MaxBytesToEmit = 0);
103   virtual void EmitValueToOffset(const MCExpr *Offset,
104                                  unsigned char Value = 0);
105
106   virtual void EmitFileDirective(StringRef Filename);
107   virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
108     DEBUG(dbgs() << "FIXME: MCELFStreamer:EmitDwarfFileDirective not implemented\n");
109   }
110
111   virtual void Finish();
112
113 private:
114   virtual void EmitInstToFragment(const MCInst &Inst);
115   virtual void EmitInstToData(const MCInst &Inst);
116
117   struct LocalCommon {
118     MCSymbolData *SD;
119     uint64_t Size;
120     unsigned ByteAlignment;
121   };
122   std::vector<LocalCommon> LocalCommons;
123
124   SmallPtrSet<MCSymbol *, 16> BindingExplicitlySet;
125   /// @}
126   void SetSection(StringRef Section, unsigned Type, unsigned Flags,
127                   SectionKind Kind) {
128     SwitchSection(getContext().getELFSection(Section, Type, Flags, Kind));
129   }
130
131   void SetSectionData() {
132     SetSection(".data", MCSectionELF::SHT_PROGBITS,
133                MCSectionELF::SHF_WRITE |MCSectionELF::SHF_ALLOC,
134                SectionKind::getDataRel());
135     EmitCodeAlignment(4, 0);
136   }
137   void SetSectionText() {
138     SetSection(".text", MCSectionELF::SHT_PROGBITS,
139                MCSectionELF::SHF_EXECINSTR |
140                MCSectionELF::SHF_ALLOC, SectionKind::getText());
141     EmitCodeAlignment(4, 0);
142   }
143   void SetSectionBss() {
144     SetSection(".bss", MCSectionELF::SHT_NOBITS,
145                MCSectionELF::SHF_WRITE |
146                MCSectionELF::SHF_ALLOC, SectionKind::getBSS());
147     EmitCodeAlignment(4, 0);
148   }
149 };
150
151 } // end anonymous namespace.
152
153 void MCELFStreamer::InitSections() {
154   // This emulates the same behavior of GNU as. This makes it easier
155   // to compare the output as the major sections are in the same order.
156   SetSectionText();
157   SetSectionData();
158   SetSectionBss();
159   SetSectionText();
160 }
161
162 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
163   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
164
165   Symbol->setSection(*CurSection);
166
167   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
168
169   // FIXME: This is wasteful, we don't necessarily need to create a data
170   // fragment. Instead, we should mark the symbol as pointing into the data
171   // fragment if it exists, otherwise we should just queue the label and set its
172   // fragment pointer when we emit the next fragment.
173   MCDataFragment *F = getOrCreateDataFragment();
174
175   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
176   SD.setFragment(F);
177   SD.setOffset(F->getContents().size());
178 }
179
180 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
181   switch (Flag) {
182   case MCAF_SyntaxUnified: return; // no-op here.
183   case MCAF_Code16: return; // no-op here.
184   case MCAF_SubsectionsViaSymbols:
185     getAssembler().setSubsectionsViaSymbols(true);
186     return;
187   }
188
189   assert(0 && "invalid assembler flag!");
190 }
191
192 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
193   // FIXME: Anything needed here to flag the function as thumb?
194 }
195
196 void MCELFStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
197   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
198   // MCObjectStreamer.
199   // FIXME: Lift context changes into super class.
200   getAssembler().getOrCreateSymbolData(*Symbol);
201   Symbol->setVariableValue(AddValueSymbols(Value));
202 }
203
204 // This is a hack. To be able to implement weakrefs the writer has to be able
205 // to distinguish
206 //    .weakref foo, bar
207 //    .long foo
208 // from
209 //   .weakref foo, bar
210 //   .long bar
211 // since the first case should produce a weak undefined reference and the second
212 // one a strong one.
213 // If we created foo as a regular alias pointing to bar (foo = bar), then
214 // MCExpr::EvaluateAsRelocatable would recurse on foo and the writer would
215 // never see it used in a relocation.
216 // What we do is create a MCTargetExpr that when evaluated produces a symbol
217 // ref to a temporary symbol. This temporary symbol in turn is a variable
218 // that equals the original symbol (tmp = bar). With this hack the writer
219 // gets a relocation with tmp and can correctly implement weak references.
220
221 namespace {
222 class WeakRefExpr : public MCTargetExpr {
223 private:
224   const MCSymbolRefExpr *Alias;
225
226   explicit WeakRefExpr(const MCSymbolRefExpr *Alias_)
227     : MCTargetExpr(), Alias(Alias_) {}
228
229 public:
230   virtual void PrintImpl(raw_ostream &OS) const {
231     llvm_unreachable("Unimplemented");
232   }
233
234   virtual bool EvaluateAsRelocatableImpl(MCValue &Res,
235                                          const MCAsmLayout *Layout) const {
236     Res = MCValue::get(Alias, 0, 0);
237     return true;
238   }
239
240   static const WeakRefExpr *Create(const MCSymbol *Alias, MCContext &Ctx) {
241     const MCSymbolRefExpr *A = MCSymbolRefExpr::Create(Alias, Ctx);
242     return new (Ctx) WeakRefExpr(A);
243   }
244 };
245 } // end anonymous namespace
246
247 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
248   getAssembler().getOrCreateSymbolData(*Symbol);
249   MCSymbolData &AliasSD = getAssembler().getOrCreateSymbolData(*Alias);
250   AliasSD.setFlags(AliasSD.getFlags() | ELF_Other_Weakref);
251
252   // Create the alias that actually points to Symbol
253   const MCSymbolRefExpr *SymRef = MCSymbolRefExpr::Create(Symbol, getContext());
254   MCSymbol *RealAlias = getContext().CreateTempSymbol();
255   RealAlias->setVariableValue(SymRef);
256
257   MCSymbolData &RealAliasSD = getAssembler().getOrCreateSymbolData(*RealAlias);
258   RealAliasSD.setFlags(RealAliasSD.getFlags() | ELF_Other_Weakref);
259
260   const MCExpr *Value = WeakRefExpr::Create(RealAlias, getContext());
261   Alias->setVariableValue(Value);
262 }
263
264 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
265   assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
266          Binding == ELF::STB_WEAK);
267   uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
268   SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
269 }
270
271 static unsigned GetBinding(const MCSymbolData &SD) {
272   uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
273   assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
274          Binding == ELF::STB_WEAK);
275   return Binding;
276 }
277
278 static void SetType(MCSymbolData &SD, unsigned Type) {
279   assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
280          Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
281          Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
282          Type == ELF::STT_TLS);
283
284   uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STT_Shift);
285   SD.setFlags(OtherFlags | (Type << ELF_STT_Shift));
286 }
287
288 static void SetVisibility(MCSymbolData &SD, unsigned Visibility) {
289   assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
290          Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
291
292   uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STV_Shift);
293   SD.setFlags(OtherFlags | (Visibility << ELF_STV_Shift));
294 }
295
296 void MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
297                                           MCSymbolAttr Attribute) {
298   // Indirect symbols are handled differently, to match how 'as' handles
299   // them. This makes writing matching .o files easier.
300   if (Attribute == MCSA_IndirectSymbol) {
301     // Note that we intentionally cannot use the symbol data here; this is
302     // important for matching the string table that 'as' generates.
303     IndirectSymbolData ISD;
304     ISD.Symbol = Symbol;
305     ISD.SectionData = getCurrentSectionData();
306     getAssembler().getIndirectSymbols().push_back(ISD);
307     return;
308   }
309
310   // Adding a symbol attribute always introduces the symbol, note that an
311   // important side effect of calling getOrCreateSymbolData here is to register
312   // the symbol with the assembler.
313   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
314
315   // The implementation of symbol attributes is designed to match 'as', but it
316   // leaves much to desired. It doesn't really make sense to arbitrarily add and
317   // remove flags, but 'as' allows this (in particular, see .desc).
318   //
319   // In the future it might be worth trying to make these operations more well
320   // defined.
321   switch (Attribute) {
322   case MCSA_LazyReference:
323   case MCSA_Reference:
324   case MCSA_NoDeadStrip:
325   case MCSA_PrivateExtern:
326   case MCSA_WeakDefinition:
327   case MCSA_WeakDefAutoPrivate:
328   case MCSA_Invalid:
329   case MCSA_ELF_TypeIndFunction:
330   case MCSA_IndirectSymbol:
331     assert(0 && "Invalid symbol attribute for ELF!");
332     break;
333
334   case MCSA_Global:
335     SetBinding(SD, ELF::STB_GLOBAL);
336     SD.setExternal(true);
337     BindingExplicitlySet.insert(Symbol);
338     break;
339
340   case MCSA_WeakReference:
341   case MCSA_Weak:
342     SetBinding(SD, ELF::STB_WEAK);
343     SD.setExternal(true);
344     BindingExplicitlySet.insert(Symbol);
345     break;
346
347   case MCSA_Local:
348     SetBinding(SD, ELF::STB_LOCAL);
349     SD.setExternal(false);
350     BindingExplicitlySet.insert(Symbol);
351     break;
352
353   case MCSA_ELF_TypeFunction:
354     SetType(SD, ELF::STT_FUNC);
355     break;
356
357   case MCSA_ELF_TypeObject:
358     SetType(SD, ELF::STT_OBJECT);
359     break;
360
361   case MCSA_ELF_TypeTLS:
362     SetType(SD, ELF::STT_TLS);
363     break;
364
365   case MCSA_ELF_TypeCommon:
366     SetType(SD, ELF::STT_COMMON);
367     break;
368
369   case MCSA_ELF_TypeNoType:
370     SetType(SD, ELF::STT_NOTYPE);
371     break;
372
373   case MCSA_Protected:
374     SetVisibility(SD, ELF::STV_PROTECTED);
375     break;
376
377   case MCSA_Hidden:
378     SetVisibility(SD, ELF::STV_HIDDEN);
379     break;
380
381   case MCSA_Internal:
382     SetVisibility(SD, ELF::STV_INTERNAL);
383     break;
384   }
385 }
386
387 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
388                                        unsigned ByteAlignment) {
389   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
390
391   if (!BindingExplicitlySet.count(Symbol)) {
392     SetBinding(SD, ELF::STB_GLOBAL);
393     SD.setExternal(true);
394   }
395
396   if (GetBinding(SD) == ELF_STB_Local) {
397     const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
398                                                                     MCSectionELF::SHT_NOBITS,
399                                                                     MCSectionELF::SHF_WRITE |
400                                                                     MCSectionELF::SHF_ALLOC,
401                                                                     SectionKind::getBSS());
402     Symbol->setSection(*Section);
403
404     struct LocalCommon L = {&SD, Size, ByteAlignment};
405     LocalCommons.push_back(L);
406   } else {
407     SD.setCommon(Size, ByteAlignment);
408   }
409
410   SD.setSize(MCConstantExpr::Create(Size, getContext()));
411 }
412
413 void MCELFStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
414   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
415   // MCObjectStreamer.
416   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
417 }
418
419 void MCELFStreamer::EmitValue(const MCExpr *Value, unsigned Size,
420                                 unsigned AddrSpace) {
421   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
422   // MCObjectStreamer.
423   MCDataFragment *DF = getOrCreateDataFragment();
424
425   // Avoid fixups when possible.
426   int64_t AbsValue;
427   if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
428     // FIXME: Endianness assumption.
429     for (unsigned i = 0; i != Size; ++i)
430       DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
431   } else {
432     DF->addFixup(MCFixup::Create(DF->getContents().size(), AddValueSymbols(Value),
433                                  MCFixup::getKindForSize(Size)));
434     DF->getContents().resize(DF->getContents().size() + Size, 0);
435   }
436 }
437
438 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
439                                            int64_t Value, unsigned ValueSize,
440                                            unsigned MaxBytesToEmit) {
441   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
442   // MCObjectStreamer.
443   if (MaxBytesToEmit == 0)
444     MaxBytesToEmit = ByteAlignment;
445   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
446                       getCurrentSectionData());
447
448   // Update the maximum alignment on the current section if necessary.
449   if (ByteAlignment > getCurrentSectionData()->getAlignment())
450     getCurrentSectionData()->setAlignment(ByteAlignment);
451 }
452
453 void MCELFStreamer::EmitCodeAlignment(unsigned ByteAlignment,
454                                         unsigned MaxBytesToEmit) {
455   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
456   // MCObjectStreamer.
457   if (MaxBytesToEmit == 0)
458     MaxBytesToEmit = ByteAlignment;
459   MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
460                                            getCurrentSectionData());
461   F->setEmitNops(true);
462
463   // Update the maximum alignment on the current section if necessary.
464   if (ByteAlignment > getCurrentSectionData()->getAlignment())
465     getCurrentSectionData()->setAlignment(ByteAlignment);
466 }
467
468 void MCELFStreamer::EmitValueToOffset(const MCExpr *Offset,
469                                         unsigned char Value) {
470   // TODO: This is exactly the same as MCMachOStreamer. Consider merging into
471   // MCObjectStreamer.
472   new MCOrgFragment(*Offset, Value, getCurrentSectionData());
473 }
474
475 // Add a symbol for the file name of this module. This is the second
476 // entry in the module's symbol table (the first being the null symbol).
477 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
478   MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
479   Symbol->setSection(*CurSection);
480   Symbol->setAbsolute();
481
482   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
483
484   SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
485 }
486
487 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
488   MCInstFragment *IF = new MCInstFragment(Inst, getCurrentSectionData());
489
490   // Add the fixups and data.
491   //
492   // FIXME: Revisit this design decision when relaxation is done, we may be
493   // able to get away with not storing any extra data in the MCInst.
494   SmallVector<MCFixup, 4> Fixups;
495   SmallString<256> Code;
496   raw_svector_ostream VecOS(Code);
497   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
498   VecOS.flush();
499
500   IF->getCode() = Code;
501   IF->getFixups() = Fixups;
502 }
503
504 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
505   MCDataFragment *DF = getOrCreateDataFragment();
506
507   SmallVector<MCFixup, 4> Fixups;
508   SmallString<256> Code;
509   raw_svector_ostream VecOS(Code);
510   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
511   VecOS.flush();
512
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]);
517   }
518   DF->getContents().append(Code.begin(), Code.end());
519 }
520
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());
528     MCDwarfFileTable::Emit(this, DwarfLineSection);
529   }
530
531   for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
532                                                 e = LocalCommons.end();
533        i != e; ++i) {
534     MCSymbolData *SD = i->SD;
535     uint64_t Size = i->Size;
536     unsigned ByteAlignment = i->ByteAlignment;
537     const MCSymbol &Symbol = SD->getSymbol();
538     const MCSection &Section = Symbol.getSection();
539
540     MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
541     new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
542
543     MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
544     SD->setFragment(F);
545
546     // Update the maximum alignment of the section if necessary.
547     if (ByteAlignment > SectData.getAlignment())
548       SectData.setAlignment(ByteAlignment);
549   }
550
551   this->MCObjectStreamer::Finish();
552 }
553
554 MCStreamer *llvm::createELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
555                                       raw_ostream &OS, MCCodeEmitter *CE,
556                                       bool RelaxAll) {
557   MCELFStreamer *S = new MCELFStreamer(Context, TAB, OS, CE);
558   if (RelaxAll)
559     S->getAssembler().setRelaxAll(true);
560   return S;
561 }