aa8b1ca1deb8a0a069e5df444aeacb62a219dfbd
[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/MC/MCMachOSymbolFlags.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Target/TargetAsmBackend.h"
23
24 using namespace llvm;
25
26 namespace {
27
28 class MCMachOStreamer : public MCStreamer {
29
30 private:
31   MCAssembler Assembler;
32   MCSectionData *CurSectionData;
33
34 private:
35   MCFragment *getCurrentFragment() const {
36     assert(CurSectionData && "No current section!");
37
38     if (!CurSectionData->empty())
39       return &CurSectionData->getFragmentList().back();
40
41     return 0;
42   }
43
44   /// Get a data fragment to write into, creating a new one if the current
45   /// fragment is not a data fragment.
46   MCDataFragment *getOrCreateDataFragment() const {
47     MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
48     if (!F)
49       F = new MCDataFragment(CurSectionData);
50     return F;
51   }
52
53 public:
54   MCMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
55                   raw_ostream &_OS, MCCodeEmitter *_Emitter)
56     : MCStreamer(Context), Assembler(Context, TAB, *_Emitter, _OS),
57       CurSectionData(0) {}
58   ~MCMachOStreamer() {}
59
60   MCAssembler &getAssembler() { return Assembler; }
61
62   const MCExpr *AddValueSymbols(const MCExpr *Value) {
63     switch (Value->getKind()) {
64     case MCExpr::Target: assert(0 && "Can't handle target exprs yet!");
65     case MCExpr::Constant:
66       break;
67
68     case MCExpr::Binary: {
69       const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
70       AddValueSymbols(BE->getLHS());
71       AddValueSymbols(BE->getRHS());
72       break;
73     }
74
75     case MCExpr::SymbolRef:
76       Assembler.getOrCreateSymbolData(
77         cast<MCSymbolRefExpr>(Value)->getSymbol());
78       break;
79
80     case MCExpr::Unary:
81       AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
82       break;
83     }
84
85     return Value;
86   }
87
88   /// @name MCStreamer Interface
89   /// @{
90
91   virtual void SwitchSection(const MCSection *Section);
92   virtual void EmitLabel(MCSymbol *Symbol);
93   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
94   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
95   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
96   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
97   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
98                                 unsigned ByteAlignment);
99   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
100     assert(0 && "macho doesn't support this directive");
101   }
102   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
103     assert(0 && "macho doesn't support this directive");
104   }
105   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
106                             unsigned Size = 0, unsigned ByteAlignment = 0);
107   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
108   virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
109   virtual void EmitGPRel32Value(const MCExpr *Value) {
110     assert(0 && "macho doesn't support this directive");
111   }
112   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
113                                     unsigned ValueSize = 1,
114                                     unsigned MaxBytesToEmit = 0);
115   virtual void EmitCodeAlignment(unsigned ByteAlignment,
116                                  unsigned MaxBytesToEmit = 0);
117   virtual void EmitValueToOffset(const MCExpr *Offset,
118                                  unsigned char Value = 0);
119   
120   virtual void EmitFileDirective(StringRef Filename) {
121     errs() << "FIXME: MCMachoStreamer:EmitFileDirective not implemented\n";
122   }
123   virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
124     errs() << "FIXME: MCMachoStreamer:EmitDwarfFileDirective not implemented\n";
125   }
126   
127   virtual void EmitInstruction(const MCInst &Inst);
128   virtual void Finish();
129
130   /// @}
131 };
132
133 } // end anonymous namespace.
134
135 void MCMachOStreamer::SwitchSection(const MCSection *Section) {
136   assert(Section && "Cannot switch to a null section!");
137   
138   // If already in this section, then this is a noop.
139   if (Section == CurSection) return;
140
141   CurSection = Section;
142   CurSectionData = &Assembler.getOrCreateSectionData(*Section);
143 }
144
145 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
146   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
147   assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
148   assert(CurSection && "Cannot emit before setting section!");
149
150   // FIXME: This is wasteful, we don't necessarily need to create a data
151   // fragment. Instead, we should mark the symbol as pointing into the data
152   // fragment if it exists, otherwise we should just queue the label and set its
153   // fragment pointer when we emit the next fragment.
154   MCDataFragment *F = getOrCreateDataFragment();
155   MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
156   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
157   SD.setFragment(F);
158   SD.setOffset(F->getContents().size());
159
160   // This causes the reference type and weak reference flags to be cleared.
161   SD.setFlags(SD.getFlags() & ~(SF_WeakReference | SF_ReferenceTypeMask));
162   
163   Symbol->setSection(*CurSection);
164 }
165
166 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
167   switch (Flag) {
168   case MCAF_SubsectionsViaSymbols:
169     Assembler.setSubsectionsViaSymbols(true);
170     return;
171   }
172
173   assert(0 && "invalid assembler flag!");
174 }
175
176 void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
177   // FIXME: Lift context changes into super class.
178   Symbol->setVariableValue(AddValueSymbols(Value));
179 }
180
181 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
182                                           MCSymbolAttr Attribute) {
183   // Indirect symbols are handled differently, to match how 'as' handles
184   // them. This makes writing matching .o files easier.
185   if (Attribute == MCSA_IndirectSymbol) {
186     // Note that we intentionally cannot use the symbol data here; this is
187     // important for matching the string table that 'as' generates.
188     IndirectSymbolData ISD;
189     ISD.Symbol = Symbol;
190     ISD.SectionData = CurSectionData;
191     Assembler.getIndirectSymbols().push_back(ISD);
192     return;
193   }
194
195   // Adding a symbol attribute always introduces the symbol, note that an
196   // important side effect of calling getOrCreateSymbolData here is to register
197   // the symbol with the assembler.
198   MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
199
200   // The implementation of symbol attributes is designed to match 'as', but it
201   // leaves much to desired. It doesn't really make sense to arbitrarily add and
202   // remove flags, but 'as' allows this (in particular, see .desc).
203   //
204   // In the future it might be worth trying to make these operations more well
205   // defined.
206   switch (Attribute) {
207   case MCSA_Invalid:
208   case MCSA_ELF_TypeFunction:
209   case MCSA_ELF_TypeIndFunction:
210   case MCSA_ELF_TypeObject:
211   case MCSA_ELF_TypeTLS:
212   case MCSA_ELF_TypeCommon:
213   case MCSA_ELF_TypeNoType:
214   case MCSA_IndirectSymbol:
215   case MCSA_Hidden:
216   case MCSA_Internal:
217   case MCSA_Protected:
218   case MCSA_Weak:
219   case MCSA_Local:
220     assert(0 && "Invalid symbol attribute for Mach-O!");
221     break;
222
223   case MCSA_Global:
224     SD.setExternal(true);
225     break;
226
227   case MCSA_LazyReference:
228     // FIXME: This requires -dynamic.
229     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
230     if (Symbol->isUndefined())
231       SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
232     break;
233
234     // Since .reference sets the no dead strip bit, it is equivalent to
235     // .no_dead_strip in practice.
236   case MCSA_Reference:
237   case MCSA_NoDeadStrip:
238     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
239     break;
240
241   case MCSA_PrivateExtern:
242     SD.setExternal(true);
243     SD.setPrivateExtern(true);
244     break;
245
246   case MCSA_WeakReference:
247     // FIXME: This requires -dynamic.
248     if (Symbol->isUndefined())
249       SD.setFlags(SD.getFlags() | SF_WeakReference);
250     break;
251
252   case MCSA_WeakDefinition:
253     // FIXME: 'as' enforces that this is defined and global. The manual claims
254     // it has to be in a coalesced section, but this isn't enforced.
255     SD.setFlags(SD.getFlags() | SF_WeakDefinition);
256     break;
257   }
258 }
259
260 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
261   // Encode the 'desc' value into the lowest implementation defined bits.
262   assert(DescValue == (DescValue & SF_DescFlagsMask) && 
263          "Invalid .desc value!");
264   Assembler.getOrCreateSymbolData(*Symbol).setFlags(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 = Assembler.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 = Assembler.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 = Assembler.getOrCreateSymbolData(*Symbol);
290
291   MCFragment *F = new MCZeroFillFragment(Size, ByteAlignment, &SectData);
292   SD.setFragment(F);
293
294   Symbol->setSection(*Section);
295
296   // Update the maximum alignment on the zero fill section if necessary.
297   if (ByteAlignment > SectData.getAlignment())
298     SectData.setAlignment(ByteAlignment);
299 }
300
301 void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
302   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
303 }
304
305 void MCMachOStreamer::EmitValue(const MCExpr *Value, unsigned Size,
306                                 unsigned AddrSpace) {
307   MCDataFragment *DF = getOrCreateDataFragment();
308
309   // Avoid fixups when possible.
310   int64_t AbsValue;
311   if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
312     // FIXME: Endianness assumption.
313     for (unsigned i = 0; i != Size; ++i)
314       DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
315   } else {
316     DF->addFixup(MCAsmFixup(DF->getContents().size(), *AddValueSymbols(Value),
317                             MCFixup::getKindForSize(Size)));
318     DF->getContents().resize(DF->getContents().size() + Size, 0);
319   }
320 }
321
322 void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
323                                            int64_t Value, unsigned ValueSize,
324                                            unsigned MaxBytesToEmit) {
325   if (MaxBytesToEmit == 0)
326     MaxBytesToEmit = ByteAlignment;
327   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
328                       false /* EmitNops */, CurSectionData);
329
330   // Update the maximum alignment on the current section if necessary.
331   if (ByteAlignment > CurSectionData->getAlignment())
332     CurSectionData->setAlignment(ByteAlignment);
333 }
334
335 void MCMachOStreamer::EmitCodeAlignment(unsigned ByteAlignment,
336                                         unsigned MaxBytesToEmit) {
337   if (MaxBytesToEmit == 0)
338     MaxBytesToEmit = ByteAlignment;
339   new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
340                       true /* EmitNops */, CurSectionData);
341
342   // Update the maximum alignment on the current section if necessary.
343   if (ByteAlignment > CurSectionData->getAlignment())
344     CurSectionData->setAlignment(ByteAlignment);
345 }
346
347 void MCMachOStreamer::EmitValueToOffset(const MCExpr *Offset,
348                                         unsigned char Value) {
349   new MCOrgFragment(*Offset, Value, CurSectionData);
350 }
351
352 void MCMachOStreamer::EmitInstruction(const MCInst &Inst) {
353   // Scan for values.
354   for (unsigned i = 0; i != Inst.getNumOperands(); ++i)
355     if (Inst.getOperand(i).isExpr())
356       AddValueSymbols(Inst.getOperand(i).getExpr());
357
358   CurSectionData->setHasInstructions(true);
359
360   // FIXME-PERF: Common case is that we don't need to relax, encode directly
361   // onto the data fragments buffers.
362
363   SmallVector<MCFixup, 4> Fixups;
364   SmallString<256> Code;
365   raw_svector_ostream VecOS(Code);
366   Assembler.getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
367   VecOS.flush();
368
369   // FIXME: Eliminate this copy.
370   SmallVector<MCAsmFixup, 4> AsmFixups;
371   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
372     MCFixup &F = Fixups[i];
373     AsmFixups.push_back(MCAsmFixup(F.getOffset(), *F.getValue(),
374                                    F.getKind()));
375   }
376
377   // See if we might need to relax this instruction, if so it needs its own
378   // fragment.
379   //
380   // FIXME-PERF: Support target hook to do a fast path that avoids the encoder,
381   // when we can immediately tell that we will get something which might need
382   // relaxation (and compute its size).
383   //
384   // FIXME-PERF: We should also be smart about immediately relaxing instructions
385   // which we can already show will never possibly fit (we can also do a very
386   // good job of this before we do the first relaxation pass, because we have
387   // total knowledge about undefined symbols at that point). Even now, though,
388   // we can do a decent job, especially on Darwin where scattering means that we
389   // are going to often know that we can never fully resolve a fixup.
390   if (Assembler.getBackend().MayNeedRelaxation(Inst, AsmFixups)) {
391     MCInstFragment *IF = new MCInstFragment(Inst, CurSectionData);
392
393     // Add the fixups and data.
394     //
395     // FIXME: Revisit this design decision when relaxation is done, we may be
396     // able to get away with not storing any extra data in the MCInst.
397     IF->getCode() = Code;
398     IF->getFixups() = AsmFixups;
399
400     return;
401   }
402
403   // Add the fixups and data.
404   MCDataFragment *DF = getOrCreateDataFragment();
405   for (unsigned i = 0, e = AsmFixups.size(); i != e; ++i) {
406     AsmFixups[i].Offset += DF->getContents().size();
407     DF->addFixup(AsmFixups[i]);
408   }
409   DF->getContents().append(Code.begin(), Code.end());
410 }
411
412 void MCMachOStreamer::Finish() {
413   Assembler.Finish();
414 }
415
416 MCStreamer *llvm::createMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
417                                       raw_ostream &OS, MCCodeEmitter *CE,
418                                       bool RelaxAll) {
419   MCMachOStreamer *S = new MCMachOStreamer(Context, TAB, OS, CE);
420   if (RelaxAll)
421     S->getAssembler().setRelaxAll(true);
422   return S;
423 }