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 EmitWin64EHStartProc(MCSymbol *Symbol, MCSymbol *EHandler = 0);
212 virtual void EmitWin64EHEndProc();
213 virtual void EmitWin64EHStartChained();
214 virtual void EmitWin64EHEndChained();
215 virtual void EmitWin64EHUnwindOnly();
216 virtual void EmitWin64EHLsda(const MCSymbol *Sym, int64_t Size);
217 virtual void EmitWin64EHPushReg(int64_t Register);
218 virtual void EmitWin64EHSetFrame(int64_t Register, int64_t Offset);
219 virtual void EmitWin64EHAllocStack(int64_t Size);
220 virtual void EmitWin64EHSaveReg(int64_t Register, int64_t Offset);
221 virtual void EmitWin64EHPushFrame(bool Code);
222 virtual void EmitWin64EHEndProlog();
224 virtual void EmitFnStart();
225 virtual void EmitFnEnd();
226 virtual void EmitCantUnwind();
227 virtual void EmitPersonality(const MCSymbol *Personality);
228 virtual void EmitHandlerData();
229 virtual void EmitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0);
230 virtual void EmitPad(int64_t Offset);
231 virtual void EmitRegSave(const SmallVectorImpl<unsigned> &RegList, bool);
234 virtual void EmitInstruction(const MCInst &Inst);
236 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
237 /// the specified string in the output .s file. This capability is
238 /// indicated by the hasRawTextSupport() predicate.
239 virtual void EmitRawText(StringRef String);
241 virtual void Finish();
246 } // end anonymous namespace.
248 /// AddComment - Add a comment that can be emitted to the generated .s
249 /// file if applicable as a QoI issue to make the output of the compiler
250 /// more readable. This only affects the MCAsmStreamer, and only when
251 /// verbose assembly output is enabled.
252 void MCAsmStreamer::AddComment(const Twine &T) {
253 if (!IsVerboseAsm) return;
255 // Make sure that CommentStream is flushed.
256 CommentStream.flush();
258 T.toVector(CommentToEmit);
259 // Each comment goes on its own line.
260 CommentToEmit.push_back('\n');
262 // Tell the comment stream that the vector changed underneath it.
263 CommentStream.resync();
266 void MCAsmStreamer::EmitCommentsAndEOL() {
267 if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) {
272 CommentStream.flush();
273 StringRef Comments = CommentToEmit.str();
275 assert(Comments.back() == '\n' &&
276 "Comment array not newline terminated");
278 // Emit a line of comments.
279 OS.PadToColumn(MAI.getCommentColumn());
280 size_t Position = Comments.find('\n');
281 OS << MAI.getCommentString() << ' ' << Comments.substr(0, Position) << '\n';
283 Comments = Comments.substr(Position+1);
284 } while (!Comments.empty());
286 CommentToEmit.clear();
287 // Tell the comment stream that the vector changed underneath it.
288 CommentStream.resync();
291 static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) {
292 assert(Bytes && "Invalid size!");
293 return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8));
296 void MCAsmStreamer::ChangeSection(const MCSection *Section) {
297 assert(Section && "Cannot switch to a null section!");
298 Section->PrintSwitchToSection(MAI, OS);
301 void MCAsmStreamer::EmitEHSymAttributes(const MCSymbol *Symbol,
302 MCSymbol *EHSymbol) {
306 unsigned Flags = FlagMap.lookup(Symbol);
308 if (Flags & EHGlobal)
309 EmitSymbolAttribute(EHSymbol, MCSA_Global);
310 if (Flags & EHWeakDefinition)
311 EmitSymbolAttribute(EHSymbol, MCSA_WeakDefinition);
312 if (Flags & EHPrivateExtern)
313 EmitSymbolAttribute(EHSymbol, MCSA_PrivateExtern);
316 void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) {
317 assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
318 MCStreamer::EmitLabel(Symbol);
320 OS << *Symbol << MAI.getLabelSuffix();
324 void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
326 default: assert(0 && "Invalid flag!");
327 case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break;
328 case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break;
329 case MCAF_Code16: OS << "\t.code\t16"; break;
330 case MCAF_Code32: OS << "\t.code\t32"; break;
335 void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) {
336 // This needs to emit to a temporary string to get properly quoted
337 // MCSymbols when they have spaces in them.
338 OS << "\t.thumb_func";
339 // Only Mach-O hasSubsectionsViaSymbols()
340 if (MAI.hasSubsectionsViaSymbols())
345 void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
346 OS << *Symbol << " = " << *Value;
349 // FIXME: Lift context changes into super class.
350 Symbol->setVariableValue(Value);
353 void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
354 OS << ".weakref " << *Alias << ", " << *Symbol;
358 void MCAsmStreamer::EmitDwarfAdvanceLineAddr(int64_t LineDelta,
359 const MCSymbol *LastLabel,
360 const MCSymbol *Label) {
361 EmitDwarfSetLineAddr(LineDelta, Label,
362 getContext().getTargetAsmInfo().getPointerSize());
365 void MCAsmStreamer::EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
366 const MCSymbol *Label) {
367 EmitIntValue(dwarf::DW_CFA_advance_loc4, 1);
368 const MCExpr *AddrDelta = BuildSymbolDiff(getContext(), Label, LastLabel);
369 AddrDelta = ForceExpAbs(this, getContext(), AddrDelta);
370 EmitValue(AddrDelta, 4);
374 void MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
375 MCSymbolAttr Attribute) {
377 case MCSA_Invalid: assert(0 && "Invalid symbol attribute");
378 case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function
379 case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC
380 case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object
381 case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object
382 case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common
383 case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype
384 case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object
385 assert(MAI.hasDotTypeDotSizeDirective() && "Symbol Attr not supported");
386 OS << "\t.type\t" << *Symbol << ','
387 << ((MAI.getCommentString()[0] != '@') ? '@' : '%');
389 default: assert(0 && "Unknown ELF .type");
390 case MCSA_ELF_TypeFunction: OS << "function"; break;
391 case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break;
392 case MCSA_ELF_TypeObject: OS << "object"; break;
393 case MCSA_ELF_TypeTLS: OS << "tls_object"; break;
394 case MCSA_ELF_TypeCommon: OS << "common"; break;
395 case MCSA_ELF_TypeNoType: OS << "no_type"; break;
396 case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break;
400 case MCSA_Global: // .globl/.global
401 OS << MAI.getGlobalDirective();
402 FlagMap[Symbol] |= EHGlobal;
404 case MCSA_Hidden: OS << "\t.hidden\t"; break;
405 case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break;
406 case MCSA_Internal: OS << "\t.internal\t"; break;
407 case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break;
408 case MCSA_Local: OS << "\t.local\t"; break;
409 case MCSA_NoDeadStrip: OS << "\t.no_dead_strip\t"; break;
410 case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break;
411 case MCSA_PrivateExtern:
412 OS << "\t.private_extern\t";
413 FlagMap[Symbol] |= EHPrivateExtern;
415 case MCSA_Protected: OS << "\t.protected\t"; break;
416 case MCSA_Reference: OS << "\t.reference\t"; break;
417 case MCSA_Weak: OS << "\t.weak\t"; break;
418 case MCSA_WeakDefinition:
419 OS << "\t.weak_definition\t";
420 FlagMap[Symbol] |= EHWeakDefinition;
423 case MCSA_WeakReference: OS << MAI.getWeakRefDirective(); break;
424 case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break;
431 void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
432 OS << ".desc" << ' ' << *Symbol << ',' << DescValue;
436 void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) {
437 OS << "\t.def\t " << *Symbol << ';';
441 void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) {
442 OS << "\t.scl\t" << StorageClass << ';';
446 void MCAsmStreamer::EmitCOFFSymbolType (int Type) {
447 OS << "\t.type\t" << Type << ';';
451 void MCAsmStreamer::EndCOFFSymbolDef() {
456 void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
457 assert(MAI.hasDotTypeDotSizeDirective());
458 OS << "\t.size\t" << *Symbol << ", " << *Value << '\n';
461 void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
462 unsigned ByteAlignment) {
463 OS << "\t.comm\t" << *Symbol << ',' << Size;
464 if (ByteAlignment != 0) {
465 if (MAI.getCOMMDirectiveAlignmentIsInBytes())
466 OS << ',' << ByteAlignment;
468 OS << ',' << Log2_32(ByteAlignment);
473 /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol.
475 /// @param Symbol - The common symbol to emit.
476 /// @param Size - The size of the common symbol.
477 void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
478 assert(MAI.hasLCOMMDirective() && "Doesn't have .lcomm, can't emit it!");
479 OS << "\t.lcomm\t" << *Symbol << ',' << Size;
483 void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
484 unsigned Size, unsigned ByteAlignment) {
485 // Note: a .zerofill directive does not switch sections.
488 // This is a mach-o specific directive.
489 const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section);
490 OS << MOSection->getSegmentName() << "," << MOSection->getSectionName();
492 if (Symbol != NULL) {
493 OS << ',' << *Symbol << ',' << Size;
494 if (ByteAlignment != 0)
495 OS << ',' << Log2_32(ByteAlignment);
500 // .tbss sym, size, align
501 // This depends that the symbol has already been mangled from the original,
503 void MCAsmStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
504 uint64_t Size, unsigned ByteAlignment) {
505 assert(Symbol != NULL && "Symbol shouldn't be NULL!");
506 // Instead of using the Section we'll just use the shortcut.
507 // This is a mach-o specific directive and section.
508 OS << ".tbss " << *Symbol << ", " << Size;
510 // Output align if we have it. We default to 1 so don't bother printing
512 if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment);
517 static inline char toOctal(int X) { return (X&7)+'0'; }
519 static void PrintQuotedString(StringRef Data, raw_ostream &OS) {
522 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
523 unsigned char C = Data[i];
524 if (C == '"' || C == '\\') {
525 OS << '\\' << (char)C;
529 if (isprint((unsigned char)C)) {
535 case '\b': OS << "\\b"; break;
536 case '\f': OS << "\\f"; break;
537 case '\n': OS << "\\n"; break;
538 case '\r': OS << "\\r"; break;
539 case '\t': OS << "\\t"; break;
542 OS << toOctal(C >> 6);
543 OS << toOctal(C >> 3);
544 OS << toOctal(C >> 0);
553 void MCAsmStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
554 assert(getCurrentSection() && "Cannot emit contents before setting section!");
555 if (Data.empty()) return;
557 if (Data.size() == 1) {
558 OS << MAI.getData8bitsDirective(AddrSpace);
559 OS << (unsigned)(unsigned char)Data[0];
564 // If the data ends with 0 and the target supports .asciz, use it, otherwise
566 if (MAI.getAscizDirective() && Data.back() == 0) {
567 OS << MAI.getAscizDirective();
568 Data = Data.substr(0, Data.size()-1);
570 OS << MAI.getAsciiDirective();
574 PrintQuotedString(Data, OS);
578 void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size,
579 unsigned AddrSpace) {
580 EmitValue(MCConstantExpr::Create(Value, getContext()), Size, AddrSpace);
583 void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
584 unsigned AddrSpace) {
585 assert(getCurrentSection() && "Cannot emit contents before setting section!");
586 const char *Directive = 0;
589 case 1: Directive = MAI.getData8bitsDirective(AddrSpace); break;
590 case 2: Directive = MAI.getData16bitsDirective(AddrSpace); break;
591 case 4: Directive = MAI.getData32bitsDirective(AddrSpace); break;
593 Directive = MAI.getData64bitsDirective(AddrSpace);
594 // If the target doesn't support 64-bit data, emit as two 32-bit halves.
595 if (Directive) break;
597 if (!Value->EvaluateAsAbsolute(IntValue))
598 report_fatal_error("Don't know how to emit this value.");
599 if (getContext().getTargetAsmInfo().isLittleEndian()) {
600 EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
601 EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
603 EmitIntValue((uint32_t)(IntValue >> 32), 4, AddrSpace);
604 EmitIntValue((uint32_t)(IntValue >> 0 ), 4, AddrSpace);
609 assert(Directive && "Invalid size for machine code value!");
610 OS << Directive << *Value;
614 void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) {
616 if (Value->EvaluateAsAbsolute(IntValue)) {
617 EmitULEB128IntValue(IntValue);
620 assert(MAI.hasLEB128() && "Cannot print a .uleb");
621 OS << ".uleb128 " << *Value;
625 void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) {
627 if (Value->EvaluateAsAbsolute(IntValue)) {
628 EmitSLEB128IntValue(IntValue);
631 assert(MAI.hasLEB128() && "Cannot print a .sleb");
632 OS << ".sleb128 " << *Value;
636 void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) {
637 assert(MAI.getGPRel32Directive() != 0);
638 OS << MAI.getGPRel32Directive() << *Value;
643 /// EmitFill - Emit NumBytes bytes worth of the value specified by
644 /// FillValue. This implements directives such as '.space'.
645 void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue,
646 unsigned AddrSpace) {
647 if (NumBytes == 0) return;
650 if (const char *ZeroDirective = MAI.getZeroDirective()) {
651 OS << ZeroDirective << NumBytes;
653 OS << ',' << (int)FillValue;
658 // Emit a byte at a time.
659 MCStreamer::EmitFill(NumBytes, FillValue, AddrSpace);
662 void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
664 unsigned MaxBytesToEmit) {
665 // Some assemblers don't support non-power of two alignments, so we always
666 // emit alignments as a power of two if possible.
667 if (isPowerOf2_32(ByteAlignment)) {
669 default: llvm_unreachable("Invalid size for machine code value!");
670 case 1: OS << MAI.getAlignDirective(); break;
671 // FIXME: use MAI for this!
672 case 2: OS << ".p2alignw "; break;
673 case 4: OS << ".p2alignl "; break;
674 case 8: llvm_unreachable("Unsupported alignment size!");
677 if (MAI.getAlignmentIsInBytes())
680 OS << Log2_32(ByteAlignment);
682 if (Value || MaxBytesToEmit) {
684 OS.write_hex(truncateToSize(Value, ValueSize));
687 OS << ", " << MaxBytesToEmit;
693 // Non-power of two alignment. This is not widely supported by assemblers.
694 // FIXME: Parameterize this based on MAI.
696 default: llvm_unreachable("Invalid size for machine code value!");
697 case 1: OS << ".balign"; break;
698 case 2: OS << ".balignw"; break;
699 case 4: OS << ".balignl"; break;
700 case 8: llvm_unreachable("Unsupported alignment size!");
703 OS << ' ' << ByteAlignment;
704 OS << ", " << truncateToSize(Value, ValueSize);
706 OS << ", " << MaxBytesToEmit;
710 void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment,
711 unsigned MaxBytesToEmit) {
712 // Emit with a text fill value.
713 EmitValueToAlignment(ByteAlignment, MAI.getTextAlignFillValue(),
717 void MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset,
718 unsigned char Value) {
719 // FIXME: Verify that Offset is associated with the current section.
720 OS << ".org " << *Offset << ", " << (unsigned) Value;
725 void MCAsmStreamer::EmitFileDirective(StringRef Filename) {
726 assert(MAI.hasSingleParameterDotFile());
728 PrintQuotedString(Filename, OS);
732 bool MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Filename){
734 OS << "\t.file\t" << FileNo << ' ';
735 PrintQuotedString(Filename, OS);
738 return this->MCStreamer::EmitDwarfFileDirective(FileNo, Filename);
741 void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
742 unsigned Column, unsigned Flags,
744 unsigned Discriminator,
745 StringRef FileName) {
746 this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags,
747 Isa, Discriminator, FileName);
751 OS << "\t.loc\t" << FileNo << " " << Line << " " << Column;
752 if (Flags & DWARF2_FLAG_BASIC_BLOCK)
753 OS << " basic_block";
754 if (Flags & DWARF2_FLAG_PROLOGUE_END)
755 OS << " prologue_end";
756 if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN)
757 OS << " epilogue_begin";
759 unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags();
760 if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) {
763 if (Flags & DWARF2_FLAG_IS_STMT)
772 OS << "discriminator " << Discriminator;
775 OS.PadToColumn(MAI.getCommentColumn());
776 OS << MAI.getCommentString() << ' ' << FileName << ':'
777 << Line << ':' << Column;
782 void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) {
783 MCStreamer::EmitCFISections(EH, Debug);
788 OS << "\t.cfi_sections ";
792 OS << ", .debug_frame";
794 OS << ".debug_frame";
800 void MCAsmStreamer::EmitCFIStartProc() {
801 MCStreamer::EmitCFIStartProc();
806 OS << "\t.cfi_startproc";
810 void MCAsmStreamer::EmitCFIEndProc() {
811 MCStreamer::EmitCFIEndProc();
816 OS << "\t.cfi_endproc";
820 void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) {
821 MCStreamer::EmitCFIDefCfa(Register, Offset);
826 OS << ".cfi_def_cfa " << Register << ", " << Offset;
830 void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) {
831 MCStreamer::EmitCFIDefCfaOffset(Offset);
836 OS << "\t.cfi_def_cfa_offset " << Offset;
840 void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) {
841 MCStreamer::EmitCFIDefCfaRegister(Register);
846 OS << "\t.cfi_def_cfa_register " << Register;
850 void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) {
851 this->MCStreamer::EmitCFIOffset(Register, Offset);
856 OS << "\t.cfi_offset " << Register << ", " << Offset;
860 void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym,
862 MCStreamer::EmitCFIPersonality(Sym, Encoding);
867 OS << "\t.cfi_personality " << Encoding << ", " << *Sym;
871 void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) {
872 MCStreamer::EmitCFILsda(Sym, Encoding);
877 OS << "\t.cfi_lsda " << Encoding << ", " << *Sym;
881 void MCAsmStreamer::EmitCFIRememberState() {
882 MCStreamer::EmitCFIRememberState();
887 OS << "\t.cfi_remember_state";
891 void MCAsmStreamer::EmitCFIRestoreState() {
892 MCStreamer::EmitCFIRestoreState();
897 OS << "\t.cfi_restore_state";
901 void MCAsmStreamer::EmitCFISameValue(int64_t Register) {
902 MCStreamer::EmitCFISameValue(Register);
907 OS << "\t.cfi_same_value " << Register;
911 void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) {
912 MCStreamer::EmitCFIRelOffset(Register, Offset);
917 OS << "\t.cfi_rel_offset " << Register << ", " << Offset;
921 void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) {
922 MCStreamer::EmitCFIAdjustCfaOffset(Adjustment);
927 OS << "\t.cfi_adjust_cfa_offset " << Adjustment;
931 void MCAsmStreamer::EmitWin64EHStartProc(MCSymbol *Symbol, MCSymbol *EHandler) {
932 OS << ".w64_startproc " << *Symbol;
934 OS << ", " << *EHandler;
938 void MCAsmStreamer::EmitWin64EHEndProc() {
939 OS << "\t.w64_endproc";
943 void MCAsmStreamer::EmitWin64EHStartChained() {
944 OS << "\t.w64_startchained";
948 void MCAsmStreamer::EmitWin64EHEndChained() {
949 OS << "\t.w64_endchained";
953 void MCAsmStreamer::EmitWin64EHUnwindOnly() {
954 OS << "\t.w64_unwind_only";
958 void MCAsmStreamer::EmitWin64EHLsda(const MCSymbol *Sym, int64_t Size) {
959 OS << "\t.w64_lsda " << *Sym << ", " << Size;
963 void MCAsmStreamer::EmitWin64EHPushReg(int64_t Register) {
964 OS << "\t.w64_pushreg " << Register;
968 void MCAsmStreamer::EmitWin64EHSetFrame(int64_t Register, int64_t Offset) {
969 OS << "\t.w64_setframe " << Register << ", " << Offset;
973 void MCAsmStreamer::EmitWin64EHAllocStack(int64_t Size) {
974 OS << "\t.w64_allocstack " << Size;
978 void MCAsmStreamer::EmitWin64EHSaveReg(int64_t Register, int64_t Offset) {
979 OS << "\t.w64_savereg " << Register << ", " << Offset;
983 void MCAsmStreamer::EmitWin64EHPushFrame(bool Code) {
984 OS << "\t.w64_pushframe";
990 void MCAsmStreamer::EmitWin64EHEndProlog(void) {
991 OS << "\t.w64_endprolog";
995 void MCAsmStreamer::AddEncodingComment(const MCInst &Inst) {
996 raw_ostream &OS = GetCommentOS();
997 SmallString<256> Code;
998 SmallVector<MCFixup, 4> Fixups;
999 raw_svector_ostream VecOS(Code);
1000 Emitter->EncodeInstruction(Inst, VecOS, Fixups);
1003 // If we are showing fixups, create symbolic markers in the encoded
1004 // representation. We do this by making a per-bit map to the fixup item index,
1005 // then trying to display it as nicely as possible.
1006 SmallVector<uint8_t, 64> FixupMap;
1007 FixupMap.resize(Code.size() * 8);
1008 for (unsigned i = 0, e = Code.size() * 8; i != e; ++i)
1011 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1012 MCFixup &F = Fixups[i];
1013 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1014 for (unsigned j = 0; j != Info.TargetSize; ++j) {
1015 unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j;
1016 assert(Index < Code.size() * 8 && "Invalid offset in fixup!");
1017 FixupMap[Index] = 1 + i;
1021 // FIXME: Node the fixup comments for Thumb2 are completely bogus since the
1022 // high order halfword of a 32-bit Thumb2 instruction is emitted first.
1023 OS << "encoding: [";
1024 for (unsigned i = 0, e = Code.size(); i != e; ++i) {
1028 // See if all bits are the same map entry.
1029 uint8_t MapEntry = FixupMap[i * 8 + 0];
1030 for (unsigned j = 1; j != 8; ++j) {
1031 if (FixupMap[i * 8 + j] == MapEntry)
1034 MapEntry = uint8_t(~0U);
1038 if (MapEntry != uint8_t(~0U)) {
1039 if (MapEntry == 0) {
1040 OS << format("0x%02x", uint8_t(Code[i]));
1043 // FIXME: Some of the 8 bits require fix up.
1044 OS << format("0x%02x", uint8_t(Code[i])) << '\''
1045 << char('A' + MapEntry - 1) << '\'';
1047 OS << char('A' + MapEntry - 1);
1050 // Otherwise, write out in binary.
1052 for (unsigned j = 8; j--;) {
1053 unsigned Bit = (Code[i] >> j) & 1;
1056 if (getContext().getTargetAsmInfo().isLittleEndian())
1057 FixupBit = i * 8 + j;
1059 FixupBit = i * 8 + (7-j);
1061 if (uint8_t MapEntry = FixupMap[FixupBit]) {
1062 assert(Bit == 0 && "Encoder wrote into fixed up bit!");
1063 OS << char('A' + MapEntry - 1);
1071 for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
1072 MCFixup &F = Fixups[i];
1073 const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind());
1074 OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset()
1075 << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n";
1079 void MCAsmStreamer::EmitFnStart() {
1084 void MCAsmStreamer::EmitFnEnd() {
1089 void MCAsmStreamer::EmitCantUnwind() {
1090 OS << "\t.cantunwind";
1094 void MCAsmStreamer::EmitHandlerData() {
1095 OS << "\t.handlerdata";
1099 void MCAsmStreamer::EmitPersonality(const MCSymbol *Personality) {
1100 OS << "\t.personality " << Personality->getName();
1104 void MCAsmStreamer::EmitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset) {
1105 OS << "\t.setfp\t" << InstPrinter->getRegName(FpReg)
1106 << ", " << InstPrinter->getRegName(SpReg);
1108 OS << ", #" << Offset;
1112 void MCAsmStreamer::EmitPad(int64_t Offset) {
1113 OS << "\t.pad\t#" << Offset;
1117 void MCAsmStreamer::EmitRegSave(const SmallVectorImpl<unsigned> &RegList,
1119 assert(RegList.size() && "RegList should not be empty");
1121 OS << "\t.vsave\t{";
1125 OS << InstPrinter->getRegName(RegList[0]);
1127 for (unsigned i = 1, e = RegList.size(); i != e; ++i)
1128 OS << ", " << InstPrinter->getRegName(RegList[i]);
1134 void MCAsmStreamer::EmitInstruction(const MCInst &Inst) {
1135 assert(getCurrentSection() && "Cannot emit contents before setting section!");
1137 // Show the encoding in a comment if we have a code emitter.
1139 AddEncodingComment(Inst);
1141 // Show the MCInst if enabled.
1143 Inst.dump_pretty(GetCommentOS(), &MAI, InstPrinter.get(), "\n ");
1144 GetCommentOS() << "\n";
1147 // If we have an AsmPrinter, use that to print, otherwise print the MCInst.
1149 InstPrinter->printInst(&Inst, OS);
1151 Inst.print(OS, &MAI);
1155 /// EmitRawText - If this file is backed by an assembly streamer, this dumps
1156 /// the specified string in the output .s file. This capability is
1157 /// indicated by the hasRawTextSupport() predicate.
1158 void MCAsmStreamer::EmitRawText(StringRef String) {
1159 if (!String.empty() && String.back() == '\n')
1160 String = String.substr(0, String.size()-1);
1165 void MCAsmStreamer::Finish() {
1166 // Dump out the dwarf file & directory tables and line tables.
1167 if (getContext().hasDwarfFiles() && !UseLoc)
1168 MCDwarfFileTable::Emit(this);
1174 MCStreamer *llvm::createAsmStreamer(MCContext &Context,
1175 formatted_raw_ostream &OS,
1176 bool isVerboseAsm, bool useLoc,
1178 MCInstPrinter *IP, MCCodeEmitter *CE,
1179 TargetAsmBackend *TAB, bool ShowInst) {
1180 return new MCAsmStreamer(Context, OS, isVerboseAsm, useLoc, useCFI,
1181 IP, CE, TAB, ShowInst);