1 //===- lib/MC/MCMachOStreamer.cpp - Mach-O Object Output ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/MCStreamer.h"
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"
32 class MCMachOStreamer : public MCObjectStreamer {
34 virtual void EmitInstToData(const MCInst &Inst);
37 MCMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
38 raw_ostream &OS, MCCodeEmitter *Emitter)
39 : MCObjectStreamer(Context, TAB, OS, Emitter, true) {}
41 /// @name MCStreamer Interface
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");
56 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
57 assert(0 && "macho doesn't support this directive");
59 virtual void EmitCOFFSymbolType(int Type) {
60 assert(0 && "macho doesn't support this directive");
62 virtual void EndCOFFSymbolDef() {
63 assert(0 && "macho doesn't support this directive");
65 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
66 assert(0 && "macho doesn't support this directive");
68 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
69 assert(0 && "macho doesn't support this directive");
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);
84 virtual void EmitFileDirective(StringRef Filename) {
85 // FIXME: Just ignore the .file; it isn't important enough to fail the
88 //report_fatal_error("unsupported directive: '.file'");
91 virtual void Finish();
96 } // end anonymous namespace.
98 void MCMachOStreamer::InitSections() {
99 SwitchSection(getContext().getMachOSection("__TEXT", "__text",
100 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
101 0, SectionKind::getText()));
105 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
106 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
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());
115 MCObjectStreamer::EmitLabel(Symbol);
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
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);
128 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag 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);
137 llvm_unreachable("invalid assembler flag!");
141 void MCMachOStreamer::EmitThumbFunc(MCSymbol *Func) {
142 // FIXME: Flag the function ISA as thumb with DW_AT_APPLE_isa.
145 void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
146 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
148 // FIXME: Lift context changes into super class.
149 getAssembler().getOrCreateSymbolData(*Symbol);
150 Symbol->setVariableValue(AddValueSymbols(Value));
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;
162 ISD.SectionData = getCurrentSectionData();
163 getAssembler().getIndirectSymbols().push_back(ISD);
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);
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).
176 // In the future it might be worth trying to make these operations more well
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:
193 assert(0 && "Invalid symbol attribute for Mach-O!");
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
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);
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);
214 // Since .reference sets the no dead strip bit, it is equivalent to
215 // .no_dead_strip in practice.
217 case MCSA_NoDeadStrip:
218 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
221 case MCSA_SymbolResolver:
222 SD.setFlags(SD.getFlags() | SF_SymbolResolver);
225 case MCSA_PrivateExtern:
226 SD.setExternal(true);
227 SD.setPrivateExtern(true);
230 case MCSA_WeakReference:
231 // FIXME: This requires -dynamic.
232 if (Symbol->isUndefined())
233 SD.setFlags(SD.getFlags() | SF_WeakReference);
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);
242 case MCSA_WeakDefAutoPrivate:
243 SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
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);
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!");
261 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
262 SD.setExternal(true);
263 SD.setCommon(Size, ByteAlignment);
266 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
267 unsigned Size, unsigned ByteAlignment) {
268 MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
270 // The symbol may not be present, which only creates the section.
274 // FIXME: Assert that this section has the zerofill type.
276 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
278 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
280 // Emit an align fragment if necessary.
281 if (ByteAlignment != 1)
282 new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
284 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
287 Symbol->setSection(*Section);
289 // Update the maximum alignment on the zero fill section if necessary.
290 if (ByteAlignment > SectData.getAlignment())
291 SectData.setAlignment(ByteAlignment);
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);
302 void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
303 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
305 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
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
313 if (MaxBytesToEmit == 0)
314 MaxBytesToEmit = ByteAlignment;
315 new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
316 getCurrentSectionData());
318 // Update the maximum alignment on the current section if necessary.
319 if (ByteAlignment > getCurrentSectionData()->getAlignment())
320 getCurrentSectionData()->setAlignment(ByteAlignment);
323 void MCMachOStreamer::EmitCodeAlignment(unsigned ByteAlignment,
324 unsigned MaxBytesToEmit) {
325 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
327 if (MaxBytesToEmit == 0)
328 MaxBytesToEmit = ByteAlignment;
329 MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
330 getCurrentSectionData());
331 F->setEmitNops(true);
333 // Update the maximum alignment on the current section if necessary.
334 if (ByteAlignment > getCurrentSectionData()->getAlignment())
335 getCurrentSectionData()->setAlignment(ByteAlignment);
338 void MCMachOStreamer::EmitValueToOffset(const MCExpr *Offset,
339 unsigned char Value) {
340 new MCOrgFragment(*Offset, Value, getCurrentSectionData());
343 void MCMachOStreamer::EmitInstToData(const MCInst &Inst) {
344 MCDataFragment *DF = getOrCreateDataFragment();
346 SmallVector<MCFixup, 4> Fixups;
347 SmallString<256> Code;
348 raw_svector_ostream VecOS(Code);
349 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
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]);
357 DF->getContents().append(Code.begin(), Code.end());
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",
365 MCSectionMachO::S_ATTR_DEBUG,
366 0, SectionKind::getDataRelLocal());
368 getAssembler().getOrCreateSectionData(*DwarfLineSection);
369 int PointerSize = getAssembler().getBackend().getPointerSize();
370 MCDwarfFileTable::Emit(this, DwarfLineSection, &DLS, PointerSize);
373 // We have to set the fragment atom associations so we can relax properly for
376 // First, scan the symbol table to build a lookup table from fragments to
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()) &&
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;
389 // Set the fragment atom associations by tracking the last seen atom defining
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))
398 it2->setAtom(CurrentAtom);
402 this->MCObjectStreamer::Finish();
405 MCStreamer *llvm::createMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
406 raw_ostream &OS, MCCodeEmitter *CE,
408 MCMachOStreamer *S = new MCMachOStreamer(Context, TAB, OS, CE);
410 S->getAssembler().setRelaxAll(true);