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