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/MCSection.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/raw_ostream.h"
25 class MCMachOStreamer : public MCStreamer {
26 /// SymbolFlags - We store the value for the 'desc' symbol field in the lowest
27 /// 16 bits of the implementation defined flags.
28 enum SymbolFlags { // See <mach-o/nlist.h>.
29 SF_DescFlagsMask = 0xFFFF,
31 // Reference type flags.
32 SF_ReferenceTypeMask = 0x0007,
33 SF_ReferenceTypeUndefinedNonLazy = 0x0000,
34 SF_ReferenceTypeUndefinedLazy = 0x0001,
35 SF_ReferenceTypeDefined = 0x0002,
36 SF_ReferenceTypePrivateDefined = 0x0003,
37 SF_ReferenceTypePrivateUndefinedNonLazy = 0x0004,
38 SF_ReferenceTypePrivateUndefinedLazy = 0x0005,
40 // Other 'desc' flags.
41 SF_NoDeadStrip = 0x0020,
42 SF_WeakReference = 0x0040,
43 SF_WeakDefinition = 0x0080
47 MCAssembler Assembler;
48 MCCodeEmitter *Emitter;
49 MCSectionData *CurSectionData;
50 DenseMap<const MCSection*, MCSectionData*> SectionMap;
51 DenseMap<const MCSymbol*, MCSymbolData*> SymbolMap;
54 MCFragment *getCurrentFragment() const {
55 assert(CurSectionData && "No current section!");
57 if (!CurSectionData->empty())
58 return &CurSectionData->getFragmentList().back();
63 MCSectionData &getSectionData(const MCSection &Section) {
64 MCSectionData *&Entry = SectionMap[&Section];
67 Entry = new MCSectionData(Section, &Assembler);
72 MCSymbolData &getSymbolData(const MCSymbol &Symbol) {
73 MCSymbolData *&Entry = SymbolMap[&Symbol];
76 Entry = new MCSymbolData(Symbol, 0, 0, &Assembler);
82 MCMachOStreamer(MCContext &Context, raw_ostream &_OS, MCCodeEmitter *_Emitter)
83 : MCStreamer(Context), Assembler(Context, _OS), Emitter(_Emitter),
87 const MCExpr *AddValueSymbols(const MCExpr *Value) {
88 switch (Value->getKind()) {
89 case MCExpr::Target: assert(0 && "Can't handle target exprs yet!");
90 case MCExpr::Constant:
93 case MCExpr::Binary: {
94 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
95 AddValueSymbols(BE->getLHS());
96 AddValueSymbols(BE->getRHS());
100 case MCExpr::SymbolRef:
101 getSymbolData(cast<MCSymbolRefExpr>(Value)->getSymbol());
105 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
112 /// @name MCStreamer Interface
115 virtual void SwitchSection(const MCSection *Section);
116 virtual void EmitLabel(MCSymbol *Symbol);
117 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
118 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
119 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
120 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
121 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
122 unsigned ByteAlignment);
123 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
124 assert(0 && "macho doesn't support this directive");
126 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
127 assert(0 && "macho doesn't support this directive");
129 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
130 unsigned Size = 0, unsigned ByteAlignment = 0);
131 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
132 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
133 virtual void EmitGPRel32Value(const MCExpr *Value) {
134 assert(0 && "macho doesn't support this directive");
136 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
137 unsigned ValueSize = 1,
138 unsigned MaxBytesToEmit = 0);
139 virtual void EmitCodeAlignment(unsigned ByteAlignment,
140 unsigned MaxBytesToEmit = 0);
141 virtual void EmitValueToOffset(const MCExpr *Offset,
142 unsigned char Value = 0);
144 virtual void EmitFileDirective(StringRef Filename) {
145 errs() << "FIXME: MCMachoStreamer:EmitFileDirective not implemented\n";
147 virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
148 errs() << "FIXME: MCMachoStreamer:EmitDwarfFileDirective not implemented\n";
151 virtual void EmitInstruction(const MCInst &Inst);
152 virtual void Finish();
157 } // end anonymous namespace.
159 void MCMachOStreamer::SwitchSection(const MCSection *Section) {
160 assert(Section && "Cannot switch to a null section!");
162 // If already in this section, then this is a noop.
163 if (Section == CurSection) return;
165 CurSection = Section;
166 CurSectionData = &getSectionData(*Section);
169 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
170 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
172 // FIXME: We should also use offsets into Fill fragments.
173 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
175 F = new MCDataFragment(CurSectionData);
177 MCSymbolData &SD = getSymbolData(*Symbol);
178 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
180 SD.setOffset(F->getContents().size());
182 // This causes the reference type and weak reference flags to be cleared.
183 SD.setFlags(SD.getFlags() & ~(SF_WeakReference | SF_ReferenceTypeMask));
185 Symbol->setSection(*CurSection);
188 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
190 case MCAF_SubsectionsViaSymbols:
191 Assembler.setSubsectionsViaSymbols(true);
195 assert(0 && "invalid assembler flag!");
198 void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
199 // Only absolute symbols can be redefined.
200 assert((Symbol->isUndefined() || Symbol->isAbsolute()) &&
201 "Cannot define a symbol twice!");
203 // FIXME: Lift context changes into super class.
204 // FIXME: Set associated section.
205 Symbol->setValue(Value);
208 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
209 MCSymbolAttr Attribute) {
210 // Indirect symbols are handled differently, to match how 'as' handles
211 // them. This makes writing matching .o files easier.
212 if (Attribute == MCSA_IndirectSymbol) {
213 // Note that we intentionally cannot use the symbol data here; this is
214 // important for matching the string table that 'as' generates.
215 IndirectSymbolData ISD;
217 ISD.SectionData = CurSectionData;
218 Assembler.getIndirectSymbols().push_back(ISD);
222 // Adding a symbol attribute always introduces the symbol, note that an
223 // important side effect of calling getSymbolData here is to register the
224 // symbol with the assembler.
225 MCSymbolData &SD = getSymbolData(*Symbol);
227 // The implementation of symbol attributes is designed to match 'as', but it
228 // leaves much to desired. It doesn't really make sense to arbitrarily add and
229 // remove flags, but 'as' allows this (in particular, see .desc).
231 // In the future it might be worth trying to make these operations more well
235 case MCSA_ELF_TypeFunction:
236 case MCSA_ELF_TypeIndFunction:
237 case MCSA_ELF_TypeObject:
238 case MCSA_ELF_TypeTLS:
239 case MCSA_ELF_TypeCommon:
240 case MCSA_ELF_TypeNoType:
241 case MCSA_IndirectSymbol:
247 assert(0 && "Invalid symbol attribute for Mach-O!");
251 SD.setExternal(true);
254 case MCSA_LazyReference:
255 // FIXME: This requires -dynamic.
256 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
257 if (Symbol->isUndefined())
258 SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
261 // Since .reference sets the no dead strip bit, it is equivalent to
262 // .no_dead_strip in practice.
264 case MCSA_NoDeadStrip:
265 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
268 case MCSA_PrivateExtern:
269 SD.setExternal(true);
270 SD.setPrivateExtern(true);
273 case MCSA_WeakReference:
274 // FIXME: This requires -dynamic.
275 if (Symbol->isUndefined())
276 SD.setFlags(SD.getFlags() | SF_WeakReference);
279 case MCSA_WeakDefinition:
280 // FIXME: 'as' enforces that this is defined and global. The manual claims
281 // it has to be in a coalesced section, but this isn't enforced.
282 SD.setFlags(SD.getFlags() | SF_WeakDefinition);
287 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
288 // Encode the 'desc' value into the lowest implementation defined bits.
289 assert(DescValue == (DescValue & SF_DescFlagsMask) &&
290 "Invalid .desc value!");
291 getSymbolData(*Symbol).setFlags(DescValue & SF_DescFlagsMask);
294 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
295 unsigned ByteAlignment) {
296 // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
297 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
299 MCSymbolData &SD = getSymbolData(*Symbol);
300 SD.setExternal(true);
301 SD.setCommon(Size, ByteAlignment);
304 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
305 unsigned Size, unsigned ByteAlignment) {
306 MCSectionData &SectData = getSectionData(*Section);
308 // The symbol may not be present, which only creates the section.
312 // FIXME: Assert that this section has the zerofill type.
314 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
316 MCSymbolData &SD = getSymbolData(*Symbol);
318 MCFragment *F = new MCZeroFillFragment(Size, ByteAlignment, &SectData);
321 Symbol->setSection(*Section);
323 // Update the maximum alignment on the zero fill section if necessary.
324 if (ByteAlignment > SectData.getAlignment())
325 SectData.setAlignment(ByteAlignment);
328 void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
329 MCDataFragment *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
331 DF = new MCDataFragment(CurSectionData);
332 DF->getContents().append(Data.begin(), Data.end());
335 void MCMachOStreamer::EmitValue(const MCExpr *Value, unsigned Size,
336 unsigned AddrSpace) {
337 MCDataFragment *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
339 DF = new MCDataFragment(CurSectionData);
341 // Avoid fixups when possible.
343 if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
344 // FIXME: Endianness assumption.
345 for (unsigned i = 0; i != Size; ++i)
346 DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
348 DF->getFixups().push_back(MCAsmFixup(DF->getContents().size(),
349 *AddValueSymbols(Value),
350 MCFixup::getKindForSize(Size)));
351 DF->getContents().resize(DF->getContents().size() + Size, 0);
355 void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
356 int64_t Value, unsigned ValueSize,
357 unsigned MaxBytesToEmit) {
358 if (MaxBytesToEmit == 0)
359 MaxBytesToEmit = ByteAlignment;
360 new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
361 false /* EmitNops */, CurSectionData);
363 // Update the maximum alignment on the current section if necessary.
364 if (ByteAlignment > CurSectionData->getAlignment())
365 CurSectionData->setAlignment(ByteAlignment);
368 void MCMachOStreamer::EmitCodeAlignment(unsigned ByteAlignment,
369 unsigned MaxBytesToEmit) {
370 if (MaxBytesToEmit == 0)
371 MaxBytesToEmit = ByteAlignment;
372 // FIXME the 0x90 is the default x86 1 byte nop opcode.
373 new MCAlignFragment(ByteAlignment, 0x90, 1, MaxBytesToEmit,
374 true /* EmitNops */, CurSectionData);
376 // Update the maximum alignment on the current section if necessary.
377 if (ByteAlignment > CurSectionData->getAlignment())
378 CurSectionData->setAlignment(ByteAlignment);
381 void MCMachOStreamer::EmitValueToOffset(const MCExpr *Offset,
382 unsigned char Value) {
383 new MCOrgFragment(*Offset, Value, CurSectionData);
386 void MCMachOStreamer::EmitInstruction(const MCInst &Inst) {
388 for (unsigned i = 0; i != Inst.getNumOperands(); ++i)
389 if (Inst.getOperand(i).isExpr())
390 AddValueSymbols(Inst.getOperand(i).getExpr());
393 llvm_unreachable("no code emitter available!");
395 CurSectionData->setHasInstructions(true);
397 SmallVector<MCFixup, 4> Fixups;
398 SmallString<256> Code;
399 raw_svector_ostream VecOS(Code);
400 Emitter->EncodeInstruction(Inst, VecOS, Fixups);
403 // Add the fixups and data.
404 MCDataFragment *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
406 DF = new MCDataFragment(CurSectionData);
407 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
408 MCFixup &F = Fixups[i];
409 DF->getFixups().push_back(MCAsmFixup(DF->getContents().size()+F.getOffset(),
413 DF->getContents().append(Code.begin(), Code.end());
416 void MCMachOStreamer::Finish() {
420 MCStreamer *llvm::createMachOStreamer(MCContext &Context, raw_ostream &OS,
422 return new MCMachOStreamer(Context, OS, CE);