2 // The LLVM Compiler Infrastructure
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===//
9 #include "llvm/MC/MCStreamer.h"
10 #include "llvm/MC/MCAsmBackend.h"
11 #include "llvm/MC/MCAssembler.h"
12 #include "llvm/MC/MCCodeEmitter.h"
13 #include "llvm/MC/MCContext.h"
14 #include "llvm/MC/MCDwarf.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCInst.h"
17 #include "llvm/MC/MCMachOSymbolFlags.h"
18 #include "llvm/MC/MCObjectStreamer.h"
19 #include "llvm/MC/MCSection.h"
20 #include "llvm/MC/MCSectionMachO.h"
21 #include "llvm/MC/MCSymbol.h"
22 #include "llvm/Support/Dwarf.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/raw_ostream.h"
30 class MCMachOStreamer : public MCObjectStreamer {
32 virtual void EmitInstToData(const MCInst &Inst);
34 void EmitDataRegion(DataRegionData::KindTy Kind);
35 void EmitDataRegionEnd();
37 MCMachOStreamer(MCContext &Context, MCAsmBackend &MAB,
38 raw_ostream &OS, MCCodeEmitter *Emitter)
39 : MCObjectStreamer(Context, MAB, OS, Emitter) {}
41 /// @name MCStreamer Interface
44 virtual void InitSections();
45 virtual void InitToTextSection();
46 virtual void EmitLabel(MCSymbol *Symbol);
47 virtual void EmitDebugLabel(MCSymbol *Symbol);
48 virtual void EmitEHSymAttributes(const MCSymbol *Symbol,
50 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
51 virtual void EmitLinkerOptions(ArrayRef<std::string> Options);
52 virtual void EmitDataRegion(MCDataRegionType Kind);
53 virtual void EmitThumbFunc(MCSymbol *Func);
54 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
55 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
56 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
57 unsigned ByteAlignment);
58 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
59 llvm_unreachable("macho doesn't support this directive");
61 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
62 llvm_unreachable("macho doesn't support this directive");
64 virtual void EmitCOFFSymbolType(int Type) {
65 llvm_unreachable("macho doesn't support this directive");
67 virtual void EndCOFFSymbolDef() {
68 llvm_unreachable("macho doesn't support this directive");
70 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
71 llvm_unreachable("macho doesn't support this directive");
73 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
74 unsigned ByteAlignment);
75 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
76 uint64_t Size = 0, unsigned ByteAlignment = 0);
77 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
78 uint64_t Size, unsigned ByteAlignment = 0);
80 virtual void EmitFileDirective(StringRef Filename) {
81 // FIXME: Just ignore the .file; it isn't important enough to fail the
84 //report_fatal_error("unsupported directive: '.file'");
87 virtual void FinishImpl();
92 } // end anonymous namespace.
94 void MCMachOStreamer::InitSections() {
98 void MCMachOStreamer::InitToTextSection() {
99 SwitchSection(getContext().getMachOSection(
101 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS, 0,
102 SectionKind::getText()));
105 void MCMachOStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
106 MCSymbol *EHSymbol) {
108 getAssembler().getOrCreateSymbolData(*Symbol);
110 EmitSymbolAttribute(EHSymbol, MCSA_Global);
111 if (SD.getFlags() & SF_WeakDefinition)
112 EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
113 if (SD.isPrivateExtern())
114 EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
117 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
118 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
120 // isSymbolLinkerVisible uses the section.
121 Symbol->setSection(*getCurrentSection());
122 // We have to create a new fragment if this is an atom defining symbol,
123 // fragments cannot span atoms.
124 if (getAssembler().isSymbolLinkerVisible(*Symbol))
125 new MCDataFragment(getCurrentSectionData());
127 MCObjectStreamer::EmitLabel(Symbol);
129 MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
130 // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
131 // to clear the weak reference and weak definition bits too, but the
132 // implementation was buggy. For now we just try to match 'as', for
135 // FIXME: Cleanup this code, these bits should be emitted based on semantic
136 // properties, not on the order of definition, etc.
137 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
140 void MCMachOStreamer::EmitDebugLabel(MCSymbol *Symbol) {
143 void MCMachOStreamer::EmitDataRegion(DataRegionData::KindTy Kind) {
144 if (!getAssembler().getBackend().hasDataInCodeSupport())
146 // Create a temporary label to mark the start of the data region.
147 MCSymbol *Start = getContext().CreateTempSymbol();
149 // Record the region for the object writer to use.
150 DataRegionData Data = { Kind, Start, NULL };
151 std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
152 Regions.push_back(Data);
155 void MCMachOStreamer::EmitDataRegionEnd() {
156 if (!getAssembler().getBackend().hasDataInCodeSupport())
158 std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
159 assert(Regions.size() && "Mismatched .end_data_region!");
160 DataRegionData &Data = Regions.back();
161 assert(Data.End == NULL && "Mismatched .end_data_region!");
162 // Create a temporary label to mark the end of the data region.
163 Data.End = getContext().CreateTempSymbol();
167 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
168 // Let the target do whatever target specific stuff it needs to do.
169 getAssembler().getBackend().handleAssemblerFlag(Flag);
170 // Do any generic stuff we need to do.
172 case MCAF_SyntaxUnified: return; // no-op here.
173 case MCAF_Code16: return; // Change parsing mode; no-op here.
174 case MCAF_Code32: return; // Change parsing mode; no-op here.
175 case MCAF_Code64: return; // Change parsing mode; no-op here.
176 case MCAF_SubsectionsViaSymbols:
177 getAssembler().setSubsectionsViaSymbols(true);
182 void MCMachOStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
183 getAssembler().getLinkerOptions().push_back(Options);
186 void MCMachOStreamer::EmitDataRegion(MCDataRegionType Kind) {
188 case MCDR_DataRegion:
189 EmitDataRegion(DataRegionData::Data);
191 case MCDR_DataRegionJT8:
192 EmitDataRegion(DataRegionData::JumpTable8);
194 case MCDR_DataRegionJT16:
195 EmitDataRegion(DataRegionData::JumpTable16);
197 case MCDR_DataRegionJT32:
198 EmitDataRegion(DataRegionData::JumpTable32);
200 case MCDR_DataRegionEnd:
206 void MCMachOStreamer::EmitThumbFunc(MCSymbol *Symbol) {
207 // Remember that the function is a thumb function. Fixup and relocation
208 // values will need adjusted.
209 getAssembler().setIsThumbFunc(Symbol);
211 // Mark the thumb bit on the symbol.
212 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
213 SD.setFlags(SD.getFlags() | SF_ThumbFunc);
216 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
217 MCSymbolAttr Attribute) {
218 // Indirect symbols are handled differently, to match how 'as' handles
219 // them. This makes writing matching .o files easier.
220 if (Attribute == MCSA_IndirectSymbol) {
221 // Note that we intentionally cannot use the symbol data here; this is
222 // important for matching the string table that 'as' generates.
223 IndirectSymbolData ISD;
225 ISD.SectionData = getCurrentSectionData();
226 getAssembler().getIndirectSymbols().push_back(ISD);
230 // Adding a symbol attribute always introduces the symbol, note that an
231 // important side effect of calling getOrCreateSymbolData here is to register
232 // the symbol with the assembler.
233 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
235 // The implementation of symbol attributes is designed to match 'as', but it
236 // leaves much to desired. It doesn't really make sense to arbitrarily add and
237 // remove flags, but 'as' allows this (in particular, see .desc).
239 // In the future it might be worth trying to make these operations more well
243 case MCSA_ELF_TypeFunction:
244 case MCSA_ELF_TypeIndFunction:
245 case MCSA_ELF_TypeObject:
246 case MCSA_ELF_TypeTLS:
247 case MCSA_ELF_TypeCommon:
248 case MCSA_ELF_TypeNoType:
249 case MCSA_ELF_TypeGnuUniqueObject:
251 case MCSA_IndirectSymbol:
256 llvm_unreachable("Invalid symbol attribute for Mach-O!");
259 SD.setExternal(true);
260 // This effectively clears the undefined lazy bit, in Darwin 'as', although
261 // it isn't very consistent because it implements this as part of symbol
264 // FIXME: Cleanup this code, these bits should be emitted based on semantic
265 // properties, not on the order of definition, etc.
266 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
269 case MCSA_LazyReference:
270 // FIXME: This requires -dynamic.
271 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
272 if (Symbol->isUndefined())
273 SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
276 // Since .reference sets the no dead strip bit, it is equivalent to
277 // .no_dead_strip in practice.
279 case MCSA_NoDeadStrip:
280 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
283 case MCSA_SymbolResolver:
284 SD.setFlags(SD.getFlags() | SF_SymbolResolver);
287 case MCSA_PrivateExtern:
288 SD.setExternal(true);
289 SD.setPrivateExtern(true);
292 case MCSA_WeakReference:
293 // FIXME: This requires -dynamic.
294 if (Symbol->isUndefined())
295 SD.setFlags(SD.getFlags() | SF_WeakReference);
298 case MCSA_WeakDefinition:
299 // FIXME: 'as' enforces that this is defined and global. The manual claims
300 // it has to be in a coalesced section, but this isn't enforced.
301 SD.setFlags(SD.getFlags() | SF_WeakDefinition);
304 case MCSA_WeakDefAutoPrivate:
305 SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
310 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
311 // Encode the 'desc' value into the lowest implementation defined bits.
312 assert(DescValue == (DescValue & SF_DescFlagsMask) &&
313 "Invalid .desc value!");
314 getAssembler().getOrCreateSymbolData(*Symbol).setFlags(
315 DescValue & SF_DescFlagsMask);
318 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
319 unsigned ByteAlignment) {
320 // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
321 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
323 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
324 SD.setExternal(true);
325 SD.setCommon(Size, ByteAlignment);
328 void MCMachOStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
329 unsigned ByteAlignment) {
330 // '.lcomm' is equivalent to '.zerofill'.
331 return EmitZerofill(getContext().getMachOSection("__DATA", "__bss",
332 MCSectionMachO::S_ZEROFILL,
333 0, SectionKind::getBSS()),
334 Symbol, Size, ByteAlignment);
337 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
338 uint64_t Size, unsigned ByteAlignment) {
339 MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
341 // The symbol may not be present, which only creates the section.
345 // FIXME: Assert that this section has the zerofill type.
347 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
349 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
351 // Emit an align fragment if necessary.
352 if (ByteAlignment != 1)
353 new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
355 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
358 Symbol->setSection(*Section);
360 // Update the maximum alignment on the zero fill section if necessary.
361 if (ByteAlignment > SectData.getAlignment())
362 SectData.setAlignment(ByteAlignment);
365 // This should always be called with the thread local bss section. Like the
366 // .zerofill directive this doesn't actually switch sections on us.
367 void MCMachOStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
368 uint64_t Size, unsigned ByteAlignment) {
369 EmitZerofill(Section, Symbol, Size, ByteAlignment);
373 void MCMachOStreamer::EmitInstToData(const MCInst &Inst) {
374 MCDataFragment *DF = getOrCreateDataFragment();
376 SmallVector<MCFixup, 4> Fixups;
377 SmallString<256> Code;
378 raw_svector_ostream VecOS(Code);
379 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
382 // Add the fixups and data.
383 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
384 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
385 DF->getFixups().push_back(Fixups[i]);
387 DF->getContents().append(Code.begin(), Code.end());
390 void MCMachOStreamer::FinishImpl() {
393 // We have to set the fragment atom associations so we can relax properly for
396 // First, scan the symbol table to build a lookup table from fragments to
398 DenseMap<const MCFragment*, MCSymbolData*> DefiningSymbolMap;
399 for (MCAssembler::symbol_iterator it = getAssembler().symbol_begin(),
400 ie = getAssembler().symbol_end(); it != ie; ++it) {
401 if (getAssembler().isSymbolLinkerVisible(it->getSymbol()) &&
403 // An atom defining symbol should never be internal to a fragment.
404 assert(it->getOffset() == 0 && "Invalid offset in atom defining symbol!");
405 DefiningSymbolMap[it->getFragment()] = it;
409 // Set the fragment atom associations by tracking the last seen atom defining
411 for (MCAssembler::iterator it = getAssembler().begin(),
412 ie = getAssembler().end(); it != ie; ++it) {
413 MCSymbolData *CurrentAtom = 0;
414 for (MCSectionData::iterator it2 = it->begin(),
415 ie2 = it->end(); it2 != ie2; ++it2) {
416 if (MCSymbolData *SD = DefiningSymbolMap.lookup(it2))
418 it2->setAtom(CurrentAtom);
422 this->MCObjectStreamer::FinishImpl();
425 MCStreamer *llvm::createMachOStreamer(MCContext &Context, MCAsmBackend &MAB,
426 raw_ostream &OS, MCCodeEmitter *CE,
428 MCMachOStreamer *S = new MCMachOStreamer(Context, MAB, OS, CE);
430 S->getAssembler().setRelaxAll(true);