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