MC: Provide MCAssembler with a TargetAsmBackend.
[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/MCSection.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/raw_ostream.h"
21 using namespace llvm;
22
23 namespace {
24
25 class MCMachOStreamer : public MCStreamer {
26   /// SymbolFlags - We store the value for the 'desc' symbol field in the lowest
27   /// 16 bits of the implementation defined flags.
28   enum SymbolFlags { // See <mach-o/nlist.h>.
29     SF_DescFlagsMask                        = 0xFFFF,
30
31     // Reference type flags.
32     SF_ReferenceTypeMask                    = 0x0007,
33     SF_ReferenceTypeUndefinedNonLazy        = 0x0000,
34     SF_ReferenceTypeUndefinedLazy           = 0x0001,
35     SF_ReferenceTypeDefined                 = 0x0002,
36     SF_ReferenceTypePrivateDefined          = 0x0003,
37     SF_ReferenceTypePrivateUndefinedNonLazy = 0x0004,
38     SF_ReferenceTypePrivateUndefinedLazy    = 0x0005,
39
40     // Other 'desc' flags.
41     SF_NoDeadStrip                          = 0x0020,
42     SF_WeakReference                        = 0x0040,
43     SF_WeakDefinition                       = 0x0080
44   };
45
46 private:
47   MCAssembler Assembler;
48   MCCodeEmitter *Emitter;
49   MCSectionData *CurSectionData;
50
51 private:
52   MCFragment *getCurrentFragment() const {
53     assert(CurSectionData && "No current section!");
54
55     if (!CurSectionData->empty())
56       return &CurSectionData->getFragmentList().back();
57
58     return 0;
59   }
60
61 public:
62   MCMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
63                   raw_ostream &_OS, MCCodeEmitter *_Emitter)
64     : MCStreamer(Context), Assembler(Context, TAB, _OS), Emitter(_Emitter),
65       CurSectionData(0) {}
66   ~MCMachOStreamer() {}
67
68   const MCExpr *AddValueSymbols(const MCExpr *Value) {
69     switch (Value->getKind()) {
70     case MCExpr::Target: assert(0 && "Can't handle target exprs yet!");
71     case MCExpr::Constant:
72       break;
73
74     case MCExpr::Binary: {
75       const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
76       AddValueSymbols(BE->getLHS());
77       AddValueSymbols(BE->getRHS());
78       break;
79     }
80
81     case MCExpr::SymbolRef:
82       Assembler.getOrCreateSymbolData(
83         cast<MCSymbolRefExpr>(Value)->getSymbol());
84       break;
85
86     case MCExpr::Unary:
87       AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
88       break;
89     }
90
91     return Value;
92   }
93
94   /// @name MCStreamer Interface
95   /// @{
96
97   virtual void SwitchSection(const MCSection *Section);
98   virtual void EmitLabel(MCSymbol *Symbol);
99   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
100   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
101   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
102   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
103   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
104                                 unsigned ByteAlignment);
105   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
106     assert(0 && "macho doesn't support this directive");
107   }
108   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
109     assert(0 && "macho doesn't support this directive");
110   }
111   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
112                             unsigned Size = 0, unsigned ByteAlignment = 0);
113   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
114   virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
115   virtual void EmitGPRel32Value(const MCExpr *Value) {
116     assert(0 && "macho doesn't support this directive");
117   }
118   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
119                                     unsigned ValueSize = 1,
120                                     unsigned MaxBytesToEmit = 0);
121   virtual void EmitCodeAlignment(unsigned ByteAlignment,
122                                  unsigned MaxBytesToEmit = 0);
123   virtual void EmitValueToOffset(const MCExpr *Offset,
124                                  unsigned char Value = 0);
125   
126   virtual void EmitFileDirective(StringRef Filename) {
127     errs() << "FIXME: MCMachoStreamer:EmitFileDirective not implemented\n";
128   }
129   virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
130     errs() << "FIXME: MCMachoStreamer:EmitDwarfFileDirective not implemented\n";
131   }
132   
133   virtual void EmitInstruction(const MCInst &Inst);
134   virtual void Finish();
135
136   /// @}
137 };
138
139 } // end anonymous namespace.
140
141 void MCMachOStreamer::SwitchSection(const MCSection *Section) {
142   assert(Section && "Cannot switch to a null section!");
143   
144   // If already in this section, then this is a noop.
145   if (Section == CurSection) return;
146
147   CurSection = Section;
148   CurSectionData = &Assembler.getOrCreateSectionData(*Section);
149 }
150
151 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
152   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
153
154   // FIXME: We should also use offsets into Fill fragments.
155   MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
156   if (!F)
157     F = new MCDataFragment(CurSectionData);
158
159   MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
160   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
161   SD.setFragment(F);
162   SD.setOffset(F->getContents().size());
163
164   // This causes the reference type and weak reference flags to be cleared.
165   SD.setFlags(SD.getFlags() & ~(SF_WeakReference | SF_ReferenceTypeMask));
166   
167   Symbol->setSection(*CurSection);
168 }
169
170 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
171   switch (Flag) {
172   case MCAF_SubsectionsViaSymbols:
173     Assembler.setSubsectionsViaSymbols(true);
174     return;
175   }
176
177   assert(0 && "invalid assembler flag!");
178 }
179
180 void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
181   // Only absolute symbols can be redefined.
182   assert((Symbol->isUndefined() || Symbol->isAbsolute()) &&
183          "Cannot define a symbol twice!");
184
185   // FIXME: Lift context changes into super class.
186   // FIXME: Set associated section.
187   Symbol->setValue(Value);
188 }
189
190 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
191                                           MCSymbolAttr Attribute) {
192   // Indirect symbols are handled differently, to match how 'as' handles
193   // them. This makes writing matching .o files easier.
194   if (Attribute == MCSA_IndirectSymbol) {
195     // Note that we intentionally cannot use the symbol data here; this is
196     // important for matching the string table that 'as' generates.
197     IndirectSymbolData ISD;
198     ISD.Symbol = Symbol;
199     ISD.SectionData = CurSectionData;
200     Assembler.getIndirectSymbols().push_back(ISD);
201     return;
202   }
203
204   // Adding a symbol attribute always introduces the symbol, note that an
205   // important side effect of calling getOrCreateSymbolData here is to register
206   // the symbol with the assembler.
207   MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
208
209   // The implementation of symbol attributes is designed to match 'as', but it
210   // leaves much to desired. It doesn't really make sense to arbitrarily add and
211   // remove flags, but 'as' allows this (in particular, see .desc).
212   //
213   // In the future it might be worth trying to make these operations more well
214   // defined.
215   switch (Attribute) {
216   case MCSA_Invalid:
217   case MCSA_ELF_TypeFunction:
218   case MCSA_ELF_TypeIndFunction:
219   case MCSA_ELF_TypeObject:
220   case MCSA_ELF_TypeTLS:
221   case MCSA_ELF_TypeCommon:
222   case MCSA_ELF_TypeNoType:
223   case MCSA_IndirectSymbol:
224   case MCSA_Hidden:
225   case MCSA_Internal:
226   case MCSA_Protected:
227   case MCSA_Weak:
228   case MCSA_Local:
229     assert(0 && "Invalid symbol attribute for Mach-O!");
230     break;
231
232   case MCSA_Global:
233     SD.setExternal(true);
234     break;
235
236   case MCSA_LazyReference:
237     // FIXME: This requires -dynamic.
238     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
239     if (Symbol->isUndefined())
240       SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
241     break;
242
243     // Since .reference sets the no dead strip bit, it is equivalent to
244     // .no_dead_strip in practice.
245   case MCSA_Reference:
246   case MCSA_NoDeadStrip:
247     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
248     break;
249
250   case MCSA_PrivateExtern:
251     SD.setExternal(true);
252     SD.setPrivateExtern(true);
253     break;
254
255   case MCSA_WeakReference:
256     // FIXME: This requires -dynamic.
257     if (Symbol->isUndefined())
258       SD.setFlags(SD.getFlags() | SF_WeakReference);
259     break;
260
261   case MCSA_WeakDefinition:
262     // FIXME: 'as' enforces that this is defined and global. The manual claims
263     // it has to be in a coalesced section, but this isn't enforced.
264     SD.setFlags(SD.getFlags() | SF_WeakDefinition);
265     break;
266   }
267 }
268
269 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
270   // Encode the 'desc' value into the lowest implementation defined bits.
271   assert(DescValue == (DescValue & SF_DescFlagsMask) && 
272          "Invalid .desc value!");
273   Assembler.getOrCreateSymbolData(*Symbol).setFlags(DescValue&SF_DescFlagsMask);
274 }
275
276 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
277                                        unsigned ByteAlignment) {
278   // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
279   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
280
281   MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
282   SD.setExternal(true);
283   SD.setCommon(Size, ByteAlignment);
284 }
285
286 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
287                                    unsigned Size, unsigned ByteAlignment) {
288   MCSectionData &SectData = Assembler.getOrCreateSectionData(*Section);
289
290   // The symbol may not be present, which only creates the section.
291   if (!Symbol)
292     return;
293
294   // FIXME: Assert that this section has the zerofill type.
295
296   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
297
298   MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
299
300   MCFragment *F = new MCZeroFillFragment(Size, ByteAlignment, &SectData);
301   SD.setFragment(F);
302
303   Symbol->setSection(*Section);
304
305   // Update the maximum alignment on the zero fill section if necessary.
306   if (ByteAlignment > SectData.getAlignment())
307     SectData.setAlignment(ByteAlignment);
308 }
309
310 void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
311   MCDataFragment *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
312   if (!DF)
313     DF = new MCDataFragment(CurSectionData);
314   DF->getContents().append(Data.begin(), Data.end());
315 }
316
317 void MCMachOStreamer::EmitValue(const MCExpr *Value, unsigned Size,
318                                 unsigned AddrSpace) {
319   MCDataFragment *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
320   if (!DF)
321     DF = new MCDataFragment(CurSectionData);
322
323   // Avoid fixups when possible.
324   int64_t AbsValue;
325   if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
326     // FIXME: Endianness assumption.
327     for (unsigned i = 0; i != Size; ++i)
328       DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
329   } else {
330     DF->getFixups().push_back(MCAsmFixup(DF->getContents().size(),
331                                          *AddValueSymbols(Value),
332                                          MCFixup::getKindForSize(Size)));
333     DF->getContents().resize(DF->getContents().size() + Size, 0);
334   }
335 }
336
337 void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
338                                            int64_t Value, unsigned ValueSize,
339                                            unsigned MaxBytesToEmit) {
340   if (MaxBytesToEmit == 0)
341     MaxBytesToEmit = ByteAlignment;
342   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
343                       false /* EmitNops */, CurSectionData);
344
345   // Update the maximum alignment on the current section if necessary.
346   if (ByteAlignment > CurSectionData->getAlignment())
347     CurSectionData->setAlignment(ByteAlignment);
348 }
349
350 void MCMachOStreamer::EmitCodeAlignment(unsigned ByteAlignment,
351                                         unsigned MaxBytesToEmit) {
352   if (MaxBytesToEmit == 0)
353     MaxBytesToEmit = ByteAlignment;
354   // FIXME the 0x90 is the default x86 1 byte nop opcode.
355   new MCAlignFragment(ByteAlignment, 0x90, 1, MaxBytesToEmit,
356                       true /* EmitNops */, CurSectionData);
357
358   // Update the maximum alignment on the current section if necessary.
359   if (ByteAlignment > CurSectionData->getAlignment())
360     CurSectionData->setAlignment(ByteAlignment);
361 }
362
363 void MCMachOStreamer::EmitValueToOffset(const MCExpr *Offset,
364                                         unsigned char Value) {
365   new MCOrgFragment(*Offset, Value, CurSectionData);
366 }
367
368 void MCMachOStreamer::EmitInstruction(const MCInst &Inst) {
369   // Scan for values.
370   for (unsigned i = 0; i != Inst.getNumOperands(); ++i)
371     if (Inst.getOperand(i).isExpr())
372       AddValueSymbols(Inst.getOperand(i).getExpr());
373
374   if (!Emitter)
375     llvm_unreachable("no code emitter available!");
376
377   CurSectionData->setHasInstructions(true);
378
379   SmallVector<MCFixup, 4> Fixups;
380   SmallString<256> Code;
381   raw_svector_ostream VecOS(Code);
382   Emitter->EncodeInstruction(Inst, VecOS, Fixups);
383   VecOS.flush();
384
385   // Add the fixups and data.
386   MCDataFragment *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
387   if (!DF)
388     DF = new MCDataFragment(CurSectionData);
389   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
390     MCFixup &F = Fixups[i];
391     DF->getFixups().push_back(MCAsmFixup(DF->getContents().size()+F.getOffset(),
392                                          *F.getValue(),
393                                          F.getKind()));
394   }
395   DF->getContents().append(Code.begin(), Code.end());
396 }
397
398 void MCMachOStreamer::Finish() {
399   Assembler.Finish();
400 }
401
402 MCStreamer *llvm::createMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
403                                       raw_ostream &OS, MCCodeEmitter *CE) {
404   return new MCMachOStreamer(Context, TAB, OS, CE);
405 }