This adds a Darwin x86_64 relocation encoding for a subtraction expression
[oota-llvm.git] / lib / MC / MCMachOStreamer.cpp
1 //===- lib/MC/MCMachOStreamer.cpp - Mach-O Object Output ------------===//
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
12 #include "llvm/MC/MCAssembler.h"
13 #include "llvm/MC/MCContext.h"
14 #include "llvm/MC/MCCodeEmitter.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCInst.h"
17 #include "llvm/MC/MCObjectStreamer.h"
18 #include "llvm/MC/MCSection.h"
19 #include "llvm/MC/MCSymbol.h"
20 #include "llvm/MC/MCMachOSymbolFlags.h"
21 #include "llvm/MC/MCSectionMachO.h"
22 #include "llvm/MC/MCDwarf.h"
23 #include "llvm/Support/Dwarf.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetAsmBackend.h"
27
28 using namespace llvm;
29
30 namespace {
31
32 class MCMachOStreamer : public MCObjectStreamer {
33 private:
34   void EmitInstToFragment(const MCInst &Inst);
35   void EmitInstToData(const MCInst &Inst);
36
37 public:
38   MCMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
39                   raw_ostream &OS, MCCodeEmitter *Emitter)
40     : MCObjectStreamer(Context, TAB, OS, Emitter, true) {}
41
42   /// @name MCStreamer Interface
43   /// @{
44
45   virtual void InitSections();
46   virtual void EmitLabel(MCSymbol *Symbol);
47   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
48   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
49   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
50   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
51   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
52                                 unsigned ByteAlignment);
53   virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
54     assert(0 && "macho doesn't support this directive");
55   }
56   virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
57     assert(0 && "macho doesn't support this directive");
58   }
59   virtual void EmitCOFFSymbolType(int Type) {
60     assert(0 && "macho doesn't support this directive");
61   }
62   virtual void EndCOFFSymbolDef() {
63     assert(0 && "macho doesn't support this directive");
64   }
65   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
66     assert(0 && "macho doesn't support this directive");
67   }
68   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
69     assert(0 && "macho doesn't support this directive");
70   }
71   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
72                             unsigned Size = 0, unsigned ByteAlignment = 0);
73   virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
74                               uint64_t Size, unsigned ByteAlignment = 0);
75   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
76   virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
77   virtual void EmitGPRel32Value(const MCExpr *Value) {
78     assert(0 && "macho doesn't support this directive");
79   }
80   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
81                                     unsigned ValueSize = 1,
82                                     unsigned MaxBytesToEmit = 0);
83   virtual void EmitCodeAlignment(unsigned ByteAlignment,
84                                  unsigned MaxBytesToEmit = 0);
85   virtual void EmitValueToOffset(const MCExpr *Offset,
86                                  unsigned char Value = 0);
87
88   virtual void EmitFileDirective(StringRef Filename) {
89     // FIXME: Just ignore the .file; it isn't important enough to fail the
90     // entire assembly.
91
92     //report_fatal_error("unsupported directive: '.file'");
93   }
94   virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
95     // FIXME: Just ignore the .file; it isn't important enough to fail the
96     // entire assembly.
97
98     //report_fatal_error("unsupported directive: '.file'");
99   }
100
101   virtual void EmitInstruction(const MCInst &Inst);
102
103   virtual void Finish();
104
105   /// @}
106 };
107
108 } // end anonymous namespace.
109
110 void MCMachOStreamer::InitSections() {
111   SwitchSection(getContext().getMachOSection("__TEXT", "__text",
112                                     MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
113                                     0, SectionKind::getText()));
114
115 }
116
117 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
118   // TODO: This is almost exactly the same as WinCOFFStreamer. Consider merging
119   // into MCObjectStreamer.
120   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
121   assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
122   assert(CurSection && "Cannot emit before setting section!");
123
124   Symbol->setSection(*CurSection);
125
126   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
127
128   // We have to create a new fragment if this is an atom defining symbol,
129   // fragments cannot span atoms.
130   if (getAssembler().isSymbolLinkerVisible(SD.getSymbol()))
131     new MCDataFragment(getCurrentSectionData());
132
133   // FIXME: This is wasteful, we don't necessarily need to create a data
134   // fragment. Instead, we should mark the symbol as pointing into the data
135   // fragment if it exists, otherwise we should just queue the label and set its
136   // fragment pointer when we emit the next fragment.
137   MCDataFragment *F = getOrCreateDataFragment();
138   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
139   SD.setFragment(F);
140   SD.setOffset(F->getContents().size());
141
142   // This causes the reference type flag to be cleared. Darwin 'as' was "trying"
143   // to clear the weak reference and weak definition bits too, but the
144   // implementation was buggy. For now we just try to match 'as', for
145   // diffability.
146   //
147   // FIXME: Cleanup this code, these bits should be emitted based on semantic
148   // properties, not on the order of definition, etc.
149   SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeMask);
150 }
151
152 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
153   switch (Flag) {
154   case MCAF_SubsectionsViaSymbols:
155     getAssembler().setSubsectionsViaSymbols(true);
156     return;
157   default:
158     llvm_unreachable("invalid assembler flag!");
159   }
160 }
161
162 void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
163   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
164   // MCObjectStreamer.
165   // FIXME: Lift context changes into super class.
166   getAssembler().getOrCreateSymbolData(*Symbol);
167   Symbol->setVariableValue(AddValueSymbols(Value));
168 }
169
170 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
171                                           MCSymbolAttr Attribute) {
172   // Indirect symbols are handled differently, to match how 'as' handles
173   // them. This makes writing matching .o files easier.
174   if (Attribute == MCSA_IndirectSymbol) {
175     // Note that we intentionally cannot use the symbol data here; this is
176     // important for matching the string table that 'as' generates.
177     IndirectSymbolData ISD;
178     ISD.Symbol = Symbol;
179     ISD.SectionData = getCurrentSectionData();
180     getAssembler().getIndirectSymbols().push_back(ISD);
181     return;
182   }
183
184   // Adding a symbol attribute always introduces the symbol, note that an
185   // important side effect of calling getOrCreateSymbolData here is to register
186   // the symbol with the assembler.
187   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
188
189   // The implementation of symbol attributes is designed to match 'as', but it
190   // leaves much to desired. It doesn't really make sense to arbitrarily add and
191   // remove flags, but 'as' allows this (in particular, see .desc).
192   //
193   // In the future it might be worth trying to make these operations more well
194   // defined.
195   switch (Attribute) {
196   case MCSA_Invalid:
197   case MCSA_ELF_TypeFunction:
198   case MCSA_ELF_TypeIndFunction:
199   case MCSA_ELF_TypeObject:
200   case MCSA_ELF_TypeTLS:
201   case MCSA_ELF_TypeCommon:
202   case MCSA_ELF_TypeNoType:
203   case MCSA_IndirectSymbol:
204   case MCSA_Hidden:
205   case MCSA_Internal:
206   case MCSA_Protected:
207   case MCSA_Weak:
208   case MCSA_Local:
209     assert(0 && "Invalid symbol attribute for Mach-O!");
210     break;
211
212   case MCSA_Global:
213     SD.setExternal(true);
214     // This effectively clears the undefined lazy bit, in Darwin 'as', although
215     // it isn't very consistent because it implements this as part of symbol
216     // lookup.
217     //
218     // FIXME: Cleanup this code, these bits should be emitted based on semantic
219     // properties, not on the order of definition, etc.
220     SD.setFlags(SD.getFlags() & ~SF_ReferenceTypeUndefinedLazy);
221     break;
222
223   case MCSA_LazyReference:
224     // FIXME: This requires -dynamic.
225     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
226     if (Symbol->isUndefined())
227       SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
228     break;
229
230     // Since .reference sets the no dead strip bit, it is equivalent to
231     // .no_dead_strip in practice.
232   case MCSA_Reference:
233   case MCSA_NoDeadStrip:
234     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
235     break;
236
237   case MCSA_PrivateExtern:
238     SD.setExternal(true);
239     SD.setPrivateExtern(true);
240     break;
241
242   case MCSA_WeakReference:
243     // FIXME: This requires -dynamic.
244     if (Symbol->isUndefined())
245       SD.setFlags(SD.getFlags() | SF_WeakReference);
246     break;
247
248   case MCSA_WeakDefinition:
249     // FIXME: 'as' enforces that this is defined and global. The manual claims
250     // it has to be in a coalesced section, but this isn't enforced.
251     SD.setFlags(SD.getFlags() | SF_WeakDefinition);
252     break;
253
254   case MCSA_WeakDefAutoPrivate:
255     SD.setFlags(SD.getFlags() | SF_WeakDefinition | SF_WeakReference);
256     break;
257   }
258 }
259
260 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
261   // Encode the 'desc' value into the lowest implementation defined bits.
262   assert(DescValue == (DescValue & SF_DescFlagsMask) &&
263          "Invalid .desc value!");
264   getAssembler().getOrCreateSymbolData(*Symbol).setFlags(
265     DescValue & SF_DescFlagsMask);
266 }
267
268 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
269                                        unsigned ByteAlignment) {
270   // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
271   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
272
273   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
274   SD.setExternal(true);
275   SD.setCommon(Size, ByteAlignment);
276 }
277
278 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
279                                    unsigned Size, unsigned ByteAlignment) {
280   MCSectionData &SectData = getAssembler().getOrCreateSectionData(*Section);
281
282   // The symbol may not be present, which only creates the section.
283   if (!Symbol)
284     return;
285
286   // FIXME: Assert that this section has the zerofill type.
287
288   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
289
290   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
291
292   // Emit an align fragment if necessary.
293   if (ByteAlignment != 1)
294     new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectData);
295
296   MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
297   SD.setFragment(F);
298
299   Symbol->setSection(*Section);
300
301   // Update the maximum alignment on the zero fill section if necessary.
302   if (ByteAlignment > SectData.getAlignment())
303     SectData.setAlignment(ByteAlignment);
304 }
305
306 // This should always be called with the thread local bss section.  Like the
307 // .zerofill directive this doesn't actually switch sections on us.
308 void MCMachOStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
309                                      uint64_t Size, unsigned ByteAlignment) {
310   EmitZerofill(Section, Symbol, Size, ByteAlignment);
311   return;
312 }
313
314 void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
315   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
316   // MCObjectStreamer.
317   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
318 }
319
320 void MCMachOStreamer::EmitValue(const MCExpr *Value, unsigned Size,
321                                 unsigned AddrSpace) {
322   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
323   // MCObjectStreamer.
324   MCDataFragment *DF = getOrCreateDataFragment();
325
326   // Avoid fixups when possible.
327   int64_t AbsValue;
328   if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
329     // FIXME: Endianness assumption.
330     for (unsigned i = 0; i != Size; ++i)
331       DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
332   } else {
333     DF->addFixup(MCFixup::Create(DF->getContents().size(),
334                                  AddValueSymbols(Value),
335                                  MCFixup::getKindForSize(Size)));
336     DF->getContents().resize(DF->getContents().size() + Size, 0);
337   }
338 }
339
340 void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
341                                            int64_t Value, unsigned ValueSize,
342                                            unsigned MaxBytesToEmit) {
343   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
344   // MCObjectStreamer.
345   if (MaxBytesToEmit == 0)
346     MaxBytesToEmit = ByteAlignment;
347   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
348                       getCurrentSectionData());
349
350   // Update the maximum alignment on the current section if necessary.
351   if (ByteAlignment > getCurrentSectionData()->getAlignment())
352     getCurrentSectionData()->setAlignment(ByteAlignment);
353 }
354
355 void MCMachOStreamer::EmitCodeAlignment(unsigned ByteAlignment,
356                                         unsigned MaxBytesToEmit) {
357   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
358   // MCObjectStreamer.
359   if (MaxBytesToEmit == 0)
360     MaxBytesToEmit = ByteAlignment;
361   MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
362                                            getCurrentSectionData());
363   F->setEmitNops(true);
364
365   // Update the maximum alignment on the current section if necessary.
366   if (ByteAlignment > getCurrentSectionData()->getAlignment())
367     getCurrentSectionData()->setAlignment(ByteAlignment);
368 }
369
370 void MCMachOStreamer::EmitValueToOffset(const MCExpr *Offset,
371                                         unsigned char Value) {
372   new MCOrgFragment(*Offset, Value, getCurrentSectionData());
373 }
374
375 void MCMachOStreamer::EmitInstToFragment(const MCInst &Inst) {
376   MCInstFragment *IF = new MCInstFragment(Inst, getCurrentSectionData());
377
378   // Add the fixups and data.
379   //
380   // FIXME: Revisit this design decision when relaxation is done, we may be
381   // able to get away with not storing any extra data in the MCInst.
382   SmallVector<MCFixup, 4> Fixups;
383   SmallString<256> Code;
384   raw_svector_ostream VecOS(Code);
385   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
386   VecOS.flush();
387
388   IF->getCode() = Code;
389   IF->getFixups() = Fixups;
390 }
391
392 void MCMachOStreamer::EmitInstToData(const MCInst &Inst) {
393   MCDataFragment *DF = getOrCreateDataFragment();
394
395   SmallVector<MCFixup, 4> Fixups;
396   SmallString<256> Code;
397   raw_svector_ostream VecOS(Code);
398   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
399   VecOS.flush();
400
401   // Add the fixups and data.
402   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
403     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
404     DF->addFixup(Fixups[i]);
405   }
406   DF->getContents().append(Code.begin(), Code.end());
407 }
408
409 void MCMachOStreamer::EmitInstruction(const MCInst &Inst) {
410   // Scan for values.
411   for (unsigned i = Inst.getNumOperands(); i--; )
412     if (Inst.getOperand(i).isExpr())
413       AddValueSymbols(Inst.getOperand(i).getExpr());
414
415   getCurrentSectionData()->setHasInstructions(true);
416
417   // Now that a machine instruction has been assembled into this section, make
418   // a line entry for any .loc directive that has been seen.
419   MCLineEntry::Make(this, getCurrentSection());
420
421   // If this instruction doesn't need relaxation, just emit it as data.
422   if (!getAssembler().getBackend().MayNeedRelaxation(Inst)) {
423     EmitInstToData(Inst);
424     return;
425   }
426
427   // Otherwise, if we are relaxing everything, relax the instruction as much as
428   // possible and emit it as data.
429   if (getAssembler().getRelaxAll()) {
430     MCInst Relaxed;
431     getAssembler().getBackend().RelaxInstruction(Inst, Relaxed);
432     while (getAssembler().getBackend().MayNeedRelaxation(Relaxed))
433       getAssembler().getBackend().RelaxInstruction(Relaxed, Relaxed);
434     EmitInstToData(Relaxed);
435     return;
436   }
437
438   // Otherwise emit to a separate fragment.
439   EmitInstToFragment(Inst);
440 }
441
442 void MCMachOStreamer::Finish() {
443   // Dump out the dwarf file & directory tables and line tables.
444   if (getContext().hasDwarfFiles()) {
445     const MCSection *DwarfLineSection = getContext().getMachOSection("__DWARF",
446                                          "__debug_line",
447                                          MCSectionMachO::S_ATTR_DEBUG,
448                                          0, SectionKind::getDataRelLocal());
449     MCDwarfFileTable::Emit(this, DwarfLineSection);
450   }
451
452   // We have to set the fragment atom associations so we can relax properly for
453   // Mach-O.
454
455   // First, scan the symbol table to build a lookup table from fragments to
456   // defining symbols.
457   DenseMap<const MCFragment*, MCSymbolData*> DefiningSymbolMap;
458   for (MCAssembler::symbol_iterator it = getAssembler().symbol_begin(),
459          ie = getAssembler().symbol_end(); it != ie; ++it) {
460     if (getAssembler().isSymbolLinkerVisible(it->getSymbol()) &&
461         it->getFragment()) {
462       // An atom defining symbol should never be internal to a fragment.
463       assert(it->getOffset() == 0 && "Invalid offset in atom defining symbol!");
464       DefiningSymbolMap[it->getFragment()] = it;
465     }
466   }
467
468   // Set the fragment atom associations by tracking the last seen atom defining
469   // symbol.
470   for (MCAssembler::iterator it = getAssembler().begin(),
471          ie = getAssembler().end(); it != ie; ++it) {
472     MCSymbolData *CurrentAtom = 0;
473     for (MCSectionData::iterator it2 = it->begin(),
474            ie2 = it->end(); it2 != ie2; ++it2) {
475       if (MCSymbolData *SD = DefiningSymbolMap.lookup(it2))
476         CurrentAtom = SD;
477       it2->setAtom(CurrentAtom);
478     }
479   }
480
481   this->MCObjectStreamer::Finish();
482 }
483
484 MCStreamer *llvm::createMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
485                                       raw_ostream &OS, MCCodeEmitter *CE,
486                                       bool RelaxAll) {
487   MCMachOStreamer *S = new MCMachOStreamer(Context, TAB, OS, CE);
488   if (RelaxAll)
489     S->getAssembler().setRelaxAll(true);
490   return S;
491 }