Roll out r126425 and r126450 to see if it fixes the failures on the buildbots.
[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 #include "llvm/Target/TargetAsmInfo.h"
28
29 using namespace llvm;
30
31 namespace {
32
33 class MCMachOStreamer : public MCObjectStreamer {
34 private:
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) {}
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 EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
78                                     unsigned ValueSize = 1,
79                                     unsigned MaxBytesToEmit = 0);
80   virtual void EmitCodeAlignment(unsigned ByteAlignment,
81                                  unsigned MaxBytesToEmit = 0);
82
83   virtual void EmitFileDirective(StringRef Filename) {
84     // FIXME: Just ignore the .file; it isn't important enough to fail the
85     // entire assembly.
86
87     //report_fatal_error("unsupported directive: '.file'");
88   }
89
90   virtual void Finish();
91
92   /// @}
93 };
94
95 } // end anonymous namespace.
96
97 void MCMachOStreamer::InitSections() {
98   SwitchSection(getContext().getMachOSection("__TEXT", "__text",
99                                     MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
100                                     0, SectionKind::getText()));
101
102 }
103
104 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
105   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
106
107   // isSymbolLinkerVisible uses the section.
108   Symbol->setSection(*getCurrentSection());
109   // We have to create a new fragment if this is an atom defining symbol,
110   // fragments cannot span atoms.
111   if (getAssembler().isSymbolLinkerVisible(*Symbol))
112     new MCDataFragment(getCurrentSectionData());
113
114   MCObjectStreamer::EmitLabel(Symbol);
115
116   MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
117   // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
118   // to clear the weak reference and weak definition bits too, but the
119   // implementation was buggy. For now we just try to match 'as', for
120   // diffability.
121   //
122   // FIXME: Cleanup this code, these bits should be emitted based on semantic
123   // properties, not on the order of definition, etc.
124   SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
125 }
126
127 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
128   // Let the target do whatever target specific stuff it needs to do.
129   getAssembler().getBackend().HandleAssemblerFlag(Flag);
130   // Do any generic stuff we need to do.
131   switch (Flag) {
132   case MCAF_SyntaxUnified: return; // no-op here.
133   case MCAF_Code16: return; // no-op here.
134   case MCAF_Code32: return; // no-op here.
135   case MCAF_SubsectionsViaSymbols:
136     getAssembler().setSubsectionsViaSymbols(true);
137     return;
138   default:
139     llvm_unreachable("invalid assembler flag!");
140   }
141 }
142
143 void MCMachOStreamer::EmitThumbFunc(MCSymbol *Symbol) {
144   // FIXME: Flag the function ISA as thumb with DW_AT_APPLE_isa.
145
146   // Remember that the function is a thumb function. Fixup and relocation
147   // values will need adjusted.
148   getAssembler().setIsThumbFunc(Symbol);
149
150   // Mark the thumb bit on the symbol.
151   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
152   SD.setFlags(SD.getFlags() | SF_ThumbFunc);
153 }
154
155 void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
156   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
157   // MCObjectStreamer.
158   // FIXME: Lift context changes into super class.
159   getAssembler().getOrCreateSymbolData(*Symbol);
160   Symbol->setVariableValue(AddValueSymbols(Value));
161 }
162
163 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
164                                           MCSymbolAttr Attribute) {
165   // Indirect symbols are handled differently, to match how 'as' handles
166   // them. This makes writing matching .o files easier.
167   if (Attribute == MCSA_IndirectSymbol) {
168     // Note that we intentionally cannot use the symbol data here; this is
169     // important for matching the string table that 'as' generates.
170     IndirectSymbolData ISD;
171     ISD.Symbol = Symbol;
172     ISD.SectionData = getCurrentSectionData();
173     getAssembler().getIndirectSymbols().push_back(ISD);
174     return;
175   }
176
177   // Adding a symbol attribute always introduces the symbol, note that an
178   // important side effect of calling getOrCreateSymbolData here is to register
179   // the symbol with the assembler.
180   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
181
182   // The implementation of symbol attributes is designed to match 'as', but it
183   // leaves much to desired. It doesn't really make sense to arbitrarily add and
184   // remove flags, but 'as' allows this (in particular, see .desc).
185   //
186   // In the future it might be worth trying to make these operations more well
187   // defined.
188   switch (Attribute) {
189   case MCSA_Invalid:
190   case MCSA_ELF_TypeFunction:
191   case MCSA_ELF_TypeIndFunction:
192   case MCSA_ELF_TypeObject:
193   case MCSA_ELF_TypeTLS:
194   case MCSA_ELF_TypeCommon:
195   case MCSA_ELF_TypeNoType:
196   case MCSA_ELF_TypeGnuUniqueObject:
197   case MCSA_IndirectSymbol:
198   case MCSA_Hidden:
199   case MCSA_Internal:
200   case MCSA_Protected:
201   case MCSA_Weak:
202   case MCSA_Local:
203     assert(0 && "Invalid symbol attribute for Mach-O!");
204     break;
205
206   case MCSA_Global:
207     SD.setExternal(true);
208     // This effectively clears the undefined lazy bit, in Darwin 'as', although
209     // it isn't very consistent because it implements this as part of symbol
210     // lookup.
211     //
212     // FIXME: Cleanup this code, these bits should be emitted based on semantic
213     // properties, not on the order of definition, etc.
214     SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
215     break;
216
217   case MCSA_LazyReference:
218     // FIXME: This requires -dynamic.
219     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
220     if (Symbol->isUndefined())
221       SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
222     break;
223
224     // Since .reference sets the no dead strip bit, it is equivalent to
225     // .no_dead_strip in practice.
226   case MCSA_Reference:
227   case MCSA_NoDeadStrip:
228     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
229     break;
230
231   case MCSA_SymbolResolver:
232     SD.setFlags(SD.getFlags() | SF_SymbolResolver);
233     break;
234
235   case MCSA_PrivateExtern:
236     SD.setExternal(true);
237     SD.setPrivateExtern(true);
238     break;
239
240   case MCSA_WeakReference:
241     // FIXME: This requires -dynamic.
242     if (Symbol->isUndefined())
243       SD.setFlags(SD.getFlags() | SF_WeakReference);
244     break;
245
246   case MCSA_WeakDefinition:
247     // FIXME: 'as' enforces that this is defined and global. The manual claims
248     // it has to be in a coalesced section, but this isn't enforced.
249     SD.setFlags(SD.getFlags() | SF_WeakDefinition);
250     break;
251
252   case MCSA_WeakDefAutoPrivate:
253     SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
254     break;
255   }
256 }
257
258 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
259   // Encode the 'desc' value into the lowest implementation defined bits.
260   assert(DescValue == (DescValue & SF_DescFlagsMask) &&
261          "Invalid .desc value!");
262   getAssembler().getOrCreateSymbolData(*Symbol).setFlags(
263     DescValue & SF_DescFlagsMask);
264 }
265
266 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
267                                        unsigned ByteAlignment) {
268   // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
269   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
270
271   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
272   SD.setExternal(true);
273   SD.setCommon(Size, ByteAlignment);
274 }
275
276 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
277                                    unsigned Size, unsigned ByteAlignment) {
278   MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
279
280   // The symbol may not be present, which only creates the section.
281   if (!Symbol)
282     return;
283
284   // FIXME: Assert that this section has the zerofill type.
285
286   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
287
288   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
289
290   // Emit an align fragment if necessary.
291   if (ByteAlignment != 1)
292     new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
293
294   MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
295   SD.setFragment(F);
296
297   Symbol->setSection(*Section);
298
299   // Update the maximum alignment on the zero fill section if necessary.
300   if (ByteAlignment > SectData.getAlignment())
301     SectData.setAlignment(ByteAlignment);
302 }
303
304 // This should always be called with the thread local bss section.  Like the
305 // .zerofill directive this doesn't actually switch sections on us.
306 void MCMachOStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
307                                      uint64_t Size, unsigned ByteAlignment) {
308   EmitZerofill(Section, Symbol, Size, ByteAlignment);
309   return;
310 }
311
312 void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
313   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
314   // MCObjectStreamer.
315   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
316 }
317
318 void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
319                                            int64_t Value, unsigned ValueSize,
320                                            unsigned MaxBytesToEmit) {
321   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
322   // MCObjectStreamer.
323   if (MaxBytesToEmit == 0)
324     MaxBytesToEmit = ByteAlignment;
325   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
326                       getCurrentSectionData());
327
328   // Update the maximum alignment on the current section if necessary.
329   if (ByteAlignment > getCurrentSectionData()->getAlignment())
330     getCurrentSectionData()->setAlignment(ByteAlignment);
331 }
332
333 void MCMachOStreamer::EmitCodeAlignment(unsigned ByteAlignment,
334                                         unsigned MaxBytesToEmit) {
335   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
336   // MCObjectStreamer.
337   if (MaxBytesToEmit == 0)
338     MaxBytesToEmit = ByteAlignment;
339   MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
340                                            getCurrentSectionData());
341   F->setEmitNops(true);
342
343   // Update the maximum alignment on the current section if necessary.
344   if (ByteAlignment > getCurrentSectionData()->getAlignment())
345     getCurrentSectionData()->setAlignment(ByteAlignment);
346 }
347
348 void MCMachOStreamer::EmitInstToData(const MCInst &Inst) {
349   MCDataFragment *DF = getOrCreateDataFragment();
350
351   SmallVector<MCFixup, 4> Fixups;
352   SmallString<256> Code;
353   raw_svector_ostream VecOS(Code);
354   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
355   VecOS.flush();
356
357   // Add the fixups and data.
358   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
359     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
360     DF->addFixup(Fixups[i]);
361   }
362   DF->getContents().append(Code.begin(), Code.end());
363 }
364
365 void MCMachOStreamer::Finish() {
366   // We have to set the fragment atom associations so we can relax properly for
367   // Mach-O.
368
369   // First, scan the symbol table to build a lookup table from fragments to
370   // defining symbols.
371   DenseMap<const MCFragment*, MCSymbolData*> DefiningSymbolMap;
372   for (MCAssembler::symbol_iterator it = getAssembler().symbol_begin(),
373          ie = getAssembler().symbol_end(); it != ie; ++it) {
374     if (getAssembler().isSymbolLinkerVisible(it->getSymbol()) &&
375         it->getFragment()) {
376       // An atom defining symbol should never be internal to a fragment.
377       assert(it->getOffset() == 0 && "Invalid offset in atom defining symbol!");
378       DefiningSymbolMap[it->getFragment()] = it;
379     }
380   }
381
382   // Set the fragment atom associations by tracking the last seen atom defining
383   // symbol.
384   for (MCAssembler::iterator it = getAssembler().begin(),
385          ie = getAssembler().end(); it != ie; ++it) {
386     MCSymbolData *CurrentAtom = 0;
387     for (MCSectionData::iterator it2 = it->begin(),
388            ie2 = it->end(); it2 != ie2; ++it2) {
389       if (MCSymbolData *SD = DefiningSymbolMap.lookup(it2))
390         CurrentAtom = SD;
391       it2->setAtom(CurrentAtom);
392     }
393   }
394
395   this->MCObjectStreamer::Finish();
396 }
397
398 MCStreamer *llvm::createMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
399                                       raw_ostream &OS, MCCodeEmitter *CE,
400                                       bool RelaxAll) {
401   MCMachOStreamer *S = new MCMachOStreamer(Context, TAB, OS, CE);
402   if (RelaxAll)
403     S->getAssembler().setRelaxAll(true);
404   return S;
405 }