74ec6a8fe26743d48109ecebd53980ed47927323
[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   if (Symbol->isExternal())
177     EmitSymbolAttribute(EHSymbol, MCSA_Global);
178   if (Symbol->getFlags() & SF_WeakDefinition)
179     EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
180   if (Symbol->isPrivateExtern())
181     EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
182 }
183
184 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
185   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
186
187   // isSymbolLinkerVisible uses the section.
188   AssignSection(Symbol, getCurrentSection().first);
189   // We have to create a new fragment if this is an atom defining symbol,
190   // fragments cannot span atoms.
191   if (getAssembler().isSymbolLinkerVisible(*Symbol))
192     insert(new MCDataFragment());
193
194   MCObjectStreamer::EmitLabel(Symbol);
195
196   // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
197   // to clear the weak reference and weak definition bits too, but the
198   // implementation was buggy. For now we just try to match 'as', for
199   // diffability.
200   //
201   // FIXME: Cleanup this code, these bits should be emitted based on semantic
202   // properties, not on the order of definition, etc.
203   Symbol->setFlags(Symbol->getFlags() & ~SF_ReferenceTypeMask);
204 }
205
206 void MCMachOStreamer::EmitDataRegion(DataRegionData::KindTy Kind) {
207   if (!getAssembler().getBackend().hasDataInCodeSupport())
208     return;
209   // Create a temporary label to mark the start of the data region.
210   MCSymbol *Start = getContext().createTempSymbol();
211   EmitLabel(Start);
212   // Record the region for the object writer to use.
213   DataRegionData Data = { Kind, Start, nullptr };
214   std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
215   Regions.push_back(Data);
216 }
217
218 void MCMachOStreamer::EmitDataRegionEnd() {
219   if (!getAssembler().getBackend().hasDataInCodeSupport())
220     return;
221   std::vector<DataRegionData> &Regions = getAssembler().getDataRegions();
222   assert(!Regions.empty() && "Mismatched .end_data_region!");
223   DataRegionData &Data = Regions.back();
224   assert(!Data.End && "Mismatched .end_data_region!");
225   // Create a temporary label to mark the end of the data region.
226   Data.End = getContext().createTempSymbol();
227   EmitLabel(Data.End);
228 }
229
230 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
231   // Let the target do whatever target specific stuff it needs to do.
232   getAssembler().getBackend().handleAssemblerFlag(Flag);
233   // Do any generic stuff we need to do.
234   switch (Flag) {
235   case MCAF_SyntaxUnified: return; // no-op here.
236   case MCAF_Code16: return; // Change parsing mode; no-op here.
237   case MCAF_Code32: return; // Change parsing mode; no-op here.
238   case MCAF_Code64: return; // Change parsing mode; no-op here.
239   case MCAF_SubsectionsViaSymbols:
240     getAssembler().setSubsectionsViaSymbols(true);
241     return;
242   }
243 }
244
245 void MCMachOStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) {
246   getAssembler().getLinkerOptions().push_back(Options);
247 }
248
249 void MCMachOStreamer::EmitDataRegion(MCDataRegionType Kind) {
250   switch (Kind) {
251   case MCDR_DataRegion:
252     EmitDataRegion(DataRegionData::Data);
253     return;
254   case MCDR_DataRegionJT8:
255     EmitDataRegion(DataRegionData::JumpTable8);
256     return;
257   case MCDR_DataRegionJT16:
258     EmitDataRegion(DataRegionData::JumpTable16);
259     return;
260   case MCDR_DataRegionJT32:
261     EmitDataRegion(DataRegionData::JumpTable32);
262     return;
263   case MCDR_DataRegionEnd:
264     EmitDataRegionEnd();
265     return;
266   }
267 }
268
269 void MCMachOStreamer::EmitVersionMin(MCVersionMinType Kind, unsigned Major,
270                                      unsigned Minor, unsigned Update) {
271   getAssembler().setVersionMinInfo(Kind, Major, Minor, Update);
272 }
273
274 void MCMachOStreamer::EmitThumbFunc(MCSymbol *Symbol) {
275   // Remember that the function is a thumb function. Fixup and relocation
276   // values will need adjusted.
277   getAssembler().setIsThumbFunc(Symbol);
278 }
279
280 bool MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
281                                           MCSymbolAttr Attribute) {
282   // Indirect symbols are handled differently, to match how 'as' handles
283   // them. This makes writing matching .o files easier.
284   if (Attribute == MCSA_IndirectSymbol) {
285     // Note that we intentionally cannot use the symbol data here; this is
286     // important for matching the string table that 'as' generates.
287     IndirectSymbolData ISD;
288     ISD.Symbol = Symbol;
289     ISD.Section = getCurrentSectionOnly();
290     getAssembler().getIndirectSymbols().push_back(ISD);
291     return true;
292   }
293
294   // Adding a symbol attribute always introduces the symbol, note that an
295   // important side effect of calling registerSymbol here is to register
296   // the symbol with the assembler.
297   getAssembler().registerSymbol(*Symbol);
298
299   // The implementation of symbol attributes is designed to match 'as', but it
300   // leaves much to desired. It doesn't really make sense to arbitrarily add and
301   // remove flags, but 'as' allows this (in particular, see .desc).
302   //
303   // In the future it might be worth trying to make these operations more well
304   // defined.
305   switch (Attribute) {
306   case MCSA_Invalid:
307   case MCSA_ELF_TypeFunction:
308   case MCSA_ELF_TypeIndFunction:
309   case MCSA_ELF_TypeObject:
310   case MCSA_ELF_TypeTLS:
311   case MCSA_ELF_TypeCommon:
312   case MCSA_ELF_TypeNoType:
313   case MCSA_ELF_TypeGnuUniqueObject:
314   case MCSA_Hidden:
315   case MCSA_IndirectSymbol:
316   case MCSA_Internal:
317   case MCSA_Protected:
318   case MCSA_Weak:
319   case MCSA_Local:
320     return false;
321
322   case MCSA_Global:
323     Symbol->setExternal(true);
324     // This effectively clears the undefined lazy bit, in Darwin 'as', although
325     // it isn't very consistent because it implements this as part of symbol
326     // lookup.
327     //
328     // FIXME: Cleanup this code, these bits should be emitted based on semantic
329     // properties, not on the order of definition, etc.
330     Symbol->setFlags(Symbol->getFlags() & ~SF_ReferenceTypeUndefinedLazy);
331     break;
332
333   case MCSA_LazyReference:
334     // FIXME: This requires -dynamic.
335     Symbol->setFlags(Symbol->getFlags() | SF_NoDeadStrip);
336     if (Symbol->isUndefined())
337       Symbol->setFlags(Symbol->getFlags() | SF_ReferenceTypeUndefinedLazy);
338     break;
339
340     // Since .reference sets the no dead strip bit, it is equivalent to
341     // .no_dead_strip in practice.
342   case MCSA_Reference:
343   case MCSA_NoDeadStrip:
344     Symbol->setFlags(Symbol->getFlags() | SF_NoDeadStrip);
345     break;
346
347   case MCSA_SymbolResolver:
348     Symbol->setFlags(Symbol->getFlags() | SF_SymbolResolver);
349     break;
350
351   case MCSA_PrivateExtern:
352     Symbol->setExternal(true);
353     Symbol->setPrivateExtern(true);
354     break;
355
356   case MCSA_WeakReference:
357     // FIXME: This requires -dynamic.
358     if (Symbol->isUndefined())
359       Symbol->setFlags(Symbol->getFlags() | SF_WeakReference);
360     break;
361
362   case MCSA_WeakDefinition:
363     // FIXME: 'as' enforces that this is defined and global. The manual claims
364     // it has to be in a coalesced section, but this isn't enforced.
365     Symbol->setFlags(Symbol->getFlags() | SF_WeakDefinition);
366     break;
367
368   case MCSA_WeakDefAutoPrivate:
369     Symbol->setFlags(Symbol->getFlags() | SF_WeakDefinition | SF_WeakReference);
370     break;
371   }
372
373   return true;
374 }
375
376 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
377   // Encode the 'desc' value into the lowest implementation defined bits.
378   assert(DescValue == (DescValue & SF_DescFlagsMask) &&
379          "Invalid .desc value!");
380   getAssembler().registerSymbol(*Symbol);
381   Symbol->setFlags(DescValue & SF_DescFlagsMask);
382 }
383
384 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
385                                        unsigned ByteAlignment) {
386   // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
387   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
388
389   AssignSection(Symbol, nullptr);
390
391   getAssembler().registerSymbol(*Symbol);
392   Symbol->setExternal(true);
393   Symbol->setCommon(Size, ByteAlignment);
394 }
395
396 void MCMachOStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
397                                             unsigned ByteAlignment) {
398   // '.lcomm' is equivalent to '.zerofill'.
399   return EmitZerofill(getContext().getObjectFileInfo()->getDataBSSSection(),
400                       Symbol, Size, ByteAlignment);
401 }
402
403 void MCMachOStreamer::EmitZerofill(MCSection *Section, MCSymbol *Symbol,
404                                    uint64_t Size, unsigned ByteAlignment) {
405   getAssembler().registerSection(*Section);
406
407   // The symbol may not be present, which only creates the section.
408   if (!Symbol)
409     return;
410
411   // On darwin all virtual sections have zerofill type.
412   assert(Section->isVirtualSection() && "Section does not have zerofill type!");
413
414   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
415
416   getAssembler().registerSymbol(*Symbol);
417
418   // Emit an align fragment if necessary.
419   if (ByteAlignment != 1)
420     new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, Section);
421
422   MCFragment *F = new MCFillFragment(0, 0, Size, Section);
423   Symbol->setFragment(F);
424
425   AssignSection(Symbol, Section);
426
427   // Update the maximum alignment on the zero fill section if necessary.
428   if (ByteAlignment > Section->getAlignment())
429     Section->setAlignment(ByteAlignment);
430 }
431
432 // This should always be called with the thread local bss section.  Like the
433 // .zerofill directive this doesn't actually switch sections on us.
434 void MCMachOStreamer::EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
435                                      uint64_t Size, unsigned ByteAlignment) {
436   EmitZerofill(Section, Symbol, Size, ByteAlignment);
437   return;
438 }
439
440 void MCMachOStreamer::EmitInstToData(const MCInst &Inst,
441                                      const MCSubtargetInfo &STI) {
442   MCDataFragment *DF = getOrCreateDataFragment();
443
444   SmallVector<MCFixup, 4> Fixups;
445   SmallString<256> Code;
446   raw_svector_ostream VecOS(Code);
447   getAssembler().getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
448   VecOS.flush();
449
450   // Add the fixups and data.
451   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
452     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
453     DF->getFixups().push_back(Fixups[i]);
454   }
455   DF->getContents().append(Code.begin(), Code.end());
456 }
457
458 void MCMachOStreamer::FinishImpl() {
459   EmitFrames(&getAssembler().getBackend());
460
461   // We have to set the fragment atom associations so we can relax properly for
462   // Mach-O.
463
464   // First, scan the symbol table to build a lookup table from fragments to
465   // defining symbols.
466   DenseMap<const MCFragment *, const MCSymbol *> DefiningSymbolMap;
467   for (const MCSymbol &Symbol : getAssembler().symbols()) {
468     if (getAssembler().isSymbolLinkerVisible(Symbol) && Symbol.getFragment()) {
469       // An atom defining symbol should never be internal to a fragment.
470       assert(Symbol.getOffset() == 0 &&
471              "Invalid offset in atom defining symbol!");
472       DefiningSymbolMap[Symbol.getFragment()] = &Symbol;
473     }
474   }
475
476   // Set the fragment atom associations by tracking the last seen atom defining
477   // symbol.
478   for (MCAssembler::iterator it = getAssembler().begin(),
479          ie = getAssembler().end(); it != ie; ++it) {
480     const MCSymbol *CurrentAtom = nullptr;
481     for (MCSection::iterator it2 = it->begin(), ie2 = it->end(); it2 != ie2;
482          ++it2) {
483       if (const MCSymbol *Symbol = DefiningSymbolMap.lookup(it2))
484         CurrentAtom = Symbol;
485       it2->setAtom(CurrentAtom);
486     }
487   }
488
489   this->MCObjectStreamer::FinishImpl();
490 }
491
492 MCStreamer *llvm::createMachOStreamer(MCContext &Context, MCAsmBackend &MAB,
493                                       raw_pwrite_stream &OS, MCCodeEmitter *CE,
494                                       bool RelaxAll, bool DWARFMustBeAtTheEnd,
495                                       bool LabelSections) {
496   MCMachOStreamer *S = new MCMachOStreamer(Context, MAB, OS, CE,
497                                            DWARFMustBeAtTheEnd, LabelSections);
498   if (RelaxAll)
499     S->getAssembler().setRelaxAll(true);
500   return S;
501 }