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