Add '.code 32' assembler directive to MC streamers.
[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_Code32: return; // no-op here.
185   case MCAF_SubsectionsViaSymbols:
186     getAssembler().setSubsectionsViaSymbols(true);
187     return;
188   }
189
190   assert(0 && "invalid assembler flag!");
191 }
192
193 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
194   // FIXME: Anything needed here to flag the function as thumb?
195 }
196
197 void MCELFStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
198   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
199   // MCObjectStreamer.
200   // FIXME: Lift context changes into super class.
201   getAssembler().getOrCreateSymbolData(*Symbol);
202   Symbol->setVariableValue(AddValueSymbols(Value));
203 }
204
205 // This is a hack. To be able to implement weakrefs the writer has to be able
206 // to distinguish
207 //    .weakref foo, bar
208 //    .long foo
209 // from
210 //   .weakref foo, bar
211 //   .long bar
212 // since the first case should produce a weak undefined reference and the second
213 // one a strong one.
214 // If we created foo as a regular alias pointing to bar (foo = bar), then
215 // MCExpr::EvaluateAsRelocatable would recurse on foo and the writer would
216 // never see it used in a relocation.
217 // What we do is create a MCTargetExpr that when evaluated produces a symbol
218 // ref to a temporary symbol. This temporary symbol in turn is a variable
219 // that equals the original symbol (tmp = bar). With this hack the writer
220 // gets a relocation with tmp and can correctly implement weak references.
221
222 namespace {
223 class WeakRefExpr : public MCTargetExpr {
224 private:
225   const MCSymbolRefExpr *Alias;
226
227   explicit WeakRefExpr(const MCSymbolRefExpr *Alias_)
228     : MCTargetExpr(), Alias(Alias_) {}
229
230 public:
231   virtual void PrintImpl(raw_ostream &OS) const {
232     llvm_unreachable("Unimplemented");
233   }
234
235   virtual bool EvaluateAsRelocatableImpl(MCValue &Res,
236                                          const MCAsmLayout *Layout) const {
237     Res = MCValue::get(Alias, 0, 0);
238     return true;
239   }
240
241   static const WeakRefExpr *Create(const MCSymbol *Alias, MCContext &Ctx) {
242     const MCSymbolRefExpr *A = MCSymbolRefExpr::Create(Alias, Ctx);
243     return new (Ctx) WeakRefExpr(A);
244   }
245 };
246 } // end anonymous namespace
247
248 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
249   getAssembler().getOrCreateSymbolData(*Symbol);
250   MCSymbolData &AliasSD = getAssembler().getOrCreateSymbolData(*Alias);
251   AliasSD.setFlags(AliasSD.getFlags() | ELF_Other_Weakref);
252
253   // Create the alias that actually points to Symbol
254   const MCSymbolRefExpr *SymRef = MCSymbolRefExpr::Create(Symbol, getContext());
255   MCSymbol *RealAlias = getContext().CreateTempSymbol();
256   RealAlias->setVariableValue(SymRef);
257
258   MCSymbolData &RealAliasSD = getAssembler().getOrCreateSymbolData(*RealAlias);
259   RealAliasSD.setFlags(RealAliasSD.getFlags() | ELF_Other_Weakref);
260
261   const MCExpr *Value = WeakRefExpr::Create(RealAlias, getContext());
262   Alias->setVariableValue(Value);
263 }
264
265 static void SetBinding(MCSymbolData &SD, unsigned Binding) {
266   assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
267          Binding == ELF::STB_WEAK);
268   uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
269   SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
270 }
271
272 static unsigned GetBinding(const MCSymbolData &SD) {
273   uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
274   assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
275          Binding == ELF::STB_WEAK);
276   return Binding;
277 }
278
279 static void SetType(MCSymbolData &SD, unsigned Type) {
280   assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
281          Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
282          Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
283          Type == ELF::STT_TLS);
284
285   uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STT_Shift);
286   SD.setFlags(OtherFlags | (Type << ELF_STT_Shift));
287 }
288
289 static void SetVisibility(MCSymbolData &SD, unsigned Visibility) {
290   assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
291          Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
292
293   uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STV_Shift);
294   SD.setFlags(OtherFlags | (Visibility << ELF_STV_Shift));
295 }
296
297 void MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
298                                           MCSymbolAttr Attribute) {
299   // Indirect symbols are handled differently, to match how 'as' handles
300   // them. This makes writing matching .o files easier.
301   if (Attribute == MCSA_IndirectSymbol) {
302     // Note that we intentionally cannot use the symbol data here; this is
303     // important for matching the string table that 'as' generates.
304     IndirectSymbolData ISD;
305     ISD.Symbol = Symbol;
306     ISD.SectionData = getCurrentSectionData();
307     getAssembler().getIndirectSymbols().push_back(ISD);
308     return;
309   }
310
311   // Adding a symbol attribute always introduces the symbol, note that an
312   // important side effect of calling getOrCreateSymbolData here is to register
313   // the symbol with the assembler.
314   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
315
316   // The implementation of symbol attributes is designed to match 'as', but it
317   // leaves much to desired. It doesn't really make sense to arbitrarily add and
318   // remove flags, but 'as' allows this (in particular, see .desc).
319   //
320   // In the future it might be worth trying to make these operations more well
321   // defined.
322   switch (Attribute) {
323   case MCSA_LazyReference:
324   case MCSA_Reference:
325   case MCSA_NoDeadStrip:
326   case MCSA_PrivateExtern:
327   case MCSA_WeakDefinition:
328   case MCSA_WeakDefAutoPrivate:
329   case MCSA_Invalid:
330   case MCSA_ELF_TypeIndFunction:
331   case MCSA_IndirectSymbol:
332     assert(0 && "Invalid symbol attribute for ELF!");
333     break;
334
335   case MCSA_Global:
336     SetBinding(SD, ELF::STB_GLOBAL);
337     SD.setExternal(true);
338     BindingExplicitlySet.insert(Symbol);
339     break;
340
341   case MCSA_WeakReference:
342   case MCSA_Weak:
343     SetBinding(SD, ELF::STB_WEAK);
344     SD.setExternal(true);
345     BindingExplicitlySet.insert(Symbol);
346     break;
347
348   case MCSA_Local:
349     SetBinding(SD, ELF::STB_LOCAL);
350     SD.setExternal(false);
351     BindingExplicitlySet.insert(Symbol);
352     break;
353
354   case MCSA_ELF_TypeFunction:
355     SetType(SD, ELF::STT_FUNC);
356     break;
357
358   case MCSA_ELF_TypeObject:
359     SetType(SD, ELF::STT_OBJECT);
360     break;
361
362   case MCSA_ELF_TypeTLS:
363     SetType(SD, ELF::STT_TLS);
364     break;
365
366   case MCSA_ELF_TypeCommon:
367     SetType(SD, ELF::STT_COMMON);
368     break;
369
370   case MCSA_ELF_TypeNoType:
371     SetType(SD, ELF::STT_NOTYPE);
372     break;
373
374   case MCSA_Protected:
375     SetVisibility(SD, ELF::STV_PROTECTED);
376     break;
377
378   case MCSA_Hidden:
379     SetVisibility(SD, ELF::STV_HIDDEN);
380     break;
381
382   case MCSA_Internal:
383     SetVisibility(SD, ELF::STV_INTERNAL);
384     break;
385   }
386 }
387
388 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
389                                        unsigned ByteAlignment) {
390   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
391
392   if (!BindingExplicitlySet.count(Symbol)) {
393     SetBinding(SD, ELF::STB_GLOBAL);
394     SD.setExternal(true);
395   }
396
397   if (GetBinding(SD) == ELF_STB_Local) {
398     const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
399                                                                     MCSectionELF::SHT_NOBITS,
400                                                                     MCSectionELF::SHF_WRITE |
401                                                                     MCSectionELF::SHF_ALLOC,
402                                                                     SectionKind::getBSS());
403     Symbol->setSection(*Section);
404
405     struct LocalCommon L = {&SD, Size, ByteAlignment};
406     LocalCommons.push_back(L);
407   } else {
408     SD.setCommon(Size, ByteAlignment);
409   }
410
411   SD.setSize(MCConstantExpr::Create(Size, getContext()));
412 }
413
414 void MCELFStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
415   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
416   // MCObjectStreamer.
417   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
418 }
419
420 void MCELFStreamer::EmitValue(const MCExpr *Value, unsigned Size,
421                                 unsigned AddrSpace) {
422   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
423   // MCObjectStreamer.
424   MCDataFragment *DF = getOrCreateDataFragment();
425
426   // Avoid fixups when possible.
427   int64_t AbsValue;
428   if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
429     // FIXME: Endianness assumption.
430     for (unsigned i = 0; i != Size; ++i)
431       DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
432   } else {
433     DF->addFixup(MCFixup::Create(DF->getContents().size(), AddValueSymbols(Value),
434                                  MCFixup::getKindForSize(Size)));
435     DF->getContents().resize(DF->getContents().size() + Size, 0);
436   }
437 }
438
439 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
440                                            int64_t Value, unsigned ValueSize,
441                                            unsigned MaxBytesToEmit) {
442   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
443   // MCObjectStreamer.
444   if (MaxBytesToEmit == 0)
445     MaxBytesToEmit = ByteAlignment;
446   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
447                       getCurrentSectionData());
448
449   // Update the maximum alignment on the current section if necessary.
450   if (ByteAlignment > getCurrentSectionData()->getAlignment())
451     getCurrentSectionData()->setAlignment(ByteAlignment);
452 }
453
454 void MCELFStreamer::EmitCodeAlignment(unsigned ByteAlignment,
455                                         unsigned MaxBytesToEmit) {
456   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
457   // MCObjectStreamer.
458   if (MaxBytesToEmit == 0)
459     MaxBytesToEmit = ByteAlignment;
460   MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
461                                            getCurrentSectionData());
462   F->setEmitNops(true);
463
464   // Update the maximum alignment on the current section if necessary.
465   if (ByteAlignment > getCurrentSectionData()->getAlignment())
466     getCurrentSectionData()->setAlignment(ByteAlignment);
467 }
468
469 void MCELFStreamer::EmitValueToOffset(const MCExpr *Offset,
470                                         unsigned char Value) {
471   // TODO: This is exactly the same as MCMachOStreamer. Consider merging into
472   // MCObjectStreamer.
473   new MCOrgFragment(*Offset, Value, getCurrentSectionData());
474 }
475
476 // Add a symbol for the file name of this module. This is the second
477 // entry in the module's symbol table (the first being the null symbol).
478 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
479   MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
480   Symbol->setSection(*CurSection);
481   Symbol->setAbsolute();
482
483   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
484
485   SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
486 }
487
488 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
489   MCInstFragment *IF = new MCInstFragment(Inst, getCurrentSectionData());
490
491   // Add the fixups and data.
492   //
493   // FIXME: Revisit this design decision when relaxation is done, we may be
494   // able to get away with not storing any extra data in the MCInst.
495   SmallVector<MCFixup, 4> Fixups;
496   SmallString<256> Code;
497   raw_svector_ostream VecOS(Code);
498   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
499   VecOS.flush();
500
501   IF->getCode() = Code;
502   IF->getFixups() = Fixups;
503 }
504
505 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
506   MCDataFragment *DF = getOrCreateDataFragment();
507
508   SmallVector<MCFixup, 4> Fixups;
509   SmallString<256> Code;
510   raw_svector_ostream VecOS(Code);
511   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
512   VecOS.flush();
513
514   // Add the fixups and data.
515   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
516     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
517     DF->addFixup(Fixups[i]);
518   }
519   DF->getContents().append(Code.begin(), Code.end());
520 }
521
522 void MCELFStreamer::Finish() {
523   // FIXME: duplicated code with the MachO streamer.
524   // Dump out the dwarf file & directory tables and line tables.
525   if (getContext().hasDwarfFiles()) {
526     const MCSection *DwarfLineSection =
527       getContext().getELFSection(".debug_line", 0, 0,
528                                  SectionKind::getDataRelLocal());
529     MCDwarfFileTable::Emit(this, DwarfLineSection);
530   }
531
532   for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
533                                                 e = LocalCommons.end();
534        i != e; ++i) {
535     MCSymbolData *SD = i->SD;
536     uint64_t Size = i->Size;
537     unsigned ByteAlignment = i->ByteAlignment;
538     const MCSymbol &Symbol = SD->getSymbol();
539     const MCSection &Section = Symbol.getSection();
540
541     MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
542     new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
543
544     MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
545     SD->setFragment(F);
546
547     // Update the maximum alignment of the section if necessary.
548     if (ByteAlignment > SectData.getAlignment())
549       SectData.setAlignment(ByteAlignment);
550   }
551
552   this->MCObjectStreamer::Finish();
553 }
554
555 MCStreamer *llvm::createELFStreamer(MCContext &Context, TargetAsmBackend &TAB,
556                                       raw_ostream &OS, MCCodeEmitter *CE,
557                                       bool RelaxAll) {
558   MCELFStreamer *S = new MCELFStreamer(Context, TAB, OS, CE);
559   if (RelaxAll)
560     S->getAssembler().setRelaxAll(true);
561   return S;
562 }