c0efc8e17bdf26d2a903cbc1502bee2700715660
[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(const 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(const MCSection *Section, MCSymbol *Symbol = nullptr,
102                     uint64_t Size = 0, unsigned ByteAlignment = 0) override;
103   void EmitTBSSSymbol(const 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(const 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     MCSymbol *Label = getContext().createLinkerPrivateTempSymbol();
167     EmitLabel(Label);
168     HasSectionLabel[Section] = true;
169   }
170 }
171
172 void MCMachOStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
173                                           MCSymbol *EHSymbol) {
174   MCSymbolData &SD =
175     getAssembler().getOrCreateSymbolData(*Symbol);
176   if (SD.isExternal())
177     EmitSymbolAttribute(EHSymbol, MCSA_Global);
178   if (SD.getFlags() & SF_WeakDefinition)
179     EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
180   if (SD.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   MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
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   SD.setFlags(SD.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.SectionData = getCurrentSectionData();
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 getOrCreateSymbolData here is to register
297   // the symbol with the assembler.
298   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
299
300   // The implementation of symbol attributes is designed to match 'as', but it
301   // leaves much to desired. It doesn't really make sense to arbitrarily add and
302   // remove flags, but 'as' allows this (in particular, see .desc).
303   //
304   // In the future it might be worth trying to make these operations more well
305   // defined.
306   switch (Attribute) {
307   case MCSA_Invalid:
308   case MCSA_ELF_TypeFunction:
309   case MCSA_ELF_TypeIndFunction:
310   case MCSA_ELF_TypeObject:
311   case MCSA_ELF_TypeTLS:
312   case MCSA_ELF_TypeCommon:
313   case MCSA_ELF_TypeNoType:
314   case MCSA_ELF_TypeGnuUniqueObject:
315   case MCSA_Hidden:
316   case MCSA_IndirectSymbol:
317   case MCSA_Internal:
318   case MCSA_Protected:
319   case MCSA_Weak:
320   case MCSA_Local:
321     return false;
322
323   case MCSA_Global:
324     SD.setExternal(true);
325     // This effectively clears the undefined lazy bit, in Darwin 'as', although
326     // it isn't very consistent because it implements this as part of symbol
327     // lookup.
328     //
329     // FIXME: Cleanup this code, these bits should be emitted based on semantic
330     // properties, not on the order of definition, etc.
331     SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
332     break;
333
334   case MCSA_LazyReference:
335     // FIXME: This requires -dynamic.
336     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
337     if (Symbol->isUndefined())
338       SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
339     break;
340
341     // Since .reference sets the no dead strip bit, it is equivalent to
342     // .no_dead_strip in practice.
343   case MCSA_Reference:
344   case MCSA_NoDeadStrip:
345     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
346     break;
347
348   case MCSA_SymbolResolver:
349     SD.setFlags(SD.getFlags() | SF_SymbolResolver);
350     break;
351
352   case MCSA_PrivateExtern:
353     SD.setExternal(true);
354     SD.setPrivateExtern(true);
355     break;
356
357   case MCSA_WeakReference:
358     // FIXME: This requires -dynamic.
359     if (Symbol->isUndefined())
360       SD.setFlags(SD.getFlags() | SF_WeakReference);
361     break;
362
363   case MCSA_WeakDefinition:
364     // FIXME: 'as' enforces that this is defined and global. The manual claims
365     // it has to be in a coalesced section, but this isn't enforced.
366     SD.setFlags(SD.getFlags() | SF_WeakDefinition);
367     break;
368
369   case MCSA_WeakDefAutoPrivate:
370     SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
371     break;
372   }
373
374   return true;
375 }
376
377 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
378   // Encode the 'desc' value into the lowest implementation defined bits.
379   assert(DescValue == (DescValue & SF_DescFlagsMask) &&
380          "Invalid .desc value!");
381   getAssembler().getOrCreateSymbolData(*Symbol).setFlags(
382     DescValue & SF_DescFlagsMask);
383 }
384
385 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
386                                        unsigned ByteAlignment) {
387   // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
388   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
389
390   AssignSection(Symbol, nullptr);
391
392   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
393   SD.setExternal(true);
394   SD.setCommon(Size, ByteAlignment);
395 }
396
397 void MCMachOStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
398                                             unsigned ByteAlignment) {
399   // '.lcomm' is equivalent to '.zerofill'.
400   return EmitZerofill(getContext().getObjectFileInfo()->getDataBSSSection(),
401                       Symbol, Size, ByteAlignment);
402 }
403
404 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
405                                    uint64_t Size, unsigned ByteAlignment) {
406   MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
407
408   // The symbol may not be present, which only creates the section.
409   if (!Symbol)
410     return;
411
412   // On darwin all virtual sections have zerofill type.
413   assert(Section->isVirtualSection() && "Section does not have zerofill type!");
414
415   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
416
417   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
418
419   // Emit an align fragment if necessary.
420   if (ByteAlignment != 1)
421     new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
422
423   MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
424   SD.setFragment(F);
425
426   AssignSection(Symbol, Section);
427
428   // Update the maximum alignment on the zero fill section if necessary.
429   if (ByteAlignment > SectData.getAlignment())
430     SectData.setAlignment(ByteAlignment);
431 }
432
433 // This should always be called with the thread local bss section.  Like the
434 // .zerofill directive this doesn't actually switch sections on us.
435 void MCMachOStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
436                                      uint64_t Size, unsigned ByteAlignment) {
437   EmitZerofill(Section, Symbol, Size, ByteAlignment);
438   return;
439 }
440
441 void MCMachOStreamer::EmitInstToData(const MCInst &Inst,
442                                      const MCSubtargetInfo &STI) {
443   MCDataFragment *DF = getOrCreateDataFragment();
444
445   SmallVector<MCFixup, 4> Fixups;
446   SmallString<256> Code;
447   raw_svector_ostream VecOS(Code);
448   getAssembler().getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
449   VecOS.flush();
450
451   // Add the fixups and data.
452   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
453     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
454     DF->getFixups().push_back(Fixups[i]);
455   }
456   DF->getContents().append(Code.begin(), Code.end());
457 }
458
459 void MCMachOStreamer::FinishImpl() {
460   EmitFrames(&getAssembler().getBackend());
461
462   // We have to set the fragment atom associations so we can relax properly for
463   // Mach-O.
464
465   // First, scan the symbol table to build a lookup table from fragments to
466   // defining symbols.
467   DenseMap<const MCFragment *, const MCSymbol *> DefiningSymbolMap;
468   for (const MCSymbol &Symbol : getAssembler().symbols()) {
469     MCSymbolData &SD = Symbol.getData();
470     if (getAssembler().isSymbolLinkerVisible(Symbol) && SD.getFragment()) {
471       // An atom defining symbol should never be internal to a fragment.
472       assert(SD.getOffset() == 0 && "Invalid offset in atom defining symbol!");
473       DefiningSymbolMap[SD.getFragment()] = &Symbol;
474     }
475   }
476
477   // Set the fragment atom associations by tracking the last seen atom defining
478   // symbol.
479   for (MCAssembler::iterator it = getAssembler().begin(),
480          ie = getAssembler().end(); it != ie; ++it) {
481     const MCSymbol *CurrentAtom = nullptr;
482     for (MCSectionData::iterator it2 = it->begin(),
483            ie2 = it->end(); it2 != ie2; ++it2) {
484       if (const MCSymbol *Symbol = DefiningSymbolMap.lookup(it2))
485         CurrentAtom = Symbol;
486       it2->setAtom(CurrentAtom);
487     }
488   }
489
490   this->MCObjectStreamer::FinishImpl();
491 }
492
493 MCStreamer *llvm::createMachOStreamer(MCContext &Context, MCAsmBackend &MAB,
494                                       raw_pwrite_stream &OS, MCCodeEmitter *CE,
495                                       bool RelaxAll, bool DWARFMustBeAtTheEnd,
496                                       bool LabelSections) {
497   MCMachOStreamer *S = new MCMachOStreamer(Context, MAB, OS, CE,
498                                            DWARFMustBeAtTheEnd, LabelSections);
499   if (RelaxAll)
500     S->getAssembler().setRelaxAll(true);
501   return S;
502 }