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