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