e89f7d8dbd353f8e854c059fbd80465efaa34f7c
[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/MCInst.h"
16 #include "llvm/MC/MCSection.h"
17 #include "llvm/MC/MCSymbol.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/raw_ostream.h"
20 using namespace llvm;
21
22 namespace {
23
24 class MCMachOStreamer : public MCStreamer {
25   /// SymbolFlags - We store the value for the 'desc' symbol field in the lowest
26   /// 16 bits of the implementation defined flags.
27   enum SymbolFlags { // See <mach-o/nlist.h>.
28     SF_DescFlagsMask                        = 0xFFFF,
29
30     // Reference type flags.
31     SF_ReferenceTypeMask                    = 0x0007,
32     SF_ReferenceTypeUndefinedNonLazy        = 0x0000,
33     SF_ReferenceTypeUndefinedLazy           = 0x0001,
34     SF_ReferenceTypeDefined                 = 0x0002,
35     SF_ReferenceTypePrivateDefined          = 0x0003,
36     SF_ReferenceTypePrivateUndefinedNonLazy = 0x0004,
37     SF_ReferenceTypePrivateUndefinedLazy    = 0x0005,
38
39     // Other 'desc' flags.
40     SF_NoDeadStrip                          = 0x0020,
41     SF_WeakReference                        = 0x0040,
42     SF_WeakDefinition                       = 0x0080
43   };
44
45 private:
46   MCAssembler Assembler;
47
48   MCCodeEmitter *Emitter;
49
50   MCSectionData *CurSectionData;
51
52   DenseMap<const MCSection*, MCSectionData*> SectionMap;
53   
54   DenseMap<const MCSymbol*, MCSymbolData*> SymbolMap;
55
56 private:
57   MCFragment *getCurrentFragment() const {
58     assert(CurSectionData && "No current section!");
59
60     if (!CurSectionData->empty())
61       return &CurSectionData->getFragmentList().back();
62
63     return 0;
64   }
65
66   MCSymbolData &getSymbolData(MCSymbol &Symbol) {
67     MCSymbolData *&Entry = SymbolMap[&Symbol];
68
69     if (!Entry)
70       Entry = new MCSymbolData(Symbol, 0, 0, &Assembler);
71
72     return *Entry;
73   }
74
75 public:
76   MCMachOStreamer(MCContext &Context, raw_ostream &_OS, MCCodeEmitter *_Emitter)
77     : MCStreamer(Context), Assembler(_OS), Emitter(_Emitter),
78       CurSectionData(0) {}
79   ~MCMachOStreamer() {}
80
81   const MCValue &AddValueSymbols(const MCValue &Value) {
82     if (Value.getSymA())
83       getSymbolData(*const_cast<MCSymbol*>(Value.getSymA()));
84     if (Value.getSymB())
85       getSymbolData(*const_cast<MCSymbol*>(Value.getSymB()));
86     return Value;
87   }
88
89   /// @name MCStreamer Interface
90   /// @{
91
92   virtual void SwitchSection(const MCSection *Section);
93
94   virtual void EmitLabel(MCSymbol *Symbol);
95
96   virtual void EmitAssemblerFlag(AssemblerFlag Flag);
97
98   virtual void EmitAssignment(MCSymbol *Symbol, const MCValue &Value,
99                               bool MakeAbsolute = false);
100
101   virtual void EmitSymbolAttribute(MCSymbol *Symbol, SymbolAttr Attribute);
102
103   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
104
105   virtual void EmitLocalSymbol(MCSymbol *Symbol, const MCValue &Value);
106
107   virtual void EmitCommonSymbol(MCSymbol *Symbol, unsigned Size,
108                                 unsigned Pow2Alignment);
109
110   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
111                             unsigned Size = 0, unsigned Pow2Alignment = 0);
112
113   virtual void EmitBytes(const StringRef &Data);
114
115   virtual void EmitValue(const MCValue &Value, unsigned Size);
116
117   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
118                                     unsigned ValueSize = 1,
119                                     unsigned MaxBytesToEmit = 0);
120
121   virtual void EmitValueToOffset(const MCValue &Offset,
122                                  unsigned char Value = 0);
123
124   virtual void EmitInstruction(const MCInst &Inst);
125
126   virtual void Finish();
127
128   /// @}
129 };
130
131 } // end anonymous namespace.
132
133 void MCMachOStreamer::SwitchSection(const MCSection *Section) {
134   assert(Section && "Cannot switch to a null section!");
135   
136   // If already in this section, then this is a noop.
137   if (Section == CurSection) return;
138   
139   CurSection = Section;
140   MCSectionData *&Entry = SectionMap[Section];
141
142   if (!Entry)
143     Entry = new MCSectionData(*Section, &Assembler);
144
145   CurSectionData = Entry;
146 }
147
148 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
149   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
150
151   // FIXME: We should also use offsets into Fill fragments.
152   MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
153   if (!F)
154     F = new MCDataFragment(CurSectionData);
155
156   MCSymbolData &SD = getSymbolData(*Symbol);
157   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
158   SD.setFragment(F);
159   SD.setOffset(F->getContents().size());
160
161   // This causes the reference type and weak reference flags to be cleared.
162   SD.setFlags(SD.getFlags() & ~(SF_WeakReference | SF_ReferenceTypeMask));
163   
164   Symbol->setSection(*CurSection);
165 }
166
167 void MCMachOStreamer::EmitAssemblerFlag(AssemblerFlag Flag) {
168   switch (Flag) {
169   default:
170     llvm_unreachable("FIXME: Not yet implemented!");
171
172   case SubsectionsViaSymbols:
173     Assembler.setSubsectionsViaSymbols(true);
174     break;
175   }
176 }
177
178 void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol,
179                                      const MCValue &Value,
180                                      bool MakeAbsolute) {
181   // Only absolute symbols can be redefined.
182   assert((Symbol->isUndefined() || Symbol->isAbsolute()) &&
183          "Cannot define a symbol twice!");
184
185   llvm_unreachable("FIXME: Not yet implemented!");
186 }
187
188 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
189                                           SymbolAttr Attribute) {
190   // Indirect symbols are handled differently, to match how 'as' handles
191   // them. This makes writing matching .o files easier.
192   if (Attribute == MCStreamer::IndirectSymbol) {
193     // Note that we intentionally cannot use the symbol data here; this is
194     // important for matching the string table that 'as' generates.
195     IndirectSymbolData ISD;
196     ISD.Symbol = Symbol;
197     ISD.SectionData = CurSectionData;
198     Assembler.getIndirectSymbols().push_back(ISD);
199     return;
200   }
201
202   // Adding a symbol attribute always introduces the symbol, note that an
203   // important side effect of calling getSymbolData here is to register the
204   // symbol with the assembler.
205   MCSymbolData &SD = getSymbolData(*Symbol);
206
207   // The implementation of symbol attributes is designed to match 'as', but it
208   // leaves much to desired. It doesn't really make sense to arbitrarily add and
209   // remove flags, but 'as' allows this (in particular, see .desc).
210   //
211   // In the future it might be worth trying to make these operations more well
212   // defined.
213   switch (Attribute) {
214   case MCStreamer::IndirectSymbol:
215   case MCStreamer::Hidden:
216   case MCStreamer::Internal:
217   case MCStreamer::Protected:
218   case MCStreamer::Weak:
219     assert(0 && "Invalid symbol attribute for Mach-O!");
220     break;
221
222   case MCStreamer::Global:
223     getSymbolData(*Symbol).setExternal(true);
224     break;
225
226   case MCStreamer::LazyReference:
227     // FIXME: This requires -dynamic.
228     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
229     if (Symbol->isUndefined())
230       SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
231     break;
232
233     // Since .reference sets the no dead strip bit, it is equivalent to
234     // .no_dead_strip in practice.
235   case MCStreamer::Reference:
236   case MCStreamer::NoDeadStrip:
237     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
238     break;
239
240   case MCStreamer::PrivateExtern:
241     SD.setExternal(true);
242     SD.setPrivateExtern(true);
243     break;
244
245   case MCStreamer::WeakReference:
246     // FIXME: This requires -dynamic.
247     if (Symbol->isUndefined())
248       SD.setFlags(SD.getFlags() | SF_WeakReference);
249     break;
250
251   case MCStreamer::WeakDefinition:
252     // FIXME: 'as' enforces that this is defined and global. The manual claims
253     // it has to be in a coalesced section, but this isn't enforced.
254     SD.setFlags(SD.getFlags() | SF_WeakDefinition);
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   getSymbolData(*Symbol).setFlags(DescValue & SF_DescFlagsMask);
264 }
265
266 void MCMachOStreamer::EmitLocalSymbol(MCSymbol *Symbol, const MCValue &Value) {
267   llvm_unreachable("FIXME: Not yet implemented!");
268 }
269
270 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, unsigned Size,
271                                        unsigned Pow2Alignment) {
272   llvm_unreachable("FIXME: Not yet implemented!");
273 }
274
275 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
276                                    unsigned Size, unsigned Pow2Alignment) {
277   llvm_unreachable("FIXME: Not yet implemented!");
278 }
279
280 void MCMachOStreamer::EmitBytes(const StringRef &Data) {
281   MCDataFragment *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
282   if (!DF)
283     DF = new MCDataFragment(CurSectionData);
284   DF->getContents().append(Data.begin(), Data.end());
285 }
286
287 void MCMachOStreamer::EmitValue(const MCValue &Value, unsigned Size) {
288   new MCFillFragment(AddValueSymbols(Value), Size, 1, CurSectionData);
289 }
290
291 void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
292                                            int64_t Value, unsigned ValueSize,
293                                            unsigned MaxBytesToEmit) {
294   if (MaxBytesToEmit == 0)
295     MaxBytesToEmit = ByteAlignment;
296   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
297                       CurSectionData);
298
299   // Update the maximum alignment on the current section if necessary.
300   if (ByteAlignment > CurSectionData->getAlignment())
301     CurSectionData->setAlignment(ByteAlignment);
302 }
303
304 void MCMachOStreamer::EmitValueToOffset(const MCValue &Offset,
305                                         unsigned char Value) {
306   new MCOrgFragment(AddValueSymbols(Offset), Value, CurSectionData);
307 }
308
309 void MCMachOStreamer::EmitInstruction(const MCInst &Inst) {
310   // Scan for values.
311   for (unsigned i = 0; i != Inst.getNumOperands(); ++i)
312     if (Inst.getOperand(i).isMCValue())
313       AddValueSymbols(Inst.getOperand(i).getMCValue());
314
315   if (!Emitter)
316     llvm_unreachable("no code emitter available!");
317
318   // FIXME: Relocations!
319   SmallString<256> Code;
320   raw_svector_ostream VecOS(Code);
321   Emitter->EncodeInstruction(Inst, VecOS);
322   EmitBytes(VecOS.str());
323 }
324
325 void MCMachOStreamer::Finish() {
326   Assembler.Finish();
327 }
328
329 MCStreamer *llvm::createMachOStreamer(MCContext &Context, raw_ostream &OS,
330                                       MCCodeEmitter *CE) {
331   return new MCMachOStreamer(Context, OS, CE);
332 }