1 //===-- MCMachOStreamer.cpp - MachO Streamer ------------------------------===//
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"
11 #include "llvm/MC/MCAsmBackend.h"
12 #include "llvm/MC/MCAssembler.h"
13 #include "llvm/MC/MCCodeEmitter.h"
14 #include "llvm/MC/MCContext.h"
15 #include "llvm/MC/MCDwarf.h"
16 #include "llvm/MC/MCExpr.h"
17 #include "llvm/MC/MCInst.h"
18 #include "llvm/MC/MCMachOSymbolFlags.h"
19 #include "llvm/MC/MCObjectStreamer.h"
20 #include "llvm/MC/MCSection.h"
21 #include "llvm/MC/MCSectionMachO.h"
22 #include "llvm/MC/MCSymbol.h"
23 #include "llvm/Support/Dwarf.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
31 class MCMachOStreamer : public MCObjectStreamer {
33 virtual void EmitInstToData(const MCInst &Inst);
35 void EmitDataRegion(DataRegionData::KindTy Kind);
36 void EmitDataRegionEnd();
38 MCMachOStreamer(MCContext &Context, MCAsmBackend &MAB, raw_ostream &OS,
39 MCCodeEmitter *Emitter)
40 : MCObjectStreamer(SK_MachOStreamer, Context, MAB, OS, Emitter) {}
42 /// @name MCStreamer Interface
45 virtual void InitSections();
46 virtual void InitToTextSection();
47 virtual void EmitLabel(MCSymbol *Symbol);
48 virtual void EmitDebugLabel(MCSymbol *Symbol);
49 virtual void EmitEHSymAttributes(const MCSymbol *Symbol,
51 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
52 virtual void EmitLinkerOptions(ArrayRef<std::string> Options);
53 virtual void EmitDataRegion(MCDataRegionType Kind);
54 virtual void EmitThumbFunc(MCSymbol *Func);
55 virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
56 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
57 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
58 unsigned ByteAlignment);
59 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
60 llvm_unreachable("macho doesn't support this directive");
62 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
63 llvm_unreachable("macho doesn't support this directive");
65 virtual void EmitCOFFSymbolType(int Type) {
66 llvm_unreachable("macho doesn't support this directive");
68 virtual void EndCOFFSymbolDef() {
69 llvm_unreachable("macho doesn't support this directive");
71 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
72 llvm_unreachable("macho doesn't support this directive");
74 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
75 unsigned ByteAlignment);
76 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
77 uint64_t Size = 0, unsigned ByteAlignment = 0);
78 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
79 uint64_t Size, unsigned ByteAlignment = 0);
81 virtual void EmitFileDirective(StringRef Filename) {
82 // FIXME: Just ignore the .file; it isn't important enough to fail the
85 //report_fatal_error("unsupported directive: '.file'");
88 virtual void FinishImpl();
92 static bool classof(const MCStreamer *S) {
93 return S->getKind() == SK_MachOStreamer;
97 } // end anonymous namespace.
99 void MCMachOStreamer::InitSections() {
103 void MCMachOStreamer::InitToTextSection() {
104 SwitchSection(getContext().getMachOSection(
106 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS, 0,
107 SectionKind::getText()));
110 void MCMachOStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
111 MCSymbol *EHSymbol) {
113 getAssembler().getOrCreateSymbolData(*Symbol);
115 EmitSymbolAttribute(EHSymbol, MCSA_Global);
116 if (SD.getFlags() & SF_WeakDefinition)
117 EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
118 if (SD.isPrivateExtern())
119 EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
122 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
123 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
125 // isSymbolLinkerVisible uses the section.
126 AssignSection(Symbol, getCurrentSection().first);
127 // We have to create a new fragment if this is an atom defining symbol,
128 // fragments cannot span atoms.
129 if (getAssembler().isSymbolLinkerVisible(*Symbol))
130 insert(new MCDataFragment());
132 MCObjectStreamer::EmitLabel(Symbol);
134 MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
135 // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
136 // to clear the weak reference and weak definition bits too, but the
137 // implementation was buggy. For now we just try to match 'as', for
140 // FIXME: Cleanup this code, these bits should be emitted based on semantic
141 // properties, not on the order of definition, etc.
142 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
145 void MCMachOStreamer::EmitDebugLabel(MCSymbol *Symbol) {
148 void MCMachOStreamer::EmitDataRegion(DataRegionData::KindTy Kind) {
149 if (!getAssembler().getBackend().hasDataInCodeSupport())
151 // Create a temporary label to mark the start of the data region.
152 MCSymbol *Start = getContext().CreateTempSymbol();
154 // Record the region for the object writer to use.
155 DataRegionData Data = { Kind, Start, NULL };
156 std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
157 Regions.push_back(Data);
160 void MCMachOStreamer::EmitDataRegionEnd() {
161 if (!getAssembler().getBackend().hasDataInCodeSupport())
163 std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
164 assert(Regions.size() && "Mismatched .end_data_region!");
165 DataRegionData &Data = Regions.back();
166 assert(Data.End == NULL && "Mismatched .end_data_region!");
167 // Create a temporary label to mark the end of the data region.
168 Data.End = getContext().CreateTempSymbol();
172 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
173 // Let the target do whatever target specific stuff it needs to do.
174 getAssembler().getBackend().handleAssemblerFlag(Flag);
175 // Do any generic stuff we need to do.
177 case MCAF_SyntaxUnified: return; // no-op here.
178 case MCAF_Code16: return; // Change parsing mode; no-op here.
179 case MCAF_Code32: return; // Change parsing mode; no-op here.
180 case MCAF_Code64: return; // Change parsing mode; no-op here.
181 case MCAF_SubsectionsViaSymbols:
182 getAssembler().setSubsectionsViaSymbols(true);
187 void MCMachOStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
188 getAssembler().getLinkerOptions().push_back(Options);
191 void MCMachOStreamer::EmitDataRegion(MCDataRegionType Kind) {
193 case MCDR_DataRegion:
194 EmitDataRegion(DataRegionData::Data);
196 case MCDR_DataRegionJT8:
197 EmitDataRegion(DataRegionData::JumpTable8);
199 case MCDR_DataRegionJT16:
200 EmitDataRegion(DataRegionData::JumpTable16);
202 case MCDR_DataRegionJT32:
203 EmitDataRegion(DataRegionData::JumpTable32);
205 case MCDR_DataRegionEnd:
211 void MCMachOStreamer::EmitThumbFunc(MCSymbol *Symbol) {
212 // Remember that the function is a thumb function. Fixup and relocation
213 // values will need adjusted.
214 getAssembler().setIsThumbFunc(Symbol);
216 // Mark the thumb bit on the symbol.
217 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
218 SD.setFlags(SD.getFlags() | SF_ThumbFunc);
221 bool MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
222 MCSymbolAttr Attribute) {
223 // Indirect symbols are handled differently, to match how 'as' handles
224 // them. This makes writing matching .o files easier.
225 if (Attribute == MCSA_IndirectSymbol) {
226 // Note that we intentionally cannot use the symbol data here; this is
227 // important for matching the string table that 'as' generates.
228 IndirectSymbolData ISD;
230 ISD.SectionData = getCurrentSectionData();
231 getAssembler().getIndirectSymbols().push_back(ISD);
235 // Adding a symbol attribute always introduces the symbol, note that an
236 // important side effect of calling getOrCreateSymbolData here is to register
237 // the symbol with the assembler.
238 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
240 // The implementation of symbol attributes is designed to match 'as', but it
241 // leaves much to desired. It doesn't really make sense to arbitrarily add and
242 // remove flags, but 'as' allows this (in particular, see .desc).
244 // In the future it might be worth trying to make these operations more well
248 case MCSA_ELF_TypeFunction:
249 case MCSA_ELF_TypeIndFunction:
250 case MCSA_ELF_TypeObject:
251 case MCSA_ELF_TypeTLS:
252 case MCSA_ELF_TypeCommon:
253 case MCSA_ELF_TypeNoType:
254 case MCSA_ELF_TypeGnuUniqueObject:
256 case MCSA_IndirectSymbol:
264 SD.setExternal(true);
265 // This effectively clears the undefined lazy bit, in Darwin 'as', although
266 // it isn't very consistent because it implements this as part of symbol
269 // FIXME: Cleanup this code, these bits should be emitted based on semantic
270 // properties, not on the order of definition, etc.
271 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
274 case MCSA_LazyReference:
275 // FIXME: This requires -dynamic.
276 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
277 if (Symbol->isUndefined())
278 SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
281 // Since .reference sets the no dead strip bit, it is equivalent to
282 // .no_dead_strip in practice.
284 case MCSA_NoDeadStrip:
285 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
288 case MCSA_SymbolResolver:
289 SD.setFlags(SD.getFlags() | SF_SymbolResolver);
292 case MCSA_PrivateExtern:
293 SD.setExternal(true);
294 SD.setPrivateExtern(true);
297 case MCSA_WeakReference:
298 // FIXME: This requires -dynamic.
299 if (Symbol->isUndefined())
300 SD.setFlags(SD.getFlags() | SF_WeakReference);
303 case MCSA_WeakDefinition:
304 // FIXME: 'as' enforces that this is defined and global. The manual claims
305 // it has to be in a coalesced section, but this isn't enforced.
306 SD.setFlags(SD.getFlags() | SF_WeakDefinition);
309 case MCSA_WeakDefAutoPrivate:
310 SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
317 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
318 // Encode the 'desc' value into the lowest implementation defined bits.
319 assert(DescValue == (DescValue & SF_DescFlagsMask) &&
320 "Invalid .desc value!");
321 getAssembler().getOrCreateSymbolData(*Symbol).setFlags(
322 DescValue & SF_DescFlagsMask);
325 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
326 unsigned ByteAlignment) {
327 // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
328 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
330 AssignSection(Symbol, NULL);
332 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
333 SD.setExternal(true);
334 SD.setCommon(Size, ByteAlignment);
337 void MCMachOStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
338 unsigned ByteAlignment) {
339 // '.lcomm' is equivalent to '.zerofill'.
340 return EmitZerofill(getContext().getMachOSection("__DATA", "__bss",
341 MCSectionMachO::S_ZEROFILL,
342 0, SectionKind::getBSS()),
343 Symbol, Size, ByteAlignment);
346 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
347 uint64_t Size, unsigned ByteAlignment) {
348 MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
350 // The symbol may not be present, which only creates the section.
354 // On darwin all virtual sections have zerofill type.
355 assert(Section->isVirtualSection() && "Section does not have zerofill type!");
357 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
359 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
361 // Emit an align fragment if necessary.
362 if (ByteAlignment != 1)
363 new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
365 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
368 AssignSection(Symbol, Section);
370 // Update the maximum alignment on the zero fill section if necessary.
371 if (ByteAlignment > SectData.getAlignment())
372 SectData.setAlignment(ByteAlignment);
375 // This should always be called with the thread local bss section. Like the
376 // .zerofill directive this doesn't actually switch sections on us.
377 void MCMachOStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
378 uint64_t Size, unsigned ByteAlignment) {
379 EmitZerofill(Section, Symbol, Size, ByteAlignment);
383 void MCMachOStreamer::EmitInstToData(const MCInst &Inst) {
384 MCDataFragment *DF = getOrCreateDataFragment();
386 SmallVector<MCFixup, 4> Fixups;
387 SmallString<256> Code;
388 raw_svector_ostream VecOS(Code);
389 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
392 // Add the fixups and data.
393 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
394 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
395 DF->getFixups().push_back(Fixups[i]);
397 DF->getContents().append(Code.begin(), Code.end());
400 void MCMachOStreamer::FinishImpl() {
401 EmitFrames(&getAssembler().getBackend(), true);
403 // We have to set the fragment atom associations so we can relax properly for
406 // First, scan the symbol table to build a lookup table from fragments to
408 DenseMap<const MCFragment*, MCSymbolData*> DefiningSymbolMap;
409 for (MCAssembler::symbol_iterator it = getAssembler().symbol_begin(),
410 ie = getAssembler().symbol_end(); it != ie; ++it) {
411 if (getAssembler().isSymbolLinkerVisible(it->getSymbol()) &&
413 // An atom defining symbol should never be internal to a fragment.
414 assert(it->getOffset() == 0 && "Invalid offset in atom defining symbol!");
415 DefiningSymbolMap[it->getFragment()] = it;
419 // Set the fragment atom associations by tracking the last seen atom defining
421 for (MCAssembler::iterator it = getAssembler().begin(),
422 ie = getAssembler().end(); it != ie; ++it) {
423 MCSymbolData *CurrentAtom = 0;
424 for (MCSectionData::iterator it2 = it->begin(),
425 ie2 = it->end(); it2 != ie2; ++it2) {
426 if (MCSymbolData *SD = DefiningSymbolMap.lookup(it2))
428 it2->setAtom(CurrentAtom);
432 this->MCObjectStreamer::FinishImpl();
435 MCStreamer *llvm::createMachOStreamer(MCContext &Context, MCAsmBackend &MAB,
436 raw_ostream &OS, MCCodeEmitter *CE,
438 MCMachOStreamer *S = new MCMachOStreamer(Context, MAB, OS, CE);
440 S->getAssembler().setRelaxAll(true);