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 ShowFixups : 1;
41 unsigned ShowInst : 1;
44 MCAsmStreamer(MCContext &Context, formatted_raw_ostream &os,
46 bool isLittleEndian, bool isVerboseAsm, MCInstPrinter *printer,
47 MCCodeEmitter *emitter, bool showInst, bool showFixups)
48 : MCStreamer(Context), OS(os), MAI(mai), InstPrinter(printer),
49 Emitter(emitter), CommentStream(CommentToEmit),
50 IsLittleEndian(isLittleEndian), IsVerboseAsm(isVerboseAsm),
51 ShowFixups(showFixups), ShowInst(showInst) {
52 if (InstPrinter && IsVerboseAsm)
53 InstPrinter->setCommentStream(CommentStream);
57 bool isLittleEndian() const { return IsLittleEndian; }
59 inline void EmitEOL() {
60 // If we don't have any comments, just emit a \n.
67 void EmitCommentsAndEOL();
69 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
71 virtual bool isVerboseAsm() const { return IsVerboseAsm; }
73 /// AddComment - Add a comment that can be emitted to the generated .s
74 /// file if applicable as a QoI issue to make the output of the compiler
75 /// more readable. This only affects the MCAsmStreamer, and only when
76 /// verbose assembly output is enabled.
77 virtual void AddComment(const Twine &T);
79 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
80 virtual void AddEncodingComment(const MCInst &Inst);
82 /// GetCommentOS - Return a raw_ostream that comments can be written to.
83 /// Unlike AddComment, you are required to terminate comments with \n if you
85 virtual raw_ostream &GetCommentOS() {
87 return nulls(); // Discard comments unless in verbose asm mode.
91 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
92 virtual void AddBlankLine() {
96 /// @name MCStreamer Interface
99 virtual void SwitchSection(const MCSection *Section);
101 virtual void EmitLabel(MCSymbol *Symbol);
103 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
105 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
107 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
109 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
111 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
112 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
113 unsigned ByteAlignment);
115 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
117 /// @param Symbol - The common symbol to emit.
118 /// @param Size - The size of the common symbol.
119 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size);
121 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
122 unsigned Size = 0, unsigned ByteAlignment = 0);
124 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
126 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
127 virtual void EmitIntValue(uint64_t Value, unsigned Size, unsigned AddrSpace);
128 virtual void EmitGPRel32Value(const MCExpr *Value);
131 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
134 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
135 unsigned ValueSize = 1,
136 unsigned MaxBytesToEmit = 0);
138 virtual void EmitValueToOffset(const MCExpr *Offset,
139 unsigned char Value = 0);
141 virtual void EmitFileDirective(StringRef Filename);
142 virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename);
144 virtual void EmitInstruction(const MCInst &Inst);
146 virtual void Finish();
151 } // end anonymous namespace.
153 /// AddComment - Add a comment that can be emitted to the generated .s
154 /// file if applicable as a QoI issue to make the output of the compiler
155 /// more readable. This only affects the MCAsmStreamer, and only when
156 /// verbose assembly output is enabled.
157 void MCAsmStreamer::AddComment(const Twine &T) {
158 if (!IsVerboseAsm) return;
160 // Make sure that CommentStream is flushed.
161 CommentStream.flush();
163 T.toVector(CommentToEmit);
164 // Each comment goes on its own line.
165 CommentToEmit.push_back('\n');
167 // Tell the comment stream that the vector changed underneath it.
168 CommentStream.resync();
171 void MCAsmStreamer::EmitCommentsAndEOL() {
172 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
177 CommentStream.flush();
178 StringRef Comments = CommentToEmit.str();
180 assert(Comments.back() == '\n' &&
181 "Comment array not newline terminated");
183 // Emit a line of comments.
184 OS.PadToColumn(MAI.getCommentColumn());
185 size_t Position = Comments.find('\n');
186 OS << MAI.getCommentString() << ' ' << Comments.substr(0, Position) << '\n';
188 Comments = Comments.substr(Position+1);
189 } while (!Comments.empty());
191 CommentToEmit.clear();
192 // Tell the comment stream that the vector changed underneath it.
193 CommentStream.resync();
197 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
198 assert(Bytes && "Invalid size!");
199 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
202 void MCAsmStreamer::SwitchSection(const MCSection *Section) {
203 assert(Section && "Cannot switch to a null section!");
204 if (Section != CurSection) {
205 CurSection = Section;
206 Section->PrintSwitchToSection(MAI, OS);
210 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
211 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
212 assert(CurSection && "Cannot emit before setting section!");
214 OS << *Symbol << ":";
216 Symbol->setSection(*CurSection);
219 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
221 default: assert(0 && "Invalid flag!");
222 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
227 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
228 // Only absolute symbols can be redefined.
229 assert((Symbol->isUndefined() || Symbol->isAbsolute()) &&
230 "Cannot define a symbol twice!");
232 OS << *Symbol << " = " << *Value;
235 // FIXME: Lift context changes into super class.
236 // FIXME: Set associated section.
237 Symbol->setValue(Value);
240 void MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
241 MCSymbolAttr Attribute) {
243 case MCSA_Invalid: assert(0 && "Invalid symbol attribute");
244 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
245 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
246 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
247 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
248 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
249 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
250 assert(MAI.hasDotTypeDotSizeDirective() && "Symbol Attr not supported");
251 OS << "\t.type\t" << *Symbol << ','
252 << ((MAI.getCommentString()[0] != '@') ? '@' : '%');
254 default: assert(0 && "Unknown ELF .type");
255 case MCSA_ELF_TypeFunction: OS << "function"; break;
256 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
257 case MCSA_ELF_TypeObject: OS << "object"; break;
258 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
259 case MCSA_ELF_TypeCommon: OS << "common"; break;
260 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
264 case MCSA_Global: // .globl/.global
265 OS << MAI.getGlobalDirective();
267 case MCSA_Hidden: OS << ".hidden "; break;
268 case MCSA_IndirectSymbol: OS << ".indirect_symbol "; break;
269 case MCSA_Internal: OS << ".internal "; break;
270 case MCSA_LazyReference: OS << ".lazy_reference "; break;
271 case MCSA_Local: OS << ".local "; break;
272 case MCSA_NoDeadStrip: OS << ".no_dead_strip "; break;
273 case MCSA_PrivateExtern: OS << ".private_extern "; break;
274 case MCSA_Protected: OS << ".protected "; break;
275 case MCSA_Reference: OS << ".reference "; break;
276 case MCSA_Weak: OS << ".weak "; break;
277 case MCSA_WeakDefinition: OS << ".weak_definition "; break;
279 case MCSA_WeakReference: OS << MAI.getWeakRefDirective(); break;
286 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
287 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
291 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
292 assert(MAI.hasDotTypeDotSizeDirective());
293 OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
296 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
297 unsigned ByteAlignment) {
298 OS << "\t.comm\t" << *Symbol << ',' << Size;
299 if (ByteAlignment != 0) {
300 if (MAI.getCOMMDirectiveAlignmentIsInBytes())
301 OS << ',' << ByteAlignment;
303 OS << ',' << Log2_32(ByteAlignment);
308 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
310 /// @param Symbol - The common symbol to emit.
311 /// @param Size - The size of the common symbol.
312 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
313 assert(MAI.hasLCOMMDirective() && "Doesn't have .lcomm, can't emit it!");
314 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
318 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
319 unsigned Size, unsigned ByteAlignment) {
320 // Note: a .zerofill directive does not switch sections.
323 // This is a mach-o specific directive.
324 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
325 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
327 if (Symbol != NULL) {
328 OS << ',' << *Symbol << ',' << Size;
329 if (ByteAlignment != 0)
330 OS << ',' << Log2_32(ByteAlignment);
335 static inline char toOctal(int X) { return (X&7)+'0'; }
337 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
340 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
341 unsigned char C = Data[i];
342 if (C == '"' || C == '\\') {
343 OS << '\\' << (char)C;
347 if (isprint((unsigned char)C)) {
353 case '\b': OS << "\\b"; break;
354 case '\f': OS << "\\f"; break;
355 case '\n': OS << "\\n"; break;
356 case '\r': OS << "\\r"; break;
357 case '\t': OS << "\\t"; break;
360 OS << toOctal(C >> 6);
361 OS << toOctal(C >> 3);
362 OS << toOctal(C >> 0);
371 void MCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
372 assert(CurSection && "Cannot emit contents before setting section!");
373 if (Data.empty()) return;
375 if (Data.size() == 1) {
376 OS << MAI.getData8bitsDirective(AddrSpace);
377 OS << (unsigned)(unsigned char)Data[0];
382 // If the data ends with 0 and the target supports .asciz, use it, otherwise
384 if (MAI.getAscizDirective() && Data.back() == 0) {
385 OS << MAI.getAscizDirective();
386 Data = Data.substr(0, Data.size()-1);
388 OS << MAI.getAsciiDirective();
392 PrintQuotedString(Data, OS);
396 /// EmitIntValue - Special case of EmitValue that avoids the client having
397 /// to pass in a MCExpr for constant integers.
398 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size,
399 unsigned AddrSpace) {
400 assert(CurSection && "Cannot emit contents before setting section!");
401 const char *Directive = 0;
404 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
405 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
406 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
408 Directive = MAI.getData64bitsDirective(AddrSpace);
409 // If the target doesn't support 64-bit data, emit as two 32-bit halves.
410 if (Directive) break;
411 if (isLittleEndian()) {
412 EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
413 EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
415 EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
416 EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
421 assert(Directive && "Invalid size for machine code value!");
422 OS << Directive << truncateToSize(Value, Size);
426 void MCAsmStreamer::EmitValue(const MCExpr *Value, unsigned Size,
427 unsigned AddrSpace) {
428 assert(CurSection && "Cannot emit contents before setting section!");
429 const char *Directive = 0;
432 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
433 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
434 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
435 case 8: Directive = MAI.getData64bitsDirective(AddrSpace); break;
438 assert(Directive && "Invalid size for machine code value!");
439 OS << Directive << *Value;
443 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
444 assert(MAI.getGPRel32Directive() != 0);
445 OS << MAI.getGPRel32Directive() << *Value;
450 /// EmitFill - Emit NumBytes bytes worth of the value specified by
451 /// FillValue. This implements directives such as '.space'.
452 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
453 unsigned AddrSpace) {
454 if (NumBytes == 0) return;
457 if (const char *ZeroDirective = MAI.getZeroDirective()) {
458 OS << ZeroDirective << NumBytes;
460 OS << ',' << (int)FillValue;
465 // Emit a byte at a time.
466 MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
469 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
471 unsigned MaxBytesToEmit) {
472 // Some assemblers don't support non-power of two alignments, so we always
473 // emit alignments as a power of two if possible.
474 if (isPowerOf2_32(ByteAlignment)) {
476 default: llvm_unreachable("Invalid size for machine code value!");
477 case 1: OS << MAI.getAlignDirective(); break;
478 // FIXME: use MAI for this!
479 case 2: OS << ".p2alignw "; break;
480 case 4: OS << ".p2alignl "; break;
481 case 8: llvm_unreachable("Unsupported alignment size!");
484 if (MAI.getAlignmentIsInBytes())
487 OS << Log2_32(ByteAlignment);
489 if (Value || MaxBytesToEmit) {
491 OS.write_hex(truncateToSize(Value, ValueSize));
494 OS << ", " << MaxBytesToEmit;
500 // Non-power of two alignment. This is not widely supported by assemblers.
501 // FIXME: Parameterize this based on MAI.
503 default: llvm_unreachable("Invalid size for machine code value!");
504 case 1: OS << ".balign"; break;
505 case 2: OS << ".balignw"; break;
506 case 4: OS << ".balignl"; break;
507 case 8: llvm_unreachable("Unsupported alignment size!");
510 OS << ' ' << ByteAlignment;
511 OS << ", " << truncateToSize(Value, ValueSize);
513 OS << ", " << MaxBytesToEmit;
517 void MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
518 unsigned char Value) {
519 // FIXME: Verify that Offset is associated with the current section.
520 OS << ".org " << *Offset << ", " << (unsigned) Value;
525 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
526 assert(MAI.hasSingleParameterDotFile());
528 PrintQuotedString(Filename, OS);
532 void MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Filename){
533 OS << "\t.file\t" << FileNo << ' ';
534 PrintQuotedString(Filename, OS);
538 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst) {
539 raw_ostream &OS = GetCommentOS();
540 SmallString<256> Code;
541 SmallVector<MCFixup, 4> Fixups;
542 raw_svector_ostream VecOS(Code);
543 Emitter->EncodeInstruction(Inst, VecOS, Fixups);
546 // If we aren't showing fixups, just show the bytes.
549 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
552 OS << format("0x%02x", uint8_t(Code[i]));
558 // If we are showing fixups, create symbolic markers in the encoded
559 // representation. We do this by making a per-bit map to the fixup item index,
560 // then trying to display it as nicely as possible.
561 uint8_t *FixupMap = new uint8_t[Code.size() * 8];
562 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
565 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
566 MCFixup &F = Fixups[i];
567 MCFixupKindInfo &Info = Emitter->getFixupKindInfo(F.getKind());
568 for (unsigned j = 0; j != Info.TargetSize; ++j) {
569 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
570 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
571 FixupMap[Index] = 1 + i;
576 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
580 // See if all bits are the same map entry.
581 uint8_t MapEntry = FixupMap[i * 8 + 0];
582 for (unsigned j = 1; j != 8; ++j) {
583 if (FixupMap[i * 8 + j] == MapEntry)
586 MapEntry = uint8_t(~0U);
590 if (MapEntry != uint8_t(~0U)) {
592 OS << format("0x%02x", uint8_t(Code[i]));
594 assert(Code[i] == 0 && "Encoder wrote into fixed up bit!");
595 OS << char('A' + MapEntry - 1);
598 // Otherwise, write out in binary.
600 for (unsigned j = 8; j--;) {
601 unsigned Bit = (Code[i] >> j) & 1;
602 if (uint8_t MapEntry = FixupMap[i * 8 + j]) {
603 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
604 OS << char('A' + MapEntry - 1);
612 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
613 MCFixup &F = Fixups[i];
614 MCFixupKindInfo &Info = Emitter->getFixupKindInfo(F.getKind());
615 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
616 << ", op: " << F.getOpIndex() << ", kind: " << Info.Name << "\n";
620 void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
621 assert(CurSection && "Cannot emit contents before setting section!");
623 // Show the encoding in a comment if we have a code emitter.
625 AddEncodingComment(Inst);
627 // Show the MCInst if enabled.
629 raw_ostream &OS = GetCommentOS();
630 OS << "<MCInst #" << Inst.getOpcode();
632 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
634 Inst.getOperand(i).print(OS, &MAI);
639 // If we have an AsmPrinter, use that to print, otherwise dump the MCInst.
641 InstPrinter->printInst(&Inst);
643 Inst.print(OS, &MAI);
647 void MCAsmStreamer::Finish() {
651 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
652 formatted_raw_ostream &OS,
653 const MCAsmInfo &MAI, bool isLittleEndian,
654 bool isVerboseAsm, MCInstPrinter *IP,
655 MCCodeEmitter *CE, bool ShowInst,
657 return new MCAsmStreamer(Context, OS, MAI, isLittleEndian, isVerboseAsm,
658 IP, CE, ShowInst, ShowFixups);