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