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/Support/ErrorHandling.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Target/TargetAsmBackend.h"
29 class MCMachOStreamer : public MCObjectStreamer {
31 void EmitInstToFragment(const MCInst &Inst);
32 void EmitInstToData(const MCInst &Inst);
35 MCMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
36 raw_ostream &OS, MCCodeEmitter *Emitter)
37 : MCObjectStreamer(Context, TAB, OS, Emitter) {}
39 /// @name MCStreamer Interface
42 virtual void EmitLabel(MCSymbol *Symbol);
43 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
44 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
45 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
46 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
47 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
48 unsigned ByteAlignment);
49 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
50 assert(0 && "macho doesn't support this directive");
52 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
53 assert(0 && "macho doesn't support this directive");
55 virtual void EmitCOFFSymbolType(int Type) {
56 assert(0 && "macho doesn't support this directive");
58 virtual void EndCOFFSymbolDef() {
59 assert(0 && "macho doesn't support this directive");
61 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
62 assert(0 && "macho doesn't support this directive");
64 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
65 assert(0 && "macho doesn't support this directive");
67 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
68 unsigned Size = 0, unsigned ByteAlignment = 0);
69 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
70 uint64_t Size, unsigned ByteAlignment = 0);
71 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
72 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
73 virtual void EmitGPRel32Value(const MCExpr *Value) {
74 assert(0 && "macho doesn't support this directive");
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 report_fatal_error("unsupported directive: '.file'");
87 virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
88 report_fatal_error("unsupported directive: '.file'");
91 virtual void EmitInstruction(const MCInst &Inst);
93 virtual void Finish();
98 } // end anonymous namespace.
100 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
101 // TODO: This is almost exactly the same as WinCOFFStreamer. Consider merging
102 // into MCObjectStreamer.
103 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
104 assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
105 assert(CurSection && "Cannot emit before setting section!");
107 Symbol->setSection(*CurSection);
109 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
111 // We have to create a new fragment if this is an atom defining symbol,
112 // fragments cannot span atoms.
113 if (getAssembler().isSymbolLinkerVisible(SD.getSymbol()))
114 new MCDataFragment(getCurrentSectionData());
116 // FIXME: This is wasteful, we don't necessarily need to create a data
117 // fragment. Instead, we should mark the symbol as pointing into the data
118 // fragment if it exists, otherwise we should just queue the label and set its
119 // fragment pointer when we emit the next fragment.
120 MCDataFragment *F = getOrCreateDataFragment();
121 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
123 SD.setOffset(F->getContents().size());
125 // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
126 // to clear the weak reference and weak definition bits too, but the
127 // implementation was buggy. For now we just try to match 'as', for
130 // FIXME: Cleanup this code, these bits should be emitted based on semantic
131 // properties, not on the order of definition, etc.
132 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
135 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
137 case MCAF_SubsectionsViaSymbols:
138 getAssembler().setSubsectionsViaSymbols(true);
142 assert(0 && "invalid assembler flag!");
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_IndirectSymbol:
192 assert(0 && "Invalid symbol attribute for Mach-O!");
196 SD.setExternal(true);
197 // This effectively clears the undefined lazy bit, in Darwin 'as', although
198 // it isn't very consistent because it implements this as part of symbol
201 // FIXME: Cleanup this code, these bits should be emitted based on semantic
202 // properties, not on the order of definition, etc.
203 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
206 case MCSA_LazyReference:
207 // FIXME: This requires -dynamic.
208 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
209 if (Symbol->isUndefined())
210 SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
213 // Since .reference sets the no dead strip bit, it is equivalent to
214 // .no_dead_strip in practice.
216 case MCSA_NoDeadStrip:
217 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
220 case MCSA_PrivateExtern:
221 SD.setExternal(true);
222 SD.setPrivateExtern(true);
225 case MCSA_WeakReference:
226 // FIXME: This requires -dynamic.
227 if (Symbol->isUndefined())
228 SD.setFlags(SD.getFlags() | SF_WeakReference);
231 case MCSA_WeakDefinition:
232 // FIXME: 'as' enforces that this is defined and global. The manual claims
233 // it has to be in a coalesced section, but this isn't enforced.
234 SD.setFlags(SD.getFlags() | SF_WeakDefinition);
237 case MCSA_WeakDefAutoPrivate:
238 SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
243 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
244 // Encode the 'desc' value into the lowest implementation defined bits.
245 assert(DescValue == (DescValue & SF_DescFlagsMask) &&
246 "Invalid .desc value!");
247 getAssembler().getOrCreateSymbolData(*Symbol).setFlags(
248 DescValue & SF_DescFlagsMask);
251 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
252 unsigned ByteAlignment) {
253 // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
254 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
256 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
257 SD.setExternal(true);
258 SD.setCommon(Size, ByteAlignment);
261 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
262 unsigned Size, unsigned ByteAlignment) {
263 MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
265 // The symbol may not be present, which only creates the section.
269 // FIXME: Assert that this section has the zerofill type.
271 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
273 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
275 // Emit an align fragment if necessary.
276 if (ByteAlignment != 1)
277 new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
279 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
282 Symbol->setSection(*Section);
284 // Update the maximum alignment on the zero fill section if necessary.
285 if (ByteAlignment > SectData.getAlignment())
286 SectData.setAlignment(ByteAlignment);
289 // This should always be called with the thread local bss section. Like the
290 // .zerofill directive this doesn't actually switch sections on us.
291 void MCMachOStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
292 uint64_t Size, unsigned ByteAlignment) {
293 EmitZerofill(Section, Symbol, Size, ByteAlignment);
297 void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
298 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
300 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
303 void MCMachOStreamer::EmitValue(const MCExpr *Value, unsigned Size,
304 unsigned AddrSpace) {
305 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
307 MCDataFragment *DF = getOrCreateDataFragment();
309 // Avoid fixups when possible.
311 if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
312 // FIXME: Endianness assumption.
313 for (unsigned i = 0; i != Size; ++i)
314 DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
316 DF->addFixup(MCFixup::Create(DF->getContents().size(),
317 AddValueSymbols(Value),
318 MCFixup::getKindForSize(Size)));
319 DF->getContents().resize(DF->getContents().size() + Size, 0);
323 void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
324 int64_t Value, unsigned ValueSize,
325 unsigned MaxBytesToEmit) {
326 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
328 if (MaxBytesToEmit == 0)
329 MaxBytesToEmit = ByteAlignment;
330 new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
331 getCurrentSectionData());
333 // Update the maximum alignment on the current section if necessary.
334 if (ByteAlignment > getCurrentSectionData()->getAlignment())
335 getCurrentSectionData()->setAlignment(ByteAlignment);
338 void MCMachOStreamer::EmitCodeAlignment(unsigned ByteAlignment,
339 unsigned MaxBytesToEmit) {
340 // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
342 if (MaxBytesToEmit == 0)
343 MaxBytesToEmit = ByteAlignment;
344 MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
345 getCurrentSectionData());
346 F->setEmitNops(true);
348 // Update the maximum alignment on the current section if necessary.
349 if (ByteAlignment > getCurrentSectionData()->getAlignment())
350 getCurrentSectionData()->setAlignment(ByteAlignment);
353 void MCMachOStreamer::EmitValueToOffset(const MCExpr *Offset,
354 unsigned char Value) {
355 new MCOrgFragment(*Offset, Value, getCurrentSectionData());
358 void MCMachOStreamer::EmitInstToFragment(const MCInst &Inst) {
359 MCInstFragment *IF = new MCInstFragment(Inst, getCurrentSectionData());
361 // Add the fixups and data.
363 // FIXME: Revisit this design decision when relaxation is done, we may be
364 // able to get away with not storing any extra data in the MCInst.
365 SmallVector<MCFixup, 4> Fixups;
366 SmallString<256> Code;
367 raw_svector_ostream VecOS(Code);
368 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
371 IF->getCode() = Code;
372 IF->getFixups() = Fixups;
375 void MCMachOStreamer::EmitInstToData(const MCInst &Inst) {
376 MCDataFragment *DF = getOrCreateDataFragment();
378 SmallVector<MCFixup, 4> Fixups;
379 SmallString<256> Code;
380 raw_svector_ostream VecOS(Code);
381 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
384 // Add the fixups and data.
385 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
386 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
387 DF->addFixup(Fixups[i]);
389 DF->getContents().append(Code.begin(), Code.end());
392 void MCMachOStreamer::EmitInstruction(const MCInst &Inst) {
394 for (unsigned i = Inst.getNumOperands(); i--; )
395 if (Inst.getOperand(i).isExpr())
396 AddValueSymbols(Inst.getOperand(i).getExpr());
398 getCurrentSectionData()->setHasInstructions(true);
400 // If this instruction doesn't need relaxation, just emit it as data.
401 if (!getAssembler().getBackend().MayNeedRelaxation(Inst)) {
402 EmitInstToData(Inst);
406 // Otherwise, if we are relaxing everything, relax the instruction as much as
407 // possible and emit it as data.
408 if (getAssembler().getRelaxAll()) {
410 getAssembler().getBackend().RelaxInstruction(Inst, Relaxed);
411 while (getAssembler().getBackend().MayNeedRelaxation(Relaxed))
412 getAssembler().getBackend().RelaxInstruction(Relaxed, Relaxed);
413 EmitInstToData(Relaxed);
417 // Otherwise emit to a separate fragment.
418 EmitInstToFragment(Inst);
421 void MCMachOStreamer::Finish() {
422 // We have to set the fragment atom associations so we can relax properly for
425 // First, scan the symbol table to build a lookup table from fragments to
427 DenseMap<const MCFragment*, MCSymbolData*> DefiningSymbolMap;
428 for (MCAssembler::symbol_iterator it = getAssembler().symbol_begin(),
429 ie = getAssembler().symbol_end(); it != ie; ++it) {
430 if (getAssembler().isSymbolLinkerVisible(it->getSymbol()) &&
432 // An atom defining symbol should never be internal to a fragment.
433 assert(it->getOffset() == 0 && "Invalid offset in atom defining symbol!");
434 DefiningSymbolMap[it->getFragment()] = it;
438 // Set the fragment atom associations by tracking the last seen atom defining
440 for (MCAssembler::iterator it = getAssembler().begin(),
441 ie = getAssembler().end(); it != ie; ++it) {
442 MCSymbolData *CurrentAtom = 0;
443 for (MCSectionData::iterator it2 = it->begin(),
444 ie2 = it->end(); it2 != ie2; ++it2) {
445 if (MCSymbolData *SD = DefiningSymbolMap.lookup(it2))
447 it2->setAtom(CurrentAtom);
451 this->MCObjectStreamer::Finish();
454 MCStreamer *llvm::createMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
455 raw_ostream &OS, MCCodeEmitter *CE,
457 MCMachOStreamer *S = new MCMachOStreamer(Context, TAB, OS, CE);
459 S->getAssembler().setRelaxAll(true);