Add EmitInstToFragment to the generic object streamer.
[oota-llvm.git] / lib / MC / MCMachOStreamer.cpp
1 //===- lib/MC/MCMachOStreamer.cpp - Mach-O 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 #include "llvm/MC/MCStreamer.h"
11
12 #include "llvm/MC/MCAssembler.h"
13 #include "llvm/MC/MCContext.h"
14 #include "llvm/MC/MCCodeEmitter.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCInst.h"
17 #include "llvm/MC/MCObjectStreamer.h"
18 #include "llvm/MC/MCSection.h"
19 #include "llvm/MC/MCSymbol.h"
20 #include "llvm/MC/MCMachOSymbolFlags.h"
21 #include "llvm/MC/MCSectionMachO.h"
22 #include "llvm/MC/MCDwarf.h"
23 #include "llvm/Support/Dwarf.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetAsmBackend.h"
27
28 using namespace llvm;
29
30 namespace {
31
32 class MCMachOStreamer : public MCObjectStreamer {
33 private:
34   virtual void EmitInstToData(const MCInst &Inst);
35
36 public:
37   MCMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
38                   raw_ostream &OS, MCCodeEmitter *Emitter)
39     : MCObjectStreamer(Context, TAB, OS, Emitter, true) {}
40
41   /// @name MCStreamer Interface
42   /// @{
43
44   virtual void InitSections();
45   virtual void EmitLabel(MCSymbol *Symbol);
46   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
47   virtual void EmitThumbFunc(MCSymbol *Func);
48   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
49   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
50   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
51   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
52                                 unsigned ByteAlignment);
53   virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
54     assert(0 && "macho doesn't support this directive");
55   }
56   virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
57     assert(0 && "macho doesn't support this directive");
58   }
59   virtual void EmitCOFFSymbolType(int Type) {
60     assert(0 && "macho doesn't support this directive");
61   }
62   virtual void EndCOFFSymbolDef() {
63     assert(0 && "macho doesn't support this directive");
64   }
65   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
66     assert(0 && "macho doesn't support this directive");
67   }
68   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
69     assert(0 && "macho doesn't support this directive");
70   }
71   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
72                             unsigned Size = 0, unsigned ByteAlignment = 0);
73   virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
74                               uint64_t Size, unsigned ByteAlignment = 0);
75   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
76   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
77                                     unsigned ValueSize = 1,
78                                     unsigned MaxBytesToEmit = 0);
79   virtual void EmitCodeAlignment(unsigned ByteAlignment,
80                                  unsigned MaxBytesToEmit = 0);
81   virtual void EmitValueToOffset(const MCExpr *Offset,
82                                  unsigned char Value = 0);
83
84   virtual void EmitFileDirective(StringRef Filename) {
85     // FIXME: Just ignore the .file; it isn't important enough to fail the
86     // entire assembly.
87
88     //report_fatal_error("unsupported directive: '.file'");
89   }
90
91   virtual void Finish();
92
93   /// @}
94 };
95
96 } // end anonymous namespace.
97
98 void MCMachOStreamer::InitSections() {
99   SwitchSection(getContext().getMachOSection("__TEXT", "__text",
100                                     MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
101                                     0, SectionKind::getText()));
102
103 }
104
105 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
106   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
107
108   // isSymbolLinkerVisible uses the section.
109   Symbol->setSection(*CurSection);
110   // We have to create a new fragment if this is an atom defining symbol,
111   // fragments cannot span atoms.
112   if (getAssembler().isSymbolLinkerVisible(*Symbol))
113     new MCDataFragment(getCurrentSectionData());
114
115   MCObjectStreamer::EmitLabel(Symbol);
116
117   MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
118   // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
119   // to clear the weak reference and weak definition bits too, but the
120   // implementation was buggy. For now we just try to match 'as', for
121   // diffability.
122   //
123   // FIXME: Cleanup this code, these bits should be emitted based on semantic
124   // properties, not on the order of definition, etc.
125   SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
126 }
127
128 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
129   switch (Flag) {
130   case MCAF_SyntaxUnified: return; // no-op here.
131   case MCAF_Code16: return; // no-op here.
132   case MCAF_Code32: return; // no-op here.
133   case MCAF_SubsectionsViaSymbols:
134     getAssembler().setSubsectionsViaSymbols(true);
135     return;
136   default:
137     llvm_unreachable("invalid assembler flag!");
138   }
139 }
140
141 void MCMachOStreamer::EmitThumbFunc(MCSymbol *Func) {
142   // FIXME: Flag the function ISA as thumb with DW_AT_APPLE_isa.
143 }
144
145 void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
146   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
147   // MCObjectStreamer.
148   // FIXME: Lift context changes into super class.
149   getAssembler().getOrCreateSymbolData(*Symbol);
150   Symbol->setVariableValue(AddValueSymbols(Value));
151 }
152
153 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
154                                           MCSymbolAttr Attribute) {
155   // Indirect symbols are handled differently, to match how 'as' handles
156   // them. This makes writing matching .o files easier.
157   if (Attribute == MCSA_IndirectSymbol) {
158     // Note that we intentionally cannot use the symbol data here; this is
159     // important for matching the string table that 'as' generates.
160     IndirectSymbolData ISD;
161     ISD.Symbol = Symbol;
162     ISD.SectionData = getCurrentSectionData();
163     getAssembler().getIndirectSymbols().push_back(ISD);
164     return;
165   }
166
167   // Adding a symbol attribute always introduces the symbol, note that an
168   // important side effect of calling getOrCreateSymbolData here is to register
169   // the symbol with the assembler.
170   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
171
172   // The implementation of symbol attributes is designed to match 'as', but it
173   // leaves much to desired. It doesn't really make sense to arbitrarily add and
174   // remove flags, but 'as' allows this (in particular, see .desc).
175   //
176   // In the future it might be worth trying to make these operations more well
177   // defined.
178   switch (Attribute) {
179   case MCSA_Invalid:
180   case MCSA_ELF_TypeFunction:
181   case MCSA_ELF_TypeIndFunction:
182   case MCSA_ELF_TypeObject:
183   case MCSA_ELF_TypeTLS:
184   case MCSA_ELF_TypeCommon:
185   case MCSA_ELF_TypeNoType:
186   case MCSA_ELF_TypeGnuUniqueObject:
187   case MCSA_IndirectSymbol:
188   case MCSA_Hidden:
189   case MCSA_Internal:
190   case MCSA_Protected:
191   case MCSA_Weak:
192   case MCSA_Local:
193     assert(0 && "Invalid symbol attribute for Mach-O!");
194     break;
195
196   case MCSA_Global:
197     SD.setExternal(true);
198     // This effectively clears the undefined lazy bit, in Darwin 'as', although
199     // it isn't very consistent because it implements this as part of symbol
200     // lookup.
201     //
202     // FIXME: Cleanup this code, these bits should be emitted based on semantic
203     // properties, not on the order of definition, etc.
204     SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
205     break;
206
207   case MCSA_LazyReference:
208     // FIXME: This requires -dynamic.
209     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
210     if (Symbol->isUndefined())
211       SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
212     break;
213
214     // Since .reference sets the no dead strip bit, it is equivalent to
215     // .no_dead_strip in practice.
216   case MCSA_Reference:
217   case MCSA_NoDeadStrip:
218     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
219     break;
220
221   case MCSA_SymbolResolver:
222     SD.setFlags(SD.getFlags() | SF_SymbolResolver);
223     break;
224
225   case MCSA_PrivateExtern:
226     SD.setExternal(true);
227     SD.setPrivateExtern(true);
228     break;
229
230   case MCSA_WeakReference:
231     // FIXME: This requires -dynamic.
232     if (Symbol->isUndefined())
233       SD.setFlags(SD.getFlags() | SF_WeakReference);
234     break;
235
236   case MCSA_WeakDefinition:
237     // FIXME: 'as' enforces that this is defined and global. The manual claims
238     // it has to be in a coalesced section, but this isn't enforced.
239     SD.setFlags(SD.getFlags() | SF_WeakDefinition);
240     break;
241
242   case MCSA_WeakDefAutoPrivate:
243     SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
244     break;
245   }
246 }
247
248 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
249   // Encode the 'desc' value into the lowest implementation defined bits.
250   assert(DescValue == (DescValue & SF_DescFlagsMask) &&
251          "Invalid .desc value!");
252   getAssembler().getOrCreateSymbolData(*Symbol).setFlags(
253     DescValue & SF_DescFlagsMask);
254 }
255
256 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
257                                        unsigned ByteAlignment) {
258   // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
259   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
260
261   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
262   SD.setExternal(true);
263   SD.setCommon(Size, ByteAlignment);
264 }
265
266 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
267                                    unsigned Size, unsigned ByteAlignment) {
268   MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
269
270   // The symbol may not be present, which only creates the section.
271   if (!Symbol)
272     return;
273
274   // FIXME: Assert that this section has the zerofill type.
275
276   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
277
278   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
279
280   // Emit an align fragment if necessary.
281   if (ByteAlignment != 1)
282     new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
283
284   MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
285   SD.setFragment(F);
286
287   Symbol->setSection(*Section);
288
289   // Update the maximum alignment on the zero fill section if necessary.
290   if (ByteAlignment > SectData.getAlignment())
291     SectData.setAlignment(ByteAlignment);
292 }
293
294 // This should always be called with the thread local bss section.  Like the
295 // .zerofill directive this doesn't actually switch sections on us.
296 void MCMachOStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
297                                      uint64_t Size, unsigned ByteAlignment) {
298   EmitZerofill(Section, Symbol, Size, ByteAlignment);
299   return;
300 }
301
302 void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
303   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
304   // MCObjectStreamer.
305   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
306 }
307
308 void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
309                                            int64_t Value, unsigned ValueSize,
310                                            unsigned MaxBytesToEmit) {
311   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
312   // MCObjectStreamer.
313   if (MaxBytesToEmit == 0)
314     MaxBytesToEmit = ByteAlignment;
315   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
316                       getCurrentSectionData());
317
318   // Update the maximum alignment on the current section if necessary.
319   if (ByteAlignment > getCurrentSectionData()->getAlignment())
320     getCurrentSectionData()->setAlignment(ByteAlignment);
321 }
322
323 void MCMachOStreamer::EmitCodeAlignment(unsigned ByteAlignment,
324                                         unsigned MaxBytesToEmit) {
325   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
326   // MCObjectStreamer.
327   if (MaxBytesToEmit == 0)
328     MaxBytesToEmit = ByteAlignment;
329   MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
330                                            getCurrentSectionData());
331   F->setEmitNops(true);
332
333   // Update the maximum alignment on the current section if necessary.
334   if (ByteAlignment > getCurrentSectionData()->getAlignment())
335     getCurrentSectionData()->setAlignment(ByteAlignment);
336 }
337
338 void MCMachOStreamer::EmitValueToOffset(const MCExpr *Offset,
339                                         unsigned char Value) {
340   new MCOrgFragment(*Offset, Value, getCurrentSectionData());
341 }
342
343 void MCMachOStreamer::EmitInstToData(const MCInst &Inst) {
344   MCDataFragment *DF = getOrCreateDataFragment();
345
346   SmallVector<MCFixup, 4> Fixups;
347   SmallString<256> Code;
348   raw_svector_ostream VecOS(Code);
349   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
350   VecOS.flush();
351
352   // Add the fixups and data.
353   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
354     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
355     DF->addFixup(Fixups[i]);
356   }
357   DF->getContents().append(Code.begin(), Code.end());
358 }
359
360 void MCMachOStreamer::Finish() {
361   // Dump out the dwarf file & directory tables and line tables.
362   if (getContext().hasDwarfFiles()) {
363     const MCSection *DwarfLineSection = getContext().getMachOSection("__DWARF",
364                                          "__debug_line",
365                                          MCSectionMachO::S_ATTR_DEBUG,
366                                          0, SectionKind::getDataRelLocal());
367     MCSectionData &DLS =
368       getAssembler().getOrCreateSectionData(*DwarfLineSection);
369     int PointerSize = getAssembler().getBackend().getPointerSize();
370     MCDwarfFileTable::Emit(this, DwarfLineSection, &DLS, PointerSize);
371   }
372
373   // We have to set the fragment atom associations so we can relax properly for
374   // Mach-O.
375
376   // First, scan the symbol table to build a lookup table from fragments to
377   // defining symbols.
378   DenseMap<const MCFragment*, MCSymbolData*> DefiningSymbolMap;
379   for (MCAssembler::symbol_iterator it = getAssembler().symbol_begin(),
380          ie = getAssembler().symbol_end(); it != ie; ++it) {
381     if (getAssembler().isSymbolLinkerVisible(it->getSymbol()) &&
382         it->getFragment()) {
383       // An atom defining symbol should never be internal to a fragment.
384       assert(it->getOffset() == 0 && "Invalid offset in atom defining symbol!");
385       DefiningSymbolMap[it->getFragment()] = it;
386     }
387   }
388
389   // Set the fragment atom associations by tracking the last seen atom defining
390   // symbol.
391   for (MCAssembler::iterator it = getAssembler().begin(),
392          ie = getAssembler().end(); it != ie; ++it) {
393     MCSymbolData *CurrentAtom = 0;
394     for (MCSectionData::iterator it2 = it->begin(),
395            ie2 = it->end(); it2 != ie2; ++it2) {
396       if (MCSymbolData *SD = DefiningSymbolMap.lookup(it2))
397         CurrentAtom = SD;
398       it2->setAtom(CurrentAtom);
399     }
400   }
401
402   this->MCObjectStreamer::Finish();
403 }
404
405 MCStreamer *llvm::createMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
406                                       raw_ostream &OS, MCCodeEmitter *CE,
407                                       bool RelaxAll) {
408   MCMachOStreamer *S = new MCMachOStreamer(Context, TAB, OS, CE);
409   if (RelaxAll)
410     S->getAssembler().setRelaxAll(true);
411   return S;
412 }