Refactor MCInstFragment and MCDataFragment to adhere to a common interface,
[oota-llvm.git] / lib / MC / MCMachOStreamer.cpp
1 //
2 //                     The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8
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"
25
26 using namespace llvm;
27
28 namespace {
29
30 class MCMachOStreamer : public MCObjectStreamer {
31 private:
32   virtual void EmitInstToData(const MCInst &Inst);
33
34   void EmitDataRegion(DataRegionData::KindTy Kind);
35   void EmitDataRegionEnd();
36 public:
37   MCMachOStreamer(MCContext &Context, MCAsmBackend &MAB,
38                   raw_ostream &OS, MCCodeEmitter *Emitter)
39     : MCObjectStreamer(Context, MAB, OS, Emitter) {}
40
41   /// @name MCStreamer Interface
42   /// @{
43
44   virtual void InitSections();
45   virtual void EmitLabel(MCSymbol *Symbol);
46   virtual void EmitEHSymAttributes(const MCSymbol *Symbol,
47                                    MCSymbol *EHSymbol);
48   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
49   virtual void EmitDataRegion(MCDataRegionType Kind);
50   virtual void EmitThumbFunc(MCSymbol *Func);
51   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
52   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
53   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
54                                 unsigned ByteAlignment);
55   virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
56     llvm_unreachable("macho doesn't support this directive");
57   }
58   virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
59     llvm_unreachable("macho doesn't support this directive");
60   }
61   virtual void EmitCOFFSymbolType(int Type) {
62     llvm_unreachable("macho doesn't support this directive");
63   }
64   virtual void EndCOFFSymbolDef() {
65     llvm_unreachable("macho doesn't support this directive");
66   }
67   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
68     llvm_unreachable("macho doesn't support this directive");
69   }
70   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
71                                      unsigned ByteAlignment);
72   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
73                             uint64_t Size = 0, unsigned ByteAlignment = 0);
74   virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
75                               uint64_t Size, unsigned ByteAlignment = 0);
76
77   virtual void EmitFileDirective(StringRef Filename) {
78     // FIXME: Just ignore the .file; it isn't important enough to fail the
79     // entire assembly.
80
81     //report_fatal_error("unsupported directive: '.file'");
82   }
83
84   virtual void FinishImpl();
85
86   /// @}
87 };
88
89 } // end anonymous namespace.
90
91 void MCMachOStreamer::InitSections() {
92   SwitchSection(getContext().getMachOSection("__TEXT", "__text",
93                                     MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
94                                     0, SectionKind::getText()));
95
96 }
97
98 void MCMachOStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
99                                           MCSymbol *EHSymbol) {
100   MCSymbolData &SD =
101     getAssembler().getOrCreateSymbolData(*Symbol);
102   if (SD.isExternal())
103     EmitSymbolAttribute(EHSymbol, MCSA_Global);
104   if (SD.getFlags() & SF_WeakDefinition)
105     EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
106   if (SD.isPrivateExtern())
107     EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
108 }
109
110 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
111   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
112
113   // isSymbolLinkerVisible uses the section.
114   Symbol->setSection(*getCurrentSection());
115   // We have to create a new fragment if this is an atom defining symbol,
116   // fragments cannot span atoms.
117   if (getAssembler().isSymbolLinkerVisible(*Symbol))
118     new MCDataFragment(getCurrentSectionData());
119
120   MCObjectStreamer::EmitLabel(Symbol);
121
122   MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
123   // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
124   // to clear the weak reference and weak definition bits too, but the
125   // implementation was buggy. For now we just try to match 'as', for
126   // diffability.
127   //
128   // FIXME: Cleanup this code, these bits should be emitted based on semantic
129   // properties, not on the order of definition, etc.
130   SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
131 }
132
133 void MCMachOStreamer::EmitDataRegion(DataRegionData::KindTy Kind) {
134   if (!getAssembler().getBackend().hasDataInCodeSupport())
135     return;
136   // Create a temporary label to mark the start of the data region.
137   MCSymbol *Start = getContext().CreateTempSymbol();
138   EmitLabel(Start);
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);
143 }
144
145 void MCMachOStreamer::EmitDataRegionEnd() {
146   if (!getAssembler().getBackend().hasDataInCodeSupport())
147     return;
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();
154   EmitLabel(Data.End);
155 }
156
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.
161   switch (Flag) {
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);
168     return;
169   }
170 }
171
172 void MCMachOStreamer::EmitDataRegion(MCDataRegionType Kind) {
173   switch (Kind) {
174   case MCDR_DataRegion:
175     EmitDataRegion(DataRegionData::Data);
176     return;
177   case MCDR_DataRegionJT8:
178     EmitDataRegion(DataRegionData::JumpTable8);
179     return;
180   case MCDR_DataRegionJT16:
181     EmitDataRegion(DataRegionData::JumpTable16);
182     return;
183   case MCDR_DataRegionJT32:
184     EmitDataRegion(DataRegionData::JumpTable32);
185     return;
186   case MCDR_DataRegionEnd:
187     EmitDataRegionEnd();
188     return;
189   }
190 }
191
192 void MCMachOStreamer::EmitThumbFunc(MCSymbol *Symbol) {
193   // Remember that the function is a thumb function. Fixup and relocation
194   // values will need adjusted.
195   getAssembler().setIsThumbFunc(Symbol);
196
197   // Mark the thumb bit on the symbol.
198   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
199   SD.setFlags(SD.getFlags() | SF_ThumbFunc);
200 }
201
202 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
203                                           MCSymbolAttr Attribute) {
204   // Indirect symbols are handled differently, to match how 'as' handles
205   // them. This makes writing matching .o files easier.
206   if (Attribute == MCSA_IndirectSymbol) {
207     // Note that we intentionally cannot use the symbol data here; this is
208     // important for matching the string table that 'as' generates.
209     IndirectSymbolData ISD;
210     ISD.Symbol = Symbol;
211     ISD.SectionData = getCurrentSectionData();
212     getAssembler().getIndirectSymbols().push_back(ISD);
213     return;
214   }
215
216   // Adding a symbol attribute always introduces the symbol, note that an
217   // important side effect of calling getOrCreateSymbolData here is to register
218   // the symbol with the assembler.
219   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
220
221   // The implementation of symbol attributes is designed to match 'as', but it
222   // leaves much to desired. It doesn't really make sense to arbitrarily add and
223   // remove flags, but 'as' allows this (in particular, see .desc).
224   //
225   // In the future it might be worth trying to make these operations more well
226   // defined.
227   switch (Attribute) {
228   case MCSA_Invalid:
229   case MCSA_ELF_TypeFunction:
230   case MCSA_ELF_TypeIndFunction:
231   case MCSA_ELF_TypeObject:
232   case MCSA_ELF_TypeTLS:
233   case MCSA_ELF_TypeCommon:
234   case MCSA_ELF_TypeNoType:
235   case MCSA_ELF_TypeGnuUniqueObject:
236   case MCSA_Hidden:
237   case MCSA_IndirectSymbol:
238   case MCSA_Internal:
239   case MCSA_Protected:
240   case MCSA_Weak:
241   case MCSA_Local:
242     llvm_unreachable("Invalid symbol attribute for Mach-O!");
243
244   case MCSA_Global:
245     SD.setExternal(true);
246     // This effectively clears the undefined lazy bit, in Darwin 'as', although
247     // it isn't very consistent because it implements this as part of symbol
248     // lookup.
249     //
250     // FIXME: Cleanup this code, these bits should be emitted based on semantic
251     // properties, not on the order of definition, etc.
252     SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
253     break;
254
255   case MCSA_LazyReference:
256     // FIXME: This requires -dynamic.
257     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
258     if (Symbol->isUndefined())
259       SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
260     break;
261
262     // Since .reference sets the no dead strip bit, it is equivalent to
263     // .no_dead_strip in practice.
264   case MCSA_Reference:
265   case MCSA_NoDeadStrip:
266     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
267     break;
268
269   case MCSA_SymbolResolver:
270     SD.setFlags(SD.getFlags() | SF_SymbolResolver);
271     break;
272
273   case MCSA_PrivateExtern:
274     SD.setExternal(true);
275     SD.setPrivateExtern(true);
276     break;
277
278   case MCSA_WeakReference:
279     // FIXME: This requires -dynamic.
280     if (Symbol->isUndefined())
281       SD.setFlags(SD.getFlags() | SF_WeakReference);
282     break;
283
284   case MCSA_WeakDefinition:
285     // FIXME: 'as' enforces that this is defined and global. The manual claims
286     // it has to be in a coalesced section, but this isn't enforced.
287     SD.setFlags(SD.getFlags() | SF_WeakDefinition);
288     break;
289
290   case MCSA_WeakDefAutoPrivate:
291     SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
292     break;
293   }
294 }
295
296 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
297   // Encode the 'desc' value into the lowest implementation defined bits.
298   assert(DescValue == (DescValue & SF_DescFlagsMask) &&
299          "Invalid .desc value!");
300   getAssembler().getOrCreateSymbolData(*Symbol).setFlags(
301     DescValue & SF_DescFlagsMask);
302 }
303
304 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
305                                        unsigned ByteAlignment) {
306   // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
307   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
308
309   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
310   SD.setExternal(true);
311   SD.setCommon(Size, ByteAlignment);
312 }
313
314 void MCMachOStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
315                                             unsigned ByteAlignment) {
316   // '.lcomm' is equivalent to '.zerofill'.
317   return EmitZerofill(getContext().getMachOSection("__DATA", "__bss",
318                                                    MCSectionMachO::S_ZEROFILL,
319                                                    0, SectionKind::getBSS()),
320                       Symbol, Size, ByteAlignment);
321 }
322
323 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
324                                    uint64_t Size, unsigned ByteAlignment) {
325   MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
326
327   // The symbol may not be present, which only creates the section.
328   if (!Symbol)
329     return;
330
331   // FIXME: Assert that this section has the zerofill type.
332
333   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
334
335   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
336
337   // Emit an align fragment if necessary.
338   if (ByteAlignment != 1)
339     new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
340
341   MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
342   SD.setFragment(F);
343
344   Symbol->setSection(*Section);
345
346   // Update the maximum alignment on the zero fill section if necessary.
347   if (ByteAlignment > SectData.getAlignment())
348     SectData.setAlignment(ByteAlignment);
349 }
350
351 // This should always be called with the thread local bss section.  Like the
352 // .zerofill directive this doesn't actually switch sections on us.
353 void MCMachOStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
354                                      uint64_t Size, unsigned ByteAlignment) {
355   EmitZerofill(Section, Symbol, Size, ByteAlignment);
356   return;
357 }
358
359 void MCMachOStreamer::EmitInstToData(const MCInst &Inst) {
360   MCDataFragment *DF = getOrCreateDataFragment();
361
362   SmallVector<MCFixup, 4> Fixups;
363   SmallString<256> Code;
364   raw_svector_ostream VecOS(Code);
365   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
366   VecOS.flush();
367
368   // Add the fixups and data.
369   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
370     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
371     DF->getFixups().push_back(Fixups[i]);
372   }
373   DF->getContents().append(Code.begin(), Code.end());
374 }
375
376 void MCMachOStreamer::FinishImpl() {
377   EmitFrames(true);
378
379   // We have to set the fragment atom associations so we can relax properly for
380   // Mach-O.
381
382   // First, scan the symbol table to build a lookup table from fragments to
383   // defining symbols.
384   DenseMap<const MCFragment*, MCSymbolData*> DefiningSymbolMap;
385   for (MCAssembler::symbol_iterator it = getAssembler().symbol_begin(),
386          ie = getAssembler().symbol_end(); it != ie; ++it) {
387     if (getAssembler().isSymbolLinkerVisible(it->getSymbol()) &&
388         it->getFragment()) {
389       // An atom defining symbol should never be internal to a fragment.
390       assert(it->getOffset() == 0 && "Invalid offset in atom defining symbol!");
391       DefiningSymbolMap[it->getFragment()] = it;
392     }
393   }
394
395   // Set the fragment atom associations by tracking the last seen atom defining
396   // symbol.
397   for (MCAssembler::iterator it = getAssembler().begin(),
398          ie = getAssembler().end(); it != ie; ++it) {
399     MCSymbolData *CurrentAtom = 0;
400     for (MCSectionData::iterator it2 = it->begin(),
401            ie2 = it->end(); it2 != ie2; ++it2) {
402       if (MCSymbolData *SD = DefiningSymbolMap.lookup(it2))
403         CurrentAtom = SD;
404       it2->setAtom(CurrentAtom);
405     }
406   }
407
408   this->MCObjectStreamer::FinishImpl();
409 }
410
411 MCStreamer *llvm::createMachOStreamer(MCContext &Context, MCAsmBackend &MAB,
412                                       raw_ostream &OS, MCCodeEmitter *CE,
413                                       bool RelaxAll) {
414   MCMachOStreamer *S = new MCMachOStreamer(Context, MAB, OS, CE);
415   if (RelaxAll)
416     S->getAssembler().setRelaxAll(true);
417   return S;
418 }