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