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 /// Track the current atom for each section.
32 DenseMap<const MCSectionData*, MCSymbolData*> CurrentAtomMap;
35 MCFragment *getCurrentFragment() const {
36 assert(getCurrentSectionData() && "No current section!");
38 if (!getCurrentSectionData()->empty())
39 return &getCurrentSectionData()->getFragmentList().back();
44 /// Get a data fragment to write into, creating a new one if the current
45 /// fragment is not a data fragment.
46 MCDataFragment *getOrCreateDataFragment() const {
47 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
49 F = createDataFragment();
53 /// Create a new data fragment in the current section.
54 MCDataFragment *createDataFragment() const {
55 MCDataFragment *DF = new MCDataFragment(getCurrentSectionData());
56 DF->setAtom(CurrentAtomMap.lookup(getCurrentSectionData()));
60 void EmitInstToFragment(const MCInst &Inst);
61 void EmitInstToData(const MCInst &Inst);
64 MCMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
65 raw_ostream &OS, MCCodeEmitter *Emitter)
66 : MCObjectStreamer(Context, TAB, OS, Emitter) {}
68 const MCExpr *AddValueSymbols(const MCExpr *Value) {
69 switch (Value->getKind()) {
70 case MCExpr::Target: assert(0 && "Can't handle target exprs yet!");
71 case MCExpr::Constant:
74 case MCExpr::Binary: {
75 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
76 AddValueSymbols(BE->getLHS());
77 AddValueSymbols(BE->getRHS());
81 case MCExpr::SymbolRef:
82 getAssembler().getOrCreateSymbolData(
83 cast<MCSymbolRefExpr>(Value)->getSymbol());
87 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
94 /// @name MCStreamer Interface
97 virtual void EmitLabel(MCSymbol *Symbol);
98 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
99 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
100 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
101 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
102 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
103 unsigned ByteAlignment);
104 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
105 assert(0 && "macho doesn't support this directive");
107 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
108 assert(0 && "macho doesn't support this directive");
110 virtual void EmitCOFFSymbolType(int Type) {
111 assert(0 && "macho doesn't support this directive");
113 virtual void EndCOFFSymbolDef() {
114 assert(0 && "macho doesn't support this directive");
116 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
117 assert(0 && "macho doesn't support this directive");
119 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
120 assert(0 && "macho doesn't support this directive");
122 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
123 unsigned Size = 0, unsigned ByteAlignment = 0);
124 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
125 uint64_t Size, unsigned ByteAlignment = 0);
126 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
127 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
128 virtual void EmitGPRel32Value(const MCExpr *Value) {
129 assert(0 && "macho doesn't support this directive");
131 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
132 unsigned ValueSize = 1,
133 unsigned MaxBytesToEmit = 0);
134 virtual void EmitCodeAlignment(unsigned ByteAlignment,
135 unsigned MaxBytesToEmit = 0);
136 virtual void EmitValueToOffset(const MCExpr *Offset,
137 unsigned char Value = 0);
139 virtual void EmitFileDirective(StringRef Filename) {
140 report_fatal_error("unsupported directive: '.file'");
142 virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
143 report_fatal_error("unsupported directive: '.file'");
146 virtual void EmitInstruction(const MCInst &Inst);
151 } // end anonymous namespace.
153 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
154 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
155 assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
156 assert(CurSection && "Cannot emit before setting section!");
158 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
160 // Update the current atom map, if necessary.
161 bool MustCreateFragment = false;
162 if (getAssembler().isSymbolLinkerVisible(&SD)) {
163 CurrentAtomMap[getCurrentSectionData()] = &SD;
165 // We have to create a new fragment, fragments cannot span atoms.
166 MustCreateFragment = true;
169 // FIXME: This is wasteful, we don't necessarily need to create a data
170 // fragment. Instead, we should mark the symbol as pointing into the data
171 // fragment if it exists, otherwise we should just queue the label and set its
172 // fragment pointer when we emit the next fragment.
174 MustCreateFragment ? createDataFragment() : getOrCreateDataFragment();
175 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
177 SD.setOffset(F->getContents().size());
179 // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
180 // to clear the weak reference and weak definition bits too, but the
181 // implementation was buggy. For now we just try to match 'as', for
184 // FIXME: Cleanup this code, these bits should be emitted based on semantic
185 // properties, not on the order of definition, etc.
186 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
188 Symbol->setSection(*CurSection);
191 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
193 case MCAF_SubsectionsViaSymbols:
194 getAssembler().setSubsectionsViaSymbols(true);
198 assert(0 && "invalid assembler flag!");
201 void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
202 // FIXME: Lift context changes into super class.
203 getAssembler().getOrCreateSymbolData(*Symbol);
204 Symbol->setVariableValue(AddValueSymbols(Value));
207 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
208 MCSymbolAttr Attribute) {
209 // Indirect symbols are handled differently, to match how 'as' handles
210 // them. This makes writing matching .o files easier.
211 if (Attribute == MCSA_IndirectSymbol) {
212 // Note that we intentionally cannot use the symbol data here; this is
213 // important for matching the string table that 'as' generates.
214 IndirectSymbolData ISD;
216 ISD.SectionData = getCurrentSectionData();
217 getAssembler().getIndirectSymbols().push_back(ISD);
221 // Adding a symbol attribute always introduces the symbol, note that an
222 // important side effect of calling getOrCreateSymbolData here is to register
223 // the symbol with the assembler.
224 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
226 // The implementation of symbol attributes is designed to match 'as', but it
227 // leaves much to desired. It doesn't really make sense to arbitrarily add and
228 // remove flags, but 'as' allows this (in particular, see .desc).
230 // In the future it might be worth trying to make these operations more well
234 case MCSA_ELF_TypeFunction:
235 case MCSA_ELF_TypeIndFunction:
236 case MCSA_ELF_TypeObject:
237 case MCSA_ELF_TypeTLS:
238 case MCSA_ELF_TypeCommon:
239 case MCSA_ELF_TypeNoType:
240 case MCSA_IndirectSymbol:
246 assert(0 && "Invalid symbol attribute for Mach-O!");
250 SD.setExternal(true);
251 // This effectively clears the undefined lazy bit, in Darwin 'as', although
252 // it isn't very consistent because it implements this as part of symbol
255 // FIXME: Cleanup this code, these bits should be emitted based on semantic
256 // properties, not on the order of definition, etc.
257 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
260 case MCSA_LazyReference:
261 // FIXME: This requires -dynamic.
262 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
263 if (Symbol->isUndefined())
264 SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
267 // Since .reference sets the no dead strip bit, it is equivalent to
268 // .no_dead_strip in practice.
270 case MCSA_NoDeadStrip:
271 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
274 case MCSA_PrivateExtern:
275 SD.setExternal(true);
276 SD.setPrivateExtern(true);
279 case MCSA_WeakReference:
280 // FIXME: This requires -dynamic.
281 if (Symbol->isUndefined())
282 SD.setFlags(SD.getFlags() | SF_WeakReference);
285 case MCSA_WeakDefinition:
286 // FIXME: 'as' enforces that this is defined and global. The manual claims
287 // it has to be in a coalesced section, but this isn't enforced.
288 SD.setFlags(SD.getFlags() | SF_WeakDefinition);
293 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
294 // Encode the 'desc' value into the lowest implementation defined bits.
295 assert(DescValue == (DescValue & SF_DescFlagsMask) &&
296 "Invalid .desc value!");
297 getAssembler().getOrCreateSymbolData(*Symbol).setFlags(
298 DescValue & SF_DescFlagsMask);
301 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
302 unsigned ByteAlignment) {
303 // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
304 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
306 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
307 SD.setExternal(true);
308 SD.setCommon(Size, ByteAlignment);
311 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
312 unsigned Size, unsigned ByteAlignment) {
313 MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
315 // The symbol may not be present, which only creates the section.
319 // FIXME: Assert that this section has the zerofill type.
321 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
323 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
325 // Emit an align fragment if necessary.
326 if (ByteAlignment != 1)
327 new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
329 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
331 if (getAssembler().isSymbolLinkerVisible(&SD))
334 Symbol->setSection(*Section);
336 // Update the maximum alignment on the zero fill section if necessary.
337 if (ByteAlignment > SectData.getAlignment())
338 SectData.setAlignment(ByteAlignment);
341 // This should always be called with the thread local bss section. Like the
342 // .zerofill directive this doesn't actually switch sections on us.
343 void MCMachOStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
344 uint64_t Size, unsigned ByteAlignment) {
345 EmitZerofill(Section, Symbol, Size, ByteAlignment);
349 void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
350 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
353 void MCMachOStreamer::EmitValue(const MCExpr *Value, unsigned Size,
354 unsigned AddrSpace) {
355 MCDataFragment *DF = getOrCreateDataFragment();
357 // Avoid fixups when possible.
359 if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
360 // FIXME: Endianness assumption.
361 for (unsigned i = 0; i != Size; ++i)
362 DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
364 DF->addFixup(MCFixup::Create(DF->getContents().size(),
365 AddValueSymbols(Value),
366 MCFixup::getKindForSize(Size)));
367 DF->getContents().resize(DF->getContents().size() + Size, 0);
371 void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
372 int64_t Value, unsigned ValueSize,
373 unsigned MaxBytesToEmit) {
374 if (MaxBytesToEmit == 0)
375 MaxBytesToEmit = ByteAlignment;
376 MCFragment *F = new MCAlignFragment(ByteAlignment, Value, ValueSize,
377 MaxBytesToEmit, getCurrentSectionData());
378 F->setAtom(CurrentAtomMap.lookup(getCurrentSectionData()));
380 // Update the maximum alignment on the current section if necessary.
381 if (ByteAlignment > getCurrentSectionData()->getAlignment())
382 getCurrentSectionData()->setAlignment(ByteAlignment);
385 void MCMachOStreamer::EmitCodeAlignment(unsigned ByteAlignment,
386 unsigned MaxBytesToEmit) {
387 if (MaxBytesToEmit == 0)
388 MaxBytesToEmit = ByteAlignment;
389 MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
390 getCurrentSectionData());
391 F->setEmitNops(true);
392 F->setAtom(CurrentAtomMap.lookup(getCurrentSectionData()));
394 // Update the maximum alignment on the current section if necessary.
395 if (ByteAlignment > getCurrentSectionData()->getAlignment())
396 getCurrentSectionData()->setAlignment(ByteAlignment);
399 void MCMachOStreamer::EmitValueToOffset(const MCExpr *Offset,
400 unsigned char Value) {
401 MCFragment *F = new MCOrgFragment(*Offset, Value, getCurrentSectionData());
402 F->setAtom(CurrentAtomMap.lookup(getCurrentSectionData()));
405 void MCMachOStreamer::EmitInstToFragment(const MCInst &Inst) {
406 MCInstFragment *IF = new MCInstFragment(Inst, getCurrentSectionData());
407 IF->setAtom(CurrentAtomMap.lookup(getCurrentSectionData()));
409 // Add the fixups and data.
411 // FIXME: Revisit this design decision when relaxation is done, we may be
412 // able to get away with not storing any extra data in the MCInst.
413 SmallVector<MCFixup, 4> Fixups;
414 SmallString<256> Code;
415 raw_svector_ostream VecOS(Code);
416 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
419 IF->getCode() = Code;
420 IF->getFixups() = Fixups;
423 void MCMachOStreamer::EmitInstToData(const MCInst &Inst) {
424 MCDataFragment *DF = getOrCreateDataFragment();
426 SmallVector<MCFixup, 4> Fixups;
427 SmallString<256> Code;
428 raw_svector_ostream VecOS(Code);
429 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
432 // Add the fixups and data.
433 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
434 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
435 DF->addFixup(Fixups[i]);
437 DF->getContents().append(Code.begin(), Code.end());
440 void MCMachOStreamer::EmitInstruction(const MCInst &Inst) {
442 for (unsigned i = Inst.getNumOperands(); i--; )
443 if (Inst.getOperand(i).isExpr())
444 AddValueSymbols(Inst.getOperand(i).getExpr());
446 getCurrentSectionData()->setHasInstructions(true);
448 // If this instruction doesn't need relaxation, just emit it as data.
449 if (!getAssembler().getBackend().MayNeedRelaxation(Inst)) {
450 EmitInstToData(Inst);
454 // Otherwise, if we are relaxing everything, relax the instruction as much as
455 // possible and emit it as data.
456 if (getAssembler().getRelaxAll()) {
458 getAssembler().getBackend().RelaxInstruction(Inst, Relaxed);
459 while (getAssembler().getBackend().MayNeedRelaxation(Relaxed))
460 getAssembler().getBackend().RelaxInstruction(Relaxed, Relaxed);
461 EmitInstToData(Relaxed);
465 // Otherwise emit to a separate fragment.
466 EmitInstToFragment(Inst);
469 MCStreamer *llvm::createMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
470 raw_ostream &OS, MCCodeEmitter *CE,
472 MCMachOStreamer *S = new MCMachOStreamer(Context, TAB, OS, CE);
474 S->getAssembler().setRelaxAll(true);