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/MCFixupKindInfo.h"
16 #include "llvm/MC/MCInst.h"
17 #include "llvm/MC/MCInstPrinter.h"
18 #include "llvm/MC/MCSectionMachO.h"
19 #include "llvm/MC/MCSymbol.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/Format.h"
26 #include "llvm/Support/FormattedStream.h"
27 #include "llvm/Target/TargetAsmBackend.h"
28 #include "llvm/Target/TargetAsmInfo.h"
29 #include "llvm/Target/TargetLoweringObjectFile.h"
35 class MCAsmStreamer : public MCStreamer {
36 formatted_raw_ostream &OS;
38 OwningPtr<MCInstPrinter> InstPrinter;
39 OwningPtr<MCCodeEmitter> Emitter;
40 OwningPtr<TargetAsmBackend> AsmBackend;
42 SmallString<128> CommentToEmit;
43 raw_svector_ostream CommentStream;
45 unsigned IsVerboseAsm : 1;
46 unsigned ShowInst : 1;
49 bool needsSet(const MCExpr *Value);
52 MCAsmStreamer(MCContext &Context, formatted_raw_ostream &os,
55 MCInstPrinter *printer, MCCodeEmitter *emitter,
56 TargetAsmBackend *asmbackend,
58 : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
59 InstPrinter(printer), Emitter(emitter), AsmBackend(asmbackend),
60 CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
61 ShowInst(showInst), UseLoc(useLoc) {
62 if (InstPrinter && IsVerboseAsm)
63 InstPrinter->setCommentStream(CommentStream);
67 inline void EmitEOL() {
68 // If we don't have any comments, just emit a \n.
75 void EmitCommentsAndEOL();
77 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
79 virtual bool isVerboseAsm() const { return IsVerboseAsm; }
81 /// hasRawTextSupport - We support EmitRawText.
82 virtual bool hasRawTextSupport() const { return true; }
84 /// AddComment - Add a comment that can be emitted to the generated .s
85 /// file if applicable as a QoI issue to make the output of the compiler
86 /// more readable. This only affects the MCAsmStreamer, and only when
87 /// verbose assembly output is enabled.
88 virtual void AddComment(const Twine &T);
90 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
91 virtual void AddEncodingComment(const MCInst &Inst);
93 /// GetCommentOS - Return a raw_ostream that comments can be written to.
94 /// Unlike AddComment, you are required to terminate comments with \n if you
96 virtual raw_ostream &GetCommentOS() {
98 return nulls(); // Discard comments unless in verbose asm mode.
102 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
103 virtual void AddBlankLine() {
107 /// @name MCStreamer Interface
110 virtual void ChangeSection(const MCSection *Section);
112 virtual void InitSections() {
113 // FIXME, this is MachO specific, but the testsuite
115 SwitchSection(getContext().getMachOSection("__TEXT", "__text",
116 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
117 0, SectionKind::getText()));
120 virtual void EmitLabel(MCSymbol *Symbol);
122 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
123 virtual void EmitThumbFunc(MCSymbol *Func);
125 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
126 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
127 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
128 const MCSymbol *LastLabel,
129 const MCSymbol *Label);
131 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
133 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
134 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol);
135 virtual void EmitCOFFSymbolStorageClass(int StorageClass);
136 virtual void EmitCOFFSymbolType(int Type);
137 virtual void EndCOFFSymbolDef();
138 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
139 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
140 unsigned ByteAlignment);
142 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
144 /// @param Symbol - The common symbol to emit.
145 /// @param Size - The size of the common symbol.
146 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size);
148 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
149 unsigned Size = 0, unsigned ByteAlignment = 0);
151 virtual void EmitTBSSSymbol (const MCSection *Section, MCSymbol *Symbol,
152 uint64_t Size, unsigned ByteAlignment = 0);
154 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
156 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
157 bool isPCRel, unsigned AddrSpace);
158 virtual void EmitIntValue(uint64_t Value, unsigned Size,
159 unsigned AddrSpace = 0);
161 virtual void EmitULEB128Value(const MCExpr *Value);
163 virtual void EmitSLEB128Value(const MCExpr *Value);
165 virtual void EmitGPRel32Value(const MCExpr *Value);
168 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
171 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
172 unsigned ValueSize = 1,
173 unsigned MaxBytesToEmit = 0);
175 virtual void EmitCodeAlignment(unsigned ByteAlignment,
176 unsigned MaxBytesToEmit = 0);
178 virtual void EmitValueToOffset(const MCExpr *Offset,
179 unsigned char Value = 0);
181 virtual void EmitFileDirective(StringRef Filename);
182 virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Filename);
183 virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
184 unsigned Column, unsigned Flags,
185 unsigned Isa, unsigned Discriminator,
188 virtual void EmitCFIStartProc();
189 virtual void EmitCFIEndProc();
190 virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset);
191 virtual void EmitCFIDefCfaOffset(int64_t Offset);
192 virtual void EmitCFIDefCfaRegister(int64_t Register);
193 virtual void EmitCFIOffset(int64_t Register, int64_t Offset);
194 virtual void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding);
195 virtual void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding);
196 virtual void EmitCFIRememberState();
197 virtual void EmitCFIRestoreState();
198 virtual void EmitCFISameValue(int64_t Register);
199 virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset);
200 virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment);
202 virtual void EmitFnStart();
203 virtual void EmitFnEnd();
204 virtual void EmitCantUnwind();
205 virtual void EmitPersonality(const MCSymbol *Personality);
206 virtual void EmitHandlerData();
207 virtual void EmitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0);
208 virtual void EmitPad(int64_t Offset);
209 virtual void EmitRegSave(const SmallVectorImpl<unsigned> &RegList, bool);
212 virtual void EmitInstruction(const MCInst &Inst);
214 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
215 /// the specified string in the output .s file. This capability is
216 /// indicated by the hasRawTextSupport() predicate.
217 virtual void EmitRawText(StringRef String);
219 virtual void Finish();
224 } // end anonymous namespace.
226 /// AddComment - Add a comment that can be emitted to the generated .s
227 /// file if applicable as a QoI issue to make the output of the compiler
228 /// more readable. This only affects the MCAsmStreamer, and only when
229 /// verbose assembly output is enabled.
230 void MCAsmStreamer::AddComment(const Twine &T) {
231 if (!IsVerboseAsm) return;
233 // Make sure that CommentStream is flushed.
234 CommentStream.flush();
236 T.toVector(CommentToEmit);
237 // Each comment goes on its own line.
238 CommentToEmit.push_back('\n');
240 // Tell the comment stream that the vector changed underneath it.
241 CommentStream.resync();
244 void MCAsmStreamer::EmitCommentsAndEOL() {
245 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
250 CommentStream.flush();
251 StringRef Comments = CommentToEmit.str();
253 assert(Comments.back() == '\n' &&
254 "Comment array not newline terminated");
256 // Emit a line of comments.
257 OS.PadToColumn(MAI.getCommentColumn());
258 size_t Position = Comments.find('\n');
259 OS << MAI.getCommentString() << ' ' << Comments.substr(0, Position) << '\n';
261 Comments = Comments.substr(Position+1);
262 } while (!Comments.empty());
264 CommentToEmit.clear();
265 // Tell the comment stream that the vector changed underneath it.
266 CommentStream.resync();
269 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
270 assert(Bytes && "Invalid size!");
271 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
274 void MCAsmStreamer::ChangeSection(const MCSection *Section) {
275 assert(Section && "Cannot switch to a null section!");
276 Section->PrintSwitchToSection(MAI, OS);
279 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
280 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
281 MCStreamer::EmitLabel(Symbol);
283 OS << *Symbol << MAI.getLabelSuffix();
287 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
289 default: assert(0 && "Invalid flag!");
290 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
291 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
292 case MCAF_Code16: OS << "\t.code\t16"; break;
293 case MCAF_Code32: OS << "\t.code\t32"; break;
298 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
299 // This needs to emit to a temporary string to get properly quoted
300 // MCSymbols when they have spaces in them.
301 OS << "\t.thumb_func";
307 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
308 OS << *Symbol << " = " << *Value;
311 // FIXME: Lift context changes into super class.
312 Symbol->setVariableValue(Value);
315 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
316 OS << ".weakref " << *Alias << ", " << *Symbol;
320 void MCAsmStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
321 const MCSymbol *LastLabel,
322 const MCSymbol *Label) {
323 EmitDwarfSetLineAddr(LineDelta, Label,
324 getContext().getTargetAsmInfo().getPointerSize());
327 void MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
328 MCSymbolAttr Attribute) {
330 case MCSA_Invalid: assert(0 && "Invalid symbol attribute");
331 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
332 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
333 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
334 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
335 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
336 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
337 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
338 assert(MAI.hasDotTypeDotSizeDirective() && "Symbol Attr not supported");
339 OS << "\t.type\t" << *Symbol << ','
340 << ((MAI.getCommentString()[0] != '@') ? '@' : '%');
342 default: assert(0 && "Unknown ELF .type");
343 case MCSA_ELF_TypeFunction: OS << "function"; break;
344 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
345 case MCSA_ELF_TypeObject: OS << "object"; break;
346 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
347 case MCSA_ELF_TypeCommon: OS << "common"; break;
348 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
349 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
353 case MCSA_Global: // .globl/.global
354 OS << MAI.getGlobalDirective();
356 case MCSA_Hidden: OS << "\t.hidden\t"; break;
357 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
358 case MCSA_Internal: OS << "\t.internal\t"; break;
359 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
360 case MCSA_Local: OS << "\t.local\t"; break;
361 case MCSA_NoDeadStrip: OS << "\t.no_dead_strip\t"; break;
362 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
363 case MCSA_PrivateExtern: OS << "\t.private_extern\t"; break;
364 case MCSA_Protected: OS << "\t.protected\t"; break;
365 case MCSA_Reference: OS << "\t.reference\t"; break;
366 case MCSA_Weak: OS << "\t.weak\t"; break;
367 case MCSA_WeakDefinition: OS << "\t.weak_definition\t"; break;
369 case MCSA_WeakReference: OS << MAI.getWeakRefDirective(); break;
370 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
377 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
378 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
382 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
383 OS << "\t.def\t " << *Symbol << ';';
387 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
388 OS << "\t.scl\t" << StorageClass << ';';
392 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
393 OS << "\t.type\t" << Type << ';';
397 void MCAsmStreamer::EndCOFFSymbolDef() {
402 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
403 assert(MAI.hasDotTypeDotSizeDirective());
404 OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
407 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
408 unsigned ByteAlignment) {
409 OS << "\t.comm\t" << *Symbol << ',' << Size;
410 if (ByteAlignment != 0) {
411 if (MAI.getCOMMDirectiveAlignmentIsInBytes())
412 OS << ',' << ByteAlignment;
414 OS << ',' << Log2_32(ByteAlignment);
419 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
421 /// @param Symbol - The common symbol to emit.
422 /// @param Size - The size of the common symbol.
423 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
424 assert(MAI.hasLCOMMDirective() && "Doesn't have .lcomm, can't emit it!");
425 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
429 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
430 unsigned Size, unsigned ByteAlignment) {
431 // Note: a .zerofill directive does not switch sections.
434 // This is a mach-o specific directive.
435 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
436 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
438 if (Symbol != NULL) {
439 OS << ',' << *Symbol << ',' << Size;
440 if (ByteAlignment != 0)
441 OS << ',' << Log2_32(ByteAlignment);
446 // .tbss sym, size, align
447 // This depends that the symbol has already been mangled from the original,
449 void MCAsmStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
450 uint64_t Size, unsigned ByteAlignment) {
451 assert(Symbol != NULL && "Symbol shouldn't be NULL!");
452 // Instead of using the Section we'll just use the shortcut.
453 // This is a mach-o specific directive and section.
454 OS << ".tbss " << *Symbol << ", " << Size;
456 // Output align if we have it. We default to 1 so don't bother printing
458 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
463 static inline char toOctal(int X) { return (X&7)+'0'; }
465 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
468 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
469 unsigned char C = Data[i];
470 if (C == '"' || C == '\\') {
471 OS << '\\' << (char)C;
475 if (isprint((unsigned char)C)) {
481 case '\b': OS << "\\b"; break;
482 case '\f': OS << "\\f"; break;
483 case '\n': OS << "\\n"; break;
484 case '\r': OS << "\\r"; break;
485 case '\t': OS << "\\t"; break;
488 OS << toOctal(C >> 6);
489 OS << toOctal(C >> 3);
490 OS << toOctal(C >> 0);
499 void MCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
500 assert(getCurrentSection() && "Cannot emit contents before setting section!");
501 if (Data.empty()) return;
503 if (Data.size() == 1) {
504 OS << MAI.getData8bitsDirective(AddrSpace);
505 OS << (unsigned)(unsigned char)Data[0];
510 // If the data ends with 0 and the target supports .asciz, use it, otherwise
512 if (MAI.getAscizDirective() && Data.back() == 0) {
513 OS << MAI.getAscizDirective();
514 Data = Data.substr(0, Data.size()-1);
516 OS << MAI.getAsciiDirective();
520 PrintQuotedString(Data, OS);
524 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size,
525 unsigned AddrSpace) {
526 EmitValue(MCConstantExpr::Create(Value, getContext()), Size, AddrSpace);
529 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
530 bool isPCRel, unsigned AddrSpace) {
531 assert(getCurrentSection() && "Cannot emit contents before setting section!");
532 assert(!isPCRel && "Cannot emit pc relative relocations!");
533 const char *Directive = 0;
536 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
537 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
538 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
540 Directive = MAI.getData64bitsDirective(AddrSpace);
541 // If the target doesn't support 64-bit data, emit as two 32-bit halves.
542 if (Directive) break;
544 if (!Value->EvaluateAsAbsolute(IntValue))
545 report_fatal_error("Don't know how to emit this value.");
546 if (getContext().getTargetAsmInfo().isLittleEndian()) {
547 EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
548 EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
550 EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
551 EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
556 assert(Directive && "Invalid size for machine code value!");
557 OS << Directive << *Value;
561 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
563 if (Value->EvaluateAsAbsolute(IntValue)) {
564 EmitULEB128IntValue(IntValue);
567 assert(MAI.hasLEB128() && "Cannot print a .uleb");
568 OS << ".uleb128 " << *Value;
572 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
574 if (Value->EvaluateAsAbsolute(IntValue)) {
575 EmitSLEB128IntValue(IntValue);
578 assert(MAI.hasLEB128() && "Cannot print a .sleb");
579 OS << ".sleb128 " << *Value;
583 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
584 assert(MAI.getGPRel32Directive() != 0);
585 OS << MAI.getGPRel32Directive() << *Value;
590 /// EmitFill - Emit NumBytes bytes worth of the value specified by
591 /// FillValue. This implements directives such as '.space'.
592 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
593 unsigned AddrSpace) {
594 if (NumBytes == 0) return;
597 if (const char *ZeroDirective = MAI.getZeroDirective()) {
598 OS << ZeroDirective << NumBytes;
600 OS << ',' << (int)FillValue;
605 // Emit a byte at a time.
606 MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
609 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
611 unsigned MaxBytesToEmit) {
612 // Some assemblers don't support non-power of two alignments, so we always
613 // emit alignments as a power of two if possible.
614 if (isPowerOf2_32(ByteAlignment)) {
616 default: llvm_unreachable("Invalid size for machine code value!");
617 case 1: OS << MAI.getAlignDirective(); break;
618 // FIXME: use MAI for this!
619 case 2: OS << ".p2alignw "; break;
620 case 4: OS << ".p2alignl "; break;
621 case 8: llvm_unreachable("Unsupported alignment size!");
624 if (MAI.getAlignmentIsInBytes())
627 OS << Log2_32(ByteAlignment);
629 if (Value || MaxBytesToEmit) {
631 OS.write_hex(truncateToSize(Value, ValueSize));
634 OS << ", " << MaxBytesToEmit;
640 // Non-power of two alignment. This is not widely supported by assemblers.
641 // FIXME: Parameterize this based on MAI.
643 default: llvm_unreachable("Invalid size for machine code value!");
644 case 1: OS << ".balign"; break;
645 case 2: OS << ".balignw"; break;
646 case 4: OS << ".balignl"; break;
647 case 8: llvm_unreachable("Unsupported alignment size!");
650 OS << ' ' << ByteAlignment;
651 OS << ", " << truncateToSize(Value, ValueSize);
653 OS << ", " << MaxBytesToEmit;
657 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
658 unsigned MaxBytesToEmit) {
659 // Emit with a text fill value.
660 EmitValueToAlignment(ByteAlignment, MAI.getTextAlignFillValue(),
664 void MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
665 unsigned char Value) {
666 // FIXME: Verify that Offset is associated with the current section.
667 OS << ".org " << *Offset << ", " << (unsigned) Value;
672 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
673 assert(MAI.hasSingleParameterDotFile());
675 PrintQuotedString(Filename, OS);
679 bool MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Filename){
681 OS << "\t.file\t" << FileNo << ' ';
682 PrintQuotedString(Filename, OS);
685 return this->MCStreamer::EmitDwarfFileDirective(FileNo, Filename);
688 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
689 unsigned Column, unsigned Flags,
691 unsigned Discriminator,
692 StringRef FileName) {
693 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
694 Isa, Discriminator, FileName);
698 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
699 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
700 OS << " basic_block";
701 if (Flags & DWARF2_FLAG_PROLOGUE_END)
702 OS << " prologue_end";
703 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
704 OS << " epilogue_begin";
706 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
707 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
710 if (Flags & DWARF2_FLAG_IS_STMT)
719 OS << "discriminator " << Discriminator;
722 OS.PadToColumn(MAI.getCommentColumn());
723 OS << MAI.getCommentString() << ' ' << FileName << ':'
724 << Line << ':' << Column;
729 void MCAsmStreamer::EmitCFIStartProc() {
730 MCStreamer::EmitCFIStartProc();
732 OS << "\t.cfi_startproc";
736 void MCAsmStreamer::EmitCFIEndProc() {
737 MCStreamer::EmitCFIEndProc();
739 OS << "\t.cfi_endproc";
743 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
747 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
748 MCStreamer::EmitCFIDefCfaOffset(Offset);
750 OS << "\t.cfi_def_cfa_offset " << Offset;
754 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
755 MCStreamer::EmitCFIDefCfaRegister(Register);
757 OS << "\t.cfi_def_cfa_register " << Register;
761 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
762 this->MCStreamer::EmitCFIOffset(Register, Offset);
764 OS << "\t.cfi_offset " << Register << ", " << Offset;
768 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
770 MCStreamer::EmitCFIPersonality(Sym, Encoding);
772 OS << "\t.cfi_personality " << Encoding << ", " << *Sym;
776 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
777 MCStreamer::EmitCFILsda(Sym, Encoding);
779 OS << "\t.cfi_lsda " << Encoding << ", " << *Sym;
783 void MCAsmStreamer::EmitCFIRememberState() {
784 MCStreamer::EmitCFIRememberState();
786 OS << "\t.cfi_remember_state";
790 void MCAsmStreamer::EmitCFIRestoreState() {
791 MCStreamer::EmitCFIRestoreState();
793 OS << "\t.cfi_restore_state";
797 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
798 MCStreamer::EmitCFISameValue(Register);
800 OS << "\t.cfi_same_value " << Register;
804 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
805 MCStreamer::EmitCFIRelOffset(Register, Offset);
807 OS << "\t.cfi_rel_offset " << Register << ", " << Offset;
811 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
812 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
814 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
818 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst) {
819 raw_ostream &OS = GetCommentOS();
820 SmallString<256> Code;
821 SmallVector<MCFixup, 4> Fixups;
822 raw_svector_ostream VecOS(Code);
823 Emitter->EncodeInstruction(Inst, VecOS, Fixups);
826 // If we are showing fixups, create symbolic markers in the encoded
827 // representation. We do this by making a per-bit map to the fixup item index,
828 // then trying to display it as nicely as possible.
829 SmallVector<uint8_t, 64> FixupMap;
830 FixupMap.resize(Code.size() * 8);
831 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
834 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
835 MCFixup &F = Fixups[i];
836 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
837 for (unsigned j = 0; j != Info.TargetSize; ++j) {
838 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
839 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
840 FixupMap[Index] = 1 + i;
844 // FIXME: Node the fixup comments for Thumb2 are completely bogus since the
845 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
847 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
851 // See if all bits are the same map entry.
852 uint8_t MapEntry = FixupMap[i * 8 + 0];
853 for (unsigned j = 1; j != 8; ++j) {
854 if (FixupMap[i * 8 + j] == MapEntry)
857 MapEntry = uint8_t(~0U);
861 if (MapEntry != uint8_t(~0U)) {
863 OS << format("0x%02x", uint8_t(Code[i]));
866 // FIXME: Some of the 8 bits require fix up.
867 OS << format("0x%02x", uint8_t(Code[i])) << '\''
868 << char('A' + MapEntry - 1) << '\'';
870 OS << char('A' + MapEntry - 1);
873 // Otherwise, write out in binary.
875 for (unsigned j = 8; j--;) {
876 unsigned Bit = (Code[i] >> j) & 1;
879 if (getContext().getTargetAsmInfo().isLittleEndian())
880 FixupBit = i * 8 + j;
882 FixupBit = i * 8 + (7-j);
884 if (uint8_t MapEntry = FixupMap[FixupBit]) {
885 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
886 OS << char('A' + MapEntry - 1);
894 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
895 MCFixup &F = Fixups[i];
896 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
897 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
898 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
902 void MCAsmStreamer::EmitFnStart() {
907 void MCAsmStreamer::EmitFnEnd() {
912 void MCAsmStreamer::EmitCantUnwind() {
913 OS << "\t.cantunwind";
917 void MCAsmStreamer::EmitHandlerData() {
918 OS << "\t.handlerdata";
922 void MCAsmStreamer::EmitPersonality(const MCSymbol *Personality) {
923 OS << "\t.personality " << Personality->getName();
927 void MCAsmStreamer::EmitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset) {
928 OS << "\t.setfp\t" << InstPrinter->getRegName(FpReg)
929 << ", " << InstPrinter->getRegName(SpReg);
931 OS << ", #" << Offset;
935 void MCAsmStreamer::EmitPad(int64_t Offset) {
936 OS << "\t.pad\t#" << Offset;
940 void MCAsmStreamer::EmitRegSave(const SmallVectorImpl<unsigned> &RegList,
942 assert(RegList.size() && "RegList should not be empty");
948 OS << InstPrinter->getRegName(RegList[0]);
950 for (unsigned i = 1, e = RegList.size(); i != e; ++i)
951 OS << ", " << InstPrinter->getRegName(RegList[i]);
957 void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
958 assert(getCurrentSection() && "Cannot emit contents before setting section!");
960 // Show the encoding in a comment if we have a code emitter.
962 AddEncodingComment(Inst);
964 // Show the MCInst if enabled.
966 Inst.dump_pretty(GetCommentOS(), &MAI, InstPrinter.get(), "\n ");
967 GetCommentOS() << "\n";
970 // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
972 InstPrinter->printInst(&Inst, OS);
974 Inst.print(OS, &MAI);
978 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
979 /// the specified string in the output .s file. This capability is
980 /// indicated by the hasRawTextSupport() predicate.
981 void MCAsmStreamer::EmitRawText(StringRef String) {
982 if (!String.empty() && String.back() == '\n')
983 String = String.substr(0, String.size()-1);
988 void MCAsmStreamer::Finish() {
989 // Dump out the dwarf file & directory tables and line tables.
990 if (getContext().hasDwarfFiles() && !UseLoc)
991 MCDwarfFileTable::Emit(this);
994 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
995 formatted_raw_ostream &OS,
996 bool isVerboseAsm, bool useLoc,
997 MCInstPrinter *IP, MCCodeEmitter *CE,
998 TargetAsmBackend *TAB, bool ShowInst) {
999 return new MCAsmStreamer(Context, OS, isVerboseAsm, useLoc,
1000 IP, CE, TAB, ShowInst);