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;
50 enum EHSymbolFlags { EHGlobal = 1,
51 EHWeakDefinition = 1 << 1,
52 EHPrivateExtern = 1 << 2 };
53 DenseMap<const MCSymbol*, unsigned> FlagMap;
55 bool needsSet(const MCExpr *Value);
58 MCAsmStreamer(MCContext &Context, formatted_raw_ostream &os,
59 bool isVerboseAsm, bool useLoc, bool useCFI,
60 MCInstPrinter *printer, MCCodeEmitter *emitter,
61 TargetAsmBackend *asmbackend,
63 : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
64 InstPrinter(printer), Emitter(emitter), AsmBackend(asmbackend),
65 CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
66 ShowInst(showInst), UseLoc(useLoc), UseCFI(useCFI) {
67 if (InstPrinter && IsVerboseAsm)
68 InstPrinter->setCommentStream(CommentStream);
72 inline void EmitEOL() {
73 // If we don't have any comments, just emit a \n.
80 void EmitCommentsAndEOL();
82 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
84 virtual bool isVerboseAsm() const { return IsVerboseAsm; }
86 /// hasRawTextSupport - We support EmitRawText.
87 virtual bool hasRawTextSupport() const { return true; }
89 /// AddComment - Add a comment that can be emitted to the generated .s
90 /// file if applicable as a QoI issue to make the output of the compiler
91 /// more readable. This only affects the MCAsmStreamer, and only when
92 /// verbose assembly output is enabled.
93 virtual void AddComment(const Twine &T);
95 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
96 virtual void AddEncodingComment(const MCInst &Inst);
98 /// GetCommentOS - Return a raw_ostream that comments can be written to.
99 /// Unlike AddComment, you are required to terminate comments with \n if you
101 virtual raw_ostream &GetCommentOS() {
103 return nulls(); // Discard comments unless in verbose asm mode.
104 return CommentStream;
107 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
108 virtual void AddBlankLine() {
112 /// @name MCStreamer Interface
115 virtual void ChangeSection(const MCSection *Section);
117 virtual void InitSections() {
118 // FIXME, this is MachO specific, but the testsuite
120 SwitchSection(getContext().getMachOSection("__TEXT", "__text",
121 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
122 0, SectionKind::getText()));
125 virtual void EmitLabel(MCSymbol *Symbol);
126 virtual void EmitEHSymAttributes(const MCSymbol *Symbol,
128 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
129 virtual void EmitThumbFunc(MCSymbol *Func);
131 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
132 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
133 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
134 const MCSymbol *LastLabel,
135 const MCSymbol *Label);
136 virtual void EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
137 const MCSymbol *Label);
139 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
141 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
142 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol);
143 virtual void EmitCOFFSymbolStorageClass(int StorageClass);
144 virtual void EmitCOFFSymbolType(int Type);
145 virtual void EndCOFFSymbolDef();
146 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
147 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
148 unsigned ByteAlignment);
150 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
152 /// @param Symbol - The common symbol to emit.
153 /// @param Size - The size of the common symbol.
154 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size);
156 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
157 unsigned Size = 0, unsigned ByteAlignment = 0);
159 virtual void EmitTBSSSymbol (const MCSection *Section, MCSymbol *Symbol,
160 uint64_t Size, unsigned ByteAlignment = 0);
162 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
164 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
166 virtual void EmitIntValue(uint64_t Value, unsigned Size,
167 unsigned AddrSpace = 0);
169 virtual void EmitULEB128Value(const MCExpr *Value);
171 virtual void EmitSLEB128Value(const MCExpr *Value);
173 virtual void EmitGPRel32Value(const MCExpr *Value);
176 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
179 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
180 unsigned ValueSize = 1,
181 unsigned MaxBytesToEmit = 0);
183 virtual void EmitCodeAlignment(unsigned ByteAlignment,
184 unsigned MaxBytesToEmit = 0);
186 virtual void EmitValueToOffset(const MCExpr *Offset,
187 unsigned char Value = 0);
189 virtual void EmitFileDirective(StringRef Filename);
190 virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Filename);
191 virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
192 unsigned Column, unsigned Flags,
193 unsigned Isa, unsigned Discriminator,
196 virtual void EmitCFISections(bool EH, bool Debug);
197 virtual void EmitCFIStartProc();
198 virtual void EmitCFIEndProc();
199 virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset);
200 virtual void EmitCFIDefCfaOffset(int64_t Offset);
201 virtual void EmitCFIDefCfaRegister(int64_t Register);
202 virtual void EmitCFIOffset(int64_t Register, int64_t Offset);
203 virtual void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding);
204 virtual void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding);
205 virtual void EmitCFIRememberState();
206 virtual void EmitCFIRestoreState();
207 virtual void EmitCFISameValue(int64_t Register);
208 virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset);
209 virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment);
211 virtual void EmitFnStart();
212 virtual void EmitFnEnd();
213 virtual void EmitCantUnwind();
214 virtual void EmitPersonality(const MCSymbol *Personality);
215 virtual void EmitHandlerData();
216 virtual void EmitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0);
217 virtual void EmitPad(int64_t Offset);
218 virtual void EmitRegSave(const SmallVectorImpl<unsigned> &RegList, bool);
221 virtual void EmitInstruction(const MCInst &Inst);
223 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
224 /// the specified string in the output .s file. This capability is
225 /// indicated by the hasRawTextSupport() predicate.
226 virtual void EmitRawText(StringRef String);
228 virtual void Finish();
233 } // end anonymous namespace.
235 /// AddComment - Add a comment that can be emitted to the generated .s
236 /// file if applicable as a QoI issue to make the output of the compiler
237 /// more readable. This only affects the MCAsmStreamer, and only when
238 /// verbose assembly output is enabled.
239 void MCAsmStreamer::AddComment(const Twine &T) {
240 if (!IsVerboseAsm) return;
242 // Make sure that CommentStream is flushed.
243 CommentStream.flush();
245 T.toVector(CommentToEmit);
246 // Each comment goes on its own line.
247 CommentToEmit.push_back('\n');
249 // Tell the comment stream that the vector changed underneath it.
250 CommentStream.resync();
253 void MCAsmStreamer::EmitCommentsAndEOL() {
254 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
259 CommentStream.flush();
260 StringRef Comments = CommentToEmit.str();
262 assert(Comments.back() == '\n' &&
263 "Comment array not newline terminated");
265 // Emit a line of comments.
266 OS.PadToColumn(MAI.getCommentColumn());
267 size_t Position = Comments.find('\n');
268 OS << MAI.getCommentString() << ' ' << Comments.substr(0, Position) << '\n';
270 Comments = Comments.substr(Position+1);
271 } while (!Comments.empty());
273 CommentToEmit.clear();
274 // Tell the comment stream that the vector changed underneath it.
275 CommentStream.resync();
278 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
279 assert(Bytes && "Invalid size!");
280 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
283 void MCAsmStreamer::ChangeSection(const MCSection *Section) {
284 assert(Section && "Cannot switch to a null section!");
285 Section->PrintSwitchToSection(MAI, OS);
288 void MCAsmStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
289 MCSymbol *EHSymbol) {
293 unsigned Flags = FlagMap.lookup(Symbol);
295 if (Flags & EHGlobal)
296 EmitSymbolAttribute(EHSymbol, MCSA_Global);
297 if (Flags & EHWeakDefinition)
298 EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
299 if (Flags & EHPrivateExtern)
300 EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
303 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
304 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
305 MCStreamer::EmitLabel(Symbol);
307 OS << *Symbol << MAI.getLabelSuffix();
311 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
313 default: assert(0 && "Invalid flag!");
314 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
315 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
316 case MCAF_Code16: OS << "\t.code\t16"; break;
317 case MCAF_Code32: OS << "\t.code\t32"; break;
322 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
323 // This needs to emit to a temporary string to get properly quoted
324 // MCSymbols when they have spaces in them.
325 OS << "\t.thumb_func";
331 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
332 OS << *Symbol << " = " << *Value;
335 // FIXME: Lift context changes into super class.
336 Symbol->setVariableValue(Value);
339 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
340 OS << ".weakref " << *Alias << ", " << *Symbol;
344 void MCAsmStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
345 const MCSymbol *LastLabel,
346 const MCSymbol *Label) {
347 EmitDwarfSetLineAddr(LineDelta, Label,
348 getContext().getTargetAsmInfo().getPointerSize());
351 void MCAsmStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
352 const MCSymbol *Label) {
353 EmitIntValue(dwarf::DW_CFA_advance_loc4, 1);
354 const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
355 AddrDelta = ForceExpAbs(this, getContext(), AddrDelta);
356 EmitValue(AddrDelta, 4);
360 void MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
361 MCSymbolAttr Attribute) {
363 case MCSA_Invalid: assert(0 && "Invalid symbol attribute");
364 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
365 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
366 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
367 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
368 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
369 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
370 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
371 assert(MAI.hasDotTypeDotSizeDirective() && "Symbol Attr not supported");
372 OS << "\t.type\t" << *Symbol << ','
373 << ((MAI.getCommentString()[0] != '@') ? '@' : '%');
375 default: assert(0 && "Unknown ELF .type");
376 case MCSA_ELF_TypeFunction: OS << "function"; break;
377 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
378 case MCSA_ELF_TypeObject: OS << "object"; break;
379 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
380 case MCSA_ELF_TypeCommon: OS << "common"; break;
381 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
382 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
386 case MCSA_Global: // .globl/.global
387 OS << MAI.getGlobalDirective();
388 FlagMap[Symbol] |= EHGlobal;
390 case MCSA_Hidden: OS << "\t.hidden\t"; break;
391 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
392 case MCSA_Internal: OS << "\t.internal\t"; break;
393 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
394 case MCSA_Local: OS << "\t.local\t"; break;
395 case MCSA_NoDeadStrip: OS << "\t.no_dead_strip\t"; break;
396 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
397 case MCSA_PrivateExtern:
398 OS << "\t.private_extern\t";
399 FlagMap[Symbol] |= EHPrivateExtern;
401 case MCSA_Protected: OS << "\t.protected\t"; break;
402 case MCSA_Reference: OS << "\t.reference\t"; break;
403 case MCSA_Weak: OS << "\t.weak\t"; break;
404 case MCSA_WeakDefinition:
405 OS << "\t.weak_definition\t";
406 FlagMap[Symbol] |= EHWeakDefinition;
409 case MCSA_WeakReference: OS << MAI.getWeakRefDirective(); break;
410 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
417 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
418 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
422 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
423 OS << "\t.def\t " << *Symbol << ';';
427 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
428 OS << "\t.scl\t" << StorageClass << ';';
432 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
433 OS << "\t.type\t" << Type << ';';
437 void MCAsmStreamer::EndCOFFSymbolDef() {
442 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
443 assert(MAI.hasDotTypeDotSizeDirective());
444 OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
447 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
448 unsigned ByteAlignment) {
449 OS << "\t.comm\t" << *Symbol << ',' << Size;
450 if (ByteAlignment != 0) {
451 if (MAI.getCOMMDirectiveAlignmentIsInBytes())
452 OS << ',' << ByteAlignment;
454 OS << ',' << Log2_32(ByteAlignment);
459 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
461 /// @param Symbol - The common symbol to emit.
462 /// @param Size - The size of the common symbol.
463 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
464 assert(MAI.hasLCOMMDirective() && "Doesn't have .lcomm, can't emit it!");
465 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
469 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
470 unsigned Size, unsigned ByteAlignment) {
471 // Note: a .zerofill directive does not switch sections.
474 // This is a mach-o specific directive.
475 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
476 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
478 if (Symbol != NULL) {
479 OS << ',' << *Symbol << ',' << Size;
480 if (ByteAlignment != 0)
481 OS << ',' << Log2_32(ByteAlignment);
486 // .tbss sym, size, align
487 // This depends that the symbol has already been mangled from the original,
489 void MCAsmStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
490 uint64_t Size, unsigned ByteAlignment) {
491 assert(Symbol != NULL && "Symbol shouldn't be NULL!");
492 // Instead of using the Section we'll just use the shortcut.
493 // This is a mach-o specific directive and section.
494 OS << ".tbss " << *Symbol << ", " << Size;
496 // Output align if we have it. We default to 1 so don't bother printing
498 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
503 static inline char toOctal(int X) { return (X&7)+'0'; }
505 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
508 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
509 unsigned char C = Data[i];
510 if (C == '"' || C == '\\') {
511 OS << '\\' << (char)C;
515 if (isprint((unsigned char)C)) {
521 case '\b': OS << "\\b"; break;
522 case '\f': OS << "\\f"; break;
523 case '\n': OS << "\\n"; break;
524 case '\r': OS << "\\r"; break;
525 case '\t': OS << "\\t"; break;
528 OS << toOctal(C >> 6);
529 OS << toOctal(C >> 3);
530 OS << toOctal(C >> 0);
539 void MCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
540 assert(getCurrentSection() && "Cannot emit contents before setting section!");
541 if (Data.empty()) return;
543 if (Data.size() == 1) {
544 OS << MAI.getData8bitsDirective(AddrSpace);
545 OS << (unsigned)(unsigned char)Data[0];
550 // If the data ends with 0 and the target supports .asciz, use it, otherwise
552 if (MAI.getAscizDirective() && Data.back() == 0) {
553 OS << MAI.getAscizDirective();
554 Data = Data.substr(0, Data.size()-1);
556 OS << MAI.getAsciiDirective();
560 PrintQuotedString(Data, OS);
564 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size,
565 unsigned AddrSpace) {
566 EmitValue(MCConstantExpr::Create(Value, getContext()), Size, AddrSpace);
569 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
570 unsigned AddrSpace) {
571 assert(getCurrentSection() && "Cannot emit contents before setting section!");
572 const char *Directive = 0;
575 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
576 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
577 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
579 Directive = MAI.getData64bitsDirective(AddrSpace);
580 // If the target doesn't support 64-bit data, emit as two 32-bit halves.
581 if (Directive) break;
583 if (!Value->EvaluateAsAbsolute(IntValue))
584 report_fatal_error("Don't know how to emit this value.");
585 if (getContext().getTargetAsmInfo().isLittleEndian()) {
586 EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
587 EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
589 EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
590 EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
595 assert(Directive && "Invalid size for machine code value!");
596 OS << Directive << *Value;
600 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
602 if (Value->EvaluateAsAbsolute(IntValue)) {
603 EmitULEB128IntValue(IntValue);
606 assert(MAI.hasLEB128() && "Cannot print a .uleb");
607 OS << ".uleb128 " << *Value;
611 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
613 if (Value->EvaluateAsAbsolute(IntValue)) {
614 EmitSLEB128IntValue(IntValue);
617 assert(MAI.hasLEB128() && "Cannot print a .sleb");
618 OS << ".sleb128 " << *Value;
622 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
623 assert(MAI.getGPRel32Directive() != 0);
624 OS << MAI.getGPRel32Directive() << *Value;
629 /// EmitFill - Emit NumBytes bytes worth of the value specified by
630 /// FillValue. This implements directives such as '.space'.
631 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
632 unsigned AddrSpace) {
633 if (NumBytes == 0) return;
636 if (const char *ZeroDirective = MAI.getZeroDirective()) {
637 OS << ZeroDirective << NumBytes;
639 OS << ',' << (int)FillValue;
644 // Emit a byte at a time.
645 MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
648 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
650 unsigned MaxBytesToEmit) {
651 // Some assemblers don't support non-power of two alignments, so we always
652 // emit alignments as a power of two if possible.
653 if (isPowerOf2_32(ByteAlignment)) {
655 default: llvm_unreachable("Invalid size for machine code value!");
656 case 1: OS << MAI.getAlignDirective(); break;
657 // FIXME: use MAI for this!
658 case 2: OS << ".p2alignw "; break;
659 case 4: OS << ".p2alignl "; break;
660 case 8: llvm_unreachable("Unsupported alignment size!");
663 if (MAI.getAlignmentIsInBytes())
666 OS << Log2_32(ByteAlignment);
668 if (Value || MaxBytesToEmit) {
670 OS.write_hex(truncateToSize(Value, ValueSize));
673 OS << ", " << MaxBytesToEmit;
679 // Non-power of two alignment. This is not widely supported by assemblers.
680 // FIXME: Parameterize this based on MAI.
682 default: llvm_unreachable("Invalid size for machine code value!");
683 case 1: OS << ".balign"; break;
684 case 2: OS << ".balignw"; break;
685 case 4: OS << ".balignl"; break;
686 case 8: llvm_unreachable("Unsupported alignment size!");
689 OS << ' ' << ByteAlignment;
690 OS << ", " << truncateToSize(Value, ValueSize);
692 OS << ", " << MaxBytesToEmit;
696 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
697 unsigned MaxBytesToEmit) {
698 // Emit with a text fill value.
699 EmitValueToAlignment(ByteAlignment, MAI.getTextAlignFillValue(),
703 void MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
704 unsigned char Value) {
705 // FIXME: Verify that Offset is associated with the current section.
706 OS << ".org " << *Offset << ", " << (unsigned) Value;
711 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
712 assert(MAI.hasSingleParameterDotFile());
714 PrintQuotedString(Filename, OS);
718 bool MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Filename){
720 OS << "\t.file\t" << FileNo << ' ';
721 PrintQuotedString(Filename, OS);
724 return this->MCStreamer::EmitDwarfFileDirective(FileNo, Filename);
727 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
728 unsigned Column, unsigned Flags,
730 unsigned Discriminator,
731 StringRef FileName) {
732 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
733 Isa, Discriminator, FileName);
737 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
738 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
739 OS << " basic_block";
740 if (Flags & DWARF2_FLAG_PROLOGUE_END)
741 OS << " prologue_end";
742 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
743 OS << " epilogue_begin";
745 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
746 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
749 if (Flags & DWARF2_FLAG_IS_STMT)
758 OS << "discriminator " << Discriminator;
761 OS.PadToColumn(MAI.getCommentColumn());
762 OS << MAI.getCommentString() << ' ' << FileName << ':'
763 << Line << ':' << Column;
768 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
769 MCStreamer::EmitCFISections(EH, Debug);
774 OS << "\t.cfi_sections ";
778 OS << ", .debug_frame";
780 OS << ".debug_frame";
786 void MCAsmStreamer::EmitCFIStartProc() {
787 MCStreamer::EmitCFIStartProc();
792 OS << "\t.cfi_startproc";
796 void MCAsmStreamer::EmitCFIEndProc() {
797 MCStreamer::EmitCFIEndProc();
802 OS << "\t.cfi_endproc";
806 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
807 MCStreamer::EmitCFIDefCfa(Register, Offset);
812 OS << ".cfi_def_cfa " << Register << ", " << Offset;
816 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
817 MCStreamer::EmitCFIDefCfaOffset(Offset);
822 OS << "\t.cfi_def_cfa_offset " << Offset;
826 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
827 MCStreamer::EmitCFIDefCfaRegister(Register);
832 OS << "\t.cfi_def_cfa_register " << Register;
836 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
837 this->MCStreamer::EmitCFIOffset(Register, Offset);
842 OS << "\t.cfi_offset " << Register << ", " << Offset;
846 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
848 MCStreamer::EmitCFIPersonality(Sym, Encoding);
853 OS << "\t.cfi_personality " << Encoding << ", " << *Sym;
857 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
858 MCStreamer::EmitCFILsda(Sym, Encoding);
863 OS << "\t.cfi_lsda " << Encoding << ", " << *Sym;
867 void MCAsmStreamer::EmitCFIRememberState() {
868 MCStreamer::EmitCFIRememberState();
873 OS << "\t.cfi_remember_state";
877 void MCAsmStreamer::EmitCFIRestoreState() {
878 MCStreamer::EmitCFIRestoreState();
883 OS << "\t.cfi_restore_state";
887 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
888 MCStreamer::EmitCFISameValue(Register);
893 OS << "\t.cfi_same_value " << Register;
897 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
898 MCStreamer::EmitCFIRelOffset(Register, Offset);
903 OS << "\t.cfi_rel_offset " << Register << ", " << Offset;
907 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
908 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
913 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
917 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst) {
918 raw_ostream &OS = GetCommentOS();
919 SmallString<256> Code;
920 SmallVector<MCFixup, 4> Fixups;
921 raw_svector_ostream VecOS(Code);
922 Emitter->EncodeInstruction(Inst, VecOS, Fixups);
925 // If we are showing fixups, create symbolic markers in the encoded
926 // representation. We do this by making a per-bit map to the fixup item index,
927 // then trying to display it as nicely as possible.
928 SmallVector<uint8_t, 64> FixupMap;
929 FixupMap.resize(Code.size() * 8);
930 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
933 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
934 MCFixup &F = Fixups[i];
935 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
936 for (unsigned j = 0; j != Info.TargetSize; ++j) {
937 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
938 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
939 FixupMap[Index] = 1 + i;
943 // FIXME: Node the fixup comments for Thumb2 are completely bogus since the
944 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
946 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
950 // See if all bits are the same map entry.
951 uint8_t MapEntry = FixupMap[i * 8 + 0];
952 for (unsigned j = 1; j != 8; ++j) {
953 if (FixupMap[i * 8 + j] == MapEntry)
956 MapEntry = uint8_t(~0U);
960 if (MapEntry != uint8_t(~0U)) {
962 OS << format("0x%02x", uint8_t(Code[i]));
965 // FIXME: Some of the 8 bits require fix up.
966 OS << format("0x%02x", uint8_t(Code[i])) << '\''
967 << char('A' + MapEntry - 1) << '\'';
969 OS << char('A' + MapEntry - 1);
972 // Otherwise, write out in binary.
974 for (unsigned j = 8; j--;) {
975 unsigned Bit = (Code[i] >> j) & 1;
978 if (getContext().getTargetAsmInfo().isLittleEndian())
979 FixupBit = i * 8 + j;
981 FixupBit = i * 8 + (7-j);
983 if (uint8_t MapEntry = FixupMap[FixupBit]) {
984 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
985 OS << char('A' + MapEntry - 1);
993 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
994 MCFixup &F = Fixups[i];
995 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
996 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
997 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1001 void MCAsmStreamer::EmitFnStart() {
1006 void MCAsmStreamer::EmitFnEnd() {
1011 void MCAsmStreamer::EmitCantUnwind() {
1012 OS << "\t.cantunwind";
1016 void MCAsmStreamer::EmitHandlerData() {
1017 OS << "\t.handlerdata";
1021 void MCAsmStreamer::EmitPersonality(const MCSymbol *Personality) {
1022 OS << "\t.personality " << Personality->getName();
1026 void MCAsmStreamer::EmitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset) {
1027 OS << "\t.setfp\t" << InstPrinter->getRegName(FpReg)
1028 << ", " << InstPrinter->getRegName(SpReg);
1030 OS << ", #" << Offset;
1034 void MCAsmStreamer::EmitPad(int64_t Offset) {
1035 OS << "\t.pad\t#" << Offset;
1039 void MCAsmStreamer::EmitRegSave(const SmallVectorImpl<unsigned> &RegList,
1041 assert(RegList.size() && "RegList should not be empty");
1043 OS << "\t.vsave\t{";
1047 OS << InstPrinter->getRegName(RegList[0]);
1049 for (unsigned i = 1, e = RegList.size(); i != e; ++i)
1050 OS << ", " << InstPrinter->getRegName(RegList[i]);
1056 void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
1057 assert(getCurrentSection() && "Cannot emit contents before setting section!");
1059 // Show the encoding in a comment if we have a code emitter.
1061 AddEncodingComment(Inst);
1063 // Show the MCInst if enabled.
1065 Inst.dump_pretty(GetCommentOS(), &MAI, InstPrinter.get(), "\n ");
1066 GetCommentOS() << "\n";
1069 // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
1071 InstPrinter->printInst(&Inst, OS);
1073 Inst.print(OS, &MAI);
1077 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1078 /// the specified string in the output .s file. This capability is
1079 /// indicated by the hasRawTextSupport() predicate.
1080 void MCAsmStreamer::EmitRawText(StringRef String) {
1081 if (!String.empty() && String.back() == '\n')
1082 String = String.substr(0, String.size()-1);
1087 void MCAsmStreamer::Finish() {
1088 // Dump out the dwarf file & directory tables and line tables.
1089 if (getContext().hasDwarfFiles() && !UseLoc)
1090 MCDwarfFileTable::Emit(this);
1096 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1097 formatted_raw_ostream &OS,
1098 bool isVerboseAsm, bool useLoc,
1100 MCInstPrinter *IP, MCCodeEmitter *CE,
1101 TargetAsmBackend *TAB, bool ShowInst) {
1102 return new MCAsmStreamer(Context, OS, isVerboseAsm, useLoc, useCFI,
1103 IP, CE, TAB, ShowInst);