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 MCInstPrinter *InstPrinter;
33 MCCodeEmitter *Emitter;
35 SmallString<128> CommentToEmit;
36 raw_svector_ostream CommentStream;
38 unsigned IsLittleEndian : 1;
39 unsigned IsVerboseAsm : 1;
40 unsigned ShowInst : 1;
43 MCAsmStreamer(MCContext &Context, formatted_raw_ostream &os,
44 bool isLittleEndian, bool isVerboseAsm, MCInstPrinter *printer,
45 MCCodeEmitter *emitter, bool showInst)
46 : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
47 InstPrinter(printer), Emitter(emitter), CommentStream(CommentToEmit),
48 IsLittleEndian(isLittleEndian), IsVerboseAsm(isVerboseAsm),
50 if (InstPrinter && IsVerboseAsm)
51 InstPrinter->setCommentStream(CommentStream);
55 bool isLittleEndian() const { return IsLittleEndian; }
57 inline void EmitEOL() {
58 // If we don't have any comments, just emit a \n.
65 void EmitCommentsAndEOL();
67 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
69 virtual bool isVerboseAsm() const { return IsVerboseAsm; }
71 /// AddComment - Add a comment that can be emitted to the generated .s
72 /// file if applicable as a QoI issue to make the output of the compiler
73 /// more readable. This only affects the MCAsmStreamer, and only when
74 /// verbose assembly output is enabled.
75 virtual void AddComment(const Twine &T);
77 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
78 virtual void AddEncodingComment(const MCInst &Inst);
80 /// GetCommentOS - Return a raw_ostream that comments can be written to.
81 /// Unlike AddComment, you are required to terminate comments with \n if you
83 virtual raw_ostream &GetCommentOS() {
85 return nulls(); // Discard comments unless in verbose asm mode.
89 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
90 virtual void AddBlankLine() {
94 /// @name MCStreamer Interface
97 virtual void SwitchSection(const MCSection *Section);
99 virtual void EmitLabel(MCSymbol *Symbol);
101 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
103 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
105 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
107 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
109 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
110 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
111 unsigned ByteAlignment);
113 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
115 /// @param Symbol - The common symbol to emit.
116 /// @param Size - The size of the common symbol.
117 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size);
119 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
120 unsigned Size = 0, unsigned ByteAlignment = 0);
122 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
124 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
125 virtual void EmitIntValue(uint64_t Value, unsigned Size, unsigned AddrSpace);
126 virtual void EmitGPRel32Value(const MCExpr *Value);
129 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
132 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
133 unsigned ValueSize = 1,
134 unsigned MaxBytesToEmit = 0);
136 virtual void EmitCodeAlignment(unsigned ByteAlignment,
137 unsigned MaxBytesToEmit = 0);
139 virtual void EmitValueToOffset(const MCExpr *Offset,
140 unsigned char Value = 0);
142 virtual void EmitFileDirective(StringRef Filename);
143 virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename);
145 virtual void EmitInstruction(const MCInst &Inst);
147 virtual void Finish();
152 } // end anonymous namespace.
154 /// AddComment - Add a comment that can be emitted to the generated .s
155 /// file if applicable as a QoI issue to make the output of the compiler
156 /// more readable. This only affects the MCAsmStreamer, and only when
157 /// verbose assembly output is enabled.
158 void MCAsmStreamer::AddComment(const Twine &T) {
159 if (!IsVerboseAsm) return;
161 // Make sure that CommentStream is flushed.
162 CommentStream.flush();
164 T.toVector(CommentToEmit);
165 // Each comment goes on its own line.
166 CommentToEmit.push_back('\n');
168 // Tell the comment stream that the vector changed underneath it.
169 CommentStream.resync();
172 void MCAsmStreamer::EmitCommentsAndEOL() {
173 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
178 CommentStream.flush();
179 StringRef Comments = CommentToEmit.str();
181 assert(Comments.back() == '\n' &&
182 "Comment array not newline terminated");
184 // Emit a line of comments.
185 OS.PadToColumn(MAI.getCommentColumn());
186 size_t Position = Comments.find('\n');
187 OS << MAI.getCommentString() << ' ' << Comments.substr(0, Position) << '\n';
189 Comments = Comments.substr(Position+1);
190 } while (!Comments.empty());
192 CommentToEmit.clear();
193 // Tell the comment stream that the vector changed underneath it.
194 CommentStream.resync();
198 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
199 assert(Bytes && "Invalid size!");
200 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
203 void MCAsmStreamer::SwitchSection(const MCSection *Section) {
204 assert(Section && "Cannot switch to a null section!");
205 if (Section != CurSection) {
206 CurSection = Section;
207 Section->PrintSwitchToSection(MAI, OS);
211 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
212 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
213 assert(CurSection && "Cannot emit before setting section!");
215 OS << *Symbol << ":";
217 Symbol->setSection(*CurSection);
220 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
222 default: assert(0 && "Invalid flag!");
223 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
228 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
229 // Only absolute symbols can be redefined.
230 assert((Symbol->isUndefined() || Symbol->isAbsolute()) &&
231 "Cannot define a symbol twice!");
233 OS << *Symbol << " = " << *Value;
236 // FIXME: Lift context changes into super class.
237 // FIXME: Set associated section.
238 Symbol->setValue(Value);
241 void MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
242 MCSymbolAttr Attribute) {
244 case MCSA_Invalid: assert(0 && "Invalid symbol attribute");
245 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
246 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
247 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
248 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
249 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
250 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
251 assert(MAI.hasDotTypeDotSizeDirective() && "Symbol Attr not supported");
252 OS << "\t.type\t" << *Symbol << ','
253 << ((MAI.getCommentString()[0] != '@') ? '@' : '%');
255 default: assert(0 && "Unknown ELF .type");
256 case MCSA_ELF_TypeFunction: OS << "function"; break;
257 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
258 case MCSA_ELF_TypeObject: OS << "object"; break;
259 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
260 case MCSA_ELF_TypeCommon: OS << "common"; break;
261 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
265 case MCSA_Global: // .globl/.global
266 OS << MAI.getGlobalDirective();
268 case MCSA_Hidden: OS << ".hidden "; break;
269 case MCSA_IndirectSymbol: OS << ".indirect_symbol "; break;
270 case MCSA_Internal: OS << ".internal "; break;
271 case MCSA_LazyReference: OS << ".lazy_reference "; break;
272 case MCSA_Local: OS << ".local "; break;
273 case MCSA_NoDeadStrip: OS << ".no_dead_strip "; break;
274 case MCSA_PrivateExtern: OS << ".private_extern "; break;
275 case MCSA_Protected: OS << ".protected "; break;
276 case MCSA_Reference: OS << ".reference "; break;
277 case MCSA_Weak: OS << ".weak "; break;
278 case MCSA_WeakDefinition: OS << ".weak_definition "; break;
280 case MCSA_WeakReference: OS << MAI.getWeakRefDirective(); break;
287 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
288 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
292 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
293 assert(MAI.hasDotTypeDotSizeDirective());
294 OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
297 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
298 unsigned ByteAlignment) {
299 OS << "\t.comm\t" << *Symbol << ',' << Size;
300 if (ByteAlignment != 0) {
301 if (MAI.getCOMMDirectiveAlignmentIsInBytes())
302 OS << ',' << ByteAlignment;
304 OS << ',' << Log2_32(ByteAlignment);
309 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
311 /// @param Symbol - The common symbol to emit.
312 /// @param Size - The size of the common symbol.
313 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
314 assert(MAI.hasLCOMMDirective() && "Doesn't have .lcomm, can't emit it!");
315 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
319 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
320 unsigned Size, unsigned ByteAlignment) {
321 // Note: a .zerofill directive does not switch sections.
324 // This is a mach-o specific directive.
325 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
326 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
328 if (Symbol != NULL) {
329 OS << ',' << *Symbol << ',' << Size;
330 if (ByteAlignment != 0)
331 OS << ',' << Log2_32(ByteAlignment);
336 static inline char toOctal(int X) { return (X&7)+'0'; }
338 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
341 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
342 unsigned char C = Data[i];
343 if (C == '"' || C == '\\') {
344 OS << '\\' << (char)C;
348 if (isprint((unsigned char)C)) {
354 case '\b': OS << "\\b"; break;
355 case '\f': OS << "\\f"; break;
356 case '\n': OS << "\\n"; break;
357 case '\r': OS << "\\r"; break;
358 case '\t': OS << "\\t"; break;
361 OS << toOctal(C >> 6);
362 OS << toOctal(C >> 3);
363 OS << toOctal(C >> 0);
372 void MCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
373 assert(CurSection && "Cannot emit contents before setting section!");
374 if (Data.empty()) return;
376 if (Data.size() == 1) {
377 OS << MAI.getData8bitsDirective(AddrSpace);
378 OS << (unsigned)(unsigned char)Data[0];
383 // If the data ends with 0 and the target supports .asciz, use it, otherwise
385 if (MAI.getAscizDirective() && Data.back() == 0) {
386 OS << MAI.getAscizDirective();
387 Data = Data.substr(0, Data.size()-1);
389 OS << MAI.getAsciiDirective();
393 PrintQuotedString(Data, OS);
397 /// EmitIntValue - Special case of EmitValue that avoids the client having
398 /// to pass in a MCExpr for constant integers.
399 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size,
400 unsigned AddrSpace) {
401 assert(CurSection && "Cannot emit contents before setting section!");
402 const char *Directive = 0;
405 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
406 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
407 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
409 Directive = MAI.getData64bitsDirective(AddrSpace);
410 // If the target doesn't support 64-bit data, emit as two 32-bit halves.
411 if (Directive) break;
412 if (isLittleEndian()) {
413 EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
414 EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
416 EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
417 EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
422 assert(Directive && "Invalid size for machine code value!");
423 OS << Directive << truncateToSize(Value, Size);
427 void MCAsmStreamer::EmitValue(const MCExpr *Value, unsigned Size,
428 unsigned AddrSpace) {
429 assert(CurSection && "Cannot emit contents before setting section!");
430 const char *Directive = 0;
433 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
434 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
435 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
436 case 8: Directive = MAI.getData64bitsDirective(AddrSpace); break;
439 assert(Directive && "Invalid size for machine code value!");
440 OS << Directive << *Value;
444 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
445 assert(MAI.getGPRel32Directive() != 0);
446 OS << MAI.getGPRel32Directive() << *Value;
451 /// EmitFill - Emit NumBytes bytes worth of the value specified by
452 /// FillValue. This implements directives such as '.space'.
453 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
454 unsigned AddrSpace) {
455 if (NumBytes == 0) return;
458 if (const char *ZeroDirective = MAI.getZeroDirective()) {
459 OS << ZeroDirective << NumBytes;
461 OS << ',' << (int)FillValue;
466 // Emit a byte at a time.
467 MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
470 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
472 unsigned MaxBytesToEmit) {
473 // Some assemblers don't support non-power of two alignments, so we always
474 // emit alignments as a power of two if possible.
475 if (isPowerOf2_32(ByteAlignment)) {
477 default: llvm_unreachable("Invalid size for machine code value!");
478 case 1: OS << MAI.getAlignDirective(); break;
479 // FIXME: use MAI for this!
480 case 2: OS << ".p2alignw "; break;
481 case 4: OS << ".p2alignl "; break;
482 case 8: llvm_unreachable("Unsupported alignment size!");
485 if (MAI.getAlignmentIsInBytes())
488 OS << Log2_32(ByteAlignment);
490 if (Value || MaxBytesToEmit) {
492 OS.write_hex(truncateToSize(Value, ValueSize));
495 OS << ", " << MaxBytesToEmit;
501 // Non-power of two alignment. This is not widely supported by assemblers.
502 // FIXME: Parameterize this based on MAI.
504 default: llvm_unreachable("Invalid size for machine code value!");
505 case 1: OS << ".balign"; break;
506 case 2: OS << ".balignw"; break;
507 case 4: OS << ".balignl"; break;
508 case 8: llvm_unreachable("Unsupported alignment size!");
511 OS << ' ' << ByteAlignment;
512 OS << ", " << truncateToSize(Value, ValueSize);
514 OS << ", " << MaxBytesToEmit;
518 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
519 unsigned MaxBytesToEmit) {
520 // Emit with a text fill value.
521 EmitValueToAlignment(ByteAlignment, MAI.getTextAlignFillValue(),
525 void MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
526 unsigned char Value) {
527 // FIXME: Verify that Offset is associated with the current section.
528 OS << ".org " << *Offset << ", " << (unsigned) Value;
533 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
534 assert(MAI.hasSingleParameterDotFile());
536 PrintQuotedString(Filename, OS);
540 void MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Filename){
541 OS << "\t.file\t" << FileNo << ' ';
542 PrintQuotedString(Filename, OS);
546 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst) {
547 raw_ostream &OS = GetCommentOS();
548 SmallString<256> Code;
549 SmallVector<MCFixup, 4> Fixups;
550 raw_svector_ostream VecOS(Code);
551 Emitter->EncodeInstruction(Inst, VecOS, Fixups);
554 // If we are showing fixups, create symbolic markers in the encoded
555 // representation. We do this by making a per-bit map to the fixup item index,
556 // then trying to display it as nicely as possible.
557 SmallVector<uint8_t, 64> FixupMap;
558 FixupMap.resize(Code.size() * 8);
559 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
562 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
563 MCFixup &F = Fixups[i];
564 const MCFixupKindInfo &Info = Emitter->getFixupKindInfo(F.getKind());
565 for (unsigned j = 0; j != Info.TargetSize; ++j) {
566 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
567 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
568 FixupMap[Index] = 1 + i;
573 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
577 // See if all bits are the same map entry.
578 uint8_t MapEntry = FixupMap[i * 8 + 0];
579 for (unsigned j = 1; j != 8; ++j) {
580 if (FixupMap[i * 8 + j] == MapEntry)
583 MapEntry = uint8_t(~0U);
587 if (MapEntry != uint8_t(~0U)) {
589 OS << format("0x%02x", uint8_t(Code[i]));
591 assert(Code[i] == 0 && "Encoder wrote into fixed up bit!");
592 OS << char('A' + MapEntry - 1);
595 // Otherwise, write out in binary.
597 for (unsigned j = 8; j--;) {
598 unsigned Bit = (Code[i] >> j) & 1;
599 if (uint8_t MapEntry = FixupMap[i * 8 + j]) {
600 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
601 OS << char('A' + MapEntry - 1);
609 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
610 MCFixup &F = Fixups[i];
611 const MCFixupKindInfo &Info = Emitter->getFixupKindInfo(F.getKind());
612 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
613 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
617 void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
618 assert(CurSection && "Cannot emit contents before setting section!");
620 // Show the encoding in a comment if we have a code emitter.
622 AddEncodingComment(Inst);
624 // Show the MCInst if enabled.
626 raw_ostream &OS = GetCommentOS();
627 OS << "<MCInst #" << Inst.getOpcode();
631 InstName = InstPrinter->getOpcodeName(Inst.getOpcode());
632 if (!InstName.empty())
633 OS << ' ' << InstName;
635 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
637 Inst.getOperand(i).print(OS, &MAI);
642 // If we have an AsmPrinter, use that to print, otherwise dump the MCInst.
644 InstPrinter->printInst(&Inst);
646 Inst.print(OS, &MAI);
650 void MCAsmStreamer::Finish() {
654 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
655 formatted_raw_ostream &OS,
657 bool isVerboseAsm, MCInstPrinter *IP,
658 MCCodeEmitter *CE, bool ShowInst) {
659 return new MCAsmStreamer(Context, OS, isLittleEndian, isVerboseAsm,