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 {
32 MCSectionData *CurSectionData;
34 /// Track the current atom for each section.
35 DenseMap<const MCSectionData*, MCSymbolData*> CurrentAtomMap;
38 MCFragment *getCurrentFragment() const {
39 assert(CurSectionData && "No current section!");
41 if (!CurSectionData->empty())
42 return &CurSectionData->getFragmentList().back();
47 /// Get a data fragment to write into, creating a new one if the current
48 /// fragment is not a data fragment.
49 MCDataFragment *getOrCreateDataFragment() const {
50 MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
52 F = createDataFragment();
56 /// Create a new data fragment in the current section.
57 MCDataFragment *createDataFragment() const {
58 MCDataFragment *DF = new MCDataFragment(CurSectionData);
59 DF->setAtom(CurrentAtomMap.lookup(CurSectionData));
63 void EmitInstToFragment(const MCInst &Inst);
64 void EmitInstToData(const MCInst &Inst);
67 MCMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
68 raw_ostream &OS, MCCodeEmitter *Emitter)
69 : MCObjectStreamer(Context, TAB, OS, Emitter), CurSectionData(0) {}
71 const MCExpr *AddValueSymbols(const MCExpr *Value) {
72 switch (Value->getKind()) {
73 case MCExpr::Target: assert(0 && "Can't handle target exprs yet!");
74 case MCExpr::Constant:
77 case MCExpr::Binary: {
78 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
79 AddValueSymbols(BE->getLHS());
80 AddValueSymbols(BE->getRHS());
84 case MCExpr::SymbolRef:
85 getAssembler().getOrCreateSymbolData(
86 cast<MCSymbolRefExpr>(Value)->getSymbol());
90 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
97 /// @name MCStreamer Interface
100 virtual void SwitchSection(const MCSection *Section);
101 virtual void EmitLabel(MCSymbol *Symbol);
102 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
103 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
104 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
105 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
106 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
107 unsigned ByteAlignment);
108 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
109 assert(0 && "macho doesn't support this directive");
111 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
112 assert(0 && "macho doesn't support this directive");
114 virtual void EmitCOFFSymbolType(int Type) {
115 assert(0 && "macho doesn't support this directive");
117 virtual void EndCOFFSymbolDef() {
118 assert(0 && "macho doesn't support this directive");
120 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
121 assert(0 && "macho doesn't support this directive");
123 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
124 assert(0 && "macho doesn't support this directive");
126 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
127 unsigned Size = 0, unsigned ByteAlignment = 0);
128 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
129 uint64_t Size, unsigned ByteAlignment = 0);
130 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
131 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
132 virtual void EmitGPRel32Value(const MCExpr *Value) {
133 assert(0 && "macho doesn't support this directive");
135 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
136 unsigned ValueSize = 1,
137 unsigned MaxBytesToEmit = 0);
138 virtual void EmitCodeAlignment(unsigned ByteAlignment,
139 unsigned MaxBytesToEmit = 0);
140 virtual void EmitValueToOffset(const MCExpr *Offset,
141 unsigned char Value = 0);
143 virtual void EmitFileDirective(StringRef Filename) {
144 report_fatal_error("unsupported directive: '.file'");
146 virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
147 report_fatal_error("unsupported directive: '.file'");
150 virtual void EmitInstruction(const MCInst &Inst);
151 virtual void Finish();
156 } // end anonymous namespace.
158 void MCMachOStreamer::SwitchSection(const MCSection *Section) {
159 assert(Section && "Cannot switch to a null section!");
161 // If already in this section, then this is a noop.
162 if (Section == CurSection) return;
164 CurSection = Section;
165 CurSectionData = &getAssembler().getOrCreateSectionData(*Section);
168 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
169 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
170 assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
171 assert(CurSection && "Cannot emit before setting section!");
173 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
175 // Update the current atom map, if necessary.
176 bool MustCreateFragment = false;
177 if (getAssembler().isSymbolLinkerVisible(&SD)) {
178 CurrentAtomMap[CurSectionData] = &SD;
180 // We have to create a new fragment, fragments cannot span atoms.
181 MustCreateFragment = true;
184 // FIXME: This is wasteful, we don't necessarily need to create a data
185 // fragment. Instead, we should mark the symbol as pointing into the data
186 // fragment if it exists, otherwise we should just queue the label and set its
187 // fragment pointer when we emit the next fragment.
189 MustCreateFragment ? createDataFragment() : getOrCreateDataFragment();
190 assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
192 SD.setOffset(F->getContents().size());
194 // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
195 // to clear the weak reference and weak definition bits too, but the
196 // implementation was buggy. For now we just try to match 'as', for
199 // FIXME: Cleanup this code, these bits should be emitted based on semantic
200 // properties, not on the order of definition, etc.
201 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
203 Symbol->setSection(*CurSection);
206 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
208 case MCAF_SubsectionsViaSymbols:
209 getAssembler().setSubsectionsViaSymbols(true);
213 assert(0 && "invalid assembler flag!");
216 void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
217 // FIXME: Lift context changes into super class.
218 getAssembler().getOrCreateSymbolData(*Symbol);
219 Symbol->setVariableValue(AddValueSymbols(Value));
222 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
223 MCSymbolAttr Attribute) {
224 // Indirect symbols are handled differently, to match how 'as' handles
225 // them. This makes writing matching .o files easier.
226 if (Attribute == MCSA_IndirectSymbol) {
227 // Note that we intentionally cannot use the symbol data here; this is
228 // important for matching the string table that 'as' generates.
229 IndirectSymbolData ISD;
231 ISD.SectionData = CurSectionData;
232 getAssembler().getIndirectSymbols().push_back(ISD);
236 // Adding a symbol attribute always introduces the symbol, note that an
237 // important side effect of calling getOrCreateSymbolData here is to register
238 // the symbol with the assembler.
239 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
241 // The implementation of symbol attributes is designed to match 'as', but it
242 // leaves much to desired. It doesn't really make sense to arbitrarily add and
243 // remove flags, but 'as' allows this (in particular, see .desc).
245 // In the future it might be worth trying to make these operations more well
249 case MCSA_ELF_TypeFunction:
250 case MCSA_ELF_TypeIndFunction:
251 case MCSA_ELF_TypeObject:
252 case MCSA_ELF_TypeTLS:
253 case MCSA_ELF_TypeCommon:
254 case MCSA_ELF_TypeNoType:
255 case MCSA_IndirectSymbol:
261 assert(0 && "Invalid symbol attribute for Mach-O!");
265 SD.setExternal(true);
266 // This effectively clears the undefined lazy bit, in Darwin 'as', although
267 // it isn't very consistent because it implements this as part of symbol
270 // FIXME: Cleanup this code, these bits should be emitted based on semantic
271 // properties, not on the order of definition, etc.
272 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
275 case MCSA_LazyReference:
276 // FIXME: This requires -dynamic.
277 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
278 if (Symbol->isUndefined())
279 SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
282 // Since .reference sets the no dead strip bit, it is equivalent to
283 // .no_dead_strip in practice.
285 case MCSA_NoDeadStrip:
286 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
289 case MCSA_PrivateExtern:
290 SD.setExternal(true);
291 SD.setPrivateExtern(true);
294 case MCSA_WeakReference:
295 // FIXME: This requires -dynamic.
296 if (Symbol->isUndefined())
297 SD.setFlags(SD.getFlags() | SF_WeakReference);
300 case MCSA_WeakDefinition:
301 // FIXME: 'as' enforces that this is defined and global. The manual claims
302 // it has to be in a coalesced section, but this isn't enforced.
303 SD.setFlags(SD.getFlags() | SF_WeakDefinition);
308 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
309 // Encode the 'desc' value into the lowest implementation defined bits.
310 assert(DescValue == (DescValue & SF_DescFlagsMask) &&
311 "Invalid .desc value!");
312 getAssembler().getOrCreateSymbolData(*Symbol).setFlags(
313 DescValue & SF_DescFlagsMask);
316 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
317 unsigned ByteAlignment) {
318 // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
319 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
321 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
322 SD.setExternal(true);
323 SD.setCommon(Size, ByteAlignment);
326 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
327 unsigned Size, unsigned ByteAlignment) {
328 MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
330 // The symbol may not be present, which only creates the section.
334 // FIXME: Assert that this section has the zerofill type.
336 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
338 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
340 // Emit an align fragment if necessary.
341 if (ByteAlignment != 1)
342 new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
344 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
346 if (getAssembler().isSymbolLinkerVisible(&SD))
349 Symbol->setSection(*Section);
351 // Update the maximum alignment on the zero fill section if necessary.
352 if (ByteAlignment > SectData.getAlignment())
353 SectData.setAlignment(ByteAlignment);
356 // This should always be called with the thread local bss section. Like the
357 // .zerofill directive this doesn't actually switch sections on us.
358 void MCMachOStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
359 uint64_t Size, unsigned ByteAlignment) {
360 EmitZerofill(Section, Symbol, Size, ByteAlignment);
364 void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
365 getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
368 void MCMachOStreamer::EmitValue(const MCExpr *Value, unsigned Size,
369 unsigned AddrSpace) {
370 MCDataFragment *DF = getOrCreateDataFragment();
372 // Avoid fixups when possible.
374 if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
375 // FIXME: Endianness assumption.
376 for (unsigned i = 0; i != Size; ++i)
377 DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
379 DF->addFixup(MCFixup::Create(DF->getContents().size(),
380 AddValueSymbols(Value),
381 MCFixup::getKindForSize(Size)));
382 DF->getContents().resize(DF->getContents().size() + Size, 0);
386 void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
387 int64_t Value, unsigned ValueSize,
388 unsigned MaxBytesToEmit) {
389 if (MaxBytesToEmit == 0)
390 MaxBytesToEmit = ByteAlignment;
391 MCFragment *F = new MCAlignFragment(ByteAlignment, Value, ValueSize,
392 MaxBytesToEmit, CurSectionData);
393 F->setAtom(CurrentAtomMap.lookup(CurSectionData));
395 // Update the maximum alignment on the current section if necessary.
396 if (ByteAlignment > CurSectionData->getAlignment())
397 CurSectionData->setAlignment(ByteAlignment);
400 void MCMachOStreamer::EmitCodeAlignment(unsigned ByteAlignment,
401 unsigned MaxBytesToEmit) {
402 if (MaxBytesToEmit == 0)
403 MaxBytesToEmit = ByteAlignment;
404 MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
406 F->setEmitNops(true);
407 F->setAtom(CurrentAtomMap.lookup(CurSectionData));
409 // Update the maximum alignment on the current section if necessary.
410 if (ByteAlignment > CurSectionData->getAlignment())
411 CurSectionData->setAlignment(ByteAlignment);
414 void MCMachOStreamer::EmitValueToOffset(const MCExpr *Offset,
415 unsigned char Value) {
416 MCFragment *F = new MCOrgFragment(*Offset, Value, CurSectionData);
417 F->setAtom(CurrentAtomMap.lookup(CurSectionData));
420 void MCMachOStreamer::EmitInstToFragment(const MCInst &Inst) {
421 MCInstFragment *IF = new MCInstFragment(Inst, CurSectionData);
422 IF->setAtom(CurrentAtomMap.lookup(CurSectionData));
424 // Add the fixups and data.
426 // FIXME: Revisit this design decision when relaxation is done, we may be
427 // able to get away with not storing any extra data in the MCInst.
428 SmallVector<MCFixup, 4> Fixups;
429 SmallString<256> Code;
430 raw_svector_ostream VecOS(Code);
431 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
434 IF->getCode() = Code;
435 IF->getFixups() = Fixups;
438 void MCMachOStreamer::EmitInstToData(const MCInst &Inst) {
439 MCDataFragment *DF = getOrCreateDataFragment();
441 SmallVector<MCFixup, 4> Fixups;
442 SmallString<256> Code;
443 raw_svector_ostream VecOS(Code);
444 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
447 // Add the fixups and data.
448 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
449 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
450 DF->addFixup(Fixups[i]);
452 DF->getContents().append(Code.begin(), Code.end());
455 void MCMachOStreamer::EmitInstruction(const MCInst &Inst) {
457 for (unsigned i = Inst.getNumOperands(); i--; )
458 if (Inst.getOperand(i).isExpr())
459 AddValueSymbols(Inst.getOperand(i).getExpr());
461 CurSectionData->setHasInstructions(true);
463 // If this instruction doesn't need relaxation, just emit it as data.
464 if (!getAssembler().getBackend().MayNeedRelaxation(Inst)) {
465 EmitInstToData(Inst);
469 // Otherwise, if we are relaxing everything, relax the instruction as much as
470 // possible and emit it as data.
471 if (getAssembler().getRelaxAll()) {
473 getAssembler().getBackend().RelaxInstruction(Inst, Relaxed);
474 while (getAssembler().getBackend().MayNeedRelaxation(Relaxed))
475 getAssembler().getBackend().RelaxInstruction(Relaxed, Relaxed);
476 EmitInstToData(Relaxed);
480 // Otherwise emit to a separate fragment.
481 EmitInstToFragment(Inst);
484 void MCMachOStreamer::Finish() {
485 getAssembler().Finish();
488 MCStreamer *llvm::createMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
489 raw_ostream &OS, MCCodeEmitter *CE,
491 MCMachOStreamer *S = new MCMachOStreamer(Context, TAB, OS, CE);
493 S->getAssembler().setRelaxAll(true);