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