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