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,
45 bool isLittleEndian, bool isVerboseAsm, MCInstPrinter *printer,
46 MCCodeEmitter *emitter, bool showInst)
47 : MCStreamer(Context), OS(os), MAI(mai), InstPrinter(printer),
48 Emitter(emitter), CommentStream(CommentToEmit),
49 IsLittleEndian(isLittleEndian), IsVerboseAsm(isVerboseAsm),
51 if (InstPrinter && IsVerboseAsm)
52 InstPrinter->setCommentStream(CommentStream);
56 bool isLittleEndian() const { return IsLittleEndian; }
58 inline void EmitEOL() {
59 // If we don't have any comments, just emit a \n.
66 void EmitCommentsAndEOL();
68 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
70 virtual bool isVerboseAsm() const { return IsVerboseAsm; }
72 /// AddComment - Add a comment that can be emitted to the generated .s
73 /// file if applicable as a QoI issue to make the output of the compiler
74 /// more readable. This only affects the MCAsmStreamer, and only when
75 /// verbose assembly output is enabled.
76 virtual void AddComment(const Twine &T);
78 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
79 virtual void AddEncodingComment(const MCInst &Inst);
81 /// GetCommentOS - Return a raw_ostream that comments can be written to.
82 /// Unlike AddComment, you are required to terminate comments with \n if you
84 virtual raw_ostream &GetCommentOS() {
86 return nulls(); // Discard comments unless in verbose asm mode.
90 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
91 virtual void AddBlankLine() {
95 /// @name MCStreamer Interface
98 virtual void SwitchSection(const MCSection *Section);
100 virtual void EmitLabel(MCSymbol *Symbol);
102 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
104 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
106 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
108 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
110 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
111 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
112 unsigned ByteAlignment);
114 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
116 /// @param Symbol - The common symbol to emit.
117 /// @param Size - The size of the common symbol.
118 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size);
120 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
121 unsigned Size = 0, unsigned ByteAlignment = 0);
123 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
125 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
126 virtual void EmitIntValue(uint64_t Value, unsigned Size, unsigned AddrSpace);
127 virtual void EmitGPRel32Value(const MCExpr *Value);
130 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
133 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
134 unsigned ValueSize = 1,
135 unsigned MaxBytesToEmit = 0);
137 virtual void EmitValueToOffset(const MCExpr *Offset,
138 unsigned char Value = 0);
140 virtual void EmitFileDirective(StringRef Filename);
141 virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename);
143 virtual void EmitInstruction(const MCInst &Inst);
145 virtual void Finish();
150 } // end anonymous namespace.
152 /// AddComment - Add a comment that can be emitted to the generated .s
153 /// file if applicable as a QoI issue to make the output of the compiler
154 /// more readable. This only affects the MCAsmStreamer, and only when
155 /// verbose assembly output is enabled.
156 void MCAsmStreamer::AddComment(const Twine &T) {
157 if (!IsVerboseAsm) return;
159 // Make sure that CommentStream is flushed.
160 CommentStream.flush();
162 T.toVector(CommentToEmit);
163 // Each comment goes on its own line.
164 CommentToEmit.push_back('\n');
166 // Tell the comment stream that the vector changed underneath it.
167 CommentStream.resync();
170 void MCAsmStreamer::EmitCommentsAndEOL() {
171 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
176 CommentStream.flush();
177 StringRef Comments = CommentToEmit.str();
179 assert(Comments.back() == '\n' &&
180 "Comment array not newline terminated");
182 // Emit a line of comments.
183 OS.PadToColumn(MAI.getCommentColumn());
184 size_t Position = Comments.find('\n');
185 OS << MAI.getCommentString() << ' ' << Comments.substr(0, Position) << '\n';
187 Comments = Comments.substr(Position+1);
188 } while (!Comments.empty());
190 CommentToEmit.clear();
191 // Tell the comment stream that the vector changed underneath it.
192 CommentStream.resync();
196 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
197 assert(Bytes && "Invalid size!");
198 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
201 void MCAsmStreamer::SwitchSection(const MCSection *Section) {
202 assert(Section && "Cannot switch to a null section!");
203 if (Section != CurSection) {
204 CurSection = Section;
205 Section->PrintSwitchToSection(MAI, OS);
209 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
210 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
211 assert(CurSection && "Cannot emit before setting section!");
213 OS << *Symbol << ":";
215 Symbol->setSection(*CurSection);
218 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
220 default: assert(0 && "Invalid flag!");
221 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
226 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
227 // Only absolute symbols can be redefined.
228 assert((Symbol->isUndefined() || Symbol->isAbsolute()) &&
229 "Cannot define a symbol twice!");
231 OS << *Symbol << " = " << *Value;
234 // FIXME: Lift context changes into super class.
235 // FIXME: Set associated section.
236 Symbol->setValue(Value);
239 void MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
240 MCSymbolAttr Attribute) {
242 case MCSA_Invalid: assert(0 && "Invalid symbol attribute");
243 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
244 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
245 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
246 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
247 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
248 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
249 assert(MAI.hasDotTypeDotSizeDirective() && "Symbol Attr not supported");
250 OS << "\t.type\t" << *Symbol << ','
251 << ((MAI.getCommentString()[0] != '@') ? '@' : '%');
253 default: assert(0 && "Unknown ELF .type");
254 case MCSA_ELF_TypeFunction: OS << "function"; break;
255 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
256 case MCSA_ELF_TypeObject: OS << "object"; break;
257 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
258 case MCSA_ELF_TypeCommon: OS << "common"; break;
259 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
263 case MCSA_Global: // .globl/.global
264 OS << MAI.getGlobalDirective();
266 case MCSA_Hidden: OS << ".hidden "; break;
267 case MCSA_IndirectSymbol: OS << ".indirect_symbol "; break;
268 case MCSA_Internal: OS << ".internal "; break;
269 case MCSA_LazyReference: OS << ".lazy_reference "; break;
270 case MCSA_Local: OS << ".local "; break;
271 case MCSA_NoDeadStrip: OS << ".no_dead_strip "; break;
272 case MCSA_PrivateExtern: OS << ".private_extern "; break;
273 case MCSA_Protected: OS << ".protected "; break;
274 case MCSA_Reference: OS << ".reference "; break;
275 case MCSA_Weak: OS << ".weak "; break;
276 case MCSA_WeakDefinition: OS << ".weak_definition "; break;
278 case MCSA_WeakReference: OS << MAI.getWeakRefDirective(); break;
285 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
286 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
290 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
291 assert(MAI.hasDotTypeDotSizeDirective());
292 OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
295 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
296 unsigned ByteAlignment) {
297 OS << "\t.comm\t" << *Symbol << ',' << Size;
298 if (ByteAlignment != 0) {
299 if (MAI.getCOMMDirectiveAlignmentIsInBytes())
300 OS << ',' << ByteAlignment;
302 OS << ',' << Log2_32(ByteAlignment);
307 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
309 /// @param Symbol - The common symbol to emit.
310 /// @param Size - The size of the common symbol.
311 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
312 assert(MAI.hasLCOMMDirective() && "Doesn't have .lcomm, can't emit it!");
313 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
317 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
318 unsigned Size, unsigned ByteAlignment) {
319 // Note: a .zerofill directive does not switch sections.
322 // This is a mach-o specific directive.
323 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
324 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
326 if (Symbol != NULL) {
327 OS << ',' << *Symbol << ',' << Size;
328 if (ByteAlignment != 0)
329 OS << ',' << Log2_32(ByteAlignment);
334 static inline char toOctal(int X) { return (X&7)+'0'; }
336 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
339 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
340 unsigned char C = Data[i];
341 if (C == '"' || C == '\\') {
342 OS << '\\' << (char)C;
346 if (isprint((unsigned char)C)) {
352 case '\b': OS << "\\b"; break;
353 case '\f': OS << "\\f"; break;
354 case '\n': OS << "\\n"; break;
355 case '\r': OS << "\\r"; break;
356 case '\t': OS << "\\t"; break;
359 OS << toOctal(C >> 6);
360 OS << toOctal(C >> 3);
361 OS << toOctal(C >> 0);
370 void MCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
371 assert(CurSection && "Cannot emit contents before setting section!");
372 if (Data.empty()) return;
374 if (Data.size() == 1) {
375 OS << MAI.getData8bitsDirective(AddrSpace);
376 OS << (unsigned)(unsigned char)Data[0];
381 // If the data ends with 0 and the target supports .asciz, use it, otherwise
383 if (MAI.getAscizDirective() && Data.back() == 0) {
384 OS << MAI.getAscizDirective();
385 Data = Data.substr(0, Data.size()-1);
387 OS << MAI.getAsciiDirective();
391 PrintQuotedString(Data, OS);
395 /// EmitIntValue - Special case of EmitValue that avoids the client having
396 /// to pass in a MCExpr for constant integers.
397 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size,
398 unsigned AddrSpace) {
399 assert(CurSection && "Cannot emit contents before setting section!");
400 const char *Directive = 0;
403 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
404 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
405 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
407 Directive = MAI.getData64bitsDirective(AddrSpace);
408 // If the target doesn't support 64-bit data, emit as two 32-bit halves.
409 if (Directive) break;
410 if (isLittleEndian()) {
411 EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
412 EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
414 EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
415 EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
420 assert(Directive && "Invalid size for machine code value!");
421 OS << Directive << truncateToSize(Value, Size);
425 void MCAsmStreamer::EmitValue(const MCExpr *Value, unsigned Size,
426 unsigned AddrSpace) {
427 assert(CurSection && "Cannot emit contents before setting section!");
428 const char *Directive = 0;
431 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
432 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
433 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
434 case 8: Directive = MAI.getData64bitsDirective(AddrSpace); break;
437 assert(Directive && "Invalid size for machine code value!");
438 OS << Directive << *Value;
442 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
443 assert(MAI.getGPRel32Directive() != 0);
444 OS << MAI.getGPRel32Directive() << *Value;
449 /// EmitFill - Emit NumBytes bytes worth of the value specified by
450 /// FillValue. This implements directives such as '.space'.
451 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
452 unsigned AddrSpace) {
453 if (NumBytes == 0) return;
456 if (const char *ZeroDirective = MAI.getZeroDirective()) {
457 OS << ZeroDirective << NumBytes;
459 OS << ',' << (int)FillValue;
464 // Emit a byte at a time.
465 MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
468 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
470 unsigned MaxBytesToEmit) {
471 // Some assemblers don't support non-power of two alignments, so we always
472 // emit alignments as a power of two if possible.
473 if (isPowerOf2_32(ByteAlignment)) {
475 default: llvm_unreachable("Invalid size for machine code value!");
476 case 1: OS << MAI.getAlignDirective(); break;
477 // FIXME: use MAI for this!
478 case 2: OS << ".p2alignw "; break;
479 case 4: OS << ".p2alignl "; break;
480 case 8: llvm_unreachable("Unsupported alignment size!");
483 if (MAI.getAlignmentIsInBytes())
486 OS << Log2_32(ByteAlignment);
488 if (Value || MaxBytesToEmit) {
490 OS.write_hex(truncateToSize(Value, ValueSize));
493 OS << ", " << MaxBytesToEmit;
499 // Non-power of two alignment. This is not widely supported by assemblers.
500 // FIXME: Parameterize this based on MAI.
502 default: llvm_unreachable("Invalid size for machine code value!");
503 case 1: OS << ".balign"; break;
504 case 2: OS << ".balignw"; break;
505 case 4: OS << ".balignl"; break;
506 case 8: llvm_unreachable("Unsupported alignment size!");
509 OS << ' ' << ByteAlignment;
510 OS << ", " << truncateToSize(Value, ValueSize);
512 OS << ", " << MaxBytesToEmit;
516 void MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
517 unsigned char Value) {
518 // FIXME: Verify that Offset is associated with the current section.
519 OS << ".org " << *Offset << ", " << (unsigned) Value;
524 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
525 assert(MAI.hasSingleParameterDotFile());
527 PrintQuotedString(Filename, OS);
531 void MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Filename){
532 OS << "\t.file\t" << FileNo << ' ';
533 PrintQuotedString(Filename, OS);
537 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst) {
538 raw_ostream &OS = GetCommentOS();
539 SmallString<256> Code;
540 SmallVector<MCFixup, 4> Fixups;
541 raw_svector_ostream VecOS(Code);
542 Emitter->EncodeInstruction(Inst, VecOS, Fixups);
545 // If we are showing fixups, create symbolic markers in the encoded
546 // representation. We do this by making a per-bit map to the fixup item index,
547 // then trying to display it as nicely as possible.
548 SmallVector<uint8_t, 64> FixupMap;
549 FixupMap.resize(Code.size() * 8);
550 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
553 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
554 MCFixup &F = Fixups[i];
555 const MCFixupKindInfo &Info = Emitter->getFixupKindInfo(F.getKind());
556 for (unsigned j = 0; j != Info.TargetSize; ++j) {
557 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
558 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
559 FixupMap[Index] = 1 + i;
564 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
568 // See if all bits are the same map entry.
569 uint8_t MapEntry = FixupMap[i * 8 + 0];
570 for (unsigned j = 1; j != 8; ++j) {
571 if (FixupMap[i * 8 + j] == MapEntry)
574 MapEntry = uint8_t(~0U);
578 if (MapEntry != uint8_t(~0U)) {
580 OS << format("0x%02x", uint8_t(Code[i]));
582 assert(Code[i] == 0 && "Encoder wrote into fixed up bit!");
583 OS << char('A' + MapEntry - 1);
586 // Otherwise, write out in binary.
588 for (unsigned j = 8; j--;) {
589 unsigned Bit = (Code[i] >> j) & 1;
590 if (uint8_t MapEntry = FixupMap[i * 8 + j]) {
591 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
592 OS << char('A' + MapEntry - 1);
600 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
601 MCFixup &F = Fixups[i];
602 const MCFixupKindInfo &Info = Emitter->getFixupKindInfo(F.getKind());
603 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
604 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
608 void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
609 assert(CurSection && "Cannot emit contents before setting section!");
611 // Show the encoding in a comment if we have a code emitter.
613 AddEncodingComment(Inst);
615 // Show the MCInst if enabled.
617 raw_ostream &OS = GetCommentOS();
618 OS << "<MCInst #" << Inst.getOpcode();
622 InstName = InstPrinter->getOpcodeName(Inst.getOpcode());
623 if (!InstName.empty())
624 OS << ' ' << InstName;
626 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
628 Inst.getOperand(i).print(OS, &MAI);
633 // If we have an AsmPrinter, use that to print, otherwise dump the MCInst.
635 InstPrinter->printInst(&Inst);
637 Inst.print(OS, &MAI);
641 void MCAsmStreamer::Finish() {
645 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
646 formatted_raw_ostream &OS,
647 const MCAsmInfo &MAI, bool isLittleEndian,
648 bool isVerboseAsm, MCInstPrinter *IP,
649 MCCodeEmitter *CE, bool ShowInst) {
650 return new MCAsmStreamer(Context, OS, MAI, isLittleEndian, isVerboseAsm,