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/MCObjectFileInfo.h"
20 #include "llvm/MC/MCObjectStreamer.h"
21 #include "llvm/MC/MCSection.h"
22 #include "llvm/MC/MCSectionMachO.h"
23 #include "llvm/MC/MCSymbol.h"
24 #include "llvm/Support/Dwarf.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
32 class MCMachOStreamer : public MCObjectStreamer {
34 void EmitInstToData(const MCInst &Inst, const MCSubtargetInfo &STI) override;
36 void EmitDataRegion(DataRegionData::KindTy Kind);
37 void EmitDataRegionEnd();
39 MCMachOStreamer(MCContext &Context, MCAsmBackend &MAB, raw_ostream &OS,
40 MCCodeEmitter *Emitter)
41 : MCObjectStreamer(Context, MAB, OS, Emitter) {}
43 /// @name MCStreamer Interface
46 void EmitLabel(MCSymbol *Symbol) override;
47 void EmitDebugLabel(MCSymbol *Symbol) override;
48 void EmitEHSymAttributes(const MCSymbol *Symbol, MCSymbol *EHSymbol) override;
49 void EmitAssemblerFlag(MCAssemblerFlag Flag) override;
50 void EmitLinkerOptions(ArrayRef<std::string> Options) override;
51 void EmitDataRegion(MCDataRegionType Kind) override;
52 void EmitThumbFunc(MCSymbol *Func) override;
53 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
54 void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
55 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
56 unsigned ByteAlignment) override;
57 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override {
58 llvm_unreachable("macho doesn't support this directive");
60 void EmitCOFFSymbolStorageClass(int StorageClass) override {
61 llvm_unreachable("macho doesn't support this directive");
63 void EmitCOFFSymbolType(int Type) override {
64 llvm_unreachable("macho doesn't support this directive");
66 void EndCOFFSymbolDef() override {
67 llvm_unreachable("macho doesn't support this directive");
69 void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) override {
70 llvm_unreachable("macho doesn't support this directive");
72 void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
73 unsigned ByteAlignment) override;
74 void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
75 uint64_t Size = 0, unsigned ByteAlignment = 0) override;
76 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
77 uint64_t Size, unsigned ByteAlignment = 0) override;
79 void EmitFileDirective(StringRef Filename) override {
80 // FIXME: Just ignore the .file; it isn't important enough to fail the
83 // report_fatal_error("unsupported directive: '.file'");
86 void EmitIdent(StringRef IdentString) override {
87 llvm_unreachable("macho doesn't support this directive");
90 void FinishImpl() override;
93 } // end anonymous namespace.
95 void MCMachOStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
98 getAssembler().getOrCreateSymbolData(*Symbol);
100 EmitSymbolAttribute(EHSymbol, MCSA_Global);
101 if (SD.getFlags() & SF_WeakDefinition)
102 EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
103 if (SD.isPrivateExtern())
104 EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
107 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
108 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
110 // isSymbolLinkerVisible uses the section.
111 AssignSection(Symbol, getCurrentSection().first);
112 // We have to create a new fragment if this is an atom defining symbol,
113 // fragments cannot span atoms.
114 if (getAssembler().isSymbolLinkerVisible(*Symbol))
115 insert(new MCDataFragment());
117 MCObjectStreamer::EmitLabel(Symbol);
119 MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
120 // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
121 // to clear the weak reference and weak definition bits too, but the
122 // implementation was buggy. For now we just try to match 'as', for
125 // FIXME: Cleanup this code, these bits should be emitted based on semantic
126 // properties, not on the order of definition, etc.
127 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
130 void MCMachOStreamer::EmitDebugLabel(MCSymbol *Symbol) {
133 void MCMachOStreamer::EmitDataRegion(DataRegionData::KindTy Kind) {
134 if (!getAssembler().getBackend().hasDataInCodeSupport())
136 // Create a temporary label to mark the start of the data region.
137 MCSymbol *Start = getContext().CreateTempSymbol();
139 // Record the region for the object writer to use.
140 DataRegionData Data = { Kind, Start, NULL };
141 std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
142 Regions.push_back(Data);
145 void MCMachOStreamer::EmitDataRegionEnd() {
146 if (!getAssembler().getBackend().hasDataInCodeSupport())
148 std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
149 assert(Regions.size() && "Mismatched .end_data_region!");
150 DataRegionData &Data = Regions.back();
151 assert(Data.End == NULL && "Mismatched .end_data_region!");
152 // Create a temporary label to mark the end of the data region.
153 Data.End = getContext().CreateTempSymbol();
157 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
158 // Let the target do whatever target specific stuff it needs to do.
159 getAssembler().getBackend().handleAssemblerFlag(Flag);
160 // Do any generic stuff we need to do.
162 case MCAF_SyntaxUnified: return; // no-op here.
163 case MCAF_Code16: return; // Change parsing mode; no-op here.
164 case MCAF_Code32: return; // Change parsing mode; no-op here.
165 case MCAF_Code64: return; // Change parsing mode; no-op here.
166 case MCAF_SubsectionsViaSymbols:
167 getAssembler().setSubsectionsViaSymbols(true);
172 void MCMachOStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
173 getAssembler().getLinkerOptions().push_back(Options);
176 void MCMachOStreamer::EmitDataRegion(MCDataRegionType Kind) {
178 case MCDR_DataRegion:
179 EmitDataRegion(DataRegionData::Data);
181 case MCDR_DataRegionJT8:
182 EmitDataRegion(DataRegionData::JumpTable8);
184 case MCDR_DataRegionJT16:
185 EmitDataRegion(DataRegionData::JumpTable16);
187 case MCDR_DataRegionJT32:
188 EmitDataRegion(DataRegionData::JumpTable32);
190 case MCDR_DataRegionEnd:
196 void MCMachOStreamer::EmitThumbFunc(MCSymbol *Symbol) {
197 // Remember that the function is a thumb function. Fixup and relocation
198 // values will need adjusted.
199 getAssembler().setIsThumbFunc(Symbol);
201 // Mark the thumb bit on the symbol.
202 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
203 SD.setFlags(SD.getFlags() | SF_ThumbFunc);
206 bool MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
207 MCSymbolAttr Attribute) {
208 // Indirect symbols are handled differently, to match how 'as' handles
209 // them. This makes writing matching .o files easier.
210 if (Attribute == MCSA_IndirectSymbol) {
211 // Note that we intentionally cannot use the symbol data here; this is
212 // important for matching the string table that 'as' generates.
213 IndirectSymbolData ISD;
215 ISD.SectionData = getCurrentSectionData();
216 getAssembler().getIndirectSymbols().push_back(ISD);
220 // Adding a symbol attribute always introduces the symbol, note that an
221 // important side effect of calling getOrCreateSymbolData here is to register
222 // the symbol with the assembler.
223 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
225 // The implementation of symbol attributes is designed to match 'as', but it
226 // leaves much to desired. It doesn't really make sense to arbitrarily add and
227 // remove flags, but 'as' allows this (in particular, see .desc).
229 // In the future it might be worth trying to make these operations more well
233 case MCSA_ELF_TypeFunction:
234 case MCSA_ELF_TypeIndFunction:
235 case MCSA_ELF_TypeObject:
236 case MCSA_ELF_TypeTLS:
237 case MCSA_ELF_TypeCommon:
238 case MCSA_ELF_TypeNoType:
239 case MCSA_ELF_TypeGnuUniqueObject:
241 case MCSA_IndirectSymbol:
249 SD.setExternal(true);
250 // This effectively clears the undefined lazy bit, in Darwin 'as', although
251 // it isn't very consistent because it implements this as part of symbol
254 // FIXME: Cleanup this code, these bits should be emitted based on semantic
255 // properties, not on the order of definition, etc.
256 SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
259 case MCSA_LazyReference:
260 // FIXME: This requires -dynamic.
261 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
262 if (Symbol->isUndefined())
263 SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
266 // Since .reference sets the no dead strip bit, it is equivalent to
267 // .no_dead_strip in practice.
269 case MCSA_NoDeadStrip:
270 SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
273 case MCSA_SymbolResolver:
274 SD.setFlags(SD.getFlags() | SF_SymbolResolver);
277 case MCSA_PrivateExtern:
278 SD.setExternal(true);
279 SD.setPrivateExtern(true);
282 case MCSA_WeakReference:
283 // FIXME: This requires -dynamic.
284 if (Symbol->isUndefined())
285 SD.setFlags(SD.getFlags() | SF_WeakReference);
288 case MCSA_WeakDefinition:
289 // FIXME: 'as' enforces that this is defined and global. The manual claims
290 // it has to be in a coalesced section, but this isn't enforced.
291 SD.setFlags(SD.getFlags() | SF_WeakDefinition);
294 case MCSA_WeakDefAutoPrivate:
295 SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
302 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
303 // Encode the 'desc' value into the lowest implementation defined bits.
304 assert(DescValue == (DescValue & SF_DescFlagsMask) &&
305 "Invalid .desc value!");
306 getAssembler().getOrCreateSymbolData(*Symbol).setFlags(
307 DescValue & SF_DescFlagsMask);
310 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
311 unsigned ByteAlignment) {
312 // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
313 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
315 AssignSection(Symbol, NULL);
317 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
318 SD.setExternal(true);
319 SD.setCommon(Size, ByteAlignment);
322 void MCMachOStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
323 unsigned ByteAlignment) {
324 // '.lcomm' is equivalent to '.zerofill'.
325 return EmitZerofill(getContext().getObjectFileInfo()->getDataBSSSection(),
326 Symbol, Size, ByteAlignment);
329 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
330 uint64_t Size, unsigned ByteAlignment) {
331 MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
333 // The symbol may not be present, which only creates the section.
337 // On darwin all virtual sections have zerofill type.
338 assert(Section->isVirtualSection() && "Section does not have zerofill type!");
340 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
342 MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
344 // Emit an align fragment if necessary.
345 if (ByteAlignment != 1)
346 new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
348 MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
351 AssignSection(Symbol, Section);
353 // Update the maximum alignment on the zero fill section if necessary.
354 if (ByteAlignment > SectData.getAlignment())
355 SectData.setAlignment(ByteAlignment);
358 // This should always be called with the thread local bss section. Like the
359 // .zerofill directive this doesn't actually switch sections on us.
360 void MCMachOStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
361 uint64_t Size, unsigned ByteAlignment) {
362 EmitZerofill(Section, Symbol, Size, ByteAlignment);
366 void MCMachOStreamer::EmitInstToData(const MCInst &Inst,
367 const MCSubtargetInfo &STI) {
368 MCDataFragment *DF = getOrCreateDataFragment();
370 SmallVector<MCFixup, 4> Fixups;
371 SmallString<256> Code;
372 raw_svector_ostream VecOS(Code);
373 getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups, STI);
376 // Add the fixups and data.
377 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
378 Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
379 DF->getFixups().push_back(Fixups[i]);
381 DF->getContents().append(Code.begin(), Code.end());
384 void MCMachOStreamer::FinishImpl() {
385 EmitFrames(&getAssembler().getBackend(), true);
387 // We have to set the fragment atom associations so we can relax properly for
390 // First, scan the symbol table to build a lookup table from fragments to
392 DenseMap<const MCFragment*, MCSymbolData*> DefiningSymbolMap;
393 for (MCAssembler::symbol_iterator it = getAssembler().symbol_begin(),
394 ie = getAssembler().symbol_end(); it != ie; ++it) {
395 if (getAssembler().isSymbolLinkerVisible(it->getSymbol()) &&
397 // An atom defining symbol should never be internal to a fragment.
398 assert(it->getOffset() == 0 && "Invalid offset in atom defining symbol!");
399 DefiningSymbolMap[it->getFragment()] = it;
403 // Set the fragment atom associations by tracking the last seen atom defining
405 for (MCAssembler::iterator it = getAssembler().begin(),
406 ie = getAssembler().end(); it != ie; ++it) {
407 MCSymbolData *CurrentAtom = 0;
408 for (MCSectionData::iterator it2 = it->begin(),
409 ie2 = it->end(); it2 != ie2; ++it2) {
410 if (MCSymbolData *SD = DefiningSymbolMap.lookup(it2))
412 it2->setAtom(CurrentAtom);
416 this->MCObjectStreamer::FinishImpl();
419 MCStreamer *llvm::createMachOStreamer(MCContext &Context, MCAsmBackend &MAB,
420 raw_ostream &OS, MCCodeEmitter *CE,
422 MCMachOStreamer *S = new MCMachOStreamer(Context, MAB, OS, CE);
424 S->getAssembler().setRelaxAll(true);