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/MCRegisterInfo.h"
19 #include "llvm/MC/MCSectionCOFF.h"
20 #include "llvm/MC/MCSectionMachO.h"
21 #include "llvm/MC/MCSymbol.h"
22 #include "llvm/MC/TargetAsmBackend.h"
23 #include "llvm/ADT/OwningPtr.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/Format.h"
30 #include "llvm/Support/FormattedStream.h"
31 #include "llvm/Target/TargetLoweringObjectFile.h"
37 class MCAsmStreamer : public MCStreamer {
39 formatted_raw_ostream &OS;
42 OwningPtr<MCInstPrinter> InstPrinter;
43 OwningPtr<MCCodeEmitter> Emitter;
44 OwningPtr<TargetAsmBackend> AsmBackend;
46 SmallString<128> CommentToEmit;
47 raw_svector_ostream CommentStream;
49 unsigned IsVerboseAsm : 1;
50 unsigned ShowInst : 1;
54 enum EHSymbolFlags { EHGlobal = 1,
55 EHWeakDefinition = 1 << 1,
56 EHPrivateExtern = 1 << 2 };
57 DenseMap<const MCSymbol*, unsigned> FlagMap;
59 bool needsSet(const MCExpr *Value);
61 void EmitRegisterName(int64_t Register);
64 MCAsmStreamer(MCContext &Context, formatted_raw_ostream &os,
65 bool isVerboseAsm, bool useLoc, bool useCFI,
66 MCInstPrinter *printer, MCCodeEmitter *emitter,
67 TargetAsmBackend *asmbackend,
69 : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()),
70 InstPrinter(printer), Emitter(emitter), AsmBackend(asmbackend),
71 CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm),
72 ShowInst(showInst), UseLoc(useLoc), UseCFI(useCFI) {
73 if (InstPrinter && IsVerboseAsm)
74 InstPrinter->setCommentStream(CommentStream);
78 inline void EmitEOL() {
79 // If we don't have any comments, just emit a \n.
86 void EmitCommentsAndEOL();
88 /// isVerboseAsm - Return true if this streamer supports verbose assembly at
90 virtual bool isVerboseAsm() const { return IsVerboseAsm; }
92 /// hasRawTextSupport - We support EmitRawText.
93 virtual bool hasRawTextSupport() const { return true; }
95 /// AddComment - Add a comment that can be emitted to the generated .s
96 /// file if applicable as a QoI issue to make the output of the compiler
97 /// more readable. This only affects the MCAsmStreamer, and only when
98 /// verbose assembly output is enabled.
99 virtual void AddComment(const Twine &T);
101 /// AddEncodingComment - Add a comment showing the encoding of an instruction.
102 virtual void AddEncodingComment(const MCInst &Inst);
104 /// GetCommentOS - Return a raw_ostream that comments can be written to.
105 /// Unlike AddComment, you are required to terminate comments with \n if you
107 virtual raw_ostream &GetCommentOS() {
109 return nulls(); // Discard comments unless in verbose asm mode.
110 return CommentStream;
113 /// AddBlankLine - Emit a blank line to a .s file to pretty it up.
114 virtual void AddBlankLine() {
118 /// @name MCStreamer Interface
121 virtual void ChangeSection(const MCSection *Section);
123 virtual void InitSections() {
124 // FIXME, this is MachO specific, but the testsuite
126 SwitchSection(getContext().getMachOSection("__TEXT", "__text",
127 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
128 0, SectionKind::getText()));
131 virtual void EmitLabel(MCSymbol *Symbol);
132 virtual void EmitEHSymAttributes(const MCSymbol *Symbol,
134 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
135 virtual void EmitThumbFunc(MCSymbol *Func);
137 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
138 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
139 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta,
140 const MCSymbol *LastLabel,
141 const MCSymbol *Label,
142 unsigned PointerSize);
143 virtual void EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
144 const MCSymbol *Label);
146 virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
148 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
149 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol);
150 virtual void EmitCOFFSymbolStorageClass(int StorageClass);
151 virtual void EmitCOFFSymbolType(int Type);
152 virtual void EndCOFFSymbolDef();
153 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
154 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
155 unsigned ByteAlignment);
157 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
159 /// @param Symbol - The common symbol to emit.
160 /// @param Size - The size of the common symbol.
161 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size);
163 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
164 unsigned Size = 0, unsigned ByteAlignment = 0);
166 virtual void EmitTBSSSymbol (const MCSection *Section, MCSymbol *Symbol,
167 uint64_t Size, unsigned ByteAlignment = 0);
169 virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
171 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
173 virtual void EmitIntValue(uint64_t Value, unsigned Size,
174 unsigned AddrSpace = 0);
176 virtual void EmitULEB128Value(const MCExpr *Value);
178 virtual void EmitSLEB128Value(const MCExpr *Value);
180 virtual void EmitGPRel32Value(const MCExpr *Value);
183 virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue,
186 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
187 unsigned ValueSize = 1,
188 unsigned MaxBytesToEmit = 0);
190 virtual void EmitCodeAlignment(unsigned ByteAlignment,
191 unsigned MaxBytesToEmit = 0);
193 virtual void EmitValueToOffset(const MCExpr *Offset,
194 unsigned char Value = 0);
196 virtual void EmitFileDirective(StringRef Filename);
197 virtual bool EmitDwarfFileDirective(unsigned FileNo, StringRef Filename);
198 virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
199 unsigned Column, unsigned Flags,
200 unsigned Isa, unsigned Discriminator,
203 virtual void EmitCFISections(bool EH, bool Debug);
204 virtual void EmitCFIStartProc();
205 virtual void EmitCFIEndProc();
206 virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset);
207 virtual void EmitCFIDefCfaOffset(int64_t Offset);
208 virtual void EmitCFIDefCfaRegister(int64_t Register);
209 virtual void EmitCFIOffset(int64_t Register, int64_t Offset);
210 virtual void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding);
211 virtual void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding);
212 virtual void EmitCFIRememberState();
213 virtual void EmitCFIRestoreState();
214 virtual void EmitCFISameValue(int64_t Register);
215 virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset);
216 virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment);
218 virtual void EmitWin64EHStartProc(const MCSymbol *Symbol);
219 virtual void EmitWin64EHEndProc();
220 virtual void EmitWin64EHStartChained();
221 virtual void EmitWin64EHEndChained();
222 virtual void EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
224 virtual void EmitWin64EHHandlerData();
225 virtual void EmitWin64EHPushReg(unsigned Register);
226 virtual void EmitWin64EHSetFrame(unsigned Register, unsigned Offset);
227 virtual void EmitWin64EHAllocStack(unsigned Size);
228 virtual void EmitWin64EHSaveReg(unsigned Register, unsigned Offset);
229 virtual void EmitWin64EHSaveXMM(unsigned Register, unsigned Offset);
230 virtual void EmitWin64EHPushFrame(bool Code);
231 virtual void EmitWin64EHEndProlog();
233 virtual void EmitFnStart();
234 virtual void EmitFnEnd();
235 virtual void EmitCantUnwind();
236 virtual void EmitPersonality(const MCSymbol *Personality);
237 virtual void EmitHandlerData();
238 virtual void EmitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0);
239 virtual void EmitPad(int64_t Offset);
240 virtual void EmitRegSave(const SmallVectorImpl<unsigned> &RegList, bool);
243 virtual void EmitInstruction(const MCInst &Inst);
245 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
246 /// the specified string in the output .s file. This capability is
247 /// indicated by the hasRawTextSupport() predicate.
248 virtual void EmitRawText(StringRef String);
250 virtual void Finish();
255 } // end anonymous namespace.
257 /// AddComment - Add a comment that can be emitted to the generated .s
258 /// file if applicable as a QoI issue to make the output of the compiler
259 /// more readable. This only affects the MCAsmStreamer, and only when
260 /// verbose assembly output is enabled.
261 void MCAsmStreamer::AddComment(const Twine &T) {
262 if (!IsVerboseAsm) return;
264 // Make sure that CommentStream is flushed.
265 CommentStream.flush();
267 T.toVector(CommentToEmit);
268 // Each comment goes on its own line.
269 CommentToEmit.push_back('\n');
271 // Tell the comment stream that the vector changed underneath it.
272 CommentStream.resync();
275 void MCAsmStreamer::EmitCommentsAndEOL() {
276 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
281 CommentStream.flush();
282 StringRef Comments = CommentToEmit.str();
284 assert(Comments.back() == '\n' &&
285 "Comment array not newline terminated");
287 // Emit a line of comments.
288 OS.PadToColumn(MAI.getCommentColumn());
289 size_t Position = Comments.find('\n');
290 OS << MAI.getCommentString() << ' ' << Comments.substr(0, Position) << '\n';
292 Comments = Comments.substr(Position+1);
293 } while (!Comments.empty());
295 CommentToEmit.clear();
296 // Tell the comment stream that the vector changed underneath it.
297 CommentStream.resync();
300 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
301 assert(Bytes && "Invalid size!");
302 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
305 void MCAsmStreamer::ChangeSection(const MCSection *Section) {
306 assert(Section && "Cannot switch to a null section!");
307 Section->PrintSwitchToSection(MAI, OS);
310 void MCAsmStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
311 MCSymbol *EHSymbol) {
315 unsigned Flags = FlagMap.lookup(Symbol);
317 if (Flags & EHGlobal)
318 EmitSymbolAttribute(EHSymbol, MCSA_Global);
319 if (Flags & EHWeakDefinition)
320 EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
321 if (Flags & EHPrivateExtern)
322 EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
325 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
326 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
327 MCStreamer::EmitLabel(Symbol);
329 OS << *Symbol << MAI.getLabelSuffix();
333 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
335 default: assert(0 && "Invalid flag!");
336 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
337 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
338 case MCAF_Code16: OS << "\t.code\t16"; break;
339 case MCAF_Code32: OS << "\t.code\t32"; break;
344 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
345 // This needs to emit to a temporary string to get properly quoted
346 // MCSymbols when they have spaces in them.
347 OS << "\t.thumb_func";
348 // Only Mach-O hasSubsectionsViaSymbols()
349 if (MAI.hasSubsectionsViaSymbols())
354 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
355 OS << *Symbol << " = " << *Value;
358 // FIXME: Lift context changes into super class.
359 Symbol->setVariableValue(Value);
362 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
363 OS << ".weakref " << *Alias << ", " << *Symbol;
367 void MCAsmStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
368 const MCSymbol *LastLabel,
369 const MCSymbol *Label,
370 unsigned PointerSize) {
371 EmitDwarfSetLineAddr(LineDelta, Label, PointerSize);
374 void MCAsmStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
375 const MCSymbol *Label) {
376 EmitIntValue(dwarf::DW_CFA_advance_loc4, 1);
377 const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
378 AddrDelta = ForceExpAbs(AddrDelta);
379 EmitValue(AddrDelta, 4);
383 void MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
384 MCSymbolAttr Attribute) {
386 case MCSA_Invalid: assert(0 && "Invalid symbol attribute");
387 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
388 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
389 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
390 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
391 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
392 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
393 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
394 assert(MAI.hasDotTypeDotSizeDirective() && "Symbol Attr not supported");
395 OS << "\t.type\t" << *Symbol << ','
396 << ((MAI.getCommentString()[0] != '@') ? '@' : '%');
398 default: assert(0 && "Unknown ELF .type");
399 case MCSA_ELF_TypeFunction: OS << "function"; break;
400 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
401 case MCSA_ELF_TypeObject: OS << "object"; break;
402 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
403 case MCSA_ELF_TypeCommon: OS << "common"; break;
404 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
405 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
409 case MCSA_Global: // .globl/.global
410 OS << MAI.getGlobalDirective();
411 FlagMap[Symbol] |= EHGlobal;
413 case MCSA_Hidden: OS << "\t.hidden\t"; break;
414 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
415 case MCSA_Internal: OS << "\t.internal\t"; break;
416 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
417 case MCSA_Local: OS << "\t.local\t"; break;
418 case MCSA_NoDeadStrip: OS << "\t.no_dead_strip\t"; break;
419 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
420 case MCSA_PrivateExtern:
421 OS << "\t.private_extern\t";
422 FlagMap[Symbol] |= EHPrivateExtern;
424 case MCSA_Protected: OS << "\t.protected\t"; break;
425 case MCSA_Reference: OS << "\t.reference\t"; break;
426 case MCSA_Weak: OS << "\t.weak\t"; break;
427 case MCSA_WeakDefinition:
428 OS << "\t.weak_definition\t";
429 FlagMap[Symbol] |= EHWeakDefinition;
432 case MCSA_WeakReference: OS << MAI.getWeakRefDirective(); break;
433 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
440 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
441 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
445 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
446 OS << "\t.def\t " << *Symbol << ';';
450 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
451 OS << "\t.scl\t" << StorageClass << ';';
455 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
456 OS << "\t.type\t" << Type << ';';
460 void MCAsmStreamer::EndCOFFSymbolDef() {
465 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
466 assert(MAI.hasDotTypeDotSizeDirective());
467 OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
470 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
471 unsigned ByteAlignment) {
472 OS << "\t.comm\t" << *Symbol << ',' << Size;
473 if (ByteAlignment != 0) {
474 if (MAI.getCOMMDirectiveAlignmentIsInBytes())
475 OS << ',' << ByteAlignment;
477 OS << ',' << Log2_32(ByteAlignment);
482 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
484 /// @param Symbol - The common symbol to emit.
485 /// @param Size - The size of the common symbol.
486 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
487 assert(MAI.hasLCOMMDirective() && "Doesn't have .lcomm, can't emit it!");
488 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
492 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
493 unsigned Size, unsigned ByteAlignment) {
494 // Note: a .zerofill directive does not switch sections.
497 // This is a mach-o specific directive.
498 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
499 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
501 if (Symbol != NULL) {
502 OS << ',' << *Symbol << ',' << Size;
503 if (ByteAlignment != 0)
504 OS << ',' << Log2_32(ByteAlignment);
509 // .tbss sym, size, align
510 // This depends that the symbol has already been mangled from the original,
512 void MCAsmStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
513 uint64_t Size, unsigned ByteAlignment) {
514 assert(Symbol != NULL && "Symbol shouldn't be NULL!");
515 // Instead of using the Section we'll just use the shortcut.
516 // This is a mach-o specific directive and section.
517 OS << ".tbss " << *Symbol << ", " << Size;
519 // Output align if we have it. We default to 1 so don't bother printing
521 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
526 static inline char toOctal(int X) { return (X&7)+'0'; }
528 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
531 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
532 unsigned char C = Data[i];
533 if (C == '"' || C == '\\') {
534 OS << '\\' << (char)C;
538 if (isprint((unsigned char)C)) {
544 case '\b': OS << "\\b"; break;
545 case '\f': OS << "\\f"; break;
546 case '\n': OS << "\\n"; break;
547 case '\r': OS << "\\r"; break;
548 case '\t': OS << "\\t"; break;
551 OS << toOctal(C >> 6);
552 OS << toOctal(C >> 3);
553 OS << toOctal(C >> 0);
562 void MCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
563 assert(getCurrentSection() && "Cannot emit contents before setting section!");
564 if (Data.empty()) return;
566 if (Data.size() == 1) {
567 OS << MAI.getData8bitsDirective(AddrSpace);
568 OS << (unsigned)(unsigned char)Data[0];
573 // If the data ends with 0 and the target supports .asciz, use it, otherwise
575 if (MAI.getAscizDirective() && Data.back() == 0) {
576 OS << MAI.getAscizDirective();
577 Data = Data.substr(0, Data.size()-1);
579 OS << MAI.getAsciiDirective();
583 PrintQuotedString(Data, OS);
587 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size,
588 unsigned AddrSpace) {
589 EmitValue(MCConstantExpr::Create(Value, getContext()), Size, AddrSpace);
592 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
593 unsigned AddrSpace) {
594 assert(getCurrentSection() && "Cannot emit contents before setting section!");
595 const char *Directive = 0;
598 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
599 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
600 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
602 Directive = MAI.getData64bitsDirective(AddrSpace);
603 // If the target doesn't support 64-bit data, emit as two 32-bit halves.
604 if (Directive) break;
606 if (!Value->EvaluateAsAbsolute(IntValue))
607 report_fatal_error("Don't know how to emit this value.");
608 if (getContext().getAsmInfo().isLittleEndian()) {
609 EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
610 EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
612 EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
613 EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
618 assert(Directive && "Invalid size for machine code value!");
619 OS << Directive << *Value;
623 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
625 if (Value->EvaluateAsAbsolute(IntValue)) {
626 EmitULEB128IntValue(IntValue);
629 assert(MAI.hasLEB128() && "Cannot print a .uleb");
630 OS << ".uleb128 " << *Value;
634 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
636 if (Value->EvaluateAsAbsolute(IntValue)) {
637 EmitSLEB128IntValue(IntValue);
640 assert(MAI.hasLEB128() && "Cannot print a .sleb");
641 OS << ".sleb128 " << *Value;
645 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
646 assert(MAI.getGPRel32Directive() != 0);
647 OS << MAI.getGPRel32Directive() << *Value;
652 /// EmitFill - Emit NumBytes bytes worth of the value specified by
653 /// FillValue. This implements directives such as '.space'.
654 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
655 unsigned AddrSpace) {
656 if (NumBytes == 0) return;
659 if (const char *ZeroDirective = MAI.getZeroDirective()) {
660 OS << ZeroDirective << NumBytes;
662 OS << ',' << (int)FillValue;
667 // Emit a byte at a time.
668 MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
671 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
673 unsigned MaxBytesToEmit) {
674 // Some assemblers don't support non-power of two alignments, so we always
675 // emit alignments as a power of two if possible.
676 if (isPowerOf2_32(ByteAlignment)) {
678 default: llvm_unreachable("Invalid size for machine code value!");
679 case 1: OS << MAI.getAlignDirective(); break;
680 // FIXME: use MAI for this!
681 case 2: OS << ".p2alignw "; break;
682 case 4: OS << ".p2alignl "; break;
683 case 8: llvm_unreachable("Unsupported alignment size!");
686 if (MAI.getAlignmentIsInBytes())
689 OS << Log2_32(ByteAlignment);
691 if (Value || MaxBytesToEmit) {
693 OS.write_hex(truncateToSize(Value, ValueSize));
696 OS << ", " << MaxBytesToEmit;
702 // Non-power of two alignment. This is not widely supported by assemblers.
703 // FIXME: Parameterize this based on MAI.
705 default: llvm_unreachable("Invalid size for machine code value!");
706 case 1: OS << ".balign"; break;
707 case 2: OS << ".balignw"; break;
708 case 4: OS << ".balignl"; break;
709 case 8: llvm_unreachable("Unsupported alignment size!");
712 OS << ' ' << ByteAlignment;
713 OS << ", " << truncateToSize(Value, ValueSize);
715 OS << ", " << MaxBytesToEmit;
719 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
720 unsigned MaxBytesToEmit) {
721 // Emit with a text fill value.
722 EmitValueToAlignment(ByteAlignment, MAI.getTextAlignFillValue(),
726 void MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
727 unsigned char Value) {
728 // FIXME: Verify that Offset is associated with the current section.
729 OS << ".org " << *Offset << ", " << (unsigned) Value;
734 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
735 assert(MAI.hasSingleParameterDotFile());
737 PrintQuotedString(Filename, OS);
741 bool MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Filename){
743 OS << "\t.file\t" << FileNo << ' ';
744 PrintQuotedString(Filename, OS);
747 return this->MCStreamer::EmitDwarfFileDirective(FileNo, Filename);
750 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
751 unsigned Column, unsigned Flags,
753 unsigned Discriminator,
754 StringRef FileName) {
755 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
756 Isa, Discriminator, FileName);
760 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
761 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
762 OS << " basic_block";
763 if (Flags & DWARF2_FLAG_PROLOGUE_END)
764 OS << " prologue_end";
765 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
766 OS << " epilogue_begin";
768 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
769 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
772 if (Flags & DWARF2_FLAG_IS_STMT)
781 OS << "discriminator " << Discriminator;
784 OS.PadToColumn(MAI.getCommentColumn());
785 OS << MAI.getCommentString() << ' ' << FileName << ':'
786 << Line << ':' << Column;
791 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
792 MCStreamer::EmitCFISections(EH, Debug);
797 OS << "\t.cfi_sections ";
801 OS << ", .debug_frame";
803 OS << ".debug_frame";
809 void MCAsmStreamer::EmitCFIStartProc() {
810 MCStreamer::EmitCFIStartProc();
815 OS << "\t.cfi_startproc";
819 void MCAsmStreamer::EmitCFIEndProc() {
820 MCStreamer::EmitCFIEndProc();
825 OS << "\t.cfi_endproc";
829 void MCAsmStreamer::EmitRegisterName(int64_t Register) {
830 if (InstPrinter && !MAI.useDwarfRegNumForCFI()) {
831 const MCRegisterInfo &MRI = getContext().getRegisterInfo();
832 unsigned LLVMRegister = MRI.getLLVMRegNum(Register, true);
833 InstPrinter->printRegName(OS, LLVMRegister);
839 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
840 MCStreamer::EmitCFIDefCfa(Register, Offset);
845 OS << "\t.cfi_def_cfa ";
846 EmitRegisterName(Register);
847 OS << ", " << Offset;
851 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
852 MCStreamer::EmitCFIDefCfaOffset(Offset);
857 OS << "\t.cfi_def_cfa_offset " << Offset;
861 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
862 MCStreamer::EmitCFIDefCfaRegister(Register);
867 OS << "\t.cfi_def_cfa_register ";
868 EmitRegisterName(Register);
872 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
873 this->MCStreamer::EmitCFIOffset(Register, Offset);
878 OS << "\t.cfi_offset ";
879 EmitRegisterName(Register);
880 OS << ", " << Offset;
884 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
886 MCStreamer::EmitCFIPersonality(Sym, Encoding);
891 OS << "\t.cfi_personality " << Encoding << ", " << *Sym;
895 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
896 MCStreamer::EmitCFILsda(Sym, Encoding);
901 OS << "\t.cfi_lsda " << Encoding << ", " << *Sym;
905 void MCAsmStreamer::EmitCFIRememberState() {
906 MCStreamer::EmitCFIRememberState();
911 OS << "\t.cfi_remember_state";
915 void MCAsmStreamer::EmitCFIRestoreState() {
916 MCStreamer::EmitCFIRestoreState();
921 OS << "\t.cfi_restore_state";
925 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
926 MCStreamer::EmitCFISameValue(Register);
931 OS << "\t.cfi_same_value ";
932 EmitRegisterName(Register);
936 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
937 MCStreamer::EmitCFIRelOffset(Register, Offset);
942 OS << "\t.cfi_rel_offset ";
943 EmitRegisterName(Register);
944 OS << ", " << Offset;
948 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
949 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
954 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
958 void MCAsmStreamer::EmitWin64EHStartProc(const MCSymbol *Symbol) {
959 MCStreamer::EmitWin64EHStartProc(Symbol);
961 OS << ".seh_proc " << *Symbol;
965 void MCAsmStreamer::EmitWin64EHEndProc() {
966 MCStreamer::EmitWin64EHEndProc();
968 OS << "\t.seh_endproc";
972 void MCAsmStreamer::EmitWin64EHStartChained() {
973 MCStreamer::EmitWin64EHStartChained();
975 OS << "\t.seh_startchained";
979 void MCAsmStreamer::EmitWin64EHEndChained() {
980 MCStreamer::EmitWin64EHEndChained();
982 OS << "\t.seh_endchained";
986 void MCAsmStreamer::EmitWin64EHHandler(const MCSymbol *Sym, bool Unwind,
988 MCStreamer::EmitWin64EHHandler(Sym, Unwind, Except);
990 OS << "\t.seh_handler " << *Sym;
998 static const MCSection *getWin64EHTableSection(StringRef suffix,
999 MCContext &context) {
1000 // FIXME: This doesn't belong in MCObjectFileInfo. However,
1001 /// this duplicate code in MCWin64EH.cpp.
1003 return context.getObjectFileInfo()->getXDataSection();
1004 return context.getCOFFSection((".xdata"+suffix).str(),
1005 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1006 COFF::IMAGE_SCN_MEM_READ |
1007 COFF::IMAGE_SCN_MEM_WRITE,
1008 SectionKind::getDataRel());
1011 void MCAsmStreamer::EmitWin64EHHandlerData() {
1012 MCStreamer::EmitWin64EHHandlerData();
1014 // Switch sections. Don't call SwitchSection directly, because that will
1015 // cause the section switch to be visible in the emitted assembly.
1016 // We only do this so the section switch that terminates the handler
1017 // data block is visible.
1018 MCWin64EHUnwindInfo *CurFrame = getCurrentW64UnwindInfo();
1019 StringRef suffix=MCWin64EHUnwindEmitter::GetSectionSuffix(CurFrame->Function);
1020 const MCSection *xdataSect = getWin64EHTableSection(suffix, getContext());
1022 SwitchSectionNoChange(xdataSect);
1024 OS << "\t.seh_handlerdata";
1028 void MCAsmStreamer::EmitWin64EHPushReg(unsigned Register) {
1029 MCStreamer::EmitWin64EHPushReg(Register);
1031 OS << "\t.seh_pushreg " << Register;
1035 void MCAsmStreamer::EmitWin64EHSetFrame(unsigned Register, unsigned Offset) {
1036 MCStreamer::EmitWin64EHSetFrame(Register, Offset);
1038 OS << "\t.seh_setframe " << Register << ", " << Offset;
1042 void MCAsmStreamer::EmitWin64EHAllocStack(unsigned Size) {
1043 MCStreamer::EmitWin64EHAllocStack(Size);
1045 OS << "\t.seh_stackalloc " << Size;
1049 void MCAsmStreamer::EmitWin64EHSaveReg(unsigned Register, unsigned Offset) {
1050 MCStreamer::EmitWin64EHSaveReg(Register, Offset);
1052 OS << "\t.seh_savereg " << Register << ", " << Offset;
1056 void MCAsmStreamer::EmitWin64EHSaveXMM(unsigned Register, unsigned Offset) {
1057 MCStreamer::EmitWin64EHSaveXMM(Register, Offset);
1059 OS << "\t.seh_savexmm " << Register << ", " << Offset;
1063 void MCAsmStreamer::EmitWin64EHPushFrame(bool Code) {
1064 MCStreamer::EmitWin64EHPushFrame(Code);
1066 OS << "\t.seh_pushframe";
1072 void MCAsmStreamer::EmitWin64EHEndProlog(void) {
1073 MCStreamer::EmitWin64EHEndProlog();
1075 OS << "\t.seh_endprologue";
1079 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst) {
1080 raw_ostream &OS = GetCommentOS();
1081 SmallString<256> Code;
1082 SmallVector<MCFixup, 4> Fixups;
1083 raw_svector_ostream VecOS(Code);
1084 Emitter->EncodeInstruction(Inst, VecOS, Fixups);
1087 // If we are showing fixups, create symbolic markers in the encoded
1088 // representation. We do this by making a per-bit map to the fixup item index,
1089 // then trying to display it as nicely as possible.
1090 SmallVector<uint8_t, 64> FixupMap;
1091 FixupMap.resize(Code.size() * 8);
1092 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1095 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1096 MCFixup &F = Fixups[i];
1097 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1098 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1099 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1100 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1101 FixupMap[Index] = 1 + i;
1105 // FIXME: Note the fixup comments for Thumb2 are completely bogus since the
1106 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1107 OS << "encoding: [";
1108 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1112 // See if all bits are the same map entry.
1113 uint8_t MapEntry = FixupMap[i * 8 + 0];
1114 for (unsigned j = 1; j != 8; ++j) {
1115 if (FixupMap[i * 8 + j] == MapEntry)
1118 MapEntry = uint8_t(~0U);
1122 if (MapEntry != uint8_t(~0U)) {
1123 if (MapEntry == 0) {
1124 OS << format("0x%02x", uint8_t(Code[i]));
1127 // FIXME: Some of the 8 bits require fix up.
1128 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1129 << char('A' + MapEntry - 1) << '\'';
1131 OS << char('A' + MapEntry - 1);
1134 // Otherwise, write out in binary.
1136 for (unsigned j = 8; j--;) {
1137 unsigned Bit = (Code[i] >> j) & 1;
1140 if (getContext().getAsmInfo().isLittleEndian())
1141 FixupBit = i * 8 + j;
1143 FixupBit = i * 8 + (7-j);
1145 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1146 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1147 OS << char('A' + MapEntry - 1);
1155 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1156 MCFixup &F = Fixups[i];
1157 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1158 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1159 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1163 void MCAsmStreamer::EmitFnStart() {
1168 void MCAsmStreamer::EmitFnEnd() {
1173 void MCAsmStreamer::EmitCantUnwind() {
1174 OS << "\t.cantunwind";
1178 void MCAsmStreamer::EmitHandlerData() {
1179 OS << "\t.handlerdata";
1183 void MCAsmStreamer::EmitPersonality(const MCSymbol *Personality) {
1184 OS << "\t.personality " << Personality->getName();
1188 void MCAsmStreamer::EmitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset) {
1190 InstPrinter->printRegName(OS, FpReg);
1192 InstPrinter->printRegName(OS, SpReg);
1194 OS << ", #" << Offset;
1198 void MCAsmStreamer::EmitPad(int64_t Offset) {
1199 OS << "\t.pad\t#" << Offset;
1203 void MCAsmStreamer::EmitRegSave(const SmallVectorImpl<unsigned> &RegList,
1205 assert(RegList.size() && "RegList should not be empty");
1207 OS << "\t.vsave\t{";
1211 InstPrinter->printRegName(OS, RegList[0]);
1213 for (unsigned i = 1, e = RegList.size(); i != e; ++i) {
1215 InstPrinter->printRegName(OS, RegList[i]);
1222 void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
1223 assert(getCurrentSection() && "Cannot emit contents before setting section!");
1225 // Show the encoding in a comment if we have a code emitter.
1227 AddEncodingComment(Inst);
1229 // Show the MCInst if enabled.
1231 Inst.dump_pretty(GetCommentOS(), &MAI, InstPrinter.get(), "\n ");
1232 GetCommentOS() << "\n";
1235 // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
1237 InstPrinter->printInst(&Inst, OS);
1239 Inst.print(OS, &MAI);
1243 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1244 /// the specified string in the output .s file. This capability is
1245 /// indicated by the hasRawTextSupport() predicate.
1246 void MCAsmStreamer::EmitRawText(StringRef String) {
1247 if (!String.empty() && String.back() == '\n')
1248 String = String.substr(0, String.size()-1);
1253 void MCAsmStreamer::Finish() {
1254 // Dump out the dwarf file & directory tables and line tables.
1255 if (getContext().hasDwarfFiles() && !UseLoc)
1256 MCDwarfFileTable::Emit(this);
1261 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1262 formatted_raw_ostream &OS,
1263 bool isVerboseAsm, bool useLoc,
1264 bool useCFI, MCInstPrinter *IP,
1265 MCCodeEmitter *CE, TargetAsmBackend *TAB,
1267 return new MCAsmStreamer(Context, OS, isVerboseAsm, useLoc, useCFI,
1268 IP, CE, TAB, ShowInst);