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/OwningPtr.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Support/Format.h"
25 #include "llvm/Support/FormattedStream.h"
30 class MCAsmStreamer : public MCStreamer {
31 formatted_raw_ostream &OS;
33 OwningPtr<MCInstPrinter> InstPrinter;
34 MCCodeEmitter *Emitter;
36 SmallString<128> CommentToEmit;
37 raw_svector_ostream CommentStream;
39 unsigned IsLittleEndian : 1;
40 unsigned IsVerboseAsm : 1;
41 unsigned ShowInst : 1;
44 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(Context.getAsmInfo()),
48 InstPrinter(printer), 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 /// hasRawTextSupport - We support EmitRawText.
73 virtual bool hasRawTextSupport() const { return true; }
75 /// AddComment - Add a comment that can be emitted to the generated .s
76 /// file if applicable as a QoI issue to make the output of the compiler
77 /// more readable. This only affects the MCAsmStreamer, and only when
78 /// verbose assembly output is enabled.
79 virtual void AddComment(const Twine &T);
81 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
82 virtual void AddEncodingComment(const MCInst &Inst);
84 /// GetCommentOS - Return a raw_ostream that comments can be written to.
85 /// Unlike AddComment, you are required to terminate comments with \n if you
87 virtual raw_ostream &GetCommentOS() {
89 return nulls(); // Discard comments unless in verbose asm mode.
93 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
94 virtual void AddBlankLine() {
98 /// @name MCStreamer Interface
101 virtual void SwitchSection(const MCSection *Section);
103 virtual void EmitLabel(MCSymbol *Symbol);
105 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
107 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
109 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
111 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
113 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
114 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
115 unsigned ByteAlignment);
117 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
119 /// @param Symbol - The common symbol to emit.
120 /// @param Size - The size of the common symbol.
121 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size);
123 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
124 unsigned Size = 0, unsigned ByteAlignment = 0);
126 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
128 virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
129 virtual void EmitIntValue(uint64_t Value, unsigned Size, unsigned AddrSpace);
130 virtual void EmitGPRel32Value(const MCExpr *Value);
133 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
136 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
137 unsigned ValueSize = 1,
138 unsigned MaxBytesToEmit = 0);
140 virtual void EmitCodeAlignment(unsigned ByteAlignment,
141 unsigned MaxBytesToEmit = 0);
143 virtual void EmitValueToOffset(const MCExpr *Offset,
144 unsigned char Value = 0);
146 virtual void EmitFileDirective(StringRef Filename);
147 virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename);
149 virtual void EmitInstruction(const MCInst &Inst);
151 /// EmitRawText - If this file is backed by a assembly streamer, this dumps
152 /// the specified string in the output .s file. This capability is
153 /// indicated by the hasRawTextSupport() predicate.
154 virtual void EmitRawText(StringRef String);
156 virtual void Finish();
161 } // end anonymous namespace.
163 /// AddComment - Add a comment that can be emitted to the generated .s
164 /// file if applicable as a QoI issue to make the output of the compiler
165 /// more readable. This only affects the MCAsmStreamer, and only when
166 /// verbose assembly output is enabled.
167 void MCAsmStreamer::AddComment(const Twine &T) {
168 if (!IsVerboseAsm) return;
170 // Make sure that CommentStream is flushed.
171 CommentStream.flush();
173 T.toVector(CommentToEmit);
174 // Each comment goes on its own line.
175 CommentToEmit.push_back('\n');
177 // Tell the comment stream that the vector changed underneath it.
178 CommentStream.resync();
181 void MCAsmStreamer::EmitCommentsAndEOL() {
182 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
187 CommentStream.flush();
188 StringRef Comments = CommentToEmit.str();
190 assert(Comments.back() == '\n' &&
191 "Comment array not newline terminated");
193 // Emit a line of comments.
194 OS.PadToColumn(MAI.getCommentColumn());
195 size_t Position = Comments.find('\n');
196 OS << MAI.getCommentString() << ' ' << Comments.substr(0, Position) << '\n';
198 Comments = Comments.substr(Position+1);
199 } while (!Comments.empty());
201 CommentToEmit.clear();
202 // Tell the comment stream that the vector changed underneath it.
203 CommentStream.resync();
206 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
207 assert(Bytes && "Invalid size!");
208 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
211 void MCAsmStreamer::SwitchSection(const MCSection *Section) {
212 assert(Section && "Cannot switch to a null section!");
213 if (Section != CurSection) {
214 CurSection = Section;
215 Section->PrintSwitchToSection(MAI, OS);
219 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
220 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
221 assert(CurSection && "Cannot emit before setting section!");
223 OS << *Symbol << ":";
225 Symbol->setSection(*CurSection);
228 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
230 default: assert(0 && "Invalid flag!");
231 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
236 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
237 // Only absolute symbols can be redefined.
238 assert((Symbol->isUndefined() || Symbol->isAbsolute()) &&
239 "Cannot define a symbol twice!");
241 OS << *Symbol << " = " << *Value;
244 // FIXME: Lift context changes into super class.
245 // FIXME: Set associated section.
246 Symbol->setValue(Value);
249 void MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
250 MCSymbolAttr Attribute) {
252 case MCSA_Invalid: assert(0 && "Invalid symbol attribute");
253 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
254 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
255 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
256 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
257 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
258 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
259 assert(MAI.hasDotTypeDotSizeDirective() && "Symbol Attr not supported");
260 OS << "\t.type\t" << *Symbol << ','
261 << ((MAI.getCommentString()[0] != '@') ? '@' : '%');
263 default: assert(0 && "Unknown ELF .type");
264 case MCSA_ELF_TypeFunction: OS << "function"; break;
265 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
266 case MCSA_ELF_TypeObject: OS << "object"; break;
267 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
268 case MCSA_ELF_TypeCommon: OS << "common"; break;
269 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
273 case MCSA_Global: // .globl/.global
274 OS << MAI.getGlobalDirective();
276 case MCSA_Hidden: OS << ".hidden "; break;
277 case MCSA_IndirectSymbol: OS << ".indirect_symbol "; break;
278 case MCSA_Internal: OS << ".internal "; break;
279 case MCSA_LazyReference: OS << ".lazy_reference "; break;
280 case MCSA_Local: OS << ".local "; break;
281 case MCSA_NoDeadStrip: OS << ".no_dead_strip "; break;
282 case MCSA_PrivateExtern: OS << ".private_extern "; break;
283 case MCSA_Protected: OS << ".protected "; break;
284 case MCSA_Reference: OS << ".reference "; break;
285 case MCSA_Weak: OS << ".weak "; break;
286 case MCSA_WeakDefinition: OS << ".weak_definition "; break;
288 case MCSA_WeakReference: OS << MAI.getWeakRefDirective(); break;
295 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
296 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
300 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
301 assert(MAI.hasDotTypeDotSizeDirective());
302 OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
305 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
306 unsigned ByteAlignment) {
307 OS << "\t.comm\t" << *Symbol << ',' << Size;
308 if (ByteAlignment != 0) {
309 if (MAI.getCOMMDirectiveAlignmentIsInBytes())
310 OS << ',' << ByteAlignment;
312 OS << ',' << Log2_32(ByteAlignment);
317 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
319 /// @param Symbol - The common symbol to emit.
320 /// @param Size - The size of the common symbol.
321 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
322 assert(MAI.hasLCOMMDirective() && "Doesn't have .lcomm, can't emit it!");
323 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
327 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
328 unsigned Size, unsigned ByteAlignment) {
329 // Note: a .zerofill directive does not switch sections.
332 // This is a mach-o specific directive.
333 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
334 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
336 if (Symbol != NULL) {
337 OS << ',' << *Symbol << ',' << Size;
338 if (ByteAlignment != 0)
339 OS << ',' << Log2_32(ByteAlignment);
344 static inline char toOctal(int X) { return (X&7)+'0'; }
346 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
349 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
350 unsigned char C = Data[i];
351 if (C == '"' || C == '\\') {
352 OS << '\\' << (char)C;
356 if (isprint((unsigned char)C)) {
362 case '\b': OS << "\\b"; break;
363 case '\f': OS << "\\f"; break;
364 case '\n': OS << "\\n"; break;
365 case '\r': OS << "\\r"; break;
366 case '\t': OS << "\\t"; break;
369 OS << toOctal(C >> 6);
370 OS << toOctal(C >> 3);
371 OS << toOctal(C >> 0);
380 void MCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
381 assert(CurSection && "Cannot emit contents before setting section!");
382 if (Data.empty()) return;
384 if (Data.size() == 1) {
385 OS << MAI.getData8bitsDirective(AddrSpace);
386 OS << (unsigned)(unsigned char)Data[0];
391 // If the data ends with 0 and the target supports .asciz, use it, otherwise
393 if (MAI.getAscizDirective() && Data.back() == 0) {
394 OS << MAI.getAscizDirective();
395 Data = Data.substr(0, Data.size()-1);
397 OS << MAI.getAsciiDirective();
401 PrintQuotedString(Data, OS);
405 /// EmitIntValue - Special case of EmitValue that avoids the client having
406 /// to pass in a MCExpr for constant integers.
407 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size,
408 unsigned AddrSpace) {
409 assert(CurSection && "Cannot emit contents before setting section!");
410 const char *Directive = 0;
413 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
414 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
415 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
417 Directive = MAI.getData64bitsDirective(AddrSpace);
418 // If the target doesn't support 64-bit data, emit as two 32-bit halves.
419 if (Directive) break;
420 if (isLittleEndian()) {
421 EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
422 EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
424 EmitIntValue((uint32_t)(Value >> 32), 4, AddrSpace);
425 EmitIntValue((uint32_t)(Value >> 0 ), 4, AddrSpace);
430 assert(Directive && "Invalid size for machine code value!");
431 OS << Directive << truncateToSize(Value, Size);
435 void MCAsmStreamer::EmitValue(const MCExpr *Value, unsigned Size,
436 unsigned AddrSpace) {
437 assert(CurSection && "Cannot emit contents before setting section!");
438 const char *Directive = 0;
441 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
442 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
443 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
444 case 8: Directive = MAI.getData64bitsDirective(AddrSpace); break;
447 assert(Directive && "Invalid size for machine code value!");
448 OS << Directive << *Value;
452 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
453 assert(MAI.getGPRel32Directive() != 0);
454 OS << MAI.getGPRel32Directive() << *Value;
459 /// EmitFill - Emit NumBytes bytes worth of the value specified by
460 /// FillValue. This implements directives such as '.space'.
461 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
462 unsigned AddrSpace) {
463 if (NumBytes == 0) return;
466 if (const char *ZeroDirective = MAI.getZeroDirective()) {
467 OS << ZeroDirective << NumBytes;
469 OS << ',' << (int)FillValue;
474 // Emit a byte at a time.
475 MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
478 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
480 unsigned MaxBytesToEmit) {
481 // Some assemblers don't support non-power of two alignments, so we always
482 // emit alignments as a power of two if possible.
483 if (isPowerOf2_32(ByteAlignment)) {
485 default: llvm_unreachable("Invalid size for machine code value!");
486 case 1: OS << MAI.getAlignDirective(); break;
487 // FIXME: use MAI for this!
488 case 2: OS << ".p2alignw "; break;
489 case 4: OS << ".p2alignl "; break;
490 case 8: llvm_unreachable("Unsupported alignment size!");
493 if (MAI.getAlignmentIsInBytes())
496 OS << Log2_32(ByteAlignment);
498 if (Value || MaxBytesToEmit) {
500 OS.write_hex(truncateToSize(Value, ValueSize));
503 OS << ", " << MaxBytesToEmit;
509 // Non-power of two alignment. This is not widely supported by assemblers.
510 // FIXME: Parameterize this based on MAI.
512 default: llvm_unreachable("Invalid size for machine code value!");
513 case 1: OS << ".balign"; break;
514 case 2: OS << ".balignw"; break;
515 case 4: OS << ".balignl"; break;
516 case 8: llvm_unreachable("Unsupported alignment size!");
519 OS << ' ' << ByteAlignment;
520 OS << ", " << truncateToSize(Value, ValueSize);
522 OS << ", " << MaxBytesToEmit;
526 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
527 unsigned MaxBytesToEmit) {
528 // Emit with a text fill value.
529 EmitValueToAlignment(ByteAlignment, MAI.getTextAlignFillValue(),
533 void MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
534 unsigned char Value) {
535 // FIXME: Verify that Offset is associated with the current section.
536 OS << ".org " << *Offset << ", " << (unsigned) Value;
541 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
542 assert(MAI.hasSingleParameterDotFile());
544 PrintQuotedString(Filename, OS);
548 void MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Filename){
549 OS << "\t.file\t" << FileNo << ' ';
550 PrintQuotedString(Filename, OS);
554 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst) {
555 raw_ostream &OS = GetCommentOS();
556 SmallString<256> Code;
557 SmallVector<MCFixup, 4> Fixups;
558 raw_svector_ostream VecOS(Code);
559 Emitter->EncodeInstruction(Inst, VecOS, Fixups);
562 // If we are showing fixups, create symbolic markers in the encoded
563 // representation. We do this by making a per-bit map to the fixup item index,
564 // then trying to display it as nicely as possible.
565 SmallVector<uint8_t, 64> FixupMap;
566 FixupMap.resize(Code.size() * 8);
567 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
570 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
571 MCFixup &F = Fixups[i];
572 const MCFixupKindInfo &Info = Emitter->getFixupKindInfo(F.getKind());
573 for (unsigned j = 0; j != Info.TargetSize; ++j) {
574 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
575 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
576 FixupMap[Index] = 1 + i;
581 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
585 // See if all bits are the same map entry.
586 uint8_t MapEntry = FixupMap[i * 8 + 0];
587 for (unsigned j = 1; j != 8; ++j) {
588 if (FixupMap[i * 8 + j] == MapEntry)
591 MapEntry = uint8_t(~0U);
595 if (MapEntry != uint8_t(~0U)) {
597 OS << format("0x%02x", uint8_t(Code[i]));
599 assert(Code[i] == 0 && "Encoder wrote into fixed up bit!");
600 OS << char('A' + MapEntry - 1);
603 // Otherwise, write out in binary.
605 for (unsigned j = 8; j--;) {
606 unsigned Bit = (Code[i] >> j) & 1;
607 if (uint8_t MapEntry = FixupMap[i * 8 + j]) {
608 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
609 OS << char('A' + MapEntry - 1);
617 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
618 MCFixup &F = Fixups[i];
619 const MCFixupKindInfo &Info = Emitter->getFixupKindInfo(F.getKind());
620 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
621 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
625 void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
626 assert(CurSection && "Cannot emit contents before setting section!");
628 // Show the encoding in a comment if we have a code emitter.
630 AddEncodingComment(Inst);
632 // Show the MCInst if enabled.
634 Inst.dump_pretty(GetCommentOS(), &MAI, InstPrinter.get(), "\n ");
636 // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
638 InstPrinter->printInst(&Inst, OS);
640 Inst.print(OS, &MAI);
644 /// EmitRawText - If this file is backed by a assembly streamer, this dumps
645 /// the specified string in the output .s file. This capability is
646 /// indicated by the hasRawTextSupport() predicate.
647 void MCAsmStreamer::EmitRawText(StringRef String) {
648 if (!String.empty() && String.back() == '\n')
649 String = String.substr(0, String.size()-1);
654 void MCAsmStreamer::Finish() {
658 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
659 formatted_raw_ostream &OS,
661 bool isVerboseAsm, MCInstPrinter *IP,
662 MCCodeEmitter *CE, bool ShowInst) {
663 return new MCAsmStreamer(Context, OS, isLittleEndian, isVerboseAsm,