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