1 //===- lib/MC/MCAsmStreamer.cpp - Text Assembly Output --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/MCStreamer.h"
11 #include "llvm/MC/MCAsmInfo.h"
12 #include "llvm/MC/MCCodeEmitter.h"
13 #include "llvm/MC/MCContext.h"
14 #include "llvm/MC/MCExpr.h"
15 #include "llvm/MC/MCInst.h"
16 #include "llvm/MC/MCInstPrinter.h"
17 #include "llvm/MC/MCSectionMachO.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/Format.h"
24 #include "llvm/Support/FormattedStream.h"
29 class MCAsmStreamer : public MCStreamer {
30 formatted_raw_ostream &OS;
32 bool IsLittleEndian, IsVerboseAsm;
33 MCInstPrinter *InstPrinter;
34 MCCodeEmitter *Emitter;
36 SmallString<128> CommentToEmit;
37 raw_svector_ostream CommentStream;
39 MCAsmStreamer(MCContext &Context, formatted_raw_ostream &os,
41 bool isLittleEndian, bool isVerboseAsm, MCInstPrinter *printer,
42 MCCodeEmitter *emitter)
43 : MCStreamer(Context), OS(os), MAI(mai), IsLittleEndian(isLittleEndian),
44 IsVerboseAsm(isVerboseAsm), InstPrinter(printer), Emitter(emitter),
45 CommentStream(CommentToEmit) {}
48 bool isLittleEndian() const { return IsLittleEndian; }
51 inline void EmitEOL() {
52 // If we don't have any comments, just emit a \n.
59 void EmitCommentsAndEOL();
61 /// AddComment - Add a comment that can be emitted to the generated .s
62 /// file if applicable as a QoI issue to make the output of the compiler
63 /// more readable. This only affects the MCAsmStreamer, and only when
64 /// verbose assembly output is enabled.
65 virtual void AddComment(const Twine &T);
67 /// GetCommentOS - Return a raw_ostream that comments can be written to.
68 /// Unlike AddComment, you are required to terminate comments with \n if you
70 virtual raw_ostream &GetCommentOS() {
72 return nulls(); // Discard comments unless in verbose asm mode.
76 /// @name MCStreamer Interface
79 virtual void SwitchSection(const MCSection *Section);
81 virtual void EmitLabel(MCSymbol *Symbol);
83 virtual void EmitAssemblerFlag(AssemblerFlag Flag);
85 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
87 virtual void EmitSymbolAttribute(MCSymbol *Symbol, SymbolAttr Attribute);
89 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
91 virtual void EmitCommonSymbol(MCSymbol *Symbol, unsigned Size,
92 unsigned ByteAlignment);
94 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
95 unsigned Size = 0, unsigned ByteAlignment = 0);
97 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
99 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
100 virtual void EmitIntValue(uint64_t Value, unsigned Size, unsigned AddrSpace);
102 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
105 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
106 unsigned ValueSize = 1,
107 unsigned MaxBytesToEmit = 0);
109 virtual void EmitValueToOffset(const MCExpr *Offset,
110 unsigned char Value = 0);
112 virtual void EmitInstruction(const MCInst &Inst);
114 virtual void Finish();
119 } // end anonymous namespace.
121 /// AddComment - Add a comment that can be emitted to the generated .s
122 /// file if applicable as a QoI issue to make the output of the compiler
123 /// more readable. This only affects the MCAsmStreamer, and only when
124 /// verbose assembly output is enabled.
125 void MCAsmStreamer::AddComment(const Twine &T) {
126 if (!IsVerboseAsm) return;
128 // Make sure that CommentStream is flushed.
129 CommentStream.flush();
131 T.toVector(CommentToEmit);
132 // Each comment goes on its own line.
133 CommentToEmit.push_back('\n');
136 void MCAsmStreamer::EmitCommentsAndEOL() {
137 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
142 CommentStream.flush();
143 StringRef Comments = CommentToEmit.str();
145 assert(Comments.back() == '\n' &&
146 "Comment array not newline terminated");
148 // Emit a line of comments.
149 OS.PadToColumn(MAI.getCommentColumn());
150 size_t Position = Comments.find('\n');
151 OS << MAI.getCommentString() << ' ' << Comments.substr(0, Position) << '\n';
153 Comments = Comments.substr(Position+1);
154 } while (!Comments.empty());
156 CommentStream.clear();
160 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
161 assert(Bytes && "Invalid size!");
162 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
165 static inline const MCExpr *truncateToSize(const MCExpr *Value,
167 // FIXME: Do we really need this routine?
171 void MCAsmStreamer::SwitchSection(const MCSection *Section) {
172 assert(Section && "Cannot switch to a null section!");
173 if (Section != CurSection) {
174 CurSection = Section;
175 Section->PrintSwitchToSection(MAI, OS);
179 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
180 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
181 assert(CurSection && "Cannot emit before setting section!");
183 OS << *Symbol << ":";
185 Symbol->setSection(*CurSection);
188 void MCAsmStreamer::EmitAssemblerFlag(AssemblerFlag Flag) {
190 default: assert(0 && "Invalid flag!");
191 case SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
196 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
197 // Only absolute symbols can be redefined.
198 assert((Symbol->isUndefined() || Symbol->isAbsolute()) &&
199 "Cannot define a symbol twice!");
201 OS << *Symbol << " = " << *Value;
204 // FIXME: Lift context changes into super class.
205 // FIXME: Set associated section.
206 Symbol->setValue(Value);
209 void MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
210 SymbolAttr Attribute) {
212 case Global: OS << MAI.getGlobalDirective(); break; // .globl
213 case Hidden: OS << ".hidden "; break;
214 case IndirectSymbol: OS << ".indirect_symbol "; break;
215 case Internal: OS << ".internal "; break;
216 case LazyReference: OS << ".lazy_reference "; break;
217 case NoDeadStrip: OS << ".no_dead_strip "; break;
218 case PrivateExtern: OS << ".private_extern "; break;
219 case Protected: OS << ".protected "; break;
220 case Reference: OS << ".reference "; break;
221 case Weak: OS << ".weak "; break;
222 case WeakDefinition: OS << ".weak_definition "; break;
223 case WeakReference: OS << ".weak_reference "; break;
230 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
231 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
235 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, unsigned Size,
236 unsigned ByteAlignment) {
237 OS << MAI.getCOMMDirective() << *Symbol << ',' << Size;
238 if (ByteAlignment != 0 && MAI.getCOMMDirectiveTakesAlignment()) {
239 if (MAI.getAlignmentIsInBytes())
240 OS << ',' << ByteAlignment;
242 OS << ',' << Log2_32(ByteAlignment);
247 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
248 unsigned Size, unsigned ByteAlignment) {
249 // Note: a .zerofill directive does not switch sections.
252 // This is a mach-o specific directive.
253 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
254 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
256 if (Symbol != NULL) {
257 OS << ',' << *Symbol << ',' << Size;
258 if (ByteAlignment != 0)
259 OS << ',' << Log2_32(ByteAlignment);
264 void MCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
265 assert(CurSection && "Cannot emit contents before setting section!");
266 const char *Directive = MAI.getData8bitsDirective(AddrSpace);
267 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
268 OS << Directive << (unsigned)(unsigned char)Data[i];
273 /// EmitIntValue - Special case of EmitValue that avoids the client having
274 /// to pass in a MCExpr for constant integers.
275 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size,
276 unsigned AddrSpace) {
277 assert(CurSection && "Cannot emit contents before setting section!");
278 const char *Directive = 0;
281 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
282 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
283 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
285 Directive = MAI.getData64bitsDirective(AddrSpace);
286 // If the target doesn't support 64-bit data, emit as two 32-bit halves.
287 if (Directive) break;
288 if (isLittleEndian()) {
289 EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
290 EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
292 EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
293 EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
298 assert(Directive && "Invalid size for machine code value!");
299 OS << Directive << truncateToSize(Value, Size);
303 void MCAsmStreamer::EmitValue(const MCExpr *Value, unsigned Size,
304 unsigned AddrSpace) {
305 assert(CurSection && "Cannot emit contents before setting section!");
306 const char *Directive = 0;
309 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
310 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
311 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
312 case 8: Directive = MAI.getData64bitsDirective(AddrSpace); break;
315 assert(Directive && "Invalid size for machine code value!");
316 OS << Directive << *truncateToSize(Value, Size);
320 /// EmitFill - Emit NumBytes bytes worth of the value specified by
321 /// FillValue. This implements directives such as '.space'.
322 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
323 unsigned AddrSpace) {
324 if (NumBytes == 0) return;
327 if (const char *ZeroDirective = MAI.getZeroDirective()) {
328 OS << ZeroDirective << NumBytes;
330 OS << ',' << (int)FillValue;
335 // Emit a byte at a time.
336 MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
339 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
341 unsigned MaxBytesToEmit) {
342 // Some assemblers don't support non-power of two alignments, so we always
343 // emit alignments as a power of two if possible.
344 if (isPowerOf2_32(ByteAlignment)) {
346 default: llvm_unreachable("Invalid size for machine code value!");
347 case 1: OS << MAI.getAlignDirective(); break;
348 // FIXME: use MAI for this!
349 case 2: OS << ".p2alignw "; break;
350 case 4: OS << ".p2alignl "; break;
351 case 8: llvm_unreachable("Unsupported alignment size!");
354 if (MAI.getAlignmentIsInBytes())
357 OS << Log2_32(ByteAlignment);
359 if (Value || MaxBytesToEmit) {
361 OS.write_hex(truncateToSize(Value, ValueSize));
364 OS << ", " << MaxBytesToEmit;
370 // Non-power of two alignment. This is not widely supported by assemblers.
371 // FIXME: Parameterize this based on MAI.
373 default: llvm_unreachable("Invalid size for machine code value!");
374 case 1: OS << ".balign"; break;
375 case 2: OS << ".balignw"; break;
376 case 4: OS << ".balignl"; break;
377 case 8: llvm_unreachable("Unsupported alignment size!");
380 OS << ' ' << ByteAlignment;
381 OS << ", " << truncateToSize(Value, ValueSize);
383 OS << ", " << MaxBytesToEmit;
387 void MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
388 unsigned char Value) {
389 // FIXME: Verify that Offset is associated with the current section.
390 OS << ".org " << *Offset << ", " << (unsigned) Value;
394 void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
395 assert(CurSection && "Cannot emit contents before setting section!");
397 // If we have an AsmPrinter, use that to print.
399 InstPrinter->printInst(&Inst);
402 // Show the encoding if we have a code emitter.
404 SmallString<256> Code;
405 raw_svector_ostream VecOS(Code);
406 Emitter->EncodeInstruction(Inst, VecOS);
410 OS << " # encoding: [";
411 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
414 OS << format("%#04x", uint8_t(Code[i]));
422 // Otherwise fall back to a structural printing for now. Eventually we should
423 // always have access to the target specific printer.
424 Inst.print(OS, &MAI);
428 void MCAsmStreamer::Finish() {
432 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
433 formatted_raw_ostream &OS,
434 const MCAsmInfo &MAI, bool isLittleEndian,
435 bool isVerboseAsm, MCInstPrinter *IP,
437 return new MCAsmStreamer(Context, OS, MAI, isLittleEndian, isVerboseAsm,