23489095893e22d8e55f59e62fcd2906b3a4b13b
[oota-llvm.git] / lib / MC / MCAsmStreamer.cpp
1 //===- lib/MC/MCAsmStreamer.cpp - Text Assembly 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 #include "llvm/ADT/SmallString.h"
12 #include "llvm/MC/MCAsmInfo.h"
13 #include "llvm/MC/MCCodeEmitter.h"
14 #include "llvm/MC/MCContext.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCInst.h"
17 #include "llvm/MC/MCInstPrinter.h"
18 #include "llvm/MC/MCSectionMachO.h"
19 #include "llvm/MC/MCSymbol.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/MathExtras.h"
22 #include "llvm/Support/Format.h"
23 #include "llvm/Support/raw_ostream.h"
24 using namespace llvm;
25
26 namespace {
27
28 class MCAsmStreamer : public MCStreamer {
29   raw_ostream &OS;
30   const MCAsmInfo &MAI;
31   bool IsLittleEndian;
32   MCInstPrinter *InstPrinter;
33   MCCodeEmitter *Emitter;
34 public:
35   MCAsmStreamer(MCContext &Context, raw_ostream &_OS, const MCAsmInfo &tai,
36                 bool isLittleEndian, MCInstPrinter *_Printer,
37                 MCCodeEmitter *_Emitter)
38     : MCStreamer(Context), OS(_OS), MAI(tai), InstPrinter(_Printer),
39       Emitter(_Emitter) {}
40   ~MCAsmStreamer() {}
41
42   bool isLittleEndian() const { return IsLittleEndian; }
43   
44   /// @name MCStreamer Interface
45   /// @{
46
47   virtual void SwitchSection(const MCSection *Section);
48
49   virtual void EmitLabel(MCSymbol *Symbol);
50
51   virtual void EmitAssemblerFlag(AssemblerFlag Flag);
52
53   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
54
55   virtual void EmitSymbolAttribute(MCSymbol *Symbol, SymbolAttr Attribute);
56
57   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
58
59   virtual void EmitCommonSymbol(MCSymbol *Symbol, unsigned Size,
60                                 unsigned ByteAlignment);
61
62   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
63                             unsigned Size = 0, unsigned ByteAlignment = 0);
64
65   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
66
67   virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
68   virtual void EmitIntValue(uint64_t Value, unsigned Size, unsigned AddrSpace);
69
70   virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
71                         unsigned AddrSpace);
72
73   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
74                                     unsigned ValueSize = 1,
75                                     unsigned MaxBytesToEmit = 0);
76
77   virtual void EmitValueToOffset(const MCExpr *Offset,
78                                  unsigned char Value = 0);
79   
80   virtual void EmitInstruction(const MCInst &Inst);
81
82   virtual void Finish();
83   
84   /// @}
85 };
86
87 } // end anonymous namespace.
88
89 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
90   assert(Bytes && "Invalid size!");
91   return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
92 }
93
94 static inline const MCExpr *truncateToSize(const MCExpr *Value,
95                                            unsigned Bytes) {
96   // FIXME: Do we really need this routine?
97   return Value;
98 }
99
100 void MCAsmStreamer::SwitchSection(const MCSection *Section) {
101   assert(Section && "Cannot switch to a null section!");
102   if (Section != CurSection) {
103     CurSection = Section;
104     Section->PrintSwitchToSection(MAI, OS);
105   }
106 }
107
108 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
109   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
110   assert(CurSection && "Cannot emit before setting section!");
111
112   OS << *Symbol << ":\n";
113   Symbol->setSection(*CurSection);
114 }
115
116 void MCAsmStreamer::EmitAssemblerFlag(AssemblerFlag Flag) {
117   switch (Flag) {
118   default: assert(0 && "Invalid flag!");
119   case SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
120   }
121   OS << '\n';
122 }
123
124 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
125   // Only absolute symbols can be redefined.
126   assert((Symbol->isUndefined() || Symbol->isAbsolute()) &&
127          "Cannot define a symbol twice!");
128
129   OS << *Symbol << " = " << *Value << '\n';
130
131   // FIXME: Lift context changes into super class.
132   // FIXME: Set associated section.
133   Symbol->setValue(Value);
134 }
135
136 void MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
137                                         SymbolAttr Attribute) {
138   switch (Attribute) {
139   case Global:         OS << ".globl";           break;
140   case Hidden:         OS << ".hidden";          break;
141   case IndirectSymbol: OS << ".indirect_symbol"; break;
142   case Internal:       OS << ".internal";        break;
143   case LazyReference:  OS << ".lazy_reference";  break;
144   case NoDeadStrip:    OS << ".no_dead_strip";   break;
145   case PrivateExtern:  OS << ".private_extern";  break;
146   case Protected:      OS << ".protected";       break;
147   case Reference:      OS << ".reference";       break;
148   case Weak:           OS << ".weak";            break;
149   case WeakDefinition: OS << ".weak_definition"; break;
150   case WeakReference:  OS << ".weak_reference";  break;
151   }
152
153   OS << ' ' << *Symbol << '\n';
154 }
155
156 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
157   OS << ".desc" << ' ' << *Symbol << ',' << DescValue << '\n';
158 }
159
160 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, unsigned Size,
161                                      unsigned ByteAlignment) {
162   OS << MAI.getCOMMDirective() << *Symbol << ',' << Size;
163   if (ByteAlignment != 0 && MAI.getCOMMDirectiveTakesAlignment()) {
164     if (MAI.getAlignmentIsInBytes())
165       OS << ',' << ByteAlignment;
166     else
167       OS << ',' << Log2_32(ByteAlignment);
168   }
169   OS << '\n';
170 }
171
172 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
173                                  unsigned Size, unsigned ByteAlignment) {
174   // Note: a .zerofill directive does not switch sections.
175   OS << ".zerofill ";
176   
177   // This is a mach-o specific directive.
178   const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
179   OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
180   
181   if (Symbol != NULL) {
182     OS << ',' << *Symbol << ',' << Size;
183     if (ByteAlignment != 0)
184       OS << ',' << Log2_32(ByteAlignment);
185   }
186   OS << '\n';
187 }
188
189 void MCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
190   assert(CurSection && "Cannot emit contents before setting section!");
191   const char *Directive = MAI.getData8bitsDirective(AddrSpace);
192   for (unsigned i = 0, e = Data.size(); i != e; ++i)
193     OS << Directive << (unsigned)(unsigned char)Data[i] << '\n';
194 }
195
196 /// EmitIntValue - Special case of EmitValue that avoids the client having
197 /// to pass in a MCExpr for constant integers.
198 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size,
199                                  unsigned AddrSpace) {
200   assert(CurSection && "Cannot emit contents before setting section!");
201   // Need target hooks to know how to print this.
202   const char *Directive = 0;
203   switch (Size) {
204   default: break;
205   case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
206   case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
207   case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
208   case 8: Directive = MAI.getData64bitsDirective(AddrSpace); break;
209   }
210   
211   assert(Directive && "Invalid size for machine code value!");
212   OS << Directive << truncateToSize(Value, Size) << '\n';
213 }
214
215 void MCAsmStreamer::EmitValue(const MCExpr *Value, unsigned Size,
216                               unsigned AddrSpace) {
217   assert(CurSection && "Cannot emit contents before setting section!");
218   // Need target hooks to know how to print this.
219   const char *Directive = 0;
220   switch (Size) {
221   default: break;
222   case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
223   case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
224   case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
225   case 8: Directive = MAI.getData64bitsDirective(AddrSpace); break;
226   }
227   
228   assert(Directive && "Invalid size for machine code value!");
229   OS << Directive << *truncateToSize(Value, Size) << '\n';
230 }
231
232 /// EmitFill - Emit NumBytes bytes worth of the value specified by
233 /// FillValue.  This implements directives such as '.space'.
234 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
235                              unsigned AddrSpace) {
236   if (NumBytes == 0) return;
237   
238   if (AddrSpace == 0)
239     if (const char *ZeroDirective = MAI.getZeroDirective()) {
240       OS << ZeroDirective << NumBytes;
241       if (FillValue != 0)
242         OS << ',' << (int)FillValue;
243       OS << '\n';
244       return;
245     }
246
247   // Emit a byte at a time.
248   MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
249 }
250
251 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
252                                          unsigned ValueSize,
253                                          unsigned MaxBytesToEmit) {
254   // Some assemblers don't support non-power of two alignments, so we always
255   // emit alignments as a power of two if possible.
256   if (isPowerOf2_32(ByteAlignment)) {
257     switch (ValueSize) {
258     default: llvm_unreachable("Invalid size for machine code value!");
259     case 1: OS << MAI.getAlignDirective(); break;
260     // FIXME: use MAI for this!
261     case 2: OS << ".p2alignw "; break;
262     case 4: OS << ".p2alignl "; break;
263     case 8: llvm_unreachable("Unsupported alignment size!");
264     }
265     
266     if (MAI.getAlignmentIsInBytes())
267       OS << ByteAlignment;
268     else
269       OS << Log2_32(ByteAlignment);
270
271     if (Value || MaxBytesToEmit) {
272       OS << ", 0x";
273       OS.write_hex(truncateToSize(Value, ValueSize));
274
275       if (MaxBytesToEmit) 
276         OS << ", " << MaxBytesToEmit;
277     }
278     OS << '\n';
279     return;
280   }
281   
282   // Non-power of two alignment.  This is not widely supported by assemblers.
283   // FIXME: Parameterize this based on MAI.
284   switch (ValueSize) {
285   default: llvm_unreachable("Invalid size for machine code value!");
286   case 1: OS << ".balign";  break;
287   case 2: OS << ".balignw"; break;
288   case 4: OS << ".balignl"; break;
289   case 8: llvm_unreachable("Unsupported alignment size!");
290   }
291
292   OS << ' ' << ByteAlignment;
293   OS << ", " << truncateToSize(Value, ValueSize);
294   if (MaxBytesToEmit) 
295     OS << ", " << MaxBytesToEmit;
296   OS << '\n';
297 }
298
299 void MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
300                                       unsigned char Value) {
301   // FIXME: Verify that Offset is associated with the current section.
302   OS << ".org " << *Offset << ", " << (unsigned) Value << '\n';
303 }
304
305 void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
306   assert(CurSection && "Cannot emit contents before setting section!");
307
308   // If we have an AsmPrinter, use that to print.
309   if (InstPrinter) {
310     InstPrinter->printInst(&Inst);
311     OS << '\n';
312
313     // Show the encoding if we have a code emitter.
314     if (Emitter) {
315       SmallString<256> Code;
316       raw_svector_ostream VecOS(Code);
317       Emitter->EncodeInstruction(Inst, VecOS);
318       VecOS.flush();
319   
320       OS.indent(20);
321       OS << " # encoding: [";
322       for (unsigned i = 0, e = Code.size(); i != e; ++i) {
323         if (i)
324           OS << ',';
325         OS << format("%#04x", uint8_t(Code[i]));
326       }
327       OS << "]\n";
328     }
329
330     return;
331   }
332
333   // Otherwise fall back to a structural printing for now. Eventually we should
334   // always have access to the target specific printer.
335   Inst.print(OS, &MAI);
336   OS << '\n';
337 }
338
339 void MCAsmStreamer::Finish() {
340   OS.flush();
341 }
342     
343 MCStreamer *llvm::createAsmStreamer(MCContext &Context, raw_ostream &OS,
344                                     const MCAsmInfo &MAI, bool isLittleEndian,
345                                     MCInstPrinter *IP,
346                                     MCCodeEmitter *CE) {
347   return new MCAsmStreamer(Context, OS, MAI, isLittleEndian, IP, CE);
348 }