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