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