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