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