Move common symbol related information from MCSectionData to MCSymbol.
[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   MCSymbolData &SD =
176     getAssembler().getOrCreateSymbolData(*Symbol);
177   if (SD.isExternal())
178     EmitSymbolAttribute(EHSymbol, MCSA_Global);
179   if (SD.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   MCSymbolData &SD = Symbol->getData();
198   // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
199   // to clear the weak reference and weak definition bits too, but the
200   // implementation was buggy. For now we just try to match 'as', for
201   // diffability.
202   //
203   // FIXME: Cleanup this code, these bits should be emitted based on semantic
204   // properties, not on the order of definition, etc.
205   SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
206 }
207
208 void MCMachOStreamer::EmitDataRegion(DataRegionData::KindTy Kind) {
209   if (!getAssembler().getBackend().hasDataInCodeSupport())
210     return;
211   // Create a temporary label to mark the start of the data region.
212   MCSymbol *Start = getContext().createTempSymbol();
213   EmitLabel(Start);
214   // Record the region for the object writer to use.
215   DataRegionData Data = { Kind, Start, nullptr };
216   std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
217   Regions.push_back(Data);
218 }
219
220 void MCMachOStreamer::EmitDataRegionEnd() {
221   if (!getAssembler().getBackend().hasDataInCodeSupport())
222     return;
223   std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
224   assert(!Regions.empty() && "Mismatched .end_data_region!");
225   DataRegionData &Data = Regions.back();
226   assert(!Data.End && "Mismatched .end_data_region!");
227   // Create a temporary label to mark the end of the data region.
228   Data.End = getContext().createTempSymbol();
229   EmitLabel(Data.End);
230 }
231
232 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
233   // Let the target do whatever target specific stuff it needs to do.
234   getAssembler().getBackend().handleAssemblerFlag(Flag);
235   // Do any generic stuff we need to do.
236   switch (Flag) {
237   case MCAF_SyntaxUnified: return; // no-op here.
238   case MCAF_Code16: return; // Change parsing mode; no-op here.
239   case MCAF_Code32: return; // Change parsing mode; no-op here.
240   case MCAF_Code64: return; // Change parsing mode; no-op here.
241   case MCAF_SubsectionsViaSymbols:
242     getAssembler().setSubsectionsViaSymbols(true);
243     return;
244   }
245 }
246
247 void MCMachOStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
248   getAssembler().getLinkerOptions().push_back(Options);
249 }
250
251 void MCMachOStreamer::EmitDataRegion(MCDataRegionType Kind) {
252   switch (Kind) {
253   case MCDR_DataRegion:
254     EmitDataRegion(DataRegionData::Data);
255     return;
256   case MCDR_DataRegionJT8:
257     EmitDataRegion(DataRegionData::JumpTable8);
258     return;
259   case MCDR_DataRegionJT16:
260     EmitDataRegion(DataRegionData::JumpTable16);
261     return;
262   case MCDR_DataRegionJT32:
263     EmitDataRegion(DataRegionData::JumpTable32);
264     return;
265   case MCDR_DataRegionEnd:
266     EmitDataRegionEnd();
267     return;
268   }
269 }
270
271 void MCMachOStreamer::EmitVersionMin(MCVersionMinType Kind, unsigned Major,
272                                      unsigned Minor, unsigned Update) {
273   getAssembler().setVersionMinInfo(Kind, Major, Minor, Update);
274 }
275
276 void MCMachOStreamer::EmitThumbFunc(MCSymbol *Symbol) {
277   // Remember that the function is a thumb function. Fixup and relocation
278   // values will need adjusted.
279   getAssembler().setIsThumbFunc(Symbol);
280 }
281
282 bool MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
283                                           MCSymbolAttr Attribute) {
284   // Indirect symbols are handled differently, to match how 'as' handles
285   // them. This makes writing matching .o files easier.
286   if (Attribute == MCSA_IndirectSymbol) {
287     // Note that we intentionally cannot use the symbol data here; this is
288     // important for matching the string table that 'as' generates.
289     IndirectSymbolData ISD;
290     ISD.Symbol = Symbol;
291     ISD.Section = getCurrentSectionOnly();
292     getAssembler().getIndirectSymbols().push_back(ISD);
293     return true;
294   }
295
296   // Adding a symbol attribute always introduces the symbol, note that an
297   // important side effect of calling getOrCreateSymbolData here is to register
298   // the symbol with the assembler.
299   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
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     SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
333     break;
334
335   case MCSA_LazyReference:
336     // FIXME: This requires -dynamic.
337     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
338     if (Symbol->isUndefined())
339       SD.setFlags(SD.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     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
347     break;
348
349   case MCSA_SymbolResolver:
350     SD.setFlags(SD.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       SD.setFlags(SD.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     SD.setFlags(SD.getFlags() | SF_WeakDefinition);
368     break;
369
370   case MCSA_WeakDefAutoPrivate:
371     SD.setFlags(SD.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().getOrCreateSymbolData(*Symbol).setFlags(
383     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   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
394   SD.setExternal(true);
395   Symbol->setCommon(Size, ByteAlignment);
396 }
397
398 void MCMachOStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
399                                             unsigned ByteAlignment) {
400   // '.lcomm' is equivalent to '.zerofill'.
401   return EmitZerofill(getContext().getObjectFileInfo()->getDataBSSSection(),
402                       Symbol, Size, ByteAlignment);
403 }
404
405 void MCMachOStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol,
406                                    uint64_t Size, unsigned ByteAlignment) {
407   getAssembler().registerSection(*Section);
408
409   // The symbol may not be present, which only creates the section.
410   if (!Symbol)
411     return;
412
413   // On darwin all virtual sections have zerofill type.
414   assert(Section->isVirtualSection() && "Section does not have zerofill type!");
415
416   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
417
418   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
419
420   // Emit an align fragment if necessary.
421   if (ByteAlignment != 1)
422     new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, Section);
423
424   MCFragment *F = new MCFillFragment(0, 0, Size, Section);
425   SD.setFragment(F);
426
427   AssignSection(Symbol, Section);
428
429   // Update the maximum alignment on the zero fill section if necessary.
430   if (ByteAlignment > Section->getAlignment())
431     Section->setAlignment(ByteAlignment);
432 }
433
434 // This should always be called with the thread local bss section.  Like the
435 // .zerofill directive this doesn't actually switch sections on us.
436 void MCMachOStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
437                                      uint64_t Size, unsigned ByteAlignment) {
438   EmitZerofill(Section, Symbol, Size, ByteAlignment);
439   return;
440 }
441
442 void MCMachOStreamer::EmitInstToData(const MCInst &Inst,
443                                      const MCSubtargetInfo &STI) {
444   MCDataFragment *DF = getOrCreateDataFragment();
445
446   SmallVector<MCFixup, 4> Fixups;
447   SmallString<256> Code;
448   raw_svector_ostream VecOS(Code);
449   getAssembler().getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
450   VecOS.flush();
451
452   // Add the fixups and data.
453   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
454     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
455     DF->getFixups().push_back(Fixups[i]);
456   }
457   DF->getContents().append(Code.begin(), Code.end());
458 }
459
460 void MCMachOStreamer::FinishImpl() {
461   EmitFrames(&getAssembler().getBackend());
462
463   // We have to set the fragment atom associations so we can relax properly for
464   // Mach-O.
465
466   // First, scan the symbol table to build a lookup table from fragments to
467   // defining symbols.
468   DenseMap<const MCFragment *, const MCSymbol *> DefiningSymbolMap;
469   for (const MCSymbol &Symbol : getAssembler().symbols()) {
470     MCSymbolData &SD = Symbol.getData();
471     if (getAssembler().isSymbolLinkerVisible(Symbol) && SD.getFragment()) {
472       // An atom defining symbol should never be internal to a fragment.
473       assert(Symbol.getOffset() == 0 &&
474              "Invalid offset in atom defining symbol!");
475       DefiningSymbolMap[SD.getFragment()] = &Symbol;
476     }
477   }
478
479   // Set the fragment atom associations by tracking the last seen atom defining
480   // symbol.
481   for (MCAssembler::iterator it = getAssembler().begin(),
482          ie = getAssembler().end(); it != ie; ++it) {
483     const MCSymbol *CurrentAtom = nullptr;
484     for (MCSection::iterator it2 = it->begin(), ie2 = it->end(); it2 != ie2;
485          ++it2) {
486       if (const MCSymbol *Symbol = DefiningSymbolMap.lookup(it2))
487         CurrentAtom = Symbol;
488       it2->setAtom(CurrentAtom);
489     }
490   }
491
492   this->MCObjectStreamer::FinishImpl();
493 }
494
495 MCStreamer *llvm::createMachOStreamer(MCContext &Context, MCAsmBackend &MAB,
496                                       raw_pwrite_stream &OS, MCCodeEmitter *CE,
497                                       bool RelaxAll, bool DWARFMustBeAtTheEnd,
498                                       bool LabelSections) {
499   MCMachOStreamer *S = new MCMachOStreamer(Context, MAB, OS, CE,
500                                            DWARFMustBeAtTheEnd, LabelSections);
501   if (RelaxAll)
502     S->getAssembler().setRelaxAll(true);
503   return S;
504 }