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 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
77 virtual void AddBlankLine() {
81 /// @name MCStreamer Interface
84 virtual void SwitchSection(const MCSection *Section);
86 virtual void EmitLabel(MCSymbol *Symbol);
88 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
90 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
92 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
94 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
96 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
97 unsigned ByteAlignment);
99 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
101 /// @param Symbol - The common symbol to emit.
102 /// @param Size - The size of the common symbol.
103 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size);
105 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
106 unsigned Size = 0, unsigned ByteAlignment = 0);
108 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
110 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
111 virtual void EmitIntValue(uint64_t Value, unsigned Size, unsigned AddrSpace);
113 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
116 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
117 unsigned ValueSize = 1,
118 unsigned MaxBytesToEmit = 0);
120 virtual void EmitValueToOffset(const MCExpr *Offset,
121 unsigned char Value = 0);
123 virtual void EmitInstruction(const MCInst &Inst);
125 virtual void Finish();
130 } // end anonymous namespace.
132 /// AddComment - Add a comment that can be emitted to the generated .s
133 /// file if applicable as a QoI issue to make the output of the compiler
134 /// more readable. This only affects the MCAsmStreamer, and only when
135 /// verbose assembly output is enabled.
136 void MCAsmStreamer::AddComment(const Twine &T) {
137 if (!IsVerboseAsm) return;
139 // Make sure that CommentStream is flushed.
140 CommentStream.flush();
142 T.toVector(CommentToEmit);
143 // Each comment goes on its own line.
144 CommentToEmit.push_back('\n');
146 // Tell the comment stream that the vector changed underneath it.
147 CommentStream.resync();
150 void MCAsmStreamer::EmitCommentsAndEOL() {
151 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
156 CommentStream.flush();
157 StringRef Comments = CommentToEmit.str();
159 assert(Comments.back() == '\n' &&
160 "Comment array not newline terminated");
162 // Emit a line of comments.
163 OS.PadToColumn(MAI.getCommentColumn());
164 size_t Position = Comments.find('\n');
165 OS << MAI.getCommentString() << ' ' << Comments.substr(0, Position) << '\n';
167 Comments = Comments.substr(Position+1);
168 } while (!Comments.empty());
170 CommentToEmit.clear();
171 // Tell the comment stream that the vector changed underneath it.
172 CommentStream.resync();
176 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
177 assert(Bytes && "Invalid size!");
178 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
181 static inline const MCExpr *truncateToSize(const MCExpr *Value,
183 // FIXME: Do we really need this routine?
187 void MCAsmStreamer::SwitchSection(const MCSection *Section) {
188 assert(Section && "Cannot switch to a null section!");
189 if (Section != CurSection) {
190 CurSection = Section;
191 Section->PrintSwitchToSection(MAI, OS);
195 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
196 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
197 assert(CurSection && "Cannot emit before setting section!");
199 OS << *Symbol << ":";
201 Symbol->setSection(*CurSection);
204 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
206 default: assert(0 && "Invalid flag!");
207 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
212 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
213 // Only absolute symbols can be redefined.
214 assert((Symbol->isUndefined() || Symbol->isAbsolute()) &&
215 "Cannot define a symbol twice!");
217 OS << *Symbol << " = " << *Value;
220 // FIXME: Lift context changes into super class.
221 // FIXME: Set associated section.
222 Symbol->setValue(Value);
225 void MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
226 MCSymbolAttr Attribute) {
228 case MCSA_Invalid: assert(0 && "Invalid symbol attribute");
229 case MCSA_Global: OS << MAI.getGlobalDirective(); break; // .globl
230 case MCSA_Hidden: OS << ".hidden "; break;
231 case MCSA_IndirectSymbol: OS << ".indirect_symbol "; break;
232 case MCSA_Internal: OS << ".internal "; break;
233 case MCSA_LazyReference: OS << ".lazy_reference "; break;
234 case MCSA_Local: OS << ".local "; break;
235 case MCSA_NoDeadStrip: OS << ".no_dead_strip "; break;
236 case MCSA_PrivateExtern: OS << ".private_extern "; break;
237 case MCSA_Protected: OS << ".protected "; break;
238 case MCSA_Reference: OS << ".reference "; break;
239 case MCSA_Weak: OS << ".weak "; break;
240 case MCSA_WeakDefinition: OS << ".weak_definition "; break;
242 case MCSA_WeakReference: OS << MAI.getWeakRefDirective(); break;
249 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
250 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
254 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
255 unsigned ByteAlignment) {
256 OS << "\t.comm\t" << *Symbol << ',' << Size;
257 if (ByteAlignment != 0) {
258 if (MAI.getAlignmentIsInBytes())
259 OS << ',' << ByteAlignment;
261 OS << ',' << Log2_32(ByteAlignment);
266 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
268 /// @param Symbol - The common symbol to emit.
269 /// @param Size - The size of the common symbol.
270 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
271 assert(MAI.hasLCOMMDirective() && "Doesn't have .lcomm, can't emit it!");
272 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
276 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
277 unsigned Size, unsigned ByteAlignment) {
278 // Note: a .zerofill directive does not switch sections.
281 // This is a mach-o specific directive.
282 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
283 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
285 if (Symbol != NULL) {
286 OS << ',' << *Symbol << ',' << Size;
287 if (ByteAlignment != 0)
288 OS << ',' << Log2_32(ByteAlignment);
293 static inline char toOctal(int X) { return (X&7)+'0'; }
295 void MCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
296 assert(CurSection && "Cannot emit contents before setting section!");
297 if (Data.empty()) return;
299 if (Data.size() == 1) {
300 OS << MAI.getData8bitsDirective(AddrSpace);
301 OS << (unsigned)(unsigned char)Data[0];
306 // If the data ends with 0 and the target supports .asciz, use it, otherwise
308 if (MAI.getAscizDirective() && Data.back() == 0) {
309 OS << MAI.getAscizDirective();
310 Data = Data.substr(0, Data.size()-1);
312 OS << MAI.getAsciiDirective();
316 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
317 unsigned char C = Data[i];
318 if (C == '"' || C == '\\') {
319 OS << '\\' << (char)C;
323 if (isprint((unsigned char)C)) {
329 case '\b': OS << "\\b"; break;
330 case '\f': OS << "\\f"; break;
331 case '\n': OS << "\\n"; break;
332 case '\r': OS << "\\r"; break;
333 case '\t': OS << "\\t"; break;
336 OS << toOctal(C >> 6);
337 OS << toOctal(C >> 3);
338 OS << toOctal(C >> 0);
346 /// EmitIntValue - Special case of EmitValue that avoids the client having
347 /// to pass in a MCExpr for constant integers.
348 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size,
349 unsigned AddrSpace) {
350 assert(CurSection && "Cannot emit contents before setting section!");
351 const char *Directive = 0;
354 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
355 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
356 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
358 Directive = MAI.getData64bitsDirective(AddrSpace);
359 // If the target doesn't support 64-bit data, emit as two 32-bit halves.
360 if (Directive) break;
361 if (isLittleEndian()) {
362 EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
363 EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
365 EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
366 EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
371 assert(Directive && "Invalid size for machine code value!");
372 OS << Directive << truncateToSize(Value, Size);
376 void MCAsmStreamer::EmitValue(const MCExpr *Value, unsigned Size,
377 unsigned AddrSpace) {
378 assert(CurSection && "Cannot emit contents before setting section!");
379 const char *Directive = 0;
382 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
383 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
384 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
385 case 8: Directive = MAI.getData64bitsDirective(AddrSpace); break;
388 assert(Directive && "Invalid size for machine code value!");
389 OS << Directive << *truncateToSize(Value, Size);
393 /// EmitFill - Emit NumBytes bytes worth of the value specified by
394 /// FillValue. This implements directives such as '.space'.
395 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
396 unsigned AddrSpace) {
397 if (NumBytes == 0) return;
400 if (const char *ZeroDirective = MAI.getZeroDirective()) {
401 OS << ZeroDirective << NumBytes;
403 OS << ',' << (int)FillValue;
408 // Emit a byte at a time.
409 MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
412 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
414 unsigned MaxBytesToEmit) {
415 // Some assemblers don't support non-power of two alignments, so we always
416 // emit alignments as a power of two if possible.
417 if (isPowerOf2_32(ByteAlignment)) {
419 default: llvm_unreachable("Invalid size for machine code value!");
420 case 1: OS << MAI.getAlignDirective(); break;
421 // FIXME: use MAI for this!
422 case 2: OS << ".p2alignw "; break;
423 case 4: OS << ".p2alignl "; break;
424 case 8: llvm_unreachable("Unsupported alignment size!");
427 if (MAI.getAlignmentIsInBytes())
430 OS << Log2_32(ByteAlignment);
432 if (Value || MaxBytesToEmit) {
434 OS.write_hex(truncateToSize(Value, ValueSize));
437 OS << ", " << MaxBytesToEmit;
443 // Non-power of two alignment. This is not widely supported by assemblers.
444 // FIXME: Parameterize this based on MAI.
446 default: llvm_unreachable("Invalid size for machine code value!");
447 case 1: OS << ".balign"; break;
448 case 2: OS << ".balignw"; break;
449 case 4: OS << ".balignl"; break;
450 case 8: llvm_unreachable("Unsupported alignment size!");
453 OS << ' ' << ByteAlignment;
454 OS << ", " << truncateToSize(Value, ValueSize);
456 OS << ", " << MaxBytesToEmit;
460 void MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
461 unsigned char Value) {
462 // FIXME: Verify that Offset is associated with the current section.
463 OS << ".org " << *Offset << ", " << (unsigned) Value;
467 void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
468 assert(CurSection && "Cannot emit contents before setting section!");
470 // If we have an AsmPrinter, use that to print.
472 InstPrinter->printInst(&Inst);
475 // Show the encoding if we have a code emitter.
477 SmallString<256> Code;
478 raw_svector_ostream VecOS(Code);
479 Emitter->EncodeInstruction(Inst, VecOS);
483 OS << " # encoding: [";
484 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
487 OS << format("%#04x", uint8_t(Code[i]));
495 // Otherwise fall back to a structural printing for now. Eventually we should
496 // always have access to the target specific printer.
497 Inst.print(OS, &MAI);
501 void MCAsmStreamer::Finish() {
505 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
506 formatted_raw_ostream &OS,
507 const MCAsmInfo &MAI, bool isLittleEndian,
508 bool isVerboseAsm, MCInstPrinter *IP,
510 return new MCAsmStreamer(Context, OS, MAI, isLittleEndian, isVerboseAsm,