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