MC: Drop support for alignment in ZeroFill fragment, we can just use
[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/MCSection.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/MC/MCMachOSymbolFlags.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Target/TargetAsmBackend.h"
23
24 using namespace llvm;
25
26 namespace {
27
28 class MCMachOStreamer : public MCStreamer {
29
30 private:
31   MCAssembler Assembler;
32   MCSectionData *CurSectionData;
33
34   /// Track the current atom for each section.
35   DenseMap<const MCSectionData*, MCSymbolData*> CurrentAtomMap;
36
37 private:
38   MCFragment *getCurrentFragment() const {
39     assert(CurSectionData && "No current section!");
40
41     if (!CurSectionData->empty())
42       return &CurSectionData->getFragmentList().back();
43
44     return 0;
45   }
46
47   /// Get a data fragment to write into, creating a new one if the current
48   /// fragment is not a data fragment.
49   MCDataFragment *getOrCreateDataFragment() const {
50     MCDataFragment *F = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
51     if (!F)
52       F = createDataFragment();
53     return F;
54   }
55
56   /// Create a new data fragment in the current section.
57   MCDataFragment *createDataFragment() const {
58     MCDataFragment *DF = new MCDataFragment(CurSectionData);
59     DF->setAtom(CurrentAtomMap.lookup(CurSectionData));
60     return DF;
61   }
62
63 public:
64   MCMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
65                   raw_ostream &_OS, MCCodeEmitter *_Emitter)
66     : MCStreamer(Context), Assembler(Context, TAB, *_Emitter, _OS),
67       CurSectionData(0) {}
68   ~MCMachOStreamer() {}
69
70   MCAssembler &getAssembler() { return Assembler; }
71
72   const MCExpr *AddValueSymbols(const MCExpr *Value) {
73     switch (Value->getKind()) {
74     case MCExpr::Target: assert(0 && "Can't handle target exprs yet!");
75     case MCExpr::Constant:
76       break;
77
78     case MCExpr::Binary: {
79       const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
80       AddValueSymbols(BE->getLHS());
81       AddValueSymbols(BE->getRHS());
82       break;
83     }
84
85     case MCExpr::SymbolRef:
86       Assembler.getOrCreateSymbolData(
87         cast<MCSymbolRefExpr>(Value)->getSymbol());
88       break;
89
90     case MCExpr::Unary:
91       AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
92       break;
93     }
94
95     return Value;
96   }
97
98   /// @name MCStreamer Interface
99   /// @{
100
101   virtual void SwitchSection(const MCSection *Section);
102   virtual void EmitLabel(MCSymbol *Symbol);
103   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
104   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
105   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
106   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
107   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
108                                 unsigned ByteAlignment);
109   virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
110     assert(0 && "macho doesn't support this directive");
111   }
112   virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
113     assert(0 && "macho doesn't support this directive");
114   }
115   virtual void EmitCOFFSymbolType(int Type) {
116     assert(0 && "macho doesn't support this directive");
117   }
118   virtual void EndCOFFSymbolDef() {
119     assert(0 && "macho doesn't support this directive");
120   }
121   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
122     assert(0 && "macho doesn't support this directive");
123   }
124   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
125     assert(0 && "macho doesn't support this directive");
126   }
127   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
128                             unsigned Size = 0, unsigned ByteAlignment = 0);
129   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
130   virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
131   virtual void EmitGPRel32Value(const MCExpr *Value) {
132     assert(0 && "macho doesn't support this directive");
133   }
134   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
135                                     unsigned ValueSize = 1,
136                                     unsigned MaxBytesToEmit = 0);
137   virtual void EmitCodeAlignment(unsigned ByteAlignment,
138                                  unsigned MaxBytesToEmit = 0);
139   virtual void EmitValueToOffset(const MCExpr *Offset,
140                                  unsigned char Value = 0);
141   
142   virtual void EmitFileDirective(StringRef Filename) {
143     errs() << "FIXME: MCMachoStreamer:EmitFileDirective not implemented\n";
144   }
145   virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
146     errs() << "FIXME: MCMachoStreamer:EmitDwarfFileDirective not implemented\n";
147   }
148   
149   virtual void EmitInstruction(const MCInst &Inst);
150   virtual void Finish();
151
152   /// @}
153 };
154
155 } // end anonymous namespace.
156
157 void MCMachOStreamer::SwitchSection(const MCSection *Section) {
158   assert(Section && "Cannot switch to a null section!");
159   
160   // If already in this section, then this is a noop.
161   if (Section == CurSection) return;
162
163   CurSection = Section;
164   CurSectionData = &Assembler.getOrCreateSectionData(*Section);
165 }
166
167 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
168   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
169   assert(!Symbol->isVariable() && "Cannot emit a variable symbol!");
170   assert(CurSection && "Cannot emit before setting section!");
171
172   MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
173
174   // Update the current atom map, if necessary.
175   bool MustCreateFragment = false;
176   if (Assembler.isSymbolLinkerVisible(&SD)) {
177     CurrentAtomMap[CurSectionData] = &SD;
178
179     // We have to create a new fragment, fragments cannot span atoms.
180     MustCreateFragment = true;
181   }
182
183   // FIXME: This is wasteful, we don't necessarily need to create a data
184   // fragment. Instead, we should mark the symbol as pointing into the data
185   // fragment if it exists, otherwise we should just queue the label and set its
186   // fragment pointer when we emit the next fragment.
187   MCDataFragment *F =
188     MustCreateFragment ? createDataFragment() : getOrCreateDataFragment();
189   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
190   SD.setFragment(F);
191   SD.setOffset(F->getContents().size());
192
193   // This causes the reference type and weak reference flags to be cleared.
194   SD.setFlags(SD.getFlags() & ~(SF_WeakReference | SF_ReferenceTypeMask));
195   
196   Symbol->setSection(*CurSection);
197 }
198
199 void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
200   switch (Flag) {
201   case MCAF_SubsectionsViaSymbols:
202     Assembler.setSubsectionsViaSymbols(true);
203     return;
204   }
205
206   assert(0 && "invalid assembler flag!");
207 }
208
209 void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
210   // FIXME: Lift context changes into super class.
211   Symbol->setVariableValue(AddValueSymbols(Value));
212 }
213
214 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
215                                           MCSymbolAttr Attribute) {
216   // Indirect symbols are handled differently, to match how 'as' handles
217   // them. This makes writing matching .o files easier.
218   if (Attribute == MCSA_IndirectSymbol) {
219     // Note that we intentionally cannot use the symbol data here; this is
220     // important for matching the string table that 'as' generates.
221     IndirectSymbolData ISD;
222     ISD.Symbol = Symbol;
223     ISD.SectionData = CurSectionData;
224     Assembler.getIndirectSymbols().push_back(ISD);
225     return;
226   }
227
228   // Adding a symbol attribute always introduces the symbol, note that an
229   // important side effect of calling getOrCreateSymbolData here is to register
230   // the symbol with the assembler.
231   MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
232
233   // The implementation of symbol attributes is designed to match 'as', but it
234   // leaves much to desired. It doesn't really make sense to arbitrarily add and
235   // remove flags, but 'as' allows this (in particular, see .desc).
236   //
237   // In the future it might be worth trying to make these operations more well
238   // defined.
239   switch (Attribute) {
240   case MCSA_Invalid:
241   case MCSA_ELF_TypeFunction:
242   case MCSA_ELF_TypeIndFunction:
243   case MCSA_ELF_TypeObject:
244   case MCSA_ELF_TypeTLS:
245   case MCSA_ELF_TypeCommon:
246   case MCSA_ELF_TypeNoType:
247   case MCSA_IndirectSymbol:
248   case MCSA_Hidden:
249   case MCSA_Internal:
250   case MCSA_Protected:
251   case MCSA_Weak:
252   case MCSA_Local:
253     assert(0 && "Invalid symbol attribute for Mach-O!");
254     break;
255
256   case MCSA_Global:
257     SD.setExternal(true);
258     break;
259
260   case MCSA_LazyReference:
261     // FIXME: This requires -dynamic.
262     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
263     if (Symbol->isUndefined())
264       SD.setFlags(SD.getFlags() | SF_ReferenceTypeUndefinedLazy);
265     break;
266
267     // Since .reference sets the no dead strip bit, it is equivalent to
268     // .no_dead_strip in practice.
269   case MCSA_Reference:
270   case MCSA_NoDeadStrip:
271     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
272     break;
273
274   case MCSA_PrivateExtern:
275     SD.setExternal(true);
276     SD.setPrivateExtern(true);
277     break;
278
279   case MCSA_WeakReference:
280     // FIXME: This requires -dynamic.
281     if (Symbol->isUndefined())
282       SD.setFlags(SD.getFlags() | SF_WeakReference);
283     break;
284
285   case MCSA_WeakDefinition:
286     // FIXME: 'as' enforces that this is defined and global. The manual claims
287     // it has to be in a coalesced section, but this isn't enforced.
288     SD.setFlags(SD.getFlags() | SF_WeakDefinition);
289     break;
290   }
291 }
292
293 void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
294   // Encode the 'desc' value into the lowest implementation defined bits.
295   assert(DescValue == (DescValue & SF_DescFlagsMask) && 
296          "Invalid .desc value!");
297   Assembler.getOrCreateSymbolData(*Symbol).setFlags(DescValue&SF_DescFlagsMask);
298 }
299
300 void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
301                                        unsigned ByteAlignment) {
302   // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
303   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
304
305   MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
306   SD.setExternal(true);
307   SD.setCommon(Size, ByteAlignment);
308 }
309
310 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
311                                    unsigned Size, unsigned ByteAlignment) {
312   MCSectionData &SectData = Assembler.getOrCreateSectionData(*Section);
313
314   // The symbol may not be present, which only creates the section.
315   if (!Symbol)
316     return;
317
318   // FIXME: Assert that this section has the zerofill type.
319
320   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
321
322   MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
323
324   // Emit an align fragment if necessary.
325   if (ByteAlignment != 1)
326     new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, /*EmitNops=*/false,
327                         &SectData);
328
329   MCFragment *F = new MCZeroFillFragment(Size, &SectData);
330   SD.setFragment(F);
331   if (Assembler.isSymbolLinkerVisible(&SD))
332     F->setAtom(&SD);
333
334   Symbol->setSection(*Section);
335
336   // Update the maximum alignment on the zero fill section if necessary.
337   if (ByteAlignment > SectData.getAlignment())
338     SectData.setAlignment(ByteAlignment);
339 }
340
341 void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
342   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
343 }
344
345 void MCMachOStreamer::EmitValue(const MCExpr *Value, unsigned Size,
346                                 unsigned AddrSpace) {
347   MCDataFragment *DF = getOrCreateDataFragment();
348
349   // Avoid fixups when possible.
350   int64_t AbsValue;
351   if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
352     // FIXME: Endianness assumption.
353     for (unsigned i = 0; i != Size; ++i)
354       DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
355   } else {
356     DF->addFixup(MCAsmFixup(DF->getContents().size(), *AddValueSymbols(Value),
357                             MCFixup::getKindForSize(Size)));
358     DF->getContents().resize(DF->getContents().size() + Size, 0);
359   }
360 }
361
362 void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
363                                            int64_t Value, unsigned ValueSize,
364                                            unsigned MaxBytesToEmit) {
365   if (MaxBytesToEmit == 0)
366     MaxBytesToEmit = ByteAlignment;
367   MCFragment *F = new MCAlignFragment(ByteAlignment, Value, ValueSize,
368                                       MaxBytesToEmit, /*EmitNops=*/false,
369                                       CurSectionData);
370   F->setAtom(CurrentAtomMap.lookup(CurSectionData));
371
372   // Update the maximum alignment on the current section if necessary.
373   if (ByteAlignment > CurSectionData->getAlignment())
374     CurSectionData->setAlignment(ByteAlignment);
375 }
376
377 void MCMachOStreamer::EmitCodeAlignment(unsigned ByteAlignment,
378                                         unsigned MaxBytesToEmit) {
379   if (MaxBytesToEmit == 0)
380     MaxBytesToEmit = ByteAlignment;
381   MCFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
382                                       /*EmitNops=*/true, CurSectionData);
383   F->setAtom(CurrentAtomMap.lookup(CurSectionData));
384
385   // Update the maximum alignment on the current section if necessary.
386   if (ByteAlignment > CurSectionData->getAlignment())
387     CurSectionData->setAlignment(ByteAlignment);
388 }
389
390 void MCMachOStreamer::EmitValueToOffset(const MCExpr *Offset,
391                                         unsigned char Value) {
392   MCFragment *F = new MCOrgFragment(*Offset, Value, CurSectionData);
393   F->setAtom(CurrentAtomMap.lookup(CurSectionData));
394 }
395
396 void MCMachOStreamer::EmitInstruction(const MCInst &Inst) {
397   // Scan for values.
398   for (unsigned i = 0; i != Inst.getNumOperands(); ++i)
399     if (Inst.getOperand(i).isExpr())
400       AddValueSymbols(Inst.getOperand(i).getExpr());
401
402   CurSectionData->setHasInstructions(true);
403
404   // FIXME-PERF: Common case is that we don't need to relax, encode directly
405   // onto the data fragments buffers.
406
407   SmallVector<MCFixup, 4> Fixups;
408   SmallString<256> Code;
409   raw_svector_ostream VecOS(Code);
410   Assembler.getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
411   VecOS.flush();
412
413   // FIXME: Eliminate this copy.
414   SmallVector<MCAsmFixup, 4> AsmFixups;
415   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
416     MCFixup &F = Fixups[i];
417     AsmFixups.push_back(MCAsmFixup(F.getOffset(), *F.getValue(),
418                                    F.getKind()));
419   }
420
421   // See if we might need to relax this instruction, if so it needs its own
422   // fragment.
423   //
424   // FIXME-PERF: Support target hook to do a fast path that avoids the encoder,
425   // when we can immediately tell that we will get something which might need
426   // relaxation (and compute its size).
427   //
428   // FIXME-PERF: We should also be smart about immediately relaxing instructions
429   // which we can already show will never possibly fit (we can also do a very
430   // good job of this before we do the first relaxation pass, because we have
431   // total knowledge about undefined symbols at that point). Even now, though,
432   // we can do a decent job, especially on Darwin where scattering means that we
433   // are going to often know that we can never fully resolve a fixup.
434   if (Assembler.getBackend().MayNeedRelaxation(Inst, AsmFixups)) {
435     MCInstFragment *IF = new MCInstFragment(Inst, CurSectionData);
436     IF->setAtom(CurrentAtomMap.lookup(CurSectionData));
437
438     // Add the fixups and data.
439     //
440     // FIXME: Revisit this design decision when relaxation is done, we may be
441     // able to get away with not storing any extra data in the MCInst.
442     IF->getCode() = Code;
443     IF->getFixups() = AsmFixups;
444
445     return;
446   }
447
448   // Add the fixups and data.
449   MCDataFragment *DF = getOrCreateDataFragment();
450   for (unsigned i = 0, e = AsmFixups.size(); i != e; ++i) {
451     AsmFixups[i].Offset += DF->getContents().size();
452     DF->addFixup(AsmFixups[i]);
453   }
454   DF->getContents().append(Code.begin(), Code.end());
455 }
456
457 void MCMachOStreamer::Finish() {
458   Assembler.Finish();
459 }
460
461 MCStreamer *llvm::createMachOStreamer(MCContext &Context, TargetAsmBackend &TAB,
462                                       raw_ostream &OS, MCCodeEmitter *CE,
463                                       bool RelaxAll) {
464   MCMachOStreamer *S = new MCMachOStreamer(Context, TAB, OS, CE);
465   if (RelaxAll)
466     S->getAssembler().setRelaxAll(true);
467   return S;
468 }