66906188d9a0979de6591df9ebb7dfaaac4ce600
[oota-llvm.git] / lib / MC / MCMachOStreamer.cpp
1 //===- lib/MC/MCMachOStreamer.cpp - Mach-O Object Output ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/MC/MCStreamer.h"
11
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/MC/MCSectionMachO.h"
22 #include "llvm/MC/MCDwarf.h"
23 #include "llvm/Support/Dwarf.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetAsmBackend.h"
27
28 using namespace llvm;
29
30 namespace {
31
32 class MCMachOStreamer : public MCObjectStreamer {
33 private:
34   virtual void EmitInstToFragment(const MCInst &Inst);
35   virtual void EmitInstToData(const MCInst &Inst);
36
37 public:
38   MCMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
39                   raw_ostream &OS, MCCodeEmitter *Emitter)
40     : MCObjectStreamer(Context, TAB, OS, Emitter, true) {}
41
42   /// @name MCStreamer Interface
43   /// @{
44
45   virtual void InitSections();
46   virtual void EmitLabel(MCSymbol *Symbol);
47   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
48   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
49   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
50   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
51   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
52                                 unsigned ByteAlignment);
53   virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
54     assert(0 && "macho doesn't support this directive");
55   }
56   virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
57     assert(0 && "macho doesn't support this directive");
58   }
59   virtual void EmitCOFFSymbolType(int Type) {
60     assert(0 && "macho doesn't support this directive");
61   }
62   virtual void EndCOFFSymbolDef() {
63     assert(0 && "macho doesn't support this directive");
64   }
65   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
66     assert(0 && "macho doesn't support this directive");
67   }
68   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
69     assert(0 && "macho doesn't support this directive");
70   }
71   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
72                             unsigned Size = 0, unsigned ByteAlignment = 0);
73   virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
74                               uint64_t Size, unsigned ByteAlignment = 0);
75   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
76   virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
77   virtual void EmitGPRel32Value(const MCExpr *Value) {
78     assert(0 && "macho doesn't support this directive");
79   }
80   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
81                                     unsigned ValueSize = 1,
82                                     unsigned MaxBytesToEmit = 0);
83   virtual void EmitCodeAlignment(unsigned ByteAlignment,
84                                  unsigned MaxBytesToEmit = 0);
85   virtual void EmitValueToOffset(const MCExpr *Offset,
86                                  unsigned char Value = 0);
87
88   virtual void EmitFileDirective(StringRef Filename) {
89     // FIXME: Just ignore the .file; it isn't important enough to fail the
90     // entire assembly.
91
92     //report_fatal_error("unsupported directive: '.file'");
93   }
94   virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
95     // FIXME: Just ignore the .file; it isn't important enough to fail the
96     // entire assembly.
97
98     //report_fatal_error("unsupported directive: '.file'");
99   }
100
101   virtual void Finish();
102
103   /// @}
104 };
105
106 } // end anonymous namespace.
107
108 void MCMachOStreamer::InitSections() {
109   SwitchSection(getContext().getMachOSection("__TEXT", "__text",
110                                     MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
111                                     0, SectionKind::getText()));
112
113 }
114
115 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
116   // TODO: This is almost exactly the same as WinCOFFStreamer. Consider merging
117   // into MCObjectStreamer.
118   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
119   assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
120   assert(CurSection && "Cannot emit before setting section!");
121
122   Symbol->setSection(*CurSection);
123
124   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
125
126   // We have to create a new fragment if this is an atom defining symbol,
127   // fragments cannot span atoms.
128   if (getAssembler().isSymbolLinkerVisible(SD.getSymbol()))
129     new MCDataFragment(getCurrentSectionData());
130
131   // FIXME: This is wasteful, we don't necessarily need to create a data
132   // fragment. Instead, we should mark the symbol as pointing into the data
133   // fragment if it exists, otherwise we should just queue the label and set its
134   // fragment pointer when we emit the next fragment.
135   MCDataFragment *F = getOrCreateDataFragment();
136   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
137   SD.setFragment(F);
138   SD.setOffset(F->getContents().size());
139
140   // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
141   // to clear the weak reference and weak definition bits too, but the
142   // implementation was buggy. For now we just try to match 'as', for
143   // diffability.
144   //
145   // FIXME: Cleanup this code, these bits should be emitted based on semantic
146   // properties, not on the order of definition, etc.
147   SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
148 }
149
150 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
151   switch (Flag) {
152   case MCAF_SyntaxUnified:  return; // no-op here.
153   case MCAF_SubsectionsViaSymbols:
154     getAssembler().setSubsectionsViaSymbols(true);
155     return;
156   default:
157     llvm_unreachable("invalid assembler flag!");
158   }
159 }
160
161 void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
162   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
163   // MCObjectStreamer.
164   // FIXME: Lift context changes into super class.
165   getAssembler().getOrCreateSymbolData(*Symbol);
166   Symbol->setVariableValue(AddValueSymbols(Value));
167 }
168
169 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
170                                           MCSymbolAttr Attribute) {
171   // Indirect symbols are handled differently, to match how 'as' handles
172   // them. This makes writing matching .o files easier.
173   if (Attribute == MCSA_IndirectSymbol) {
174     // Note that we intentionally cannot use the symbol data here; this is
175     // important for matching the string table that 'as' generates.
176     IndirectSymbolData ISD;
177     ISD.Symbol = Symbol;
178     ISD.SectionData = getCurrentSectionData();
179     getAssembler().getIndirectSymbols().push_back(ISD);
180     return;
181   }
182
183   // Adding a symbol attribute always introduces the symbol, note that an
184   // important side effect of calling getOrCreateSymbolData here is to register
185   // the symbol with the assembler.
186   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
187
188   // The implementation of symbol attributes is designed to match 'as', but it
189   // leaves much to desired. It doesn't really make sense to arbitrarily add and
190   // remove flags, but 'as' allows this (in particular, see .desc).
191   //
192   // In the future it might be worth trying to make these operations more well
193   // defined.
194   switch (Attribute) {
195   case MCSA_Invalid:
196   case MCSA_ELF_TypeFunction:
197   case MCSA_ELF_TypeIndFunction:
198   case MCSA_ELF_TypeObject:
199   case MCSA_ELF_TypeTLS:
200   case MCSA_ELF_TypeCommon:
201   case MCSA_ELF_TypeNoType:
202   case MCSA_IndirectSymbol:
203   case MCSA_Hidden:
204   case MCSA_Internal:
205   case MCSA_Protected:
206   case MCSA_Weak:
207   case MCSA_Local:
208     assert(0 && "Invalid symbol attribute for Mach-O!");
209     break;
210
211   case MCSA_Global:
212     SD.setExternal(true);
213     // This effectively clears the undefined lazy bit, in Darwin 'as', although
214     // it isn't very consistent because it implements this as part of symbol
215     // lookup.
216     //
217     // FIXME: Cleanup this code, these bits should be emitted based on semantic
218     // properties, not on the order of definition, etc.
219     SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
220     break;
221
222   case MCSA_LazyReference:
223     // FIXME: This requires -dynamic.
224     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
225     if (Symbol->isUndefined())
226       SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
227     break;
228
229     // Since .reference sets the no dead strip bit, it is equivalent to
230     // .no_dead_strip in practice.
231   case MCSA_Reference:
232   case MCSA_NoDeadStrip:
233     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
234     break;
235
236   case MCSA_PrivateExtern:
237     SD.setExternal(true);
238     SD.setPrivateExtern(true);
239     break;
240
241   case MCSA_WeakReference:
242     // FIXME: This requires -dynamic.
243     if (Symbol->isUndefined())
244       SD.setFlags(SD.getFlags() | SF_WeakReference);
245     break;
246
247   case MCSA_WeakDefinition:
248     // FIXME: 'as' enforces that this is defined and global. The manual claims
249     // it has to be in a coalesced section, but this isn't enforced.
250     SD.setFlags(SD.getFlags() | SF_WeakDefinition);
251     break;
252
253   case MCSA_WeakDefAutoPrivate:
254     SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
255     break;
256   }
257 }
258
259 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
260   // Encode the 'desc' value into the lowest implementation defined bits.
261   assert(DescValue == (DescValue & SF_DescFlagsMask) &&
262          "Invalid .desc value!");
263   getAssembler().getOrCreateSymbolData(*Symbol).setFlags(
264     DescValue & SF_DescFlagsMask);
265 }
266
267 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
268                                        unsigned ByteAlignment) {
269   // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
270   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
271
272   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
273   SD.setExternal(true);
274   SD.setCommon(Size, ByteAlignment);
275 }
276
277 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
278                                    unsigned Size, unsigned ByteAlignment) {
279   MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
280
281   // The symbol may not be present, which only creates the section.
282   if (!Symbol)
283     return;
284
285   // FIXME: Assert that this section has the zerofill type.
286
287   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
288
289   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
290
291   // Emit an align fragment if necessary.
292   if (ByteAlignment != 1)
293     new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
294
295   MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
296   SD.setFragment(F);
297
298   Symbol->setSection(*Section);
299
300   // Update the maximum alignment on the zero fill section if necessary.
301   if (ByteAlignment > SectData.getAlignment())
302     SectData.setAlignment(ByteAlignment);
303 }
304
305 // This should always be called with the thread local bss section.  Like the
306 // .zerofill directive this doesn't actually switch sections on us.
307 void MCMachOStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
308                                      uint64_t Size, unsigned ByteAlignment) {
309   EmitZerofill(Section, Symbol, Size, ByteAlignment);
310   return;
311 }
312
313 void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
314   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
315   // MCObjectStreamer.
316   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
317 }
318
319 void MCMachOStreamer::EmitValue(const MCExpr *Value, unsigned Size,
320                                 unsigned AddrSpace) {
321   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
322   // MCObjectStreamer.
323   MCDataFragment *DF = getOrCreateDataFragment();
324
325   // Avoid fixups when possible.
326   int64_t AbsValue;
327   if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
328     // FIXME: Endianness assumption.
329     for (unsigned i = 0; i != Size; ++i)
330       DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
331   } else {
332     DF->addFixup(MCFixup::Create(DF->getContents().size(),
333                                  AddValueSymbols(Value),
334                                  MCFixup::getKindForSize(Size)));
335     DF->getContents().resize(DF->getContents().size() + Size, 0);
336   }
337 }
338
339 void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
340                                            int64_t Value, unsigned ValueSize,
341                                            unsigned MaxBytesToEmit) {
342   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
343   // MCObjectStreamer.
344   if (MaxBytesToEmit == 0)
345     MaxBytesToEmit = ByteAlignment;
346   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
347                       getCurrentSectionData());
348
349   // Update the maximum alignment on the current section if necessary.
350   if (ByteAlignment > getCurrentSectionData()->getAlignment())
351     getCurrentSectionData()->setAlignment(ByteAlignment);
352 }
353
354 void MCMachOStreamer::EmitCodeAlignment(unsigned ByteAlignment,
355                                         unsigned MaxBytesToEmit) {
356   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
357   // MCObjectStreamer.
358   if (MaxBytesToEmit == 0)
359     MaxBytesToEmit = ByteAlignment;
360   MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
361                                            getCurrentSectionData());
362   F->setEmitNops(true);
363
364   // Update the maximum alignment on the current section if necessary.
365   if (ByteAlignment > getCurrentSectionData()->getAlignment())
366     getCurrentSectionData()->setAlignment(ByteAlignment);
367 }
368
369 void MCMachOStreamer::EmitValueToOffset(const MCExpr *Offset,
370                                         unsigned char Value) {
371   new MCOrgFragment(*Offset, Value, getCurrentSectionData());
372 }
373
374 void MCMachOStreamer::EmitInstToFragment(const MCInst &Inst) {
375   MCInstFragment *IF = new MCInstFragment(Inst, getCurrentSectionData());
376
377   // Add the fixups and data.
378   //
379   // FIXME: Revisit this design decision when relaxation is done, we may be
380   // able to get away with not storing any extra data in the MCInst.
381   SmallVector<MCFixup, 4> Fixups;
382   SmallString<256> Code;
383   raw_svector_ostream VecOS(Code);
384   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
385   VecOS.flush();
386
387   IF->getCode() = Code;
388   IF->getFixups() = Fixups;
389 }
390
391 void MCMachOStreamer::EmitInstToData(const MCInst &Inst) {
392   MCDataFragment *DF = getOrCreateDataFragment();
393
394   SmallVector<MCFixup, 4> Fixups;
395   SmallString<256> Code;
396   raw_svector_ostream VecOS(Code);
397   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
398   VecOS.flush();
399
400   // Add the fixups and data.
401   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
402     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
403     DF->addFixup(Fixups[i]);
404   }
405   DF->getContents().append(Code.begin(), Code.end());
406 }
407
408 void MCMachOStreamer::Finish() {
409   // Dump out the dwarf file & directory tables and line tables.
410   if (getContext().hasDwarfFiles()) {
411     const MCSection *DwarfLineSection = getContext().getMachOSection("__DWARF",
412                                          "__debug_line",
413                                          MCSectionMachO::S_ATTR_DEBUG,
414                                          0, SectionKind::getDataRelLocal());
415     MCDwarfFileTable::Emit(this, DwarfLineSection);
416   }
417
418   // We have to set the fragment atom associations so we can relax properly for
419   // Mach-O.
420
421   // First, scan the symbol table to build a lookup table from fragments to
422   // defining symbols.
423   DenseMap<const MCFragment*, MCSymbolData*> DefiningSymbolMap;
424   for (MCAssembler::symbol_iterator it = getAssembler().symbol_begin(),
425          ie = getAssembler().symbol_end(); it != ie; ++it) {
426     if (getAssembler().isSymbolLinkerVisible(it->getSymbol()) &&
427         it->getFragment()) {
428       // An atom defining symbol should never be internal to a fragment.
429       assert(it->getOffset() == 0 && "Invalid offset in atom defining symbol!");
430       DefiningSymbolMap[it->getFragment()] = it;
431     }
432   }
433
434   // Set the fragment atom associations by tracking the last seen atom defining
435   // symbol.
436   for (MCAssembler::iterator it = getAssembler().begin(),
437          ie = getAssembler().end(); it != ie; ++it) {
438     MCSymbolData *CurrentAtom = 0;
439     for (MCSectionData::iterator it2 = it->begin(),
440            ie2 = it->end(); it2 != ie2; ++it2) {
441       if (MCSymbolData *SD = DefiningSymbolMap.lookup(it2))
442         CurrentAtom = SD;
443       it2->setAtom(CurrentAtom);
444     }
445   }
446
447   this->MCObjectStreamer::Finish();
448 }
449
450 MCStreamer *llvm::createMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
451                                       raw_ostream &OS, MCCodeEmitter *CE,
452                                       bool RelaxAll) {
453   MCMachOStreamer *S = new MCMachOStreamer(Context, TAB, OS, CE);
454   if (RelaxAll)
455     S->getAssembler().setRelaxAll(true);
456   return S;
457 }